File size: 8,839 Bytes
e63fa6f
ff7c80c
 
8f77f9f
 
e63fa6f
8f77f9f
6f5a567
e63fa6f
8f77f9f
ff7c80c
 
8f77f9f
 
 
f376eb0
ea99815
ff7c80c
8f77f9f
f376eb0
8f77f9f
 
 
 
e63fa6f
f376eb0
8f77f9f
e63fa6f
ff7c80c
 
 
8f77f9f
ff7c80c
 
f376eb0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6f5a567
 
 
ff7c80c
8f77f9f
 
 
 
f376eb0
6f5a567
8f77f9f
f376eb0
8f77f9f
 
 
f376eb0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6f5a567
 
f376eb0
 
6f5a567
f376eb0
 
 
 
 
 
 
 
 
 
8f77f9f
f376eb0
8f77f9f
f376eb0
 
8f77f9f
 
 
f376eb0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8f77f9f
f376eb0
 
e63fa6f
f376eb0
e63fa6f
8f77f9f
e63fa6f
8f77f9f
f376eb0
e63fa6f
8f77f9f
e63fa6f
8f77f9f
 
 
f376eb0
6f5a567
f376eb0
2c1b19a
 
 
dbf13db
f376eb0
2c1b19a
 
8f77f9f
e63fa6f
ff7c80c
8f77f9f
 
dbf13db
 
 
 
 
 
 
 
 
 
 
 
 
2c1b19a
 
 
 
 
8f77f9f
dbf13db
f376eb0
dbf13db
f376eb0
2c1b19a
 
dbf13db
2c1b19a
 
 
f376eb0
 
 
 
 
6f5a567
f376eb0
2c1b19a
 
 
f376eb0
2c1b19a
 
 
 
 
 
f376eb0
2c1b19a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8f77f9f
 
2c1b19a
 
 
 
 
 
8f77f9f
 
 
 
 
f37bb94
41859c4
 
f376eb0
41859c4
 
 
f376eb0
f37bb94
f5e0831
 
f376eb0
 
41859c4
 
 
 
 
 
 
 
 
 
 
 
f5e0831
 
41859c4
 
 
 
 
 
 
f376eb0
41859c4
 
f376eb0
f37bb94
 
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
284
285
286
287
288
289
290
291
292
import gradio as gr
import pandas as pd
import matplotlib.pyplot as plt
import tempfile
import hopsworks
from xgboost import XGBRegressor
from datetime import datetime, timedelta
import numpy as np

from airquality.util import plot_air_quality_forecast


# -------------------------
# HOPSWORKS LOGIN + MODEL LOAD
# -------------------------
def load_resources_v1():
    project = hopsworks.login()
    fs = project.get_feature_store()

    fv = fs.get_feature_view("air_quality_fv", version=1)
    fv.init_batch_scoring(1)

    weather_fg = fs.get_feature_group("weather", 1)

    mr = project.get_model_registry()
    model_obj = mr.get_model("air_quality_xgboost_model", version=1)
    model_dir = model_obj.download()

    model = XGBRegressor()
    model.load_model(model_dir + "/model.json")

    return model, fv, weather_fg, project


def load_resources_v2():
    project = hopsworks.login()
    fs = project.get_feature_store()

    fv = fs.get_feature_view("air_quality_fv", version=2)
    fv.init_batch_scoring(1)

    weather_fg = fs.get_feature_group("weather", 1)

    mr = project.get_model_registry()
    model_obj = mr.get_model("air_quality_xgboost_model", version=2)
    model_dir = model_obj.download()

    model = XGBRegressor()
    model.load_model(model_dir + "/model.json")

    return model, fv, weather_fg, project

resources_v1 = load_resources_v1()
resources_v2 = load_resources_v2()



