diff --git a/pandapower/README.md b/pandapower/README.md index 70afe6c3..08839393 100644 --- a/pandapower/README.md +++ b/pandapower/README.md @@ -39,7 +39,7 @@ Configure in your MCP client (e.g., Cursor, Claude Desktop): - **load_network_from_json(...)**: Load serialized PowerIO IR, or one selected entry of it, without staging a file. - **export_network_to_format(to_format: str)**: Export the active network through PowerIO's native writer. - **run_power_flow(algorithm, calculate_voltage_angles, max_iteration, tolerance_mva)**: Run power flow analysis (Newton-Raphson or Backward/Forward Sweep). -- **run_contingency_analysis(contingency_type, elements)**: Run N-1 or N-2 contingency analysis on lines and transformers. +- **run_contingency_analysis(contingency_type, elements, max_contingencies)**: Run topology-aware N-1 or simultaneous N-2 contingency analysis on selected in-service elements. N-2 evaluates unordered outage pairs and rejects requests exceeding the configurable candidate limit (default 10,000). - **get_network_info()**: Get statistics and data for buses, lines, transformers, generators, loads, and switches. ## Prompt Example diff --git a/pandapower/panda_mcp.py b/pandapower/panda_mcp.py index ea2fc548..ba91abc3 100644 --- a/pandapower/panda_mcp.py +++ b/pandapower/panda_mcp.py @@ -13,6 +13,10 @@ 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, + run_n2_security_assessment as _run_n2_security_assessment, +) _repo_root = str(Path(__file__).resolve().parents[1]) _repo_root_added = _repo_root not in sys.path @@ -250,78 +254,72 @@ 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, + max_contingencies: int = 10000, +) -> Dict[str, Any]: + """Run topology-aware N-1 or N-2 security assessment on the current network. + + The analysis checks switch-aware islands before solving each outage, + reports unsupplied load, and checks voltage plus line and transformer + loading. N-2 evaluates simultaneous unordered pairs of selected elements. + Args: - contingency_type: Type of contingency analysis ("N-1" or "N-2") - elements: List of specific elements to analyze (optional) - + contingency_type: "N-1" for single outages or "N-2" for outage pairs. + 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. + max_contingencies: Maximum number of N-2 outage pairs to evaluate. + The request is rejected before simulation if the pair count exceeds + this safeguard. + Returns: - Dict containing contingency analysis results + Structured N-1 or N-2 report with islanding classification, + violations, severity components, and summary counts. """ - logger.info("Running contingency analysis") + logger.info("Running topology-aware %s security assessment", contingency_type) 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 - } - except RuntimeError as re: - return { - "status": "error", - "message": str(re) - } - except Exception as e: + selected_type = contingency_type.strip().upper() + if selected_type == "N-1": + 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, + ) + if selected_type == "N-2": + return _run_n2_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, + max_contingencies=max_contingencies, + ) return { "status": "error", - "message": f"Contingency analysis failed: {str(e)}" + "message": "contingency_type must be 'N-1' or 'N-2'.", } + except RuntimeError as re: + 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]: diff --git a/pandapower/security_assessment.py b/pandapower/security_assessment.py new file mode 100644 index 00000000..11fc79ee --- /dev/null +++ b/pandapower/security_assessment.py @@ -0,0 +1,484 @@ +"""Topology-aware N-1 and N-2 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 math +from itertools import combinations +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] = {} + # 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 + 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((int(bus) for bus in component),), + "source_buses": sorted((int(bus) for bus in 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 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)), + -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) + 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, + } + + +def run_n2_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, + max_contingencies: int = 10000, + runpp_options: Optional[Mapping[str, Any]] = None, +) -> Dict[str, Any]: + """Run deterministic simultaneous two-element (N-2) outage assessment. + + All unordered pairs from the selected in-service element tables are + evaluated. The candidate-count guard prevents accidental combinatorial + runs on large networks; callers must explicitly raise it when needed. + """ + 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 isinstance(max_contingencies, bool) or not isinstance(max_contingencies, int) or max_contingencies < 1: + raise ValueError("max_contingencies must be a positive integer.") + 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}") + + candidates = [ + (element_type, idx) + for element_type in requested + for idx, _ in _active_rows(net, element_type) + ] + pair_count = len(candidates) * (len(candidates) - 1) // 2 + if pair_count > max_contingencies: + raise ValueError( + f"N-2 assessment requires {pair_count} outage pairs, exceeding " + f"max_contingencies={max_contingencies}; narrow elements or raise the limit." + ) + if pair_count == 0: + raise ValueError("N-2 assessment requires at least two in-service contingency elements.") + + base_islands = _topology_islands(net) + results = [] + for first, second in combinations(candidates, 2): + outages = (first, second) + case = copy.deepcopy(net) + labels = [] + for element_type, idx in outages: + case[element_type].at[idx, "in_service"] = False + labels.append(f"{element_type}_{idx}") + label = "+".join(labels) + 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: + 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, + }, + } + results.append({ + "contingency": label, + "elements": [ + {"element": element_type, "index": idx} + for element_type, idx in outages + ], + "converged": False, + "classification": "islanding", + "islands": islands, + "unsupplied_islands": unsupplied, + "violations": violations, + }) + continue + + pp.runpp(case, **dict(runpp_options or {})) + if not bool(getattr(case, "converged", False)): + results.append({ + "contingency": label, + "elements": [ + {"element": element_type, "index": idx} + for element_type, idx in outages + ], + "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, + ) + has_violations = any(( + violations["voltage_violations"], + violations["line_overloads"], + violations["transformer_overloads"], + )) + results.append({ + "contingency": label, + "elements": [ + {"element": element_type, "index": idx} + for element_type, idx in outages + ], + "converged": True, + "classification": "limit_violations" if has_violations else "secure", + "islands": islands, + "violations": violations, + }) + except Exception as exc: + results.append({ + "contingency": label, + "elements": [ + {"element": element_type, "index": idx} + for element_type, idx in outages + ], + "converged": False, + "classification": "analysis_error", + "error": f"{type(exc).__name__}: {exc}", + }) + + classification_order = { + "islanding": 0, + "limit_violations": 1, + "power_flow_nonconvergence": 2, + "analysis_error": 3, + "secure": 4, + } + + def rank(item: Dict[str, Any]) -> Tuple[float, int, 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)), + -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) + return { + "status": "success", + "analysis_type": "N-2", + "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, + } diff --git a/tests/test_pandapower_security_assessment.py b/tests/test_pandapower_security_assessment.py new file mode 100644 index 00000000..120a1e76 --- /dev/null +++ b/tests/test_pandapower_security_assessment.py @@ -0,0 +1,210 @@ +"""Tests for topology-aware pandapower N-1 security assessment.""" +from pathlib import Path +import json +import sys + +import pandapower as pp +import pandapower.networks as pn + +_SERVER_DIR = str(Path(__file__).resolve().parents[1] / "pandapower") +sys.path.insert(0, _SERVER_DIR) +try: + from security_assessment import _evaluate_results, run_security_assessment +finally: + sys.path.remove(_SERVER_DIR) + + +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) + # 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"]) + + 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 + pp.runpp(net) + + violations = _evaluate_results( + net, + voltage_min_pu=0.95, + voltage_max_pu=1.05, + line_loading_limit_percent=1000.0, + trafo_loading_limit_percent=1000.0, + ) + + 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(): + 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") + + + +def _three_bus_mesh(): + net = pp.create_empty_network() + buses = [pp.create_bus(net, vn_kv=110) for _ in range(3)] + pp.create_ext_grid(net, bus=buses[0]) + lines = [ + pp.create_line_from_parameters( + net, from_bus=buses[a], to_bus=buses[b], length_km=1, + r_ohm_per_km=0.1, x_ohm_per_km=0.1, + c_nf_per_km=0, max_i_ka=1, + ) + for a, b in ((0, 1), (1, 2), (0, 2)) + ] + pp.create_load(net, bus=buses[2], p_mw=8.0, q_mvar=1.0) + return net, lines, buses + + +def test_n2_assessment_evaluates_simultaneous_pairs_deterministically(): + from security_assessment import run_n2_security_assessment + + net, lines, _ = _three_bus_mesh() + before = net.line.in_service.copy() + + first = run_n2_security_assessment(net, elements=["line"]) + second = run_n2_security_assessment(net, elements=["line"]) + + assert first["status"] == "success" + assert first["analysis_type"] == "N-2" + assert first["contingency_count"] == 3 + assert first["results"] == second["results"] + assert all(len(result["elements"]) == 2 for result in first["results"]) + assert { + tuple(item["index"] for item in result["elements"]) + for result in first["results"] + } == {(lines[0], lines[1]), (lines[0], lines[2]), (lines[1], lines[2])} + assert (net.line.in_service == before).all() + + +def test_n2_assessment_reports_load_islanded_by_two_simultaneous_outages(): + from security_assessment import run_n2_security_assessment + + net = pp.create_empty_network() + source, middle, remote = [ + pp.create_bus(net, vn_kv=110) for _ in range(3) + ] + pp.create_ext_grid(net, bus=source) + first = pp.create_line_from_parameters( + net, from_bus=source, to_bus=middle, length_km=1, + r_ohm_per_km=0.1, x_ohm_per_km=0.1, + c_nf_per_km=0, max_i_ka=1, + ) + second = pp.create_line_from_parameters( + net, from_bus=middle, 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=8.0, q_mvar=1.0) + + report = run_n2_security_assessment(net, elements=["line"]) + + assert report["contingency_count"] == 1 + result = report["results"][0] + assert result["elements"] == [ + {"element": "line", "index": first}, + {"element": "line", "index": second}, + ] + assert result["classification"] == "islanding" + assert result["violations"]["severity"]["unserved_load_mw"] == 8.0 + + +def test_n2_candidate_limit_rejects_before_running_contingencies(): + from security_assessment import run_n2_security_assessment + + net, _, _ = _three_bus_mesh() + try: + run_n2_security_assessment( + net, elements=["line"], max_contingencies=2 + ) + except ValueError as exc: + assert "3 outage pairs" in str(exc) + assert "max_contingencies=2" in str(exc) + else: + raise AssertionError("N-2 candidate limit was not enforced") + + +def test_n2_requires_at_least_two_active_elements(): + from security_assessment import run_n2_security_assessment + + net = pp.create_empty_network() + bus = pp.create_bus(net, vn_kv=110) + pp.create_ext_grid(net, bus=bus) + try: + run_n2_security_assessment(net, elements=["line"]) + except ValueError as exc: + assert "at least two" in str(exc) + else: + raise AssertionError("N-2 accepted fewer than two candidate elements") + + +def test_n1_and_n2_reports_are_json_serializable_and_use_native_bus_ids(): + from security_assessment import run_n2_security_assessment + + n1_net = pn.case14() + n1_report = run_security_assessment(n1_net) + json.dumps(n1_report) + assert all(type(bus) is int for island in n1_report["base_islands"] for bus in island["buses"]) + assert all(type(bus) is int for island in n1_report["base_islands" ] for bus in island["source_buses"]) + + + n2_net, _, _ = _three_bus_mesh() + n2_report = run_n2_security_assessment(n2_net, elements=["line"]) + json.dumps(n2_report) + assert all(type(bus) is int for island in n2_report["base_islands"] for bus in island["buses"]) + assert all(type(bus) is int for island in n2_report["base_islands"] for bus in island["source_buses"]) + for result in n2_report["results"]: + for island in result.get("islands", []): + assert all(type(bus) is int for bus in island["buses"]) + assert all(type(bus) is int for bus in island["source_buses"])