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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions src/fluxopt/stats.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,3 +100,33 @@ def effect_contributions(self) -> xr.Dataset:
self._result.data,
self._result.solution,
)

def summary(self) -> xr.Dataset:
"""Headline KPIs overview.

Returns a tidy dataset with the objective value, total effects,
and per-flow full load hours.
"""
import numpy as np
import xarray as xr

ds = xr.Dataset()
ds['objective'] = xr.DataArray(self._result.objective)

if self._result.effect_totals is not None and len(self._result.effect_totals) > 0:
ds['effect_totals'] = self._result.effect_totals

# Compute full load hours
combined_size = self._result.data.flows.size.copy()
sizes = self._result.sizes
# `sizes` is an empty 0-d DataArray when no flow has an investment size;
# only fill from it when it actually carries per-flow sizes.
if 'flow' in sizes.dims:
combined_size = combined_size.fillna(sizes)

with xr.set_options(keep_attrs=True):
flh = self.total_flow_hours / combined_size
flh = flh.where(np.isfinite(flh))

ds['full_load_hours'] = flh
return ds
35 changes: 35 additions & 0 deletions tests/test_stats_summary.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import numpy as np
from conftest import ts

from fluxopt import Carrier, Effect, Flow, Port, optimize


def test_stats_summary_quickstart():
"""`result.stats.summary()` exposes objective, effect totals and full-load hours."""
demand = Flow('elec', size=100, fixed_relative_profile=[0.5, 0.8, 0.6])
source = Flow('elec', size=200, effects_per_flow_hour={'cost': 0.04})

result = optimize(
timesteps=ts(3),
carriers=[Carrier('elec')],
effects=[Effect('cost')],
objective_effects='cost',
ports=[Port('grid', imports=[source]), Port('demand', exports=[demand])],
)

summary = result.stats.summary()

# KPIs are present...
assert 'objective' in summary
assert 'effect_totals' in summary
assert 'full_load_hours' in summary

# ...and carry meaningful content, not just keys.
assert np.isfinite(summary['objective'].item())
assert 'cost' in summary['effect_totals'].coords['effect'].values

flh = summary['full_load_hours']
assert 'grid(elec)' in flh.coords['flow'].values
source_flh = flh.sel(flow='grid(elec)').item()
assert np.isfinite(source_flh)
assert source_flh >= 0