# -------------------------
# FORECAST LOGIC (NEXT 7 DAYS)
# -------------------------
def generate_forecast_v1(days):
    model, fv, weather_fg, project = resources_v1

    today = datetime.utcnow().date()
    df_future = weather_fg.read()
    df_future["date"] = pd.to_datetime(df_future["date"]).dt.date

    predictions = []
    for offset in range(1, days + 1):
        target_date = today + timedelta(days=offset)
        row = df_future[df_future["date"] == target_date]

        if len(row) == 0:
            continue

        X = row[["temperature_2m_mean", "precipitation_sum",
                 "wind_speed_10m_max", "wind_direction_10m_dominant"]]

        pred = float(model.predict(X)[0])

        predictions.append({"date": target_date, "predicted_pm25": pred})

    df_preds = pd.DataFrame(predictions)

    tmp_path = tempfile.NamedTemporaryFile(suffix=".png", delete=False).name
    plot_air_quality_forecast("linkoping", "hamngatan-10", df_preds, tmp_path)

    return tmp_path


def generate_forecast_v2(days):
    model, fv, weather_fg, project = resources_v2

    today = datetime.utcnow().date()
    df_future = weather_fg.read().sort_values("date")
    df_future["date"] = pd.to_datetime(df_future["date"]).dt.date

    # Load real PM2.5 history
    aq_fg = project.get_feature_store().get_feature_group("air_quality", version=1)
    hist_pm25 = aq_fg.read().sort_values("date")
    pm25_history = list(hist_pm25["pm25"].values[-3:])

    preds = []
    for offset in range(1, days + 1):

        target_date = today + timedelta(days=offset)
        row = df_future[df_future["date"] == target_date]
        if len(row) == 0:
            continue

        lag1, lag2, lag3 = pm25_history[-1], pm25_history[-2], pm25_history[-3]
        roll_mean = np.mean(pm25_history[-3:])
        roll_std = np.std(pm25_history[-3:])

        X = pd.DataFrame({
            "temperature_2m_mean": [row.iloc[0]["temperature_2m_mean"]],
            "precipitation_sum": [row.iloc[0]["precipitation_sum"]],
            "wind_speed_10m_max": [row.iloc[0]["wind_speed_10m_max"]],
            "wind_direction_10m_dominant": [row.iloc[0]["wind_direction_10m_dominant"]],
            "pm25_lag1": [lag1],
            "pm25_lag2": [lag2],
            "pm25_lag3": [lag3],
            "pm25_roll3_mean": [roll_mean],
            "pm25_roll3_std": [roll_std],
        })

        pred = float(model.predict(X)[0])
        preds.append({"date": target_date, "predicted_pm25": pred})

        pm25_history.append(pred)

    df_preds = pd.DataFrame(preds)

    tmp_path = tempfile.NamedTemporaryFile(suffix=".png", delete=False).name
    plot_air_quality_forecast("linkoping", "hamngatan-10", df_preds, tmp_path)

    return tmp_path

# -------------------------
# HINDCAST LOGIC (LAST 7 DAYS)
# -------------------------
def generate_hindcast_v1(days):
    model, fv, weather_fg, project = resources_v1

    start_date = datetime.utcnow().date() - timedelta(days=days)
    end_date = datetime.utcnow().date()

    # 1. Read weather + feature view data (for prediction)
    features_df, labels_df = fv.training_data(
        start_time=start_date,
        end_time=end_date,
        statistics_config=False
    )

    features_df["date"] = pd.to_datetime(features_df["date"]).dt.date

    # 2. Load ACTUAL PM2.5 values for the same time range
    aq_fg = project.get_feature_store().get_feature_group("air_quality", version=1)
    aq_df = aq_fg.read()
    aq_df["date"] = pd.to_datetime(aq_df["date"]).dt.date

    # Reduce to matching period
    aq_df = aq_df[(aq_df["date"] >= start_date) & (aq_df["date"] <= end_date)]

    # 3. Merge actual pm25 onto features_df
    merged = pd.merge(features_df, aq_df[["date", "pm25"]], on="date", how="inner")

    # 4. Predict using v1 model
    X = merged[[
        "temperature_2m_mean", 
        "precipitation_sum",
        "wind_speed_10m_max", 
        "wind_direction_10m_dominant"
    ]]

    merged["predicted_pm25"] = model.predict(X)

    # 5. Plot
    tmp_path = tempfile.NamedTemporaryFile(suffix=".png", delete=False).name
    plot_air_quality_forecast(
        "linkoping", "hamngatan-10",
        merged,
        tmp_path,
        hindcast=True
    )

    return tmp_path


