Using trustlayer with your own data¶
Trustlayer adds calibrated bounds to the predictions of any model: a GridFM model, another neural network, a DC power flow, a commercial tool. The command-line tool reads GridFM's file layout; with any other model, use the Python API as described here. You need:
- a calibration set: scenarios with your model's predictions and the true values (e.g. from an AC power flow), separate from the scenarios you evaluate or operate on;
- the predictions for new scenarios (and, to check the coverage on test scenarios, their true values);
- for the kernel method (
KernelIntervalCalibrator), one vector per scenario that describes it, e.g. your model's embeddings averaged over the buses.
The notebook examples/notebooks/own_model.ipynb goes through every step with a simple regression model on real contingency scenarios of the IEEE 14-bus grid.
This guide ships with the package: gridfm_trustlayer guide prints it and gridfm_trustlayer guide --path gives its location, so that you, or an AI coding assistant, can read the version that matches your installation. It is also online at https://gridfm.github.io/gridfm-trustlayer/user-guide/own-data/.
1. Put your data in a long table¶
One row per scenario and element (bus or line):
| Column | Content | Needed |
|---|---|---|
| scenario id | integer | always |
| element id | integer, numbered the same way in every dataset | always |
| prediction | one column per variable, e.g. loading_pred |
always |
| true value | one column per variable, e.g. loading_true |
calibration, and test scenarios to check coverage |
| validity | boolean, False where a value must not be calibrated |
optional |
| stratum | integer per scenario, e.g. the number of outages | optional, for strat |
For the kernel method, add a second table with one row per scenario: the scenario id as its index (or a scenario column) and one column per embedding dimension.
Every scenario should list the same elements. An element that does not apply in a scenario (e.g. an out-of-service line) can be left out of the table or marked invalid: either way it is not used for fitting and gets no interval.
Strata can also come from a table with one row per scenario. ChannelSet.from_frame(..., strata={"n_outages": series}) takes a Series indexed by scenario id, such as those of two helpers that compute the command-line tool's strata:
OutageStrata.fit(branch_in_service, generator_in_service)on the calibration set, then.n_outages(...)or.outage_type(...)on any dataset. The inputs are in-service flags, one row per scenario and one column per line (or generator). An element counts as an outage when it is out of service but in service in some calibration scenario.LoadBins.fit(total_load, n_bins)on the calibration set, then.assign(total_load): percentile bins of the total load of each scenario.
2. Mistakes to avoid¶
- Calibrating and evaluating on the same scenarios. Coverage measured on the calibration data says nothing about new scenarios. Use separately generated datasets.
- Values the model does not predict. Inputs that the model copies (e.g. set-points) are exact and would make the bounds too narrow: mark them invalid.
- Embeddings in another order than the predictions. Pass them as a table indexed by scenario id;
ChannelSet.from_framealigns them by id. - One embedding per bus. The kernel needs one vector per scenario: average (or otherwise pool) the per-bus vectors of each scenario first, the same way for calibration and new scenarios.
- Different elements or numbering between the calibration set and new scenarios.
- Strata that are not integers, or that change within a scenario: bin continuous quantities (e.g. the total load) into integers first.
3. Example¶
A model's outputs on 4,000 contingency scenarios of 20 lines, as a long table. Its errors grow with the number of outages and are three times larger in half of the scenarios ("hard" ones), which its embedding can tell apart:
import numpy as np
import pandas as pd
from gridfm_trustlayer import (
ChannelSet,
KernelIntervalCalibrator,
NaiveIntervalCalibrator,
check_inputs,
)
rng = np.random.default_rng(0)
n_scenarios, n_lines = 4000, 20
scenario = np.repeat(np.arange(n_scenarios), n_lines)
line = np.tile(np.arange(n_lines), n_scenarios)
n_outages = rng.integers(1, 4, n_scenarios) # contingency level of each scenario
hard = rng.random(n_scenarios) < 0.5 # scenarios where the model is less accurate
predicted = rng.uniform(0.2, 1.1, scenario.size)
scale = 0.01 * n_outages[scenario] * np.where(hard[scenario], 3.0, 1.0)
table = pd.DataFrame(
{
"scenario": scenario,
"line": line,
"n_outages": n_outages[scenario],
"loading_pred": predicted,
"loading_true": predicted + rng.normal(0.0, scale),
"in_service": rng.random(scenario.size) > 0.02, # False: no interval
}
)
# One vector per scenario, e.g. the model's embeddings averaged over the buses.
embeddings = pd.DataFrame(
{
"z1": hard + rng.normal(0.0, 0.2, n_scenarios),
"z2": rng.normal(size=n_scenarios),
},
index=pd.Index(np.arange(n_scenarios), name="scenario"),
)
Build the predictions and the true values from the same rows, then check them before fitting. Here the first half of the scenarios is the calibration set:
def channel_sets(rows):
"""Predictions and true values of these rows, as aligned ChannelSets."""
common = {
"entity": "line",
"entity_name": "branch",
"valid": "in_service",
"strata": ["n_outages"],
"embeddings": embeddings,
}
predictions = ChannelSet.from_frame(
rows, {"line_loading": "loading_pred"}, **common
)
true_values = ChannelSet.from_frame(
rows, {"line_loading": "loading_true"}, **common
)
return predictions, true_values
calibration = table[table["scenario"] < 2000]
calibration_predictions, calibration_true = channel_sets(calibration)
print(
check_inputs(
calibration_predictions,
calibration_true,
strat="n_outages",
alpha=0.1,
kernel=True,
)
)
check_inputs prints No problems found., or the errors to fix and the warnings to read (section 6). Fit both methods with 90% intervals (alpha=0.1, 5% per tail), stratified by the number of outages:
settings = {"alpha": 0.1, "channel_names": ("line_loading",), "strat": "n_outages"}
scp = NaiveIntervalCalibrator.fit(calibration_predictions, calibration_true, **settings)
kcp = KernelIntervalCalibrator.fit(
calibration_predictions,
calibration_true,
embeddings=calibration_predictions.scenario_embeddings,
n_eff_target=200, # about 200 calibration scenarios weigh in each bound
**settings,
)
Apply them to the other scenarios. New scenarios need only the predictions, with the same validity, strata and embeddings; here the true values are known, so the coverage can be checked:
test = table[table["scenario"] >= 2000]
test_predictions, test_true = channel_sets(test)
print(check_inputs(test_predictions, calibrator=kcp))
valid = test_predictions.valid_masks["line_loading"]
truth = test_true.channels["line_loading"]
hard_test = hard[test_predictions.scenario_ids][:, None]
for name, calibrator in (("SCP", scp), ("KCP", kcp)):
lower, upper = calibrator.predict_intervals(test_predictions)["line_loading"]
covered = (lower <= truth) & (truth <= upper)
print(
f"{name}: coverage {covered[valid].mean():.3f} "
f"(easy {covered[valid & ~hard_test].mean():.3f}, "
f"hard {covered[valid & hard_test].mean():.3f}), "
f"mean width {(upper - lower)[valid].mean():.3f}"
)
No problems found.
No problems found.
SCP: coverage 0.905 (easy 1.000, hard 0.805), mean width 0.157
KCP: coverage 0.924 (easy 0.944, hard 0.903), mean width 0.141
SCP covers 90% overall, as guaranteed, but with one margin per line and stratum: easy scenarios are over-covered and hard ones under-covered. KCP weighs the calibration scenarios by their distance to each test scenario in the embedding, so its margins follow the difficulty of each scenario: it gets close to 90% in both groups, with narrower intervals on average. Its coverage is checked on test data, not guaranteed: here it is slightly above the target.
4. Results as tables¶
coverage_report gives the coverage and width per stratum (or per element, with by_element=True), as the command-line tool's coverage_by_stratum.csv. screening_report compares the bounds with operating limits: the violations caught, missed and falsely flagged when the true values are known, and the status of every scenario. to_frame returns the bounds and statuses as a long table, one row per scenario and element, to join back onto your own data:
from gridfm_trustlayer import coverage_report, screening_report
bounds = kcp.predict_intervals(test_predictions)
coverage = coverage_report(
test_predictions, test_true, bounds, alpha=0.1, strat="n_outages"
)
print(coverage[["stratum", "coverage", "mean_width"]].round(3).to_string(index=False))
limits = {"line_loading": {"upper": 1.0}}
report = screening_report(test_predictions, bounds, limits, true_values=test_true)
alarms = report.alarms[report.alarms["stratum"] == "all"]
counts = ["method", "violations", "caught", "missed", "false_alarms"]
print(alarms[counts].to_string(index=False))
rows = test_predictions.to_frame(bounds, entity="line", limits=limits)
print(list(rows.columns))
stratum coverage mean_width
all 0.924 0.141
n_outages=1 0.920 0.071
n_outages=2 0.925 0.142
n_outages=3 0.928 0.213
method violations caught missed false_alarms
interval 4417 4386 31 2903
point 4417 3741 676 607
['scenario', 'line', 'n_outages', 'line_loading', 'line_loading_valid', 'line_loading_lower', 'line_loading_upper', 'line_loading_status', 'line_loading_point_status']
A value is within_limits when its whole interval is inside the limits, a violation when it is entirely beyond one and uncertain otherwise; the point rows judge the prediction alone. Here the bounds miss 31 of the 4,417 overloads, the point predictions 676. report.scenarios gives each scenario's status (secure, uncertain or insecure, the worst of its values). Pass the buses and the lines together, screening_report([buses, lines], ...), for that status to cover both. A limit can also differ per element, e.g. {"Vm": {"lower": vmin, "upper": vmax}} with vmin and vmax Series indexed by bus id (NaN: no limit). Unlike the command-line tool, which widens the limits by 1e-6 to absorb rounding, the reports use the limits as given.
5. Buses and lines together, and saving¶
The calibrators above handle one ChannelSet each. TrustLayer fits one per set with the same settings, sends new data to the calibrator of its variables, and saves them all in one file, with the definitions of the strata:
TrustLayer.fit([buses, lines], [bus_truth, line_truth], alpha=..., strat=..., method="element" or "kernel"), thenpredict_intervals([new_buses, new_lines]);n_eff_target="auto"chooses the kernel'sn_eff_targetby cross-validation on the calibration set, for all sets at once;strata={"n_outages": outage_strata}saves anOutageStrataorLoadBinswith the layer: afterTrustLayer.load,layer.strata["n_outages"].n_outages(...)gives the strata of new scenarios as at fit.
With the example's lines alone:
import tempfile
from pathlib import Path
from gridfm_trustlayer import TrustLayer
layer = TrustLayer.fit(
calibration_predictions,
calibration_true,
alpha=0.1,
strat="n_outages",
method="kernel",
n_eff_target="auto", # cross-validated on the calibration set
)
print(f"n_eff_target: {layer.tuning['line_loading'].selected_n_eff_target:g}")
with tempfile.TemporaryDirectory() as folder:
layer.save(Path(folder) / "lines.trustlayer")
loaded = TrustLayer.load(Path(folder) / "lines.trustlayer")
bounds = loaded.predict_intervals(test_predictions)
lower, upper = bounds["line_loading"]
covered = (lower <= truth) & (truth <= upper)
print(
f"coverage {covered[valid].mean():.3f}, mean width {(upper - lower)[valid].mean():.3f}"
)
The cross-validation picks the n_eff_target used above, so the bounds are those of kcp. fit runs check_inputs first and raises its errors. The file is an ordinary .trustlayer artifact, and TrustLayer.load also reads those of the command-line tool.
6. What check_inputs reports¶
check_inputs(predictions, true_values, strat=..., alpha=..., kernel=...) before fitting, and check_inputs(new_predictions, calibrator=...) before predicting, return an InputCheck with:
- errors, to fix first: predictions and true values with different or differently ordered scenarios or elements; ids that are not integers; a missing variable or stratum column; strata that are not integers; missing, NaN or constant embeddings for the kernel; new data with other elements or another embedding width than the fitted calibrator;
- warnings: values that are NaN but marked valid; elements without any valid calibration value; elements with too few calibration values in a stratum for a finite bound there (they use their quantile over all strata, without a guarantee within that stratum), or too few overall (infinite bounds); new scenarios in strata absent from the calibration data.
check.ok is True when there are no errors, and check.raise_for_errors() raises them.
7. Choosing a method¶
NaiveIntervalCalibrator(SCP) needs only predictions and true values. When calibration and new scenarios are exchangeable, its intervals cover with probability at least1 - alphawithin each stratum, for any calibration size. An element needs at leastceil(2 / alpha) - 1valid calibration values in a stratum (19 atalpha=0.1) for a finite bound there.KernelIntervalCalibrator(KCP) also needs one vector per scenario, and adapts the margin to each scenario. Choosen_eff_targetwithgridfm_trustlayer.conformal.tuning.tune_n_eff_target, a cross-validation on the calibration set alone, or check the coverage on held-out data. A model without embeddings can use any vector that describes the scenario (e.g. its loads and outages, or its own predictions); whether it separates easy from hard scenarios has to be checked the same way. When the calibration scenarios are too far from the new ones in that vector (often with many dimensions), most scenarios fall back to the stratum quantiles, the bounds of SCP:predict_intervalsand the tuning then raise aKernelFallbackWarning, anddiagnostics["kernel_fallback"]marks those scenarios.alphais two-sided:alpha=0.1gives 90% intervals with 5% per tail. For a one-sided screen at level1 - a, fit withalpha = 2 * aand use the upper bound.
8. Next steps¶
- The notebook
examples/notebooks/own_model.ipynb: the whole workflow with a model of your own on real data, including the kernel method with a model that has no embeddings. - The status rule alone:
classify_statusandscenario_statusapply it to any bounds. - Saving and loading a single calibrator:
save_interval_artifactandload_interval_artifact. - More: the Python API guide (https://gridfm.github.io/gridfm-trustlayer/user-guide/python-api/), the API reference (https://gridfm.github.io/gridfm-trustlayer/reference/api/) and the kernel method (https://gridfm.github.io/gridfm-trustlayer/user-guide/kernel/).