File size: 9,504 Bytes
20004e3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
"""Streamlit UI for BijliCast (shared by local/Community Cloud and HF Spaces).

The wrapper (:mod:`app.streamlit_app`) passes the repository root; this module
only knows about ``<root>/models`` and ``<root>/src``. That keeps the exact same
UI working inside a Hugging Face Space, where the app files live at the root.
"""
from __future__ import annotations

import sys
from pathlib import Path

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import streamlit as st

_THIS_DIR = Path(__file__).resolve().parent
if str(_THIS_DIR) not in sys.path:
    sys.path.insert(0, str(_THIS_DIR))

from service import BijliCastError, get_service  # noqa: E402

from src.utils.config import (  # noqa: E402
    CITY_COL,
    HOUSE_COL,
    INPUT_WEATHER_FEATURES,
    STATIC_CATEGORICAL_FEATURES,
    STATIC_NUMERIC_FEATURES,
    TIME_COL,
)

WEATHER_SPECS = {
    "temperature": ("Temperature (°C)", -10.0, 50.0, 0.5, "%.1f"),
    "humidity": ("Humidity (%)", 0.0, 100.0, 1.0, "%.0f"),
    "dew": ("Dew point (°C)", -25.0, 35.0, 0.5, "%.1f"),
    "precipitation": ("Precipitation (mm)", 0.0, 25.0, 0.1, "%.1f"),
    "wind_speed": ("Wind speed (km/h)", 0.0, 50.0, 0.5, "%.1f"),
    "wind_direction": ("Wind direction (°)", 0.0, 360.0, 5.0, "%.0f"),
    "pressure": ("Pressure (hPa)", 700.0, 1050.0, 1.0, "%.0f"),
    "solar_radiation": ("Solar radiation (W/m²)", 0.0, 1100.0, 10.0, "%.0f"),
}

PROFILE_METRICS = [
    ("No. of people (Temp+Perm)", "People", "%.0f"),
    ("Air Conditioners", "Air conditioners", "%.0f"),
    ("No. of rooms", "Rooms", "%.0f"),
]

PROFILE_TABLE_COLUMNS = [
    "No. of people (Temp+Perm)",
    "No. of Adults (14-60)",
    "No. of Children (0-13)",
    "Property Area (Marla)",
    "Covered Area",
    "No of Floors",
    "No. of rooms",
    "Air Conditioners",
    "Air Coolers",
    "Refrigerators",
    "Washing Machines",
    "Celling Fans",
    "Wall Fans",
    "Water Pumps",
    "Geysers",
    "Electric heaters",
    "UPS",
    "Build year of house",
    "Owner/Rented",
]


def _fmt(value, spec: str = "%.0f") -> str:
    if value is None:
        return "n/a"
    try:
        number = float(value)
    except (TypeError, ValueError):
        return str(value)
    if not np.isfinite(number):
        return "n/a"
    return spec % number


def _static_dict(profile: pd.Series) -> dict:
    static = {}
    for col in STATIC_NUMERIC_FEATURES:
        static[col] = profile[col]
    for col in STATIC_CATEGORICAL_FEATURES:
        static[col] = profile[col]
    return static