def generate_hindcast_v2(days):
    model, fv, weather_fg, project = resources_v2

    # Time window
    start_date = datetime.utcnow().date() - timedelta(days=days + 3)
    end_date = datetime.utcnow().date()

    # Load weather history
    weather_df = weather_fg.read()
    weather_df["date"] = pd.to_datetime(weather_df["date"]).dt.date
    weather_df = weather_df[(weather_df["date"] >= start_date) &
                            (weather_df["date"] <= end_date)]
    weather_df = weather_df.sort_values("date")

    # Load PM2.5 history (actual values, not predictions)
    aq_fg = project.get_feature_store().get_feature_group("air_quality", version=1)
    aq_df = aq_fg.read()
    aq_df["date"] = pd.to_datetime(aq_df["date"]).dt.date
    aq_df = aq_df[(aq_df["date"] >= start_date) &
                  (aq_df["date"] <= end_date)]
    aq_df = aq_df.sort_values("date")

    # Merge actual historical PM2.5 + weather
    df = pd.merge(weather_df, aq_df, on="date")

    # Build lag features
    df["pm25_lag1"] = df["pm25"].shift(1)
    df["pm25_lag2"] = df["pm25"].shift(2)
    df["pm25_lag3"] = df["pm25"].shift(3)
    df["pm25_roll3_mean"] = df["pm25"].rolling(3).mean()
    df["pm25_roll3_std"] = df["pm25"].rolling(3).std()

    # Only keep the last N days (where all lags exist)
    df = df.dropna().tail(days)

    # Features for model v2
    X = df[[
        "temperature_2m_mean",
        "precipitation_sum",
        "wind_speed_10m_max",
        "wind_direction_10m_dominant",
        "pm25_lag1",
        "pm25_lag2",
        "pm25_lag3",
        "pm25_roll3_mean",
        "pm25_roll3_std",
    ]]

    df["predicted_pm25"] = model.predict(X)

    tmp_path = tempfile.NamedTemporaryFile(suffix=".png", delete=False).name
    plot_air_quality_forecast(
        "linkoping", "hamngatan-10",
        df,
        tmp_path,
        hindcast=True
    )

    return tmp_path



with gr.Blocks() as iface:
    
    gr.Markdown("# Air Quality Dashboard (Model v1 & Model v2)")

    with gr.Row():
        gr.Markdown("### **Model v1 (No lag features)**")
        gr.Markdown("### **Model v2 (Lag-aware)**")

    with gr.Row():
        days_v1_f = gr.Slider(3, 10, value=7, step=1, label="Forecast Days (v1)")
        days_v2_f = gr.Slider(3, 10, value=7, step=1, label="Forecast Days (v2)")

    with gr.Row():
        btn_v1_f = gr.Button("Generate Forecast (v1)")
        btn_v2_f = gr.Button("Generate Forecast (v2)")

    out_v1_f = gr.Image()
    out_v2_f = gr.Image()

    btn_v1_f.click(generate_forecast_v1, inputs=days_v1_f, outputs=out_v1_f)
    btn_v2_f.click(generate_forecast_v2, inputs=days_v2_f, outputs=out_v2_f)


    # HINDCAST
    with gr.Row():
        days_v1_h = gr.Slider(3, 10, value=7, step=1, label="Hindcast Days (v1)")
        days_v2_h = gr.Slider(3, 10, value=7, step=1, label="Hindcast Days (v2)")

    with gr.Row():
        btn_v1_h = gr.Button("Generate Hindcast (v1)")
        btn_v2_h = gr.Button("Generate Hindcast (v2)")

    out_v1_h = gr.Image()
    out_v2_h = gr.Image()

    btn_v1_h.click(generate_hindcast_v1, inputs=days_v1_h, outputs=out_v1_h)
    btn_v2_h.click(generate_hindcast_v2, inputs=days_v2_h, outputs=out_v2_h)


iface.launch()