Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
11 changes: 11 additions & 0 deletions NARP/Pipfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
[[source]]
name = "pypi"
url = "https://pypi.org/simple"
verify_ssl = true

[dev-packages]
black = "*"
pytest = "*"

[packages]
numpy = "~=1.20"
41 changes: 41 additions & 0 deletions NARP/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
# reliability-assessment
Reliability Assessment Module

The goal of this project is to port an original Fortran-based power system reliability assessment program (“NARP”) to Python. The program calculates reliability indices such as LOLE (Loss of Load Expectation), HLOLE (Hourly LOLE), and EUE (Expected Unserved Energy) for transmission systems. The Python implementation closely matches the original FORTRAN behaviour when benchmarked via RMSE metrics.

## PowerMCP Integration

Within the PowerMCP repository the MCP entry point is exposed via `NARP/narp_mcp.py`.
You can launch the server with `python -m NARP.narp_mcp`, which registers tools like `submit_simulation`, `get_job_summary`, and `validate_input` – matching the pattern used by other integrations (e.g. pandapower).
This integration builds on the open-source Python port maintained at [zylpascal/NARP](https://github.com/zylpascal/NARP).

## Using NARP with PowerMCP

### Start the server

```bash
python -m NARP.narp_mcp
```

Run this command from the PowerMCP repository root. The server copies each submitted test directory into `NARP/mcp_jobs/`, executes `narpMain.py`, and tracks job metadata so you can retrieve logs and summaries later.

### Example prompts for MCP clients

Use any MCP-aware assistant to issue natural-language instructions. A few examples:

- “List the available tools and give me a short description of each.”
- “Use the reliability analysis tool with the input directory C:/cases/narp_case1, run the simulation, and send me the summary of the results afterward.”
- “Please validate the NARP inputs located at `C:/cases/narp_case1` before running the reliability study.”
- “Submit a NARP reliability job for `C:/cases/narp_case1`, keep checking until it finishes, then send me the TABLE 12/13 summary.”
- “Cancel the current NARP reliability run with job id `job_abcd1234` and confirm the status change.”

Adjust directory paths to match your environment. After completion you can inspect `output_python.txt` and `run.log` inside the corresponding folder under `NARP/mcp_jobs/`.

## Additional resources

For full algorithmic documentation, data formats, and advanced usage, refer to the upstream project at [zylpascal/NARP](https://github.com/zylpascal/NARP).

## Contacts

- Shan Yang – yangsh237@mail2.sysu.edu.cn
- Yongli Zhu – yzhu16@alum.utk.edu
30 changes: 30 additions & 0 deletions NARP/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
"""
NARP reliability assessment integration for PowerMCP.

Re-exports the MCP server instance and tool functions from :mod:`NARP.narp_mcp`
so callers can simply import ``NARP`` and access the registered tools.
"""

from .narp_mcp import (
mcp,
submit_simulation,
run_simulation_sync,
get_job_status,
get_job_result,
get_job_summary,
list_jobs,
cancel_job,
validate_input,
)

__all__ = [
"mcp",
"submit_simulation",
"run_simulation_sync",
"get_job_status",
"get_job_result",
"get_job_summary",
"list_jobs",
"cancel_job",
"validate_input",
]
Empty file added NARP/common/__init__.py
Empty file.
69 changes: 69 additions & 0 deletions NARP/common/utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
from dataclasses import dataclass
from typing import Callable, Dict, Any, Optional
import functools
from mcp.server.fastmcp import FastMCP




def power_mcp_tool(mcp: FastMCP):
"""
Decorator to register a PowerMCP tool.

A decorator that wraps a function and transforms the result to a dictionary if it is an instance of PowerError.
It also adds the function to the MCP server automatically.

Args:
mcp: The MCP server to register the tool to.

Example:
@power_mcp_tool(mcp)
def my_tool(x: int) -> str:
return str(x)
"""
def decorator(func):

@mcp.tool()
@functools.wraps(func)
def wrapper(*args, **kwargs):
result = func(*args, **kwargs)
return _transform_power_mcp_result(result)
return wrapper
return decorator



def _transform_power_mcp_result(result: Any) -> Any:
"""
Transforms the result of a function to a dictionary if it is an instance of PowerError.
"""
if isinstance(result, PowerError):
base: Dict[str, Any] = {
"status": result.status,
"message": result.message
}
if result.info:
# We have some additional data, we will add the keys.
for key, value in result.info.items():
base[key] = value
return base
else:
return result

@dataclass
class PowerError:
"""
A custom error class that is used to return errors from the MCP server.
It is used to return errors in a consistent format.
The info field is used to return additional data about the error.

Attributes:
status: The status of the error.
message: The message of the error.
info: Additional data about the error, this is a dictionary of key-value pairs,
and is added alongside the other fields. For instance, if this field were to be {"hello": "world"},
then the returned object would be {"status": "error", "message": "An error occurred", "hello": "world"}
"""
status: str
message: str
info: Optional[Dict[str, Any]] = None
21 changes: 21 additions & 0 deletions NARP/conftest.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import pytest


def pytest_addoption(parser):
parser.addoption(
"--runslow", action="store_true", default=False, help="run slow tests"
)


def pytest_configure(config):
config.addinivalue_line("markers", "slow: mark test as slow to run")


def pytest_collection_modifyitems(config, items):
if config.getoption("--runslow"):
# --runslow given in cli: do not skip slow tests
return
skip_slow = pytest.mark.skip(reason="need --runslow option to run")
for item in items:
if "slow" in item.keywords:
item.add_marker(skip_slow)
11 changes: 11 additions & 0 deletions NARP/docs/data.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
Capabilities and Data
---------------------
The reliability assessment program reads in and interprets generation properties,
ownership, firm contracts, transmission link data between areas, and other important
power system data with simulation settings on an area basis. Then the program calculates
key reliability indices according to industry standards, including LOLE (Loss of Load
Expectations), Hourly LOLE (HLOLE in short), and EUE (Expected Unserved Energy, in kWh or
MWh) for electric systems. Those reliability indices measure the availability of
generation and transmission capacity given a preset table of failure probabilities. It
also creates a planned generation unit maintenance library and the probabilistic
distribution of each defined outage for the users to assess the system reliability risk.
20 changes: 20 additions & 0 deletions NARP/docs/index.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
Reliability Assessment
======================
Collaborators: Dr. Chanan Singh, Dr. Yongli Zhu

.. contents:: :local:

.. include::
summary.rst

.. include::
data.rst

.. include::
manual.rst

.. include::
installation.rst

.. include::
usage.rst
13 changes: 13 additions & 0 deletions NARP/docs/installation.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
Installation
------------

This project requires Python 3.8 and relies on the ``numpy`` and ``pandas`` packages
both available on `PyPi <https://pypi.org/>`_. We recommend that you use ``pipenv`` to
install the dependencies in an isolated environment

+ Clone or fork the source code from
`GitHub <https://github.com/Breakthrough-Energy/reliability-assessment>`_
+ Install dependencies using the **Pipfile** or *requirements.txt* files located at the
root of the package, e.g., using ``pip install -r requirements.txt``
+ Install the ``reliabilityassessment`` package as a third-party library in your working
environment with ``pip install .``
10 changes: 10 additions & 0 deletions NARP/docs/manual.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
User Manual
-----------
The **reliability-assessment** project is available on GitHub
(https://github.com/Breakthrough-Energy/reliability-assessment).
The package can be used as a standalone application with separate
Input/Output pipeline, to maintain the integrity and performance
inherited from the original NARP software.

A short guide of the usage of the ``reliabilityassessment``
package can be found below.
33 changes: 33 additions & 0 deletions NARP/docs/summary.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
Summary
-------

Reliability performance is the most important criteria for any electric power system
planning and operation activity to comply with. This becomes increasingly challenging
as more intermittent energy resources are added to the system with an accelerated pace
of the retirement of fossil fuel generation. In addition, more frequent extreme weather
events and climate change also leads to more severe blackouts, as measured by both the
time duration of the blackout and the magnitude of affected demand. Understanding the
reliability performance of the existing system and accordingly planning for a reliable
future energy system requires a comprehensive reliability assessment module with
flexible demand and variable generation that can assess the fundamental elements of a
system’s reliability, including:

+ Generator’s availability and capacity contribution to system adequacy;
+ System resource balancing capability to satisfy demand needs with renewable generation;
+ Risk of load interruptions under modeled events and outages.

The objective of this project is to develop and translate an add-on module embedded
into the modeling framework to enable the simulation of reliability performance metrics
of an electric system’s transmission and generation equipment to identify future
planning needs. Underlying this project is the reliability assessment currently used as
the industry standard – General Electric’s Multi Area Reliability Simulation (GE-MARS).
GE-MARS calculates reliability performance indices in a multi-area interconnected
electric power system to evaluate system risk and guide generation capacity planning.
The program is based on a Monte Carlo simulation approach to reflect the effects of
random events such as generator and transmission link failures as well as deterministic
operating rules and policies. The original concept and codes came from
Prof. Chanan Singh, currently at Texas A&M University. This project ports an original
Fortran-based power system reliability assessment program ('NARP') into a modern
language (Python and Julia) and publishes it as an open-source tool as the final
deliverable, not only for industry application but also for the research community
to continue building upon.
Loading