def run(root: str | Path | None = None) -> None:
    root = Path(root or Path(__file__).resolve().parents[1]).resolve()

    st.set_page_config(
        page_title="BijliCast - next-hour electricity forecast",
        page_icon="⚡",
        layout="wide",
    )

    try:
        service = get_service(str(root))
    except BijliCastError as exc:
        st.error(f"Deployment bundle error: {exc}")
        st.stop()
    except Exception as exc:  # noqa: BLE001 - surfaced in the UI
        st.error(f"Could not load the deployment bundle: {exc}")
        st.stop()

    model_info = service.model_info()
    houses = service.houses()
    by_house = {h["house_id"]: h for h in houses}

    st.title("⚡ BijliCast")
    st.caption(
        "Weather-aware next-hour household electricity forecast for Pakistan · "
        "LUMS REWD-P households + Open-Meteo ERA5 weather"
    )

    # ------------------------------------------------------------- sidebar
    with st.sidebar:
        st.header("Household")
        labels = {f"{h['house_id']} · {h['city']}": h["house_id"] for h in houses}
        choice = st.selectbox("Select a household", list(labels), index=0)
        house = labels[choice]
        context = by_house[house]
        city = context["city"]

        st.divider()
        st.subheader("Model")
        st.write(f"**{model_info['name']}**")
        if model_info["test_mae"] is not None:
            st.write(f"Held-out test MAE: **{model_info['test_mae']:.3f} kWh**")
        if model_info["test_r2"] is not None:
            st.write(f"Test R²: **{model_info['test_r2']:.3f}**")
        coverage = model_info["interval_val_coverage"]
        coverage_text = (
            f"{coverage:.0%} coverage" if coverage is not None else "coverage unavailable"
        )
        st.caption(
            f"Trained on {model_info['n_train_rows']:,} rows. "
            f"Prediction interval from validation residuals ({coverage_text})."
        )
        st.divider()
        st.caption(
            "Uses only current-hour weather and the last 168 h of usage. "
            "No next-hour weather is used, so the forecast does not depend on "
            "a perfect weather forecast."
        )

    # ------------------------------------------------------------- profile
    profile = service.profiles[service.profiles[HOUSE_COL] == house].iloc[0]

    c1, c2, c3, c4 = st.columns(4)
    c1.metric("City", city)
    for col, (source, label, spec) in zip(
        (c2, c3, c4), PROFILE_METRICS
    ):
        col.metric(label, _fmt(profile[source], spec))

    with st.expander("Household profile used by the model", expanded=False):
        table = pd.DataFrame(
            {
                house: [
                    profile[col] if pd.notna(profile[col]) else "n/a"
                    for col in PROFILE_TABLE_COLUMNS
                ]
            },
            index=PROFILE_TABLE_COLUMNS,
        ).astype(str)
        st.dataframe(table, width="stretch")

    # ------------------------------------------------------------- inputs
    origin = pd.Timestamp(context["origin_time"])
    st.subheader("Current-hour conditions")
    st.caption(
        f"Origin reading: **{origin:%Y-%m-%d %H:%M}** · "
        f"forecast target: **{origin + pd.Timedelta(hours=1):%Y-%m-%d %H:%M}**. "
        "Defaults are the last known weather for this household; adjust them to "
        "ask a what-if question."
    )

    defaults = context["defaults"]
    weather_inputs: dict[str, float] = {}
    keys = list(INPUT_WEATHER_FEATURES)
    for row_start in range(0, len(keys), 4):
        cols = st.columns(4)
        for col, key in zip(cols, keys[row_start : row_start + 4]):
            label, lo, hi, step, fmt = WEATHER_SPECS[key]
            default = min(max(defaults[key], lo), hi)
            weather_inputs[key] = col.number_input(
                label,
                min_value=lo,
                max_value=hi,
                value=default,
                step=step,
                format=fmt,
                key=f"w_{key}",
            )

    predict = st.button(
        "⚡ Predict next hour", type="primary", width="stretch"
    )

    if predict:
        try:
            result = service.predict(house, weather_inputs)
            st.session_state["result"] = result.to_dict()
        except Exception as exc:  # noqa: BLE001 - shown to the user
            st.error(f"Prediction failed: {exc}")
            st.stop()

    result = st.session_state.get("result")
    if result and result["house_id"] == house:
        r1, r2, r3 = st.columns(3)
        r1.metric(
            "Predicted next-hour energy", f"{result['prediction_kwh']:.3f} kWh"
        )
        r2.metric(
            "90% prediction interval",
            f"{result['interval_low_kwh']:.2f} – "
            f"{result['interval_high_kwh']:.2f} kWh",
        )
        r3.metric("Change vs last hour", f"{result['delta_kwh']:+.3f} kWh")

        st.subheader("Last 72 hours and the forecast")
        history = pd.DataFrame(result["history"])
        history[TIME_COL] = pd.to_datetime(history["time"])
        history = history.set_index(TIME_COL)["usage_kwh"]

        fig, ax = plt.subplots(figsize=(11, 3.4))
        ax.plot(
            history.index, history.to_numpy(), color="#1f77b4", lw=1.5,
            label="actual usage",
        )
        ax.axvline(
            origin, color="grey", ls="--", lw=1, label="origin (last reading)"
        )
        target = pd.Timestamp(result["target_time"])
        ax.errorbar(
            [target],
            [result["prediction_kwh"]],
            yerr=[
                [result["prediction_kwh"] - result["interval_low_kwh"]],
                [result["interval_high_kwh"] - result["prediction_kwh"]],
            ],
            fmt="o",
            color="#d62728",
            capsize=5,
            label="forecast (90% interval)",
        )
        ax.set_ylabel("kWh")
        ax.set_xlabel("datetime")
        ax.legend(loc="upper left", fontsize=8)
        ax.grid(alpha=0.3)
        fig.autofmt_xdate()
        st.pyplot(fig)
        plt.close(fig)

        test_mae = model_info["test_mae"]
        test_mae_text = f"{test_mae:.3f} kWh" if test_mae is not None else "n/a"
        coverage = model_info["interval_val_coverage"]
        coverage_text = (
            f"{coverage:.0%} coverage" if coverage is not None else "coverage unavailable"
        )
        st.caption(
            f"Model: {model_info['name']} · test MAE {test_mae_text} · "
            f"interval calibrated on validation residuals ({coverage_text})."
        )
    else:
        st.info(
            "Choose a household, adjust the weather if you like, then press "
            "**Predict next hour**."
        )

    st.divider()
    st.caption(
        "Data: LUMS REWD-P (59 households) and Open-Meteo ERA5 (6 cities). "
        "Predictions are for research/demo purposes, not billing or grid "
        "operations."
    )