From e78b03da10318414988e07def19770d6578853e2 Mon Sep 17 00:00:00 2001 From: Burhan Abdullah <131237388+BurhanAbdullah@users.noreply.github.com> Date: Sat, 14 Nov 2026 11:43:04 +0530 Subject: [PATCH 1/8] feat(pandapower): add topology-aware security assessment --- pandapower/security_assessment.py | 296 ++++++++++++++++++++++++++++++ 1 file changed, 296 insertions(+) create mode 100644 pandapower/security_assessment.py diff --git a/pandapower/security_assessment.py b/pandapower/security_assessment.py new file mode 100644 index 00000000..ba710fd1 --- /dev/null +++ b/pandapower/security_assessment.py @@ -0,0 +1,296 @@ +"""Topology-aware N-1 security assessment for pandapower networks. + +The assessment operates on private network copies. It uses pandapower's +switch-aware topology graph to identify load-bearing islands without a +voltage-controlling source before attempting an AC power flow. +""" +from __future__ import annotations + +import copy +import itertools +import math +from typing import Any, Dict, Iterable, List, Mapping, Optional, Sequence, Tuple + +import pandapower as pp +import pandapower.topology as topology +import networkx as nx + + +DEFAULT_CONTINGENCY_ELEMENTS = ("line", "trafo") + + +def _finite_number(value: Any) -> Optional[float]: + try: + number = float(value) + except (TypeError, ValueError): + return None + return number if math.isfinite(number) else None + + +def _active_rows(net: Any, table: str) -> Iterable[Tuple[Any, Any]]: + frame = net.get(table) + if frame is None or not hasattr(frame, "iterrows") or "in_service" not in frame: + return () + return ((idx, row) for idx, row in frame.iterrows() if bool(row.get("in_service", True))) + + +def _topology_islands(net: Any) -> List[Dict[str, Any]]: + """Return graph components and classify islands with active load but no slack.""" + graph = topology.create_nxgraph( + net, + respect_switches=True, + include_out_of_service=False, + multi=True, + ) + active_buses = set( + net.bus.index[net.bus.in_service.astype(bool)] + ) if "in_service" in net.bus else set(net.bus.index) + graph.add_nodes_from(active_buses) + + sources = set() + for _, row in _active_rows(net, "ext_grid"): + sources.add(row["bus"]) + for _, row in _active_rows(net, "gen"): + if bool(row.get("slack", False)): + sources.add(row["bus"]) + + loads_by_bus: Dict[Any, float] = {} + for table in ("load", "sgen", "storage"): + for _, row in _active_rows(net, table): + p_mw = _finite_number(row.get("p_mw")) or 0.0 + # Only positive net consumption contributes to unsupplied demand. + loads_by_bus[row["bus"]] = loads_by_bus.get(row["bus"], 0.0) + max(p_mw, 0.0) + + islands = [] + components = sorted( + (set(component) for component in nx.connected_components(graph)), + key=lambda component: (min(map(str, component)) if component else ""), + ) + for component in components: + load_mw = sum(loads_by_bus.get(bus, 0.0) for bus in component) + island_sources = sorted((bus for bus in component if bus in sources), key=str) + islands.append({ + "buses": sorted(component, key=str), + "source_buses": island_sources, + "load_mw": round(load_mw, 9), + "supplied": bool(island_sources) or load_mw <= 1e-9, + }) + return islands + + +def _limits(net: Any, table: str, row: Any, default: float) -> float: + value = _finite_number(row.get("max_loading_percent")) + if value is None: + return default + return value + + +def _evaluate_results( + net: Any, + *, + voltage_min_pu: float, + voltage_max_pu: float, + line_loading_limit_percent: float, + trafo_loading_limit_percent: float, +) -> Dict[str, Any]: + voltage_violations = [] + if hasattr(net, "res_bus") and not net.res_bus.empty: + for bus, result in net.res_bus.iterrows(): + if bus not in net.bus.index or not bool(net.bus.at[bus, "in_service"]): + continue + vm = _finite_number(result.get("vm_pu")) + if vm is None: + continue + row = net.bus.loc[bus] + lower = _finite_number(row.get("min_vm_pu")) + upper = _finite_number(row.get("max_vm_pu")) + lower = voltage_min_pu if lower is None else lower + upper = voltage_max_pu if upper is None else upper + if vm < lower: + voltage_violations.append({"bus": bus, "vm_pu": vm, "limit_pu": lower, "kind": "undervoltage", "deviation_pu": round(lower - vm, 9)}) + elif vm > upper: + voltage_violations.append({"bus": bus, "vm_pu": vm, "limit_pu": upper, "kind": "overvoltage", "deviation_pu": round(vm - upper, 9)}) + + line_violations = [] + if hasattr(net, "res_line") and not net.res_line.empty: + for idx, result in net.res_line.iterrows(): + if idx not in net.line.index or not bool(net.line.at[idx, "in_service"]): + continue + loading = _finite_number(result.get("loading_percent")) + if loading is None: + continue + limit = _limits(net, "line", net.line.loc[idx], line_loading_limit_percent) + if loading > limit: + line_violations.append({"element": "line", "index": idx, "loading_percent": loading, "limit_percent": limit, "excess_percent": round(loading - limit, 9)}) + + transformer_violations = [] + for table, result_table in (("trafo", "res_trafo"), ("trafo3w", "res_trafo3w")): + if table not in net or result_table not in net or net[result_table].empty: + continue + for idx, result in net[result_table].iterrows(): + if idx not in net[table].index or not bool(net[table].at[idx, "in_service"]): + continue + loading = _finite_number(result.get("loading_percent")) + if loading is None: + continue + limit = _limits(net, table, net[table].loc[idx], trafo_loading_limit_percent) + if loading > limit: + transformer_violations.append({"element": table, "index": idx, "loading_percent": loading, "limit_percent": limit, "excess_percent": round(loading - limit, 9)}) + + max_thermal_excess = max( + [item["excess_percent"] for item in line_violations + transformer_violations], + default=0.0, + ) + max_voltage_deviation = max( + [item["deviation_pu"] for item in voltage_violations], + default=0.0, + ) + return { + "voltage_violations": voltage_violations, + "line_overloads": line_violations, + "transformer_overloads": transformer_violations, + "severity": { + "unserved_load_mw": 0.0, + "voltage_violation_count": len(voltage_violations), + "max_voltage_deviation_pu": round(max_voltage_deviation, 9), + "thermal_overload_count": len(line_violations) + len(transformer_violations), + "max_thermal_excess_percent": round(max_thermal_excess, 9), + }, + } + + +def run_security_assessment( + net: Any, + *, + elements: Optional[Sequence[str]] = None, + voltage_min_pu: float = 0.95, + voltage_max_pu: float = 1.05, + line_loading_limit_percent: float = 100.0, + trafo_loading_limit_percent: float = 100.0, + runpp_options: Optional[Mapping[str, Any]] = None, +) -> Dict[str, Any]: + """Run deterministic single-element outages and quantify post-contingency security. + + Only N-1 is implemented. The default outage set deliberately preserves the + historical line/two-winding-transformer scope; callers can request other + pandapower element tables explicitly. + """ + if not (math.isfinite(voltage_min_pu) and math.isfinite(voltage_max_pu) and voltage_min_pu < voltage_max_pu): + raise ValueError("Voltage limits must be finite and voltage_min_pu must be below voltage_max_pu.") + if not (math.isfinite(line_loading_limit_percent) and line_loading_limit_percent > 0): + raise ValueError("line_loading_limit_percent must be finite and positive.") + if not (math.isfinite(trafo_loading_limit_percent) and trafo_loading_limit_percent > 0): + raise ValueError("trafo_loading_limit_percent must be finite and positive.") + if runpp_options and not isinstance(runpp_options, Mapping): + raise TypeError("runpp_options must be a mapping.") + + requested = tuple(DEFAULT_CONTINGENCY_ELEMENTS if elements is None else elements) + if not requested: + raise ValueError("At least one contingency element table must be selected.") + unsupported = [name for name in requested if name not in net or "in_service" not in net[name].columns] + if unsupported: + raise ValueError(f"Unsupported contingency element table(s): {unsupported}") + + base_islands = _topology_islands(net) + results = [] + for element_type in requested: + for idx, _ in _active_rows(net, element_type): + case = copy.deepcopy(net) + case[element_type].at[idx, "in_service"] = False + label = f"{element_type}_{idx}" + try: + islands = _topology_islands(case) + unsupplied = [island for island in islands if not island["supplied"]] + unserved_load = sum(island["load_mw"] for island in unsupplied) + if unsupplied: + results.append({ + "contingency": label, + "element": element_type, + "index": idx, + "converged": False, + "classification": "islanding", + "islands": islands, + "unsupplied_islands": unsupplied, + "violations": { + "voltage_violations": [], + "line_overloads": [], + "transformer_overloads": [], + "severity": { + "unserved_load_mw": round(unserved_load, 9), + "voltage_violation_count": 0, + "max_voltage_deviation_pu": 0.0, + "thermal_overload_count": 0, + "max_thermal_excess_percent": 0.0, + }, + }, + }) + continue + + pp.runpp(case, **dict(runpp_options or {})) + if not bool(getattr(case, "converged", False)): + results.append({ + "contingency": label, + "element": element_type, + "index": idx, + "converged": False, + "classification": "power_flow_nonconvergence", + "islands": islands, + "violations": None, + }) + continue + violations = _evaluate_results( + case, + voltage_min_pu=voltage_min_pu, + voltage_max_pu=voltage_max_pu, + line_loading_limit_percent=line_loading_limit_percent, + trafo_loading_limit_percent=trafo_loading_limit_percent, + ) + results.append({ + "contingency": label, + "element": element_type, + "index": idx, + "converged": True, + "classification": "secure" if not any(( + violations["voltage_violations"], + violations["line_overloads"], + violations["transformer_overloads"], + )) else "limit_violations", + "islands": islands, + "violations": violations, + }) + except Exception as exc: + results.append({ + "contingency": label, + "element": element_type, + "index": idx, + "converged": False, + "classification": "analysis_error", + "error": f"{type(exc).__name__}: {exc}", + }) + + # Stable, transparent ordering: islanding/unserved load first, then + # limit violations by counts and magnitudes, then solver/error outcomes. + def rank(item: Dict[str, Any]) -> Tuple[float, int, float, int, str]: + severity = ((item.get("violations") or {}).get("severity") or {}) + return ( + -float(severity.get("unserved_load_mw", 0.0)), + -int(severity.get("voltage_violation_count", 0)) - int(severity.get("thermal_overload_count", 0)), + -float(severity.get("max_voltage_deviation_pu", 0.0)) - float(severity.get("max_thermal_excess_percent", 0.0)), + 0 if item["classification"] == "islanding" else 1, + item["contingency"], + ) + results.sort(key=rank) + return { + "status": "success", + "analysis_type": "N-1", + "base_islands": base_islands, + "contingency_count": len(results), + "summary": { + "secure": sum(item["classification"] == "secure" for item in results), + "limit_violations": sum(item["classification"] == "limit_violations" for item in results), + "islanding": sum(item["classification"] == "islanding" for item in results), + "nonconvergent": sum(item["classification"] == "power_flow_nonconvergence" for item in results), + "errors": sum(item["classification"] == "analysis_error" for item in results), + }, + "results": results, + } From a4fe5559ea17348d72deb93530a9bc56deccda06 Mon Sep 17 00:00:00 2001 From: Burhan Abdullah <131237388+BurhanAbdullah@users.noreply.github.com> Date: Sat, 14 Nov 2026 11:43:17 +0530 Subject: [PATCH 2/8] feat(pandapower): expose topology-aware N-1 assessment --- pandapower/panda_mcp.py | 115 +++++++++++++++++----------------------- 1 file changed, 48 insertions(+), 67 deletions(-) diff --git a/pandapower/panda_mcp.py b/pandapower/panda_mcp.py index ea2fc548..90647ead 100644 --- a/pandapower/panda_mcp.py +++ b/pandapower/panda_mcp.py @@ -13,6 +13,7 @@ sys.path.insert(0, _server_dir) from audit import audit_network as _audit_network from operating_point import validate_operating_point as _validate_operating_point +from security_assessment import run_security_assessment as _run_security_assessment _repo_root = str(Path(__file__).resolve().parents[1]) _repo_root_added = _repo_root not in sys.path @@ -250,78 +251,58 @@ def validate_operating_point( return {"status": "success", "validation_status": verdict, **report} @mcp.tool() -def run_contingency_analysis(contingency_type: str = "N-1", - elements: Optional[List[str]] = None) -> Dict[str, Any]: - """Run contingency analysis on the current network. - +def run_contingency_analysis( + contingency_type: str = "N-1", + elements: Optional[List[str]] = None, + voltage_min_pu: float = 0.95, + voltage_max_pu: float = 1.05, + line_loading_limit_percent: float = 100.0, + trafo_loading_limit_percent: float = 100.0, +) -> Dict[str, Any]: + """Run topology-aware N-1 security assessment on the current network. + + The analysis checks switch-aware islands before solving each outage, reports + unsupplied load, and checks bus voltage plus line and transformer loading. + Only N-1 is currently implemented; N-2 is rejected rather than silently + running single outages under an N-2 label. + Args: - contingency_type: Type of contingency analysis ("N-1" or "N-2") - elements: List of specific elements to analyze (optional) - + contingency_type: Must be "N-1" (N-2 combinations are not implemented). + elements: Optional pandapower element tables to outage. Defaults to + lines and two-winding transformers for backward compatibility. + voltage_min_pu: Fallback lower voltage limit; bus min_vm_pu overrides it. + voltage_max_pu: Fallback upper voltage limit; bus max_vm_pu overrides it. + line_loading_limit_percent: Fallback line loading limit; line-specific + max_loading_percent overrides it. + trafo_loading_limit_percent: Loading limit for two- and three-winding + transformers; element-specific max_loading_percent overrides it. + Returns: - Dict containing contingency analysis results + Structured N-1 report with islanding classification, violations, + severity components, and summary counts. """ - logger.info("Running contingency analysis") + logger.info("Running topology-aware N-1 security assessment") try: - net = _get_network() - - # Store original state - orig_net = copy.deepcopy(net) - results = [] - - # Define elements to analyze - if elements is None: - elements = ['line', 'trafo'] - - # Perform contingency analysis - for element_type in elements: - for idx in net[element_type].index: - # Create contingency by taking element out of service - contingency_net = copy.deepcopy(orig_net) - contingency_net[element_type].at[idx, 'in_service'] = False - - try: - pp.runpp(contingency_net) - - # Check for violations - violations = { - 'voltage_violations': contingency_net.res_bus[ - (contingency_net.res_bus.vm_pu < 0.95) | - (contingency_net.res_bus.vm_pu > 1.05) - ].index.tolist(), - 'loading_violations': contingency_net.res_line[ - contingency_net.res_line.loading_percent > 100 - ].index.tolist() - } - - results.append({ - 'contingency': f"{element_type}_{idx}", - 'converged': contingency_net.converged, - 'violations': violations - }) - - except Exception as e: - results.append({ - 'contingency': f"{element_type}_{idx}", - 'converged': False, - 'error': str(e) - }) - - return { - "status": "success", - "message": "Contingency analysis completed", - "results": results - } + if contingency_type.strip().upper() != "N-1": + return { + "status": "error", + "message": "Only N-1 contingency analysis is implemented; N-2 is not silently approximated.", + } + return _run_security_assessment( + _get_network(), + elements=elements, + voltage_min_pu=voltage_min_pu, + voltage_max_pu=voltage_max_pu, + line_loading_limit_percent=line_loading_limit_percent, + trafo_loading_limit_percent=trafo_loading_limit_percent, + ) except RuntimeError as re: - return { - "status": "error", - "message": str(re) - } - except Exception as e: - return { - "status": "error", - "message": f"Contingency analysis failed: {str(e)}" - } + return {"status": "error", "message": str(re)} + except (TypeError, ValueError) as exc: + return {"status": "error", "message": str(exc)} + except Exception as exc: + logger.exception("Contingency analysis failed") + return {"status": "error", "message": f"Contingency analysis failed: {exc}"} @mcp.tool() def get_network_info() -> Dict[str, Any]: From 4d6e8e97804320b7fad608812da14590de6ea375 Mon Sep 17 00:00:00 2001 From: Burhan Abdullah <131237388+BurhanAbdullah@users.noreply.github.com> Date: Sat, 14 Nov 2026 11:43:29 +0530 Subject: [PATCH 3/8] test(pandapower): cover topology-aware N-1 assessment --- tests/test_pandapower_security_assessment.py | 74 ++++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 tests/test_pandapower_security_assessment.py diff --git a/tests/test_pandapower_security_assessment.py b/tests/test_pandapower_security_assessment.py new file mode 100644 index 00000000..6c6e47e1 --- /dev/null +++ b/tests/test_pandapower_security_assessment.py @@ -0,0 +1,74 @@ +"""Tests for topology-aware pandapower N-1 security assessment.""" +import pandapower as pp +import pandapower.networks as pn + +from pandapower.security_assessment import run_security_assessment + + +def test_case14_assessment_is_deterministic_and_does_not_mutate_input(): + net = pn.case14() + before = net.line.in_service.copy(), net.trafo.in_service.copy() + + first = run_security_assessment(net) + second = run_security_assessment(net) + + assert first["status"] == "success" + assert first["analysis_type"] == "N-1" + assert first["contingency_count"] == len(net.line) + len(net.trafo) + assert first["results"] == second["results"] + assert (net.line.in_service == before[0]).all() + assert (net.trafo.in_service == before[1]).all() + assert set(first["summary"]) == { + "secure", "limit_violations", "islanding", "nonconvergent", "errors" + } + + +def test_line_outage_reports_unsupplied_load_instead_of_generic_solver_error(): + net = pp.create_empty_network() + source = pp.create_bus(net, vn_kv=110) + remote = pp.create_bus(net, vn_kv=110) + pp.create_ext_grid(net, bus=source) + line = pp.create_line_from_parameters( + net, from_bus=source, to_bus=remote, length_km=1, + r_ohm_per_km=0.1, x_ohm_per_km=0.1, + c_nf_per_km=0, max_i_ka=1, + ) + pp.create_load(net, bus=remote, p_mw=12.5, q_mvar=2.0) + + report = run_security_assessment(net, elements=["line"]) + + assert report["contingency_count"] == 1 + result = report["results"][0] + assert result["contingency"] == f"line_{line}" + assert result["classification"] == "islanding" + assert result["converged"] is False + assert result["violations"]["severity"]["unserved_load_mw"] == 12.5 + assert result["unsupplied_islands"][0]["buses"] == [remote] + assert bool(net.line.at[line, "in_service"]) + + +def test_element_specific_line_loading_limit_overrides_fallback(): + net = pn.case14() + line = net.line.index[0] + net.line.at[line, "max_loading_percent"] = 1.0 + + report = run_security_assessment( + net, + elements=["line"], + line_loading_limit_percent=1000.0, + ) + + result = next(item for item in report["results"] if item["index"] == line) + if result["converged"]: + assert result["classification"] == "limit_violations" + assert any(item["index"] == line for item in result["violations"]["line_overloads"]) + + +def test_invalid_voltage_limits_are_rejected(): + net = pn.case14() + try: + run_security_assessment(net, voltage_min_pu=1.05, voltage_max_pu=0.95) + except ValueError as exc: + assert "Voltage limits" in str(exc) + else: + raise AssertionError("Invalid voltage limits were accepted") From 6594cd8b3a6dc7b43ef3772b20857ae21835c53e Mon Sep 17 00:00:00 2001 From: Burhan Abdullah <131237388+BurhanAbdullah@users.noreply.github.com> Date: Sat, 14 Nov 2026 11:44:09 +0530 Subject: [PATCH 4/8] test(pandapower): load security module like server runtime --- tests/test_pandapower_security_assessment.py | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/tests/test_pandapower_security_assessment.py b/tests/test_pandapower_security_assessment.py index 6c6e47e1..42f2712a 100644 --- a/tests/test_pandapower_security_assessment.py +++ b/tests/test_pandapower_security_assessment.py @@ -1,8 +1,16 @@ """Tests for topology-aware pandapower N-1 security assessment.""" +from pathlib import Path +import sys + import pandapower as pp import pandapower.networks as pn -from pandapower.security_assessment import run_security_assessment +_SERVER_DIR = str(Path(__file__).resolve().parents[1] / "pandapower") +sys.path.insert(0, _SERVER_DIR) +try: + from security_assessment import run_security_assessment +finally: + sys.path.remove(_SERVER_DIR) def test_case14_assessment_is_deterministic_and_does_not_mutate_input(): From 45ff5c237daf174680f3baba154d24b1dfb42662 Mon Sep 17 00:00:00 2001 From: Burhan Abdullah <131237388+BurhanAbdullah@users.noreply.github.com> Date: Sat, 14 Nov 2026 11:44:19 +0530 Subject: [PATCH 5/8] style(pandapower): remove unused contingency import --- pandapower/security_assessment.py | 1 - 1 file changed, 1 deletion(-) diff --git a/pandapower/security_assessment.py b/pandapower/security_assessment.py index ba710fd1..96cf3dd7 100644 --- a/pandapower/security_assessment.py +++ b/pandapower/security_assessment.py @@ -7,7 +7,6 @@ from __future__ import annotations import copy -import itertools import math from typing import Any, Dict, Iterable, List, Mapping, Optional, Sequence, Tuple From 53184839e004a110dad2c93c68d95bbb76dd8ab5 Mon Sep 17 00:00:00 2001 From: Burhan Abdullah <131237388+BurhanAbdullah@users.noreply.github.com> Date: Sat, 14 Nov 2026 12:36:01 +0530 Subject: [PATCH 6/8] fix(pandapower): correct island demand and severity ranking --- pandapower/security_assessment.py | 28 ++++++++++++++++++++-------- 1 file changed, 20 insertions(+), 8 deletions(-) diff --git a/pandapower/security_assessment.py b/pandapower/security_assessment.py index 96cf3dd7..a0a8b7c4 100644 --- a/pandapower/security_assessment.py +++ b/pandapower/security_assessment.py @@ -54,10 +54,11 @@ def _topology_islands(net: Any) -> List[Dict[str, Any]]: sources.add(row["bus"]) loads_by_bus: Dict[Any, float] = {} - for table in ("load", "sgen", "storage"): + # Positive sgen.p_mw is generation, not demand. Storage follows the + # pandapower convention: positive p_mw is charging/consumption. + for table in ("load", "storage"): for _, row in _active_rows(net, table): p_mw = _finite_number(row.get("p_mw")) or 0.0 - # Only positive net consumption contributes to unsupplied demand. loads_by_bus[row["bus"]] = loads_by_bus.get(row["bus"], 0.0) + max(p_mw, 0.0) islands = [] @@ -267,15 +268,26 @@ def run_security_assessment( "error": f"{type(exc).__name__}: {exc}", }) - # Stable, transparent ordering: islanding/unserved load first, then - # limit violations by counts and magnitudes, then solver/error outcomes. - def rank(item: Dict[str, Any]) -> Tuple[float, int, float, int, str]: + # Stable lexicographic ordering keeps unlike engineering quantities + # separate: p.u. voltage deviation is never added to thermal percent. + # Priority: unserved MW, voltage count/magnitude, thermal count/excess, + # then outcome class and contingency identifier. + def rank(item: Dict[str, Any]) -> Tuple[float, int, float, int, float, int, str]: severity = ((item.get("violations") or {}).get("severity") or {}) + classification_order = { + "islanding": 0, + "limit_violations": 1, + "power_flow_nonconvergence": 2, + "analysis_error": 3, + "secure": 4, + } return ( -float(severity.get("unserved_load_mw", 0.0)), - -int(severity.get("voltage_violation_count", 0)) - int(severity.get("thermal_overload_count", 0)), - -float(severity.get("max_voltage_deviation_pu", 0.0)) - float(severity.get("max_thermal_excess_percent", 0.0)), - 0 if item["classification"] == "islanding" else 1, + -int(severity.get("voltage_violation_count", 0)), + -float(severity.get("max_voltage_deviation_pu", 0.0)), + -int(severity.get("thermal_overload_count", 0)), + -float(severity.get("max_thermal_excess_percent", 0.0)), + classification_order.get(item["classification"], 5), item["contingency"], ) results.sort(key=rank) From 2b69d36bbd1b11fc734fc680f0a55de97ff3cc1c Mon Sep 17 00:00:00 2001 From: Burhan Abdullah <131237388+BurhanAbdullah@users.noreply.github.com> Date: Sat, 14 Nov 2026 12:36:04 +0530 Subject: [PATCH 7/8] test(pandapower): verify generation is excluded from unserved load --- tests/test_pandapower_security_assessment.py | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/tests/test_pandapower_security_assessment.py b/tests/test_pandapower_security_assessment.py index 42f2712a..4f5571f8 100644 --- a/tests/test_pandapower_security_assessment.py +++ b/tests/test_pandapower_security_assessment.py @@ -42,6 +42,8 @@ def test_line_outage_reports_unsupplied_load_instead_of_generic_solver_error(): c_nf_per_km=0, max_i_ka=1, ) pp.create_load(net, bus=remote, p_mw=12.5, q_mvar=2.0) + # Positive sgen power is generation, not additional unserved demand. + pp.create_sgen(net, bus=remote, p_mw=7.5, q_mvar=0.0) report = run_security_assessment(net, elements=["line"]) @@ -67,9 +69,9 @@ def test_element_specific_line_loading_limit_overrides_fallback(): ) result = next(item for item in report["results"] if item["index"] == line) - if result["converged"]: - assert result["classification"] == "limit_violations" - assert any(item["index"] == line for item in result["violations"]["line_overloads"]) + assert result["converged"] is True + assert result["classification"] == "limit_violations" + assert any(item["index"] == line for item in result["violations"]["line_overloads"]) def test_invalid_voltage_limits_are_rejected(): From da48ba1e1663ae2cfde8a5b8de03abc4157d9a1b Mon Sep 17 00:00:00 2001 From: Burhan Abdullah <131237388+BurhanAbdullah@users.noreply.github.com> Date: Sat, 14 Nov 2026 13:43:10 +0530 Subject: [PATCH 8/8] test(pandapower): fix element-specific loading limit test --- tests/test_pandapower_security_assessment.py | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/tests/test_pandapower_security_assessment.py b/tests/test_pandapower_security_assessment.py index 4f5571f8..eb919894 100644 --- a/tests/test_pandapower_security_assessment.py +++ b/tests/test_pandapower_security_assessment.py @@ -8,7 +8,7 @@ _SERVER_DIR = str(Path(__file__).resolve().parents[1] / "pandapower") sys.path.insert(0, _SERVER_DIR) try: - from security_assessment import run_security_assessment + from security_assessment import _evaluate_results, run_security_assessment finally: sys.path.remove(_SERVER_DIR) @@ -61,17 +61,22 @@ def test_element_specific_line_loading_limit_overrides_fallback(): net = pn.case14() line = net.line.index[0] net.line.at[line, "max_loading_percent"] = 1.0 + pp.runpp(net) - report = run_security_assessment( + violations = _evaluate_results( net, - elements=["line"], + voltage_min_pu=0.95, + voltage_max_pu=1.05, line_loading_limit_percent=1000.0, + trafo_loading_limit_percent=1000.0, ) - result = next(item for item in report["results"] if item["index"] == line) - assert result["converged"] is True - assert result["classification"] == "limit_violations" - assert any(item["index"] == line for item in result["violations"]["line_overloads"]) + assert any(item["index"] == line for item in violations["line_overloads"]) + assert all( + item["limit_percent"] == 1.0 + for item in violations["line_overloads"] + if item["index"] == line + ) def test_invalid_voltage_limits_are_rejected():