power-grid-model 1.11.48__py3-none-win_amd64.whl → 1.12.72__py3-none-win_amd64.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 might be problematic. Click here for more details.

Files changed (60) hide show
  1. power_grid_model/__init__.py +54 -54
  2. power_grid_model/_core/__init__.py +3 -3
  3. power_grid_model/_core/buffer_handling.py +493 -487
  4. power_grid_model/_core/data_handling.py +195 -141
  5. power_grid_model/_core/data_types.py +143 -132
  6. power_grid_model/_core/dataset_definitions.py +109 -109
  7. power_grid_model/_core/enum.py +226 -226
  8. power_grid_model/_core/error_handling.py +206 -206
  9. power_grid_model/_core/errors.py +130 -130
  10. power_grid_model/_core/index_integer.py +17 -17
  11. power_grid_model/_core/options.py +71 -71
  12. power_grid_model/_core/power_grid_core.py +563 -563
  13. power_grid_model/_core/power_grid_dataset.py +535 -535
  14. power_grid_model/_core/power_grid_meta.py +257 -243
  15. power_grid_model/_core/power_grid_model.py +969 -686
  16. power_grid_model/_core/power_grid_model_c/__init__.py +3 -3
  17. power_grid_model/_core/power_grid_model_c/bin/power_grid_model_c.dll +0 -0
  18. power_grid_model/_core/power_grid_model_c/get_pgm_dll_path.py +63 -63
  19. power_grid_model/_core/power_grid_model_c/include/power_grid_model_c/basics.h +255 -255
  20. power_grid_model/_core/power_grid_model_c/include/power_grid_model_c/buffer.h +108 -108
  21. power_grid_model/_core/power_grid_model_c/include/power_grid_model_c/dataset.h +316 -316
  22. power_grid_model/_core/power_grid_model_c/include/power_grid_model_c/dataset_definitions.h +1052 -1052
  23. power_grid_model/_core/power_grid_model_c/include/power_grid_model_c/handle.h +99 -99
  24. power_grid_model/_core/power_grid_model_c/include/power_grid_model_c/meta_data.h +189 -189
  25. power_grid_model/_core/power_grid_model_c/include/power_grid_model_c/model.h +125 -125
  26. power_grid_model/_core/power_grid_model_c/include/power_grid_model_c/options.h +142 -142
  27. power_grid_model/_core/power_grid_model_c/include/power_grid_model_c/serialization.h +118 -118
  28. power_grid_model/_core/power_grid_model_c/include/power_grid_model_c.h +36 -36
  29. power_grid_model/_core/power_grid_model_c/include/power_grid_model_cpp/basics.hpp +65 -65
  30. power_grid_model/_core/power_grid_model_c/include/power_grid_model_cpp/buffer.hpp +61 -61
  31. power_grid_model/_core/power_grid_model_c/include/power_grid_model_cpp/dataset.hpp +220 -220
  32. power_grid_model/_core/power_grid_model_c/include/power_grid_model_cpp/handle.hpp +108 -108
  33. power_grid_model/_core/power_grid_model_c/include/power_grid_model_cpp/meta_data.hpp +84 -84
  34. power_grid_model/_core/power_grid_model_c/include/power_grid_model_cpp/model.hpp +63 -63
  35. power_grid_model/_core/power_grid_model_c/include/power_grid_model_cpp/options.hpp +52 -52
  36. power_grid_model/_core/power_grid_model_c/include/power_grid_model_cpp/serialization.hpp +124 -124
  37. power_grid_model/_core/power_grid_model_c/include/power_grid_model_cpp/utils.hpp +81 -81
  38. power_grid_model/_core/power_grid_model_c/include/power_grid_model_cpp.hpp +19 -19
  39. power_grid_model/_core/power_grid_model_c/lib/cmake/power_grid_model/power_grid_modelConfigVersion.cmake +3 -3
  40. power_grid_model/_core/power_grid_model_c/lib/power_grid_model_c.lib +0 -0
  41. power_grid_model/_core/serialization.py +317 -317
  42. power_grid_model/_core/typing.py +20 -20
  43. power_grid_model/_core/utils.py +798 -793
  44. power_grid_model/data_types.py +321 -321
  45. power_grid_model/enum.py +27 -27
  46. power_grid_model/errors.py +37 -37
  47. power_grid_model/typing.py +43 -43
  48. power_grid_model/utils.py +473 -469
  49. power_grid_model/validation/__init__.py +25 -25
  50. power_grid_model/validation/_rules.py +1171 -1176
  51. power_grid_model/validation/_validation.py +1172 -1172
  52. power_grid_model/validation/assertions.py +93 -93
  53. power_grid_model/validation/errors.py +602 -602
  54. power_grid_model/validation/utils.py +313 -314
  55. {power_grid_model-1.11.48.dist-info → power_grid_model-1.12.72.dist-info}/METADATA +4 -2
  56. power_grid_model-1.12.72.dist-info/RECORD +65 -0
  57. {power_grid_model-1.11.48.dist-info → power_grid_model-1.12.72.dist-info}/WHEEL +1 -1
  58. power_grid_model-1.11.48.dist-info/RECORD +0 -65
  59. {power_grid_model-1.11.48.dist-info → power_grid_model-1.12.72.dist-info}/entry_points.txt +0 -0
  60. {power_grid_model-1.11.48.dist-info → power_grid_model-1.12.72.dist-info}/licenses/LICENSE +0 -0
@@ -1,686 +1,969 @@
1
- # SPDX-FileCopyrightText: Contributors to the Power Grid Model project <powergridmodel@lfenergy.org>
2
- #
3
- # SPDX-License-Identifier: MPL-2.0
4
-
5
- """
6
- Main power grid model class
7
- """
8
-
9
- from enum import IntEnum
10
-
11
- import numpy as np
12
-
13
- from power_grid_model._core.data_handling import (
14
- create_output_data,
15
- get_output_type,
16
- prepare_input_view,
17
- prepare_output_view,
18
- prepare_update_view,
19
- )
20
- from power_grid_model._core.data_types import Dataset, SingleDataset
21
- from power_grid_model._core.dataset_definitions import (
22
- ComponentType,
23
- ComponentTypeLike,
24
- _map_to_component_types,
25
- _str_to_component_type,
26
- )
27
- from power_grid_model._core.enum import (
28
- CalculationMethod,
29
- CalculationType,
30
- ShortCircuitVoltageScaling,
31
- TapChangingStrategy,
32
- _ExperimentalFeatures,
33
- )
34
- from power_grid_model._core.error_handling import PowerGridBatchError, assert_no_error, handle_errors
35
- from power_grid_model._core.index_integer import IdNp, IdxNp
36
- from power_grid_model._core.options import Options
37
- from power_grid_model._core.power_grid_core import ConstDatasetPtr, IDPtr, IdxPtr, ModelPtr, power_grid_core as pgc
38
- from power_grid_model._core.typing import ComponentAttributeMapping
39
-
40
-
41
- class PowerGridModel:
42
- """
43
- Main class for Power Grid Model
44
- """
45
-
46
- _model_ptr: ModelPtr
47
- _all_component_count: dict[ComponentType, int] | None
48
- _batch_error: PowerGridBatchError | None
49
-
50
- @property
51
- def batch_error(self) -> PowerGridBatchError | None:
52
- """
53
- Get the batch error object, if present, after a batch calculation with errors.
54
-
55
- Also works when continue_on_batch_error was set to True during the calculation.
56
-
57
- Returns:
58
- Batch error object, or None
59
- """
60
- return self._batch_error
61
-
62
- @property
63
- def _model(self):
64
- if not self._model_ptr:
65
- raise TypeError("You have an empty instance of PowerGridModel!")
66
- return self._model_ptr
67
-
68
- @property
69
- def all_component_count(self) -> dict[ComponentType, int]:
70
- """
71
- Get amount of elements per component type.
72
- If the count for a component type is zero, it will not be in the returned dictionary.
73
-
74
- Returns:
75
- A dictionary with
76
-
77
- - key: Component type name
78
- - value: Integer count of elements of this type
79
- """
80
- if self._all_component_count is None:
81
- raise TypeError("You have an empty instance of PowerGridModel!")
82
- return self._all_component_count
83
-
84
- def copy(self) -> "PowerGridModel":
85
- """
86
- Copy the current model
87
-
88
- Returns:
89
- A copy of PowerGridModel
90
- """
91
- new_model = PowerGridModel.__new__(PowerGridModel)
92
- new_model._model_ptr = pgc.copy_model(self._model)
93
- assert_no_error()
94
- new_model._all_component_count = self._all_component_count
95
- return new_model
96
-
97
- def __copy__(self):
98
- return self.copy()
99
-
100
- def __new__(cls, *_args, **_kwargs):
101
- instance = super().__new__(cls)
102
- instance._model_ptr = ModelPtr()
103
- instance._all_component_count = None
104
- return instance
105
-
106
- def __init__(self, input_data: SingleDataset, system_frequency: float = 50.0):
107
- """
108
- Initialize the model from an input data set.
109
-
110
- Args:
111
- input_data: Input data dictionary
112
-
113
- - key: Component type
114
- - value: Component data with the correct type :class:`SingleComponentData`
115
-
116
- system_frequency: Frequency of the power system, default 50 Hz
117
- """
118
- # destroy old instance
119
- pgc.destroy_model(self._model_ptr)
120
- self._all_component_count = None
121
- # create new
122
- prepared_input = prepare_input_view(_map_to_component_types(input_data))
123
- self._model_ptr = pgc.create_model(system_frequency, input_data=prepared_input.get_dataset_ptr())
124
- assert_no_error()
125
- self._all_component_count = {k: v for k, v in prepared_input.get_info().total_elements().items() if v > 0}
126
-
127
- def update(self, *, update_data: Dataset):
128
- """
129
- Update the model with changes.
130
-
131
- The model will be in an invalid state if the update fails and should be discarded.
132
-
133
- Args:
134
- update_data: Update data dictionary
135
-
136
- - key: Component type
137
- - value: Component data with the correct type :class:`ComponentData` (single scenario or batch)
138
-
139
- Raises:
140
- PowerGridError if the update fails. The model is left in an invalid state and should be discarded.
141
-
142
- Returns:
143
- None
144
- """
145
- prepared_update = prepare_update_view(_map_to_component_types(update_data))
146
- pgc.update_model(self._model, prepared_update.get_dataset_ptr())
147
- assert_no_error()
148
-
149
- def get_indexer(self, component_type: ComponentTypeLike, ids: np.ndarray):
150
- """
151
- Get array of indexers given array of ids for component type.
152
-
153
- This enables syntax like input_data[ComponentType.node][get_indexer(ids)]
154
-
155
- Args:
156
- component_type: Type of component
157
- ids: Array of ids
158
-
159
- Returns:
160
- Array of indexers, same shape as input array ids
161
- """
162
- component_type = _str_to_component_type(component_type)
163
- ids_c = np.ascontiguousarray(ids, dtype=IdNp).ctypes.data_as(IDPtr)
164
- indexer = np.empty_like(ids, dtype=IdxNp, order="C")
165
- indexer_c = indexer.ctypes.data_as(IdxPtr)
166
- size = ids.size
167
- # call c function
168
- pgc.get_indexer(self._model, component_type, size, ids_c, indexer_c)
169
- assert_no_error()
170
- return indexer
171
-
172
- def _get_output_component_count(self, calculation_type: CalculationType):
173
- exclude_types = {
174
- CalculationType.power_flow: [
175
- ComponentType.sym_voltage_sensor,
176
- ComponentType.asym_voltage_sensor,
177
- ComponentType.sym_power_sensor,
178
- ComponentType.asym_power_sensor,
179
- ComponentType.fault,
180
- ],
181
- CalculationType.state_estimation: [ComponentType.fault],
182
- CalculationType.short_circuit: [
183
- ComponentType.sym_voltage_sensor,
184
- ComponentType.asym_voltage_sensor,
185
- ComponentType.sym_power_sensor,
186
- ComponentType.asym_power_sensor,
187
- ],
188
- }.get(calculation_type, [])
189
-
190
- def include_type(component_type: ComponentType):
191
- return all(exclude_type.value not in component_type.value for exclude_type in exclude_types)
192
-
193
- return {ComponentType[k]: v for k, v in self.all_component_count.items() if include_type(k)}
194
-
195
- def _construct_output(
196
- self,
197
- output_component_types: ComponentAttributeMapping,
198
- calculation_type: CalculationType,
199
- symmetric: bool,
200
- is_batch: bool,
201
- batch_size: int,
202
- ) -> dict[ComponentType, np.ndarray]:
203
- all_component_count = self._get_output_component_count(calculation_type=calculation_type)
204
- return create_output_data(
205
- output_component_types=output_component_types,
206
- output_type=get_output_type(calculation_type=calculation_type, symmetric=symmetric),
207
- all_component_count=all_component_count,
208
- is_batch=is_batch,
209
- batch_size=batch_size,
210
- )
211
-
212
- @staticmethod
213
- def _options(**kwargs) -> Options:
214
- def as_enum_value(key_enum: str, type_: type[IntEnum]):
215
- if key_enum in kwargs:
216
- value_enum = kwargs[key_enum]
217
- if isinstance(value_enum, str):
218
- kwargs[key_enum] = type_[value_enum]
219
-
220
- as_enum_value("calculation_method", CalculationMethod)
221
- as_enum_value("tap_changing_strategy", TapChangingStrategy)
222
- as_enum_value("short_circuit_voltage_scaling", ShortCircuitVoltageScaling)
223
- as_enum_value("experimental_features", _ExperimentalFeatures)
224
-
225
- opt = Options()
226
- for key, value in kwargs.items():
227
- setattr(opt, key, value.value if isinstance(value, IntEnum) else value)
228
- return opt
229
-
230
- def _handle_errors(self, continue_on_batch_error: bool, batch_size: int, decode_error: bool):
231
- self._batch_error = handle_errors(
232
- continue_on_batch_error=continue_on_batch_error,
233
- batch_size=batch_size,
234
- decode_error=decode_error,
235
- )
236
-
237
- def _calculate_impl( # noqa: PLR0913
238
- self,
239
- calculation_type: CalculationType,
240
- symmetric: bool,
241
- update_data: Dataset | None,
242
- output_component_types: ComponentAttributeMapping,
243
- options: Options,
244
- continue_on_batch_error: bool,
245
- decode_error: bool,
246
- experimental_features: _ExperimentalFeatures | str, # NOSONAR # noqa: ARG002
247
- ):
248
- """
249
- Core calculation routine
250
-
251
- Args:
252
- calculation_type:
253
- symmetric:
254
- update_data:
255
- output_component_types:
256
- options:
257
- continue_on_batch_error:
258
- decode_error:
259
-
260
- Returns:
261
- """
262
- self._batch_error = None
263
- is_batch = update_data is not None
264
-
265
- if update_data is not None:
266
- prepared_update = prepare_update_view(update_data)
267
- update_ptr = prepared_update.get_dataset_ptr()
268
- batch_size = prepared_update.get_info().batch_size()
269
- else:
270
- update_ptr = ConstDatasetPtr()
271
- batch_size = 1
272
-
273
- output_data = self._construct_output(
274
- output_component_types=output_component_types,
275
- calculation_type=calculation_type,
276
- symmetric=symmetric,
277
- is_batch=is_batch,
278
- batch_size=batch_size,
279
- )
280
- prepared_result = prepare_output_view(
281
- output_data=output_data,
282
- output_type=get_output_type(calculation_type=calculation_type, symmetric=symmetric),
283
- )
284
-
285
- # run calculation
286
- pgc.calculate(
287
- # model and options
288
- self._model,
289
- options.opt,
290
- output_data=prepared_result.get_dataset_ptr(),
291
- update_data=update_ptr,
292
- )
293
-
294
- self._handle_errors(
295
- continue_on_batch_error=continue_on_batch_error,
296
- batch_size=batch_size,
297
- decode_error=decode_error,
298
- )
299
-
300
- return output_data
301
-
302
- def _calculate_power_flow( # noqa: PLR0913
303
- self,
304
- *,
305
- symmetric: bool = True,
306
- error_tolerance: float = 1e-8,
307
- max_iterations: int = 20,
308
- calculation_method: CalculationMethod | str = CalculationMethod.newton_raphson,
309
- update_data: Dataset | None = None,
310
- threading: int = -1,
311
- output_component_types: ComponentAttributeMapping = None,
312
- continue_on_batch_error: bool = False,
313
- decode_error: bool = True,
314
- tap_changing_strategy: TapChangingStrategy | str = TapChangingStrategy.disabled,
315
- experimental_features: _ExperimentalFeatures | str = _ExperimentalFeatures.disabled,
316
- ):
317
- calculation_type = CalculationType.power_flow
318
- options = self._options(
319
- calculation_type=calculation_type,
320
- symmetric=symmetric,
321
- error_tolerance=error_tolerance,
322
- max_iterations=max_iterations,
323
- calculation_method=calculation_method,
324
- tap_changing_strategy=tap_changing_strategy,
325
- threading=threading,
326
- experimental_features=experimental_features,
327
- )
328
- return self._calculate_impl(
329
- calculation_type=calculation_type,
330
- symmetric=symmetric,
331
- update_data=update_data,
332
- output_component_types=output_component_types,
333
- options=options,
334
- continue_on_batch_error=continue_on_batch_error,
335
- decode_error=decode_error,
336
- experimental_features=experimental_features,
337
- )
338
-
339
- def _calculate_state_estimation( # noqa: PLR0913
340
- self,
341
- *,
342
- symmetric: bool = True,
343
- error_tolerance: float = 1e-8,
344
- max_iterations: int = 20,
345
- calculation_method: CalculationMethod | str = CalculationMethod.iterative_linear,
346
- update_data: Dataset | None = None,
347
- threading: int = -1,
348
- output_component_types: ComponentAttributeMapping = None,
349
- continue_on_batch_error: bool = False,
350
- decode_error: bool = True,
351
- experimental_features: _ExperimentalFeatures | str = _ExperimentalFeatures.disabled,
352
- ) -> dict[ComponentType, np.ndarray]:
353
- calculation_type = CalculationType.state_estimation
354
- options = self._options(
355
- calculation_type=calculation_type,
356
- symmetric=symmetric,
357
- error_tolerance=error_tolerance,
358
- max_iterations=max_iterations,
359
- calculation_method=calculation_method,
360
- threading=threading,
361
- experimental_features=experimental_features,
362
- )
363
- return self._calculate_impl(
364
- calculation_type=calculation_type,
365
- symmetric=symmetric,
366
- update_data=update_data,
367
- output_component_types=output_component_types,
368
- options=options,
369
- continue_on_batch_error=continue_on_batch_error,
370
- decode_error=decode_error,
371
- experimental_features=experimental_features,
372
- )
373
-
374
- def _calculate_short_circuit( # noqa: PLR0913
375
- self,
376
- *,
377
- calculation_method: CalculationMethod | str = CalculationMethod.iec60909,
378
- update_data: Dataset | None = None,
379
- threading: int = -1,
380
- output_component_types: ComponentAttributeMapping = None,
381
- continue_on_batch_error: bool = False,
382
- decode_error: bool = True,
383
- short_circuit_voltage_scaling: ShortCircuitVoltageScaling | str = ShortCircuitVoltageScaling.maximum,
384
- experimental_features: _ExperimentalFeatures | str = _ExperimentalFeatures.disabled,
385
- ) -> dict[ComponentType, np.ndarray]:
386
- calculation_type = CalculationType.short_circuit
387
- symmetric = False
388
-
389
- options = self._options(
390
- calculation_type=calculation_type,
391
- symmetric=symmetric,
392
- calculation_method=calculation_method,
393
- threading=threading,
394
- short_circuit_voltage_scaling=short_circuit_voltage_scaling,
395
- experimental_features=experimental_features,
396
- )
397
- return self._calculate_impl(
398
- calculation_type=calculation_type,
399
- symmetric=symmetric,
400
- update_data=update_data,
401
- output_component_types=output_component_types,
402
- options=options,
403
- continue_on_batch_error=continue_on_batch_error,
404
- decode_error=decode_error,
405
- experimental_features=experimental_features,
406
- )
407
-
408
- def calculate_power_flow( # noqa: PLR0913
409
- self,
410
- *,
411
- symmetric: bool = True,
412
- error_tolerance: float = 1e-8,
413
- max_iterations: int = 20,
414
- calculation_method: CalculationMethod | str = CalculationMethod.newton_raphson,
415
- update_data: dict[str, np.ndarray | dict[str, np.ndarray]] | Dataset | None = None,
416
- threading: int = -1,
417
- output_component_types: ComponentAttributeMapping = None,
418
- continue_on_batch_error: bool = False,
419
- decode_error: bool = True,
420
- tap_changing_strategy: TapChangingStrategy | str = TapChangingStrategy.disabled,
421
- ) -> dict[ComponentType, np.ndarray]:
422
- """
423
- Calculate power flow once with the current model attributes.
424
- Or calculate in batch with the given update dataset in batch.
425
-
426
- Args:
427
- symmetric (bool, optional): Whether to perform a three-phase symmetric calculation.
428
-
429
- - True: Three-phase symmetric calculation, even for asymmetric loads/generations (Default).
430
- - False: Three-phase asymmetric calculation.
431
- error_tolerance (float, optional): Error tolerance for voltage in p.u., applicable only when the
432
- calculation method is iterative.
433
- max_iterations (int, optional): Maximum number of iterations, applicable only when the calculation method
434
- is iterative.
435
- calculation_method (an enumeration or string): The calculation method to use.
436
-
437
- - newton_raphson: Use Newton-Raphson iterative method (default).
438
- - linear: Use linear method.
439
- update_data (dict, optional):
440
- None: Calculate power flow once with the current model attributes.
441
- Or a dictionary for batch calculation with batch update.
442
-
443
- - key: Component type name to be updated in batch.
444
- - value:
445
-
446
- - For homogeneous update batch (a 2D numpy structured array):
447
-
448
- - Dimension 0: Each batch.
449
- - Dimension 1: Each updated element per batch for this component type.
450
- - For inhomogeneous update batch (a dictionary containing two keys):
451
-
452
- - indptr: A 1D numpy int64 array with length n_batch + 1. Given batch number k, the
453
- update array for this batch is data[indptr[k]:indptr[k + 1]]. This is the concept of
454
- compressed sparse structure.
455
- https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.csr_matrix.html
456
- - data: 1D numpy structured array in flat.
457
- threading (int, optional): Applicable only for batch calculation.
458
-
459
- - < 0: Sequential
460
- - = 0: Parallel, use number of hardware threads
461
- - > 0: Specify number of parallel threads
462
- output_component_types (ComponentAttributeMapping):
463
-
464
- - None: Row based data for all component types.
465
- - set[ComponentTypeVar] or list[ComponentTypeVar]: Row based data for the specified component types.
466
- - ComponentAttributeFilterOptions: Columnar data for all component types.
467
- - dict[ComponentType, set[str] | list[str] | None | ComponentAttributeFilterOptions]:
468
- key: ComponentType
469
- value:
470
- - None: Row based data for the specified component types.
471
- - ComponentAttributeFilterOptions: Columnar data for the specified component types.
472
- - set[str] | list[str]: Columnar data for the specified component types and attributes.
473
- continue_on_batch_error (bool, optional):
474
- Continue the program (instead of throwing error) if some scenarios fail.
475
- You can still retrieve the errors and succeeded/failed scenarios via the batch_error.
476
- decode_error (bool, optional):
477
- Decode error messages to their derived types if possible.
478
-
479
- Returns:
480
- Dictionary of results of all components.
481
-
482
- - key: Component type name to be updated in batch.
483
- - value:
484
-
485
- - For single calculation: 1D numpy structured array for the results of this component type.
486
- - For batch calculation: 2D numpy structured array for the results of this component type.
487
-
488
- - Dimension 0: Each batch.
489
- - Dimension 1: The result of each element for this component type.
490
-
491
- Raises:
492
- Exception: In case an error in the core occurs, an exception will be thrown.
493
- """
494
- return self._calculate_power_flow(
495
- symmetric=symmetric,
496
- error_tolerance=error_tolerance,
497
- max_iterations=max_iterations,
498
- calculation_method=calculation_method,
499
- update_data=(_map_to_component_types(update_data) if update_data is not None else None),
500
- threading=threading,
501
- output_component_types=output_component_types,
502
- continue_on_batch_error=continue_on_batch_error,
503
- decode_error=decode_error,
504
- tap_changing_strategy=tap_changing_strategy,
505
- )
506
-
507
- def calculate_state_estimation( # noqa: PLR0913
508
- self,
509
- *,
510
- symmetric: bool = True,
511
- error_tolerance: float = 1e-8,
512
- max_iterations: int = 20,
513
- calculation_method: CalculationMethod | str = CalculationMethod.iterative_linear,
514
- update_data: dict[str, np.ndarray | dict[str, np.ndarray]] | Dataset | None = None,
515
- threading: int = -1,
516
- output_component_types: ComponentAttributeMapping = None,
517
- continue_on_batch_error: bool = False,
518
- decode_error: bool = True,
519
- ) -> dict[ComponentType, np.ndarray]:
520
- """
521
- Calculate state estimation once with the current model attributes.
522
- Or calculate in batch with the given update dataset in batch.
523
-
524
- Args:
525
- symmetric (bool, optional): Whether to perform a three-phase symmetric calculation.
526
-
527
- - True: Three-phase symmetric calculation, even for asymmetric loads/generations (Default).
528
- - False: Three-phase asymmetric calculation.
529
- error_tolerance (float, optional): error tolerance for voltage in p.u., only applicable when the
530
- calculation method is iterative.
531
- max_iterations (int, optional): Maximum number of iterations, applicable only when the calculation method
532
- is iterative.
533
- calculation_method (an enumeration): Use iterative linear method.
534
- update_data (dict, optional):
535
- None: Calculate state estimation once with the current model attributes.
536
- Or a dictionary for batch calculation with batch update.
537
-
538
- - key: Component type name to be updated in batch.
539
- - value:
540
-
541
- - For homogeneous update batch (a 2D numpy structured array):
542
-
543
- - Dimension 0: Each batch.
544
- - Dimension 1: Each updated element per batch for this component type.
545
- - For inhomogeneous update batch (a dictionary containing two keys):
546
-
547
- - indptr: A 1D numpy int64 array with length n_batch + 1. Given batch number k, the
548
- update array for this batch is data[indptr[k]:indptr[k + 1]]. This is the concept of
549
- compressed sparse structure.
550
- https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.csr_matrix.html
551
- - data: 1D numpy structured array in flat.
552
- threading (int, optional): Applicable only for batch calculation.
553
-
554
- - < 0: Sequential
555
- - = 0: Parallel, use number of hardware threads
556
- - > 0: Specify number of parallel threads
557
- output_component_types (ComponentAttributeMapping):
558
-
559
- - None: Row based data for all component types.
560
- - set[ComponentTypeVar] or list[ComponentTypeVar]: Row based data for the specified component types.
561
- - ComponentAttributeFilterOptions: Columnar data for all component types.
562
- - dict[ComponentType, set[str] | list[str] | None | ComponentAttributeFilterOptions]:
563
- key: ComponentType
564
- value:
565
- - None: Row based data for the specified component types.
566
- - ComponentAttributeFilterOptions: Columnar data for the specified component types.
567
- - set[str] | list[str]: Columnar data for the specified component types and attributes.
568
- continue_on_batch_error (bool, optional):
569
- Continue the program (instead of throwing error) if some scenarios fail.
570
- You can still retrieve the errors and succeeded/failed scenarios via the batch_error.
571
- decode_error (bool, optional):
572
- Decode error messages to their derived types if possible.
573
-
574
- Returns:
575
- Dictionary of results of all components.
576
-
577
- - key: Component type name to be updated in batch.
578
- - value:
579
-
580
- - For single calculation: 1D numpy structured array for the results of this component type.
581
- - For batch calculation: 2D numpy structured array for the results of this component type.
582
-
583
- - Dimension 0: Each batch.
584
- - Dimension 1: The result of each element for this component type.
585
-
586
- Raises:
587
- Exception: In case an error in the core occurs, an exception will be thrown.
588
- """
589
- return self._calculate_state_estimation(
590
- symmetric=symmetric,
591
- error_tolerance=error_tolerance,
592
- max_iterations=max_iterations,
593
- calculation_method=calculation_method,
594
- update_data=(_map_to_component_types(update_data) if update_data is not None else None),
595
- threading=threading,
596
- output_component_types=output_component_types,
597
- continue_on_batch_error=continue_on_batch_error,
598
- decode_error=decode_error,
599
- )
600
-
601
- def calculate_short_circuit( # noqa: PLR0913
602
- self,
603
- *,
604
- calculation_method: CalculationMethod | str = CalculationMethod.iec60909,
605
- update_data: dict[str, np.ndarray | dict[str, np.ndarray]] | Dataset | None = None,
606
- threading: int = -1,
607
- output_component_types: ComponentAttributeMapping = None,
608
- continue_on_batch_error: bool = False,
609
- decode_error: bool = True,
610
- short_circuit_voltage_scaling: ShortCircuitVoltageScaling | str = ShortCircuitVoltageScaling.maximum,
611
- ) -> dict[ComponentType, np.ndarray]:
612
- """
613
- Calculate a short circuit once with the current model attributes.
614
- Or calculate in batch with the given update dataset in batch
615
-
616
- Args:
617
- calculation_method (an enumeration): Use the iec60909 standard.
618
- update_data:
619
- None: calculate a short circuit once with the current model attributes.
620
- Or a dictionary for batch calculation with batch update
621
-
622
- - key: Component type name to be updated in batch
623
- - value:
624
-
625
- - For homogeneous update batch (a 2D numpy structured array):
626
-
627
- - Dimension 0: each batch
628
- - Dimension 1: each updated element per batch for this component type
629
- - For inhomogeneous update batch (a dictionary containing two keys):
630
-
631
- - indptr: A 1D numpy int64 array with length n_batch + 1. Given batch number k, the
632
- update array for this batch is data[indptr[k]:indptr[k + 1]]. This is the concept of
633
- compressed sparse structure.
634
- https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.csr_matrix.html
635
- - data: 1D numpy structured array in flat.
636
- threading (int, optional): Applicable only for batch calculation.
637
-
638
- - < 0: Sequential
639
- - = 0: Parallel, use number of hardware threads
640
- - > 0: Specify number of parallel threads
641
- output_component_types (ComponentAttributeMapping):
642
-
643
- - None: Row based data for all component types.
644
- - set[ComponentTypeVar] or list[ComponentTypeVar]: Row based data for the specified component types.
645
- - ComponentAttributeFilterOptions: Columnar data for all component types.
646
- - dict[ComponentType, set[str] | list[str] | None | ComponentAttributeFilterOptions]:
647
- key: ComponentType
648
- value:
649
- - None: Row based data for the specified component types.
650
- - ComponentAttributeFilterOptions: Columnar data for the specified component types.
651
- - set[str] | list[str]: Columnar data for the specified component types and attributes.
652
- continue_on_batch_error (bool, optional):
653
- Continue the program (instead of throwing error) if some scenarios fail.
654
- You can still retrieve the errors and succeeded/failed scenarios via the batch_error.
655
- decode_error (bool, optional):
656
- Decode error messages to their derived types if possible.
657
- short_circuit_voltage_scaling ({ShortCircuitVoltageSaling, str}, optional):
658
- Whether to use the maximum or minimum voltage scaling.
659
- By default, the maximum voltage scaling is used to calculate the short circuit.
660
-
661
- Returns:
662
- Dictionary of results of all components.
663
-
664
- - key: Component type name to be updated in batch.
665
- - value:
666
-
667
- - For single calculation: 1D numpy structured array for the results of this component type.
668
- - For batch calculation: 2D numpy structured array for the results of this component type.
669
-
670
- - Dimension 0: Each batch.
671
- - Dimension 1: The result of each element for this component type.
672
- Raises:
673
- Exception: In case an error in the core occurs, an exception will be thrown.
674
- """
675
- return self._calculate_short_circuit(
676
- calculation_method=calculation_method,
677
- update_data=(_map_to_component_types(update_data) if update_data is not None else None),
678
- threading=threading,
679
- output_component_types=output_component_types,
680
- continue_on_batch_error=continue_on_batch_error,
681
- decode_error=decode_error,
682
- short_circuit_voltage_scaling=short_circuit_voltage_scaling,
683
- )
684
-
685
- def __del__(self):
686
- pgc.destroy_model(self._model_ptr)
1
+ # SPDX-FileCopyrightText: Contributors to the Power Grid Model project <powergridmodel@lfenergy.org>
2
+ #
3
+ # SPDX-License-Identifier: MPL-2.0
4
+
5
+ """
6
+ Main power grid model class
7
+ """
8
+
9
+ from enum import IntEnum
10
+ from typing import Any, overload
11
+
12
+ import numpy as np
13
+
14
+ from power_grid_model._core.data_handling import (
15
+ create_output_data,
16
+ get_output_type,
17
+ prepare_input_view,
18
+ prepare_output_view,
19
+ prepare_update_view,
20
+ )
21
+ from power_grid_model._core.data_types import (
22
+ BatchDataset,
23
+ Dataset,
24
+ DenseBatchColumnarOutputDataset,
25
+ DenseBatchOutputDataset,
26
+ DenseBatchRowBasedOutputDataset,
27
+ SingleColumnarOutputDataset,
28
+ SingleDataset,
29
+ SingleOutputDataset,
30
+ SingleRowBasedDataset,
31
+ SingleRowBasedOutputDataset,
32
+ )
33
+ from power_grid_model._core.dataset_definitions import (
34
+ ComponentType,
35
+ ComponentTypeLike,
36
+ ComponentTypeVar,
37
+ _map_to_component_types,
38
+ _str_to_component_type,
39
+ )
40
+ from power_grid_model._core.enum import (
41
+ CalculationMethod,
42
+ CalculationType,
43
+ ComponentAttributeFilterOptions,
44
+ ShortCircuitVoltageScaling,
45
+ TapChangingStrategy,
46
+ _ExperimentalFeatures,
47
+ )
48
+ from power_grid_model._core.error_handling import PowerGridBatchError, assert_no_error, handle_errors
49
+ from power_grid_model._core.index_integer import IdNp, IdxNp
50
+ from power_grid_model._core.options import Options
51
+ from power_grid_model._core.power_grid_core import ConstDatasetPtr, IDPtr, IdxPtr, ModelPtr, power_grid_core as pgc
52
+ from power_grid_model._core.typing import ComponentAttributeMapping, ComponentAttributeMappingDict
53
+
54
+
55
+ class PowerGridModel:
56
+ """
57
+ Main class for Power Grid Model
58
+ """
59
+
60
+ _model_ptr: ModelPtr
61
+ _all_component_count: dict[ComponentType, int] | None
62
+ _batch_error: PowerGridBatchError | None
63
+
64
+ @property
65
+ def batch_error(self) -> PowerGridBatchError | None:
66
+ """
67
+ Get the batch error object, if present, after a batch calculation with errors.
68
+
69
+ Also works when continue_on_batch_error was set to True during the calculation.
70
+
71
+ Returns:
72
+ Batch error object, or None
73
+ """
74
+ return self._batch_error
75
+
76
+ @property
77
+ def _model(self):
78
+ if not self._model_ptr:
79
+ raise TypeError("You have an empty instance of PowerGridModel!")
80
+ return self._model_ptr
81
+
82
+ @property
83
+ def all_component_count(self) -> dict[ComponentType, int]:
84
+ """
85
+ Get amount of elements per component type.
86
+ If the count for a component type is zero, it will not be in the returned dictionary.
87
+
88
+ Returns:
89
+ A dictionary with
90
+
91
+ - key: Component type name
92
+ - value: Integer count of elements of this type
93
+ """
94
+ if self._all_component_count is None:
95
+ raise TypeError("You have an empty instance of PowerGridModel!")
96
+ return self._all_component_count
97
+
98
+ def copy(self) -> "PowerGridModel":
99
+ """
100
+ Copy the current model
101
+
102
+ Returns:
103
+ A copy of PowerGridModel
104
+ """
105
+ new_model = PowerGridModel.__new__(PowerGridModel)
106
+ new_model._model_ptr = pgc.copy_model(self._model)
107
+ assert_no_error()
108
+ new_model._all_component_count = self._all_component_count
109
+ return new_model
110
+
111
+ def __copy__(self) -> "PowerGridModel":
112
+ return self.copy()
113
+
114
+ def __deepcopy__(self, memo: dict[int, Any]) -> "PowerGridModel":
115
+ # PowerGridModel.copy makes already a deepcopy
116
+ new_model = self.copy()
117
+
118
+ # memorize that this object (self) has been deepcopied
119
+ memo[id(self)] = new_model
120
+
121
+ return new_model
122
+
123
+ def __new__(cls, *_args, **_kwargs):
124
+ instance = super().__new__(cls)
125
+ instance._model_ptr = ModelPtr()
126
+ instance._all_component_count = None
127
+ return instance
128
+
129
+ def __init__(self, input_data: SingleDataset, system_frequency: float = 50.0):
130
+ """
131
+ Initialize the model from an input data set.
132
+
133
+ Args:
134
+ input_data: Input data dictionary
135
+
136
+ - key: Component type
137
+ - value: Component data with the correct type :class:`SingleComponentData`
138
+
139
+ system_frequency: Frequency of the power system, default 50 Hz
140
+ """
141
+ # destroy old instance
142
+ pgc.destroy_model(self._model_ptr)
143
+ self._all_component_count = None
144
+ # create new
145
+ prepared_input = prepare_input_view(_map_to_component_types(input_data))
146
+ self._model_ptr = pgc.create_model(system_frequency, input_data=prepared_input.get_dataset_ptr())
147
+ assert_no_error()
148
+ self._all_component_count = {k: v for k, v in prepared_input.get_info().total_elements().items() if v > 0}
149
+
150
+ def update(self, *, update_data: Dataset):
151
+ """
152
+ Update the model with changes.
153
+
154
+ The model will be in an invalid state if the update fails and should be discarded.
155
+
156
+ Args:
157
+ update_data: Update data dictionary
158
+
159
+ - key: Component type
160
+ - value: Component data with the correct type :class:`ComponentData` (single scenario or batch)
161
+
162
+ Raises:
163
+ PowerGridError if the update fails. The model is left in an invalid state and should be discarded.
164
+
165
+ Returns:
166
+ None
167
+ """
168
+ prepared_update = prepare_update_view(_map_to_component_types(update_data))
169
+ pgc.update_model(self._model, prepared_update.get_dataset_ptr())
170
+ assert_no_error()
171
+
172
+ def get_indexer(self, component_type: ComponentTypeLike, ids: np.ndarray):
173
+ """
174
+ Get array of indexers given array of ids for component type.
175
+
176
+ This enables syntax like input_data[ComponentType.node][get_indexer(ids)]
177
+
178
+ Args:
179
+ component_type: Type of component
180
+ ids: Array of ids
181
+
182
+ Returns:
183
+ Array of indexers, same shape as input array ids
184
+ """
185
+ component_type = _str_to_component_type(component_type)
186
+ ids_c = np.ascontiguousarray(ids, dtype=IdNp).ctypes.data_as(IDPtr)
187
+ indexer = np.empty_like(ids, dtype=IdxNp, order="C")
188
+ indexer_c = indexer.ctypes.data_as(IdxPtr)
189
+ size = ids.size
190
+ # call c function
191
+ pgc.get_indexer(self._model, component_type, size, ids_c, indexer_c)
192
+ assert_no_error()
193
+ return indexer
194
+
195
+ def _get_output_component_count(self, calculation_type: CalculationType):
196
+ exclude_types = {
197
+ CalculationType.power_flow: [
198
+ ComponentType.sym_voltage_sensor,
199
+ ComponentType.asym_voltage_sensor,
200
+ ComponentType.sym_power_sensor,
201
+ ComponentType.asym_power_sensor,
202
+ ComponentType.fault,
203
+ ],
204
+ CalculationType.state_estimation: [ComponentType.fault],
205
+ CalculationType.short_circuit: [
206
+ ComponentType.sym_voltage_sensor,
207
+ ComponentType.asym_voltage_sensor,
208
+ ComponentType.sym_power_sensor,
209
+ ComponentType.asym_power_sensor,
210
+ ],
211
+ }.get(calculation_type, [])
212
+
213
+ def include_type(component_type: ComponentType):
214
+ return all(exclude_type.value not in component_type.value for exclude_type in exclude_types)
215
+
216
+ return {ComponentType[k]: v for k, v in self.all_component_count.items() if include_type(k)}
217
+
218
+ def _construct_output(
219
+ self,
220
+ output_component_types: ComponentAttributeMapping,
221
+ calculation_type: CalculationType,
222
+ symmetric: bool,
223
+ is_batch: bool,
224
+ batch_size: int,
225
+ ):
226
+ all_component_count = self._get_output_component_count(calculation_type=calculation_type)
227
+ return create_output_data(
228
+ output_component_types=output_component_types,
229
+ output_type=get_output_type(calculation_type=calculation_type, symmetric=symmetric),
230
+ all_component_count=all_component_count,
231
+ is_batch=is_batch,
232
+ batch_size=batch_size,
233
+ )
234
+
235
+ @staticmethod
236
+ def _options(**kwargs) -> Options:
237
+ def as_enum_value(key_enum: str, type_: type[IntEnum]):
238
+ if key_enum in kwargs:
239
+ value_enum = kwargs[key_enum]
240
+ if isinstance(value_enum, str):
241
+ kwargs[key_enum] = type_[value_enum] # NOSONAR(S5864) IntEnum has __getitem__
242
+
243
+ as_enum_value("calculation_method", CalculationMethod)
244
+ as_enum_value("tap_changing_strategy", TapChangingStrategy)
245
+ as_enum_value("short_circuit_voltage_scaling", ShortCircuitVoltageScaling)
246
+ as_enum_value("experimental_features", _ExperimentalFeatures)
247
+
248
+ opt = Options()
249
+ for key, value in kwargs.items():
250
+ setattr(opt, key, value.value if isinstance(value, IntEnum) else value)
251
+ return opt
252
+
253
+ def _handle_errors(self, continue_on_batch_error: bool, batch_size: int, decode_error: bool):
254
+ self._batch_error = handle_errors(
255
+ continue_on_batch_error=continue_on_batch_error,
256
+ batch_size=batch_size,
257
+ decode_error=decode_error,
258
+ )
259
+
260
+ def _calculate_impl( # noqa: PLR0913
261
+ self,
262
+ calculation_type: CalculationType,
263
+ symmetric: bool,
264
+ update_data: Dataset | None,
265
+ output_component_types: ComponentAttributeMapping,
266
+ options: Options,
267
+ continue_on_batch_error: bool,
268
+ decode_error: bool,
269
+ experimental_features: _ExperimentalFeatures | str, # NOSONAR # noqa: ARG002
270
+ ) -> Dataset:
271
+ """
272
+ Core calculation routine
273
+
274
+ Args:
275
+ calculation_type:
276
+ symmetric:
277
+ update_data:
278
+ output_component_types:
279
+ options:
280
+ continue_on_batch_error:
281
+ decode_error:
282
+
283
+ Returns:
284
+ """
285
+ self._batch_error = None
286
+ is_batch = update_data is not None
287
+
288
+ if update_data is not None:
289
+ prepared_update = prepare_update_view(update_data)
290
+ update_ptr = prepared_update.get_dataset_ptr()
291
+ batch_size = prepared_update.get_info().batch_size()
292
+ else:
293
+ update_ptr = ConstDatasetPtr()
294
+ batch_size = 1
295
+
296
+ output_data = self._construct_output(
297
+ output_component_types=output_component_types,
298
+ calculation_type=calculation_type,
299
+ symmetric=symmetric,
300
+ is_batch=is_batch,
301
+ batch_size=batch_size,
302
+ )
303
+ prepared_result = prepare_output_view(
304
+ output_data=output_data,
305
+ output_type=get_output_type(calculation_type=calculation_type, symmetric=symmetric),
306
+ )
307
+
308
+ # run calculation
309
+ pgc.calculate(
310
+ # model and options
311
+ self._model,
312
+ options.opt,
313
+ output_data=prepared_result.get_dataset_ptr(),
314
+ update_data=update_ptr,
315
+ )
316
+
317
+ self._handle_errors(
318
+ continue_on_batch_error=continue_on_batch_error,
319
+ batch_size=batch_size,
320
+ decode_error=decode_error,
321
+ )
322
+
323
+ return output_data
324
+
325
+ def _calculate_power_flow( # noqa: PLR0913
326
+ self,
327
+ *,
328
+ symmetric: bool = True,
329
+ error_tolerance: float = 1e-8,
330
+ max_iterations: int = 20,
331
+ calculation_method: CalculationMethod | str = CalculationMethod.newton_raphson,
332
+ update_data: Dataset | None = None,
333
+ threading: int = -1,
334
+ output_component_types: ComponentAttributeMapping = None,
335
+ continue_on_batch_error: bool = False,
336
+ decode_error: bool = True,
337
+ tap_changing_strategy: TapChangingStrategy | str = TapChangingStrategy.disabled,
338
+ experimental_features: _ExperimentalFeatures | str = _ExperimentalFeatures.disabled,
339
+ ) -> Dataset:
340
+ calculation_type = CalculationType.power_flow
341
+ options = self._options(
342
+ calculation_type=calculation_type,
343
+ symmetric=symmetric,
344
+ error_tolerance=error_tolerance,
345
+ max_iterations=max_iterations,
346
+ calculation_method=calculation_method,
347
+ tap_changing_strategy=tap_changing_strategy,
348
+ threading=threading,
349
+ experimental_features=experimental_features,
350
+ )
351
+ return self._calculate_impl(
352
+ calculation_type=calculation_type,
353
+ symmetric=symmetric,
354
+ update_data=update_data,
355
+ output_component_types=output_component_types,
356
+ options=options,
357
+ continue_on_batch_error=continue_on_batch_error,
358
+ decode_error=decode_error,
359
+ experimental_features=experimental_features,
360
+ )
361
+
362
+ def _calculate_state_estimation( # noqa: PLR0913
363
+ self,
364
+ *,
365
+ symmetric: bool = True,
366
+ error_tolerance: float = 1e-8,
367
+ max_iterations: int = 20,
368
+ calculation_method: CalculationMethod | str = CalculationMethod.iterative_linear,
369
+ update_data: Dataset | None = None,
370
+ threading: int = -1,
371
+ output_component_types: ComponentAttributeMapping = None,
372
+ continue_on_batch_error: bool = False,
373
+ decode_error: bool = True,
374
+ experimental_features: _ExperimentalFeatures | str = _ExperimentalFeatures.disabled,
375
+ ) -> Dataset:
376
+ calculation_type = CalculationType.state_estimation
377
+ options = self._options(
378
+ calculation_type=calculation_type,
379
+ symmetric=symmetric,
380
+ error_tolerance=error_tolerance,
381
+ max_iterations=max_iterations,
382
+ calculation_method=calculation_method,
383
+ threading=threading,
384
+ experimental_features=experimental_features,
385
+ )
386
+ return self._calculate_impl(
387
+ calculation_type=calculation_type,
388
+ symmetric=symmetric,
389
+ update_data=update_data,
390
+ output_component_types=output_component_types,
391
+ options=options,
392
+ continue_on_batch_error=continue_on_batch_error,
393
+ decode_error=decode_error,
394
+ experimental_features=experimental_features,
395
+ )
396
+
397
+ def _calculate_short_circuit( # noqa: PLR0913
398
+ self,
399
+ *,
400
+ calculation_method: CalculationMethod | str = CalculationMethod.iec60909,
401
+ update_data: Dataset | None = None,
402
+ threading: int = -1,
403
+ output_component_types: ComponentAttributeMapping = None,
404
+ continue_on_batch_error: bool = False,
405
+ decode_error: bool = True,
406
+ short_circuit_voltage_scaling: ShortCircuitVoltageScaling | str = ShortCircuitVoltageScaling.maximum,
407
+ experimental_features: _ExperimentalFeatures | str = _ExperimentalFeatures.disabled,
408
+ ) -> Dataset:
409
+ calculation_type = CalculationType.short_circuit
410
+ symmetric = False
411
+
412
+ options = self._options(
413
+ calculation_type=calculation_type,
414
+ symmetric=symmetric,
415
+ calculation_method=calculation_method,
416
+ threading=threading,
417
+ short_circuit_voltage_scaling=short_circuit_voltage_scaling,
418
+ experimental_features=experimental_features,
419
+ )
420
+ return self._calculate_impl(
421
+ calculation_type=calculation_type,
422
+ symmetric=symmetric,
423
+ update_data=update_data,
424
+ output_component_types=output_component_types,
425
+ options=options,
426
+ continue_on_batch_error=continue_on_batch_error,
427
+ decode_error=decode_error,
428
+ experimental_features=experimental_features,
429
+ )
430
+
431
+ @overload
432
+ def calculate_power_flow(
433
+ self,
434
+ *,
435
+ symmetric: bool = ...,
436
+ error_tolerance: float = ...,
437
+ max_iterations: int = ...,
438
+ calculation_method: CalculationMethod | str = ...,
439
+ threading: int = ...,
440
+ output_component_types: None | set[ComponentTypeVar] | list[ComponentTypeVar] = ...,
441
+ continue_on_batch_error: bool = ...,
442
+ decode_error: bool = ...,
443
+ tap_changing_strategy: TapChangingStrategy | str = ...,
444
+ ) -> SingleRowBasedDataset: ...
445
+ @overload
446
+ def calculate_power_flow(
447
+ self,
448
+ *,
449
+ symmetric: bool = ...,
450
+ error_tolerance: float = ...,
451
+ max_iterations: int = ...,
452
+ calculation_method: CalculationMethod | str = ...,
453
+ update_data: None = ...,
454
+ threading: int = ...,
455
+ output_component_types: None | set[ComponentTypeVar] | list[ComponentTypeVar] = ...,
456
+ continue_on_batch_error: bool = ...,
457
+ decode_error: bool = ...,
458
+ tap_changing_strategy: TapChangingStrategy | str = ...,
459
+ ) -> SingleRowBasedDataset: ...
460
+ @overload
461
+ def calculate_power_flow(
462
+ self,
463
+ *,
464
+ symmetric: bool = ...,
465
+ error_tolerance: float = ...,
466
+ max_iterations: int = ...,
467
+ calculation_method: CalculationMethod | str = ...,
468
+ update_data: None = ...,
469
+ threading: int = ...,
470
+ output_component_types: ComponentAttributeFilterOptions = ...,
471
+ continue_on_batch_error: bool = ...,
472
+ decode_error: bool = ...,
473
+ tap_changing_strategy: TapChangingStrategy | str = ...,
474
+ ) -> SingleColumnarOutputDataset: ...
475
+ @overload
476
+ def calculate_power_flow(
477
+ self,
478
+ *,
479
+ symmetric: bool = ...,
480
+ error_tolerance: float = ...,
481
+ max_iterations: int = ...,
482
+ calculation_method: CalculationMethod | str = ...,
483
+ update_data: None = ...,
484
+ threading: int = ...,
485
+ output_component_types: ComponentAttributeMappingDict = ...,
486
+ continue_on_batch_error: bool = ...,
487
+ decode_error: bool = ...,
488
+ tap_changing_strategy: TapChangingStrategy | str = ...,
489
+ ) -> SingleOutputDataset: ...
490
+ @overload
491
+ def calculate_power_flow(
492
+ self,
493
+ *,
494
+ symmetric: bool = ...,
495
+ error_tolerance: float = ...,
496
+ max_iterations: int = ...,
497
+ calculation_method: CalculationMethod | str = ...,
498
+ update_data: BatchDataset = ...,
499
+ threading: int = ...,
500
+ output_component_types: None | set[ComponentTypeVar] | list[ComponentTypeVar] = ...,
501
+ continue_on_batch_error: bool = ...,
502
+ decode_error: bool = ...,
503
+ tap_changing_strategy: TapChangingStrategy | str = ...,
504
+ ) -> DenseBatchRowBasedOutputDataset: ...
505
+ @overload
506
+ def calculate_power_flow(
507
+ self,
508
+ *,
509
+ symmetric: bool = ...,
510
+ error_tolerance: float = ...,
511
+ max_iterations: int = ...,
512
+ calculation_method: CalculationMethod | str = ...,
513
+ update_data: BatchDataset = ...,
514
+ threading: int = ...,
515
+ output_component_types: ComponentAttributeFilterOptions = ...,
516
+ continue_on_batch_error: bool = ...,
517
+ decode_error: bool = ...,
518
+ tap_changing_strategy: TapChangingStrategy | str = ...,
519
+ ) -> DenseBatchColumnarOutputDataset: ...
520
+ @overload
521
+ def calculate_power_flow(
522
+ self,
523
+ *,
524
+ symmetric: bool = ...,
525
+ error_tolerance: float = ...,
526
+ max_iterations: int = ...,
527
+ calculation_method: CalculationMethod | str = ...,
528
+ update_data: BatchDataset = ...,
529
+ threading: int = ...,
530
+ output_component_types: ComponentAttributeMappingDict = ...,
531
+ continue_on_batch_error: bool = ...,
532
+ decode_error: bool = ...,
533
+ tap_changing_strategy: TapChangingStrategy | str = ...,
534
+ ) -> DenseBatchOutputDataset: ...
535
+ def calculate_power_flow( # noqa: PLR0913
536
+ self,
537
+ *,
538
+ symmetric: bool = True,
539
+ error_tolerance: float = 1e-8,
540
+ max_iterations: int = 20,
541
+ calculation_method: CalculationMethod | str = CalculationMethod.newton_raphson,
542
+ update_data: BatchDataset | None = None,
543
+ threading: int = -1,
544
+ output_component_types: ComponentAttributeMapping = None,
545
+ continue_on_batch_error: bool = False,
546
+ decode_error: bool = True,
547
+ tap_changing_strategy: TapChangingStrategy | str = TapChangingStrategy.disabled,
548
+ ) -> Dataset:
549
+ """
550
+ Calculate power flow once with the current model attributes.
551
+ Or calculate in batch with the given update dataset in batch.
552
+
553
+ Args:
554
+ symmetric (bool, optional): Whether to perform a three-phase symmetric calculation.
555
+
556
+ - True: Three-phase symmetric calculation, even for asymmetric loads/generations (Default).
557
+ - False: Three-phase asymmetric calculation.
558
+ error_tolerance (float, optional): Error tolerance for voltage in p.u., applicable only when the
559
+ calculation method is iterative.
560
+ max_iterations (int, optional): Maximum number of iterations, applicable only when the calculation method
561
+ is iterative.
562
+ calculation_method (an enumeration or string): The calculation method to use.
563
+
564
+ - newton_raphson: Use Newton-Raphson iterative method (default).
565
+ - linear: Use linear method.
566
+ update_data (dict, optional):
567
+ None: Calculate power flow once with the current model attributes.
568
+ Or a dictionary for batch calculation with batch update.
569
+
570
+ - key: Component type name to be updated in batch.
571
+ - value:
572
+
573
+ - For homogeneous update batch (a 2D numpy structured array):
574
+
575
+ - Dimension 0: Each batch.
576
+ - Dimension 1: Each updated element per batch for this component type.
577
+ - For inhomogeneous update batch (a dictionary containing two keys):
578
+
579
+ - indptr: A 1D numpy int64 array with length n_batch + 1. Given batch number k, the
580
+ update array for this batch is data[indptr[k]:indptr[k + 1]]. This is the concept of
581
+ compressed sparse structure.
582
+ https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.csr_matrix.html
583
+ - data: 1D numpy structured array in flat.
584
+ threading (int, optional): Applicable only for batch calculation.
585
+
586
+ - < 0: Sequential
587
+ - = 0: Parallel, use number of hardware threads
588
+ - > 0: Specify number of parallel threads
589
+ output_component_types (ComponentAttributeMapping):
590
+
591
+ - None: Row based data for all component types.
592
+ - set[ComponentTypeVar] or list[ComponentTypeVar]: Row based data for the specified component types.
593
+ - ComponentAttributeFilterOptions: Columnar data for all component types.
594
+ - ComponentAttributeMappingDict:
595
+ key: ComponentType
596
+ value:
597
+ - None: Row based data for the specified component types.
598
+ - ComponentAttributeFilterOptions: Columnar data for the specified component types.
599
+ - set[str] | list[str]: Columnar data for the specified component types and attributes.
600
+ continue_on_batch_error (bool, optional):
601
+ Continue the program (instead of throwing error) if some scenarios fail.
602
+ You can still retrieve the errors and succeeded/failed scenarios via the batch_error.
603
+ decode_error (bool, optional):
604
+ Decode error messages to their derived types if possible.
605
+
606
+ Returns:
607
+ Dictionary of results of all components.
608
+
609
+ - key: Component type name to be updated in batch.
610
+ - value:
611
+
612
+ - For single calculation: 1D numpy structured array for the results of this component type.
613
+ - For batch calculation: 2D numpy structured array for the results of this component type.
614
+
615
+ - Dimension 0: Each batch.
616
+ - Dimension 1: The result of each element for this component type.
617
+
618
+ Raises:
619
+ Exception: In case an error in the core occurs, an exception will be thrown.
620
+ """
621
+ return self._calculate_power_flow(
622
+ symmetric=symmetric,
623
+ error_tolerance=error_tolerance,
624
+ max_iterations=max_iterations,
625
+ calculation_method=calculation_method,
626
+ update_data=(_map_to_component_types(update_data) if update_data is not None else None),
627
+ threading=threading,
628
+ output_component_types=output_component_types,
629
+ continue_on_batch_error=continue_on_batch_error,
630
+ decode_error=decode_error,
631
+ tap_changing_strategy=tap_changing_strategy,
632
+ )
633
+
634
+ @overload
635
+ def calculate_state_estimation(
636
+ self,
637
+ *,
638
+ symmetric: bool = ...,
639
+ error_tolerance: float = ...,
640
+ max_iterations: int = ...,
641
+ calculation_method: CalculationMethod | str = ...,
642
+ update_data: None = ...,
643
+ threading: int = ...,
644
+ output_component_types: None | set[ComponentTypeVar] | list[ComponentTypeVar] = ...,
645
+ continue_on_batch_error: bool = ...,
646
+ decode_error: bool = ...,
647
+ ) -> SingleRowBasedOutputDataset: ...
648
+ @overload
649
+ def calculate_state_estimation(
650
+ self,
651
+ *,
652
+ symmetric: bool = ...,
653
+ error_tolerance: float = ...,
654
+ max_iterations: int = ...,
655
+ calculation_method: CalculationMethod | str = ...,
656
+ update_data: None = ...,
657
+ threading: int = ...,
658
+ output_component_types: ComponentAttributeFilterOptions = ...,
659
+ continue_on_batch_error: bool = ...,
660
+ decode_error: bool = ...,
661
+ ) -> SingleColumnarOutputDataset: ...
662
+ @overload
663
+ def calculate_state_estimation(
664
+ self,
665
+ *,
666
+ symmetric: bool = ...,
667
+ error_tolerance: float = ...,
668
+ max_iterations: int = ...,
669
+ calculation_method: CalculationMethod | str = ...,
670
+ update_data: None = ...,
671
+ threading: int = ...,
672
+ output_component_types: ComponentAttributeMappingDict = ...,
673
+ continue_on_batch_error: bool = ...,
674
+ decode_error: bool = ...,
675
+ ) -> SingleOutputDataset: ...
676
+ @overload
677
+ def calculate_state_estimation(
678
+ self,
679
+ *,
680
+ symmetric: bool = ...,
681
+ error_tolerance: float = ...,
682
+ max_iterations: int = ...,
683
+ calculation_method: CalculationMethod | str = ...,
684
+ update_data: BatchDataset = ...,
685
+ threading: int = ...,
686
+ output_component_types: None | set[ComponentTypeVar] | list[ComponentTypeVar] = ...,
687
+ continue_on_batch_error: bool = ...,
688
+ decode_error: bool = ...,
689
+ ) -> DenseBatchRowBasedOutputDataset: ...
690
+ @overload
691
+ def calculate_state_estimation(
692
+ self,
693
+ *,
694
+ symmetric: bool = ...,
695
+ error_tolerance: float = ...,
696
+ max_iterations: int = ...,
697
+ calculation_method: CalculationMethod | str = ...,
698
+ update_data: BatchDataset = ...,
699
+ threading: int = ...,
700
+ output_component_types: ComponentAttributeFilterOptions = ...,
701
+ continue_on_batch_error: bool = ...,
702
+ decode_error: bool = ...,
703
+ ) -> DenseBatchColumnarOutputDataset: ...
704
+ @overload
705
+ def calculate_state_estimation(
706
+ self,
707
+ *,
708
+ symmetric: bool = ...,
709
+ error_tolerance: float = ...,
710
+ max_iterations: int = ...,
711
+ calculation_method: CalculationMethod | str = ...,
712
+ update_data: BatchDataset = ...,
713
+ threading: int = ...,
714
+ output_component_types: ComponentAttributeMappingDict = ...,
715
+ continue_on_batch_error: bool = ...,
716
+ decode_error: bool = ...,
717
+ ) -> DenseBatchOutputDataset: ...
718
+ def calculate_state_estimation( # noqa: PLR0913
719
+ self,
720
+ *,
721
+ symmetric: bool = True,
722
+ error_tolerance: float = 1e-8,
723
+ max_iterations: int = 20,
724
+ calculation_method: CalculationMethod | str = CalculationMethod.iterative_linear,
725
+ update_data: BatchDataset | None = None,
726
+ threading: int = -1,
727
+ output_component_types: ComponentAttributeMapping = None,
728
+ continue_on_batch_error: bool = False,
729
+ decode_error: bool = True,
730
+ ) -> Dataset:
731
+ """
732
+ Calculate state estimation once with the current model attributes.
733
+ Or calculate in batch with the given update dataset in batch.
734
+
735
+ Args:
736
+ symmetric (bool, optional): Whether to perform a three-phase symmetric calculation.
737
+
738
+ - True: Three-phase symmetric calculation, even for asymmetric loads/generations (Default).
739
+ - False: Three-phase asymmetric calculation.
740
+ error_tolerance (float, optional): error tolerance for voltage in p.u., only applicable when the
741
+ calculation method is iterative.
742
+ max_iterations (int, optional): Maximum number of iterations, applicable only when the calculation method
743
+ is iterative.
744
+ calculation_method (an enumeration): Use iterative linear method.
745
+ update_data (dict, optional):
746
+ None: Calculate state estimation once with the current model attributes.
747
+ Or a dictionary for batch calculation with batch update.
748
+
749
+ - key: Component type name to be updated in batch.
750
+ - value:
751
+
752
+ - For homogeneous update batch (a 2D numpy structured array):
753
+
754
+ - Dimension 0: Each batch.
755
+ - Dimension 1: Each updated element per batch for this component type.
756
+ - For inhomogeneous update batch (a dictionary containing two keys):
757
+
758
+ - indptr: A 1D numpy int64 array with length n_batch + 1. Given batch number k, the
759
+ update array for this batch is data[indptr[k]:indptr[k + 1]]. This is the concept of
760
+ compressed sparse structure.
761
+ https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.csr_matrix.html
762
+ - data: 1D numpy structured array in flat.
763
+ threading (int, optional): Applicable only for batch calculation.
764
+
765
+ - < 0: Sequential
766
+ - = 0: Parallel, use number of hardware threads
767
+ - > 0: Specify number of parallel threads
768
+ output_component_types (ComponentAttributeMapping):
769
+
770
+ - None: Row based data for all component types.
771
+ - set[ComponentTypeVar] or list[ComponentTypeVar]: Row based data for the specified component types.
772
+ - ComponentAttributeFilterOptions: Columnar data for all component types.
773
+ - ComponentAttributeMappingDict:
774
+ key: ComponentType
775
+ value:
776
+ - None: Row based data for the specified component types.
777
+ - ComponentAttributeFilterOptions: Columnar data for the specified component types.
778
+ - set[str] | list[str]: Columnar data for the specified component types and attributes.
779
+ continue_on_batch_error (bool, optional):
780
+ Continue the program (instead of throwing error) if some scenarios fail.
781
+ You can still retrieve the errors and succeeded/failed scenarios via the batch_error.
782
+ decode_error (bool, optional):
783
+ Decode error messages to their derived types if possible.
784
+
785
+ Returns:
786
+ Dictionary of results of all components.
787
+
788
+ - key: Component type name to be updated in batch.
789
+ - value:
790
+
791
+ - For single calculation: 1D numpy structured array for the results of this component type.
792
+ - For batch calculation: 2D numpy structured array for the results of this component type.
793
+
794
+ - Dimension 0: Each batch.
795
+ - Dimension 1: The result of each element for this component type.
796
+
797
+ Raises:
798
+ Exception: In case an error in the core occurs, an exception will be thrown.
799
+ """
800
+ return self._calculate_state_estimation(
801
+ symmetric=symmetric,
802
+ error_tolerance=error_tolerance,
803
+ max_iterations=max_iterations,
804
+ calculation_method=calculation_method,
805
+ update_data=(_map_to_component_types(update_data) if update_data is not None else None),
806
+ threading=threading,
807
+ output_component_types=output_component_types,
808
+ continue_on_batch_error=continue_on_batch_error,
809
+ decode_error=decode_error,
810
+ )
811
+
812
+ @overload
813
+ def calculate_short_circuit(
814
+ self,
815
+ *,
816
+ calculation_method: CalculationMethod | str = ...,
817
+ update_data: None = ...,
818
+ threading: int = ...,
819
+ output_component_types: None | set[ComponentTypeVar] | list[ComponentTypeVar] = ...,
820
+ continue_on_batch_error: bool = ...,
821
+ decode_error: bool = ...,
822
+ short_circuit_voltage_scaling: ShortCircuitVoltageScaling | str,
823
+ ) -> SingleRowBasedDataset: ...
824
+ @overload
825
+ def calculate_short_circuit(
826
+ self,
827
+ *,
828
+ calculation_method: CalculationMethod | str = ...,
829
+ update_data: None = ...,
830
+ threading: int = ...,
831
+ output_component_types: ComponentAttributeFilterOptions = ...,
832
+ continue_on_batch_error: bool = ...,
833
+ decode_error: bool = ...,
834
+ short_circuit_voltage_scaling: ShortCircuitVoltageScaling | str,
835
+ ) -> SingleColumnarOutputDataset: ...
836
+ @overload
837
+ def calculate_short_circuit(
838
+ self,
839
+ *,
840
+ calculation_method: CalculationMethod | str = ...,
841
+ update_data: None = ...,
842
+ threading: int = ...,
843
+ output_component_types: ComponentAttributeMappingDict = ...,
844
+ continue_on_batch_error: bool = ...,
845
+ decode_error: bool = ...,
846
+ short_circuit_voltage_scaling: ShortCircuitVoltageScaling | str,
847
+ ) -> SingleOutputDataset: ...
848
+ @overload
849
+ def calculate_short_circuit(
850
+ self,
851
+ *,
852
+ calculation_method: CalculationMethod | str = ...,
853
+ update_data: BatchDataset = ...,
854
+ threading: int = ...,
855
+ output_component_types: None | set[ComponentTypeVar] | list[ComponentTypeVar] = ...,
856
+ continue_on_batch_error: bool = ...,
857
+ decode_error: bool = ...,
858
+ short_circuit_voltage_scaling: ShortCircuitVoltageScaling | str,
859
+ ) -> DenseBatchRowBasedOutputDataset: ...
860
+ @overload
861
+ def calculate_short_circuit(
862
+ self,
863
+ *,
864
+ calculation_method: CalculationMethod | str = ...,
865
+ update_data: BatchDataset = ...,
866
+ threading: int = ...,
867
+ output_component_types: ComponentAttributeFilterOptions = ...,
868
+ continue_on_batch_error: bool = ...,
869
+ decode_error: bool = ...,
870
+ short_circuit_voltage_scaling: ShortCircuitVoltageScaling | str,
871
+ ) -> DenseBatchColumnarOutputDataset: ...
872
+ @overload
873
+ def calculate_short_circuit(
874
+ self,
875
+ *,
876
+ calculation_method: CalculationMethod | str = ...,
877
+ update_data: BatchDataset = ...,
878
+ threading: int = ...,
879
+ output_component_types: ComponentAttributeMappingDict = ...,
880
+ continue_on_batch_error: bool = ...,
881
+ decode_error: bool = ...,
882
+ short_circuit_voltage_scaling: ShortCircuitVoltageScaling | str,
883
+ ) -> DenseBatchOutputDataset: ...
884
+ def calculate_short_circuit( # noqa: PLR0913
885
+ self,
886
+ *,
887
+ calculation_method: CalculationMethod | str = CalculationMethod.iec60909,
888
+ update_data: BatchDataset | None = None,
889
+ threading: int = -1,
890
+ output_component_types: ComponentAttributeMapping = None,
891
+ continue_on_batch_error: bool = False,
892
+ decode_error: bool = True,
893
+ short_circuit_voltage_scaling: ShortCircuitVoltageScaling | str = ShortCircuitVoltageScaling.maximum,
894
+ ) -> Dataset:
895
+ """
896
+ Calculate a short circuit once with the current model attributes.
897
+ Or calculate in batch with the given update dataset in batch
898
+
899
+ Args:
900
+ calculation_method (an enumeration): Use the iec60909 standard.
901
+ update_data:
902
+ None: calculate a short circuit once with the current model attributes.
903
+ Or a dictionary for batch calculation with batch update
904
+
905
+ - key: Component type name to be updated in batch
906
+ - value:
907
+
908
+ - For homogeneous update batch (a 2D numpy structured array):
909
+
910
+ - Dimension 0: each batch
911
+ - Dimension 1: each updated element per batch for this component type
912
+ - For inhomogeneous update batch (a dictionary containing two keys):
913
+
914
+ - indptr: A 1D numpy int64 array with length n_batch + 1. Given batch number k, the
915
+ update array for this batch is data[indptr[k]:indptr[k + 1]]. This is the concept of
916
+ compressed sparse structure.
917
+ https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.csr_matrix.html
918
+ - data: 1D numpy structured array in flat.
919
+ threading (int, optional): Applicable only for batch calculation.
920
+
921
+ - < 0: Sequential
922
+ - = 0: Parallel, use number of hardware threads
923
+ - > 0: Specify number of parallel threads
924
+ output_component_types (ComponentAttributeMapping):
925
+
926
+ - None: Row based data for all component types.
927
+ - set[ComponentTypeVar] or list[ComponentTypeVar]: Row based data for the specified component types.
928
+ - ComponentAttributeFilterOptions: Columnar data for all component types.
929
+ - ComponentAttributeMappingDict:
930
+ key: ComponentType
931
+ value:
932
+ - None: Row based data for the specified component types.
933
+ - ComponentAttributeFilterOptions: Columnar data for the specified component types.
934
+ - set[str] | list[str]: Columnar data for the specified component types and attributes.
935
+ continue_on_batch_error (bool, optional):
936
+ Continue the program (instead of throwing error) if some scenarios fail.
937
+ You can still retrieve the errors and succeeded/failed scenarios via the batch_error.
938
+ decode_error (bool, optional):
939
+ Decode error messages to their derived types if possible.
940
+ short_circuit_voltage_scaling ({ShortCircuitVoltageSaling, str}, optional):
941
+ Whether to use the maximum or minimum voltage scaling.
942
+ By default, the maximum voltage scaling is used to calculate the short circuit.
943
+
944
+ Returns:
945
+ Dictionary of results of all components.
946
+
947
+ - key: Component type name to be updated in batch.
948
+ - value:
949
+
950
+ - For single calculation: 1D numpy structured array for the results of this component type.
951
+ - For batch calculation: 2D numpy structured array for the results of this component type.
952
+
953
+ - Dimension 0: Each batch.
954
+ - Dimension 1: The result of each element for this component type.
955
+ Raises:
956
+ Exception: In case an error in the core occurs, an exception will be thrown.
957
+ """
958
+ return self._calculate_short_circuit(
959
+ calculation_method=calculation_method,
960
+ update_data=(_map_to_component_types(update_data) if update_data is not None else None),
961
+ threading=threading,
962
+ output_component_types=output_component_types,
963
+ continue_on_batch_error=continue_on_batch_error,
964
+ decode_error=decode_error,
965
+ short_circuit_voltage_scaling=short_circuit_voltage_scaling,
966
+ )
967
+
968
+ def __del__(self):
969
+ pgc.destroy_model(self._model_ptr)