Delete app.py
Browse files
app.py
DELETED
|
@@ -1,221 +0,0 @@
|
|
| 1 |
-
"""Gradio interface for the DWDM KPI Linear Regression Trend Forecast.
|
| 2 |
-
|
| 3 |
-
Wraps the forecast logic of Trend.ipynb in a web UI: the user uploads an
|
| 4 |
-
Optical Power Report (.xlsx), types the Receiver Optical Power Sensitivity and
|
| 5 |
-
gets back the fitted trend, the crossing date and the forecast graphs.
|
| 6 |
-
"""
|
| 7 |
-
|
| 8 |
-
import os
|
| 9 |
-
from datetime import datetime, timedelta
|
| 10 |
-
|
| 11 |
-
import gradio as gr
|
| 12 |
-
import matplotlib
|
| 13 |
-
import numpy as np
|
| 14 |
-
import pandas as pd
|
| 15 |
-
from sklearn.linear_model import LinearRegression
|
| 16 |
-
|
| 17 |
-
matplotlib.use("Agg") # No GUI backend: figures are handed to Gradio, not shown
|
| 18 |
-
import matplotlib.pyplot as plt
|
| 19 |
-
|
| 20 |
-
FMT = "%m/%d/%Y %H:%M:%S"
|
| 21 |
-
DEFAULT_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)),
|
| 22 |
-
"Historical_Performance.xlsx")
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
def read_report(dataset):
|
| 26 |
-
"""Read an Optical Power Report and return its timestamps and values sorted in time.
|
| 27 |
-
|
| 28 |
-
Expects the columns "End Time" (m/d/Y H:M:S) and "Value" produced by the NMS.
|
| 29 |
-
Raises gr.Error with a readable reason when the file cannot be parsed.
|
| 30 |
-
"""
|
| 31 |
-
try:
|
| 32 |
-
f = pd.read_excel(dataset)
|
| 33 |
-
except Exception as e:
|
| 34 |
-
raise gr.Error(f"The Excel File could not be read because: {e!r}")
|
| 35 |
-
|
| 36 |
-
for column in ("End Time", "Value"):
|
| 37 |
-
if column not in f.columns:
|
| 38 |
-
raise gr.Error(
|
| 39 |
-
f'The Excel File has no "{column}" column. '
|
| 40 |
-
f"Columns found: {', '.join(map(str, f.columns))}"
|
| 41 |
-
)
|
| 42 |
-
|
| 43 |
-
try:
|
| 44 |
-
timestamps = [datetime.strptime(str(t).strip(), FMT) for t in f["End Time"]]
|
| 45 |
-
except ValueError:
|
| 46 |
-
# The NMS export is usually plain text, but pandas may already have
|
| 47 |
-
# typed the column as datetime, in which case FMT no longer matches.
|
| 48 |
-
try:
|
| 49 |
-
timestamps = pd.to_datetime(f["End Time"]).dt.to_pydatetime().tolist()
|
| 50 |
-
except Exception as e:
|
| 51 |
-
raise gr.Error(f'The "End Time" column could not be parsed because: {e!r}')
|
| 52 |
-
|
| 53 |
-
try:
|
| 54 |
-
values = pd.to_numeric(f["Value"]).tolist()
|
| 55 |
-
except Exception as e:
|
| 56 |
-
raise gr.Error(f'The "Value" column could not be parsed because: {e!r}')
|
| 57 |
-
|
| 58 |
-
if len(timestamps) < 2:
|
| 59 |
-
raise gr.Error("At least 2 samples are needed to fit a trend.")
|
| 60 |
-
|
| 61 |
-
order = np.argsort(timestamps) # the report is not guaranteed to be chronological
|
| 62 |
-
timestamps = [timestamps[i] for i in order]
|
| 63 |
-
values = [values[i] for i in order]
|
| 64 |
-
return timestamps, values
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
def observed_figure(timestamps, values):
|
| 68 |
-
"""Scatter plot of the raw KPI samples."""
|
| 69 |
-
fig, ax = plt.subplots(figsize=(8, 4.5))
|
| 70 |
-
ax.scatter(timestamps, values, label="Observed")
|
| 71 |
-
ax.set_xlabel("Time")
|
| 72 |
-
ax.set_ylabel("Value")
|
| 73 |
-
ax.set_title("Observed KPI")
|
| 74 |
-
ax.legend()
|
| 75 |
-
fig.autofmt_xdate()
|
| 76 |
-
fig.tight_layout()
|
| 77 |
-
return fig
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
def fit_figure(timestamps, values, x, w, b):
|
| 81 |
-
"""Scatter plot of the samples with the fitted regression line on top."""
|
| 82 |
-
fig, ax = plt.subplots(figsize=(8, 4.5))
|
| 83 |
-
ax.scatter(timestamps, values, label="Observed")
|
| 84 |
-
ax.plot([timestamps[0], timestamps[-1]],
|
| 85 |
-
[x[0][0] * w + b, x[-1][0] * w + b],
|
| 86 |
-
color="tab:orange", label="Fit")
|
| 87 |
-
ax.set_xlabel("Time")
|
| 88 |
-
ax.set_ylabel("Value")
|
| 89 |
-
ax.set_title("Linear Regression Fit")
|
| 90 |
-
ax.legend()
|
| 91 |
-
fig.autofmt_xdate()
|
| 92 |
-
fig.tight_layout()
|
| 93 |
-
return fig
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
def forecast_figure(timestamps, values, x, w, b, sensitivity, t0,
|
| 97 |
-
x_at_threshold, predicted_date):
|
| 98 |
-
"""Fit extended up to the threshold crossing, with the crossing point marked."""
|
| 99 |
-
fig, ax = plt.subplots(figsize=(8, 4.5))
|
| 100 |
-
if x_at_threshold is None:
|
| 101 |
-
x_start, x_end = x[0][0], x[-1][0]
|
| 102 |
-
else:
|
| 103 |
-
x_start = min(x[0][0], x_at_threshold)
|
| 104 |
-
x_end = max(x[-1][0], x_at_threshold)
|
| 105 |
-
lx = np.linspace(x_start, x_end, 100)
|
| 106 |
-
ld = [t0 + timedelta(days=float(d)) for d in lx]
|
| 107 |
-
ax.scatter(timestamps, values, label="Observed")
|
| 108 |
-
ax.plot(ld, w * lx + b, color="tab:orange", label="Fit")
|
| 109 |
-
ax.axhline(sensitivity, linestyle="--", color="tab:red", label="Threshold")
|
| 110 |
-
if predicted_date is not None:
|
| 111 |
-
ax.scatter([predicted_date], [sensitivity], marker="X", s=120,
|
| 112 |
-
color="red", zorder=5, label="Crossing")
|
| 113 |
-
ax.set_xlabel("Time")
|
| 114 |
-
ax.set_ylabel("Value")
|
| 115 |
-
ax.set_title("Trend Forecast")
|
| 116 |
-
ax.legend()
|
| 117 |
-
fig.autofmt_xdate()
|
| 118 |
-
fig.tight_layout()
|
| 119 |
-
return fig
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
def forecast(dataset, sensitivity):
|
| 123 |
-
"""Fit y = wx + b over the report and predict when the KPI reaches the sensitivity.
|
| 124 |
-
|
| 125 |
-
Returns the summary in Markdown plus the observed, fit and forecast figures.
|
| 126 |
-
"""
|
| 127 |
-
if dataset is None:
|
| 128 |
-
raise gr.Error("Please upload an Optical Power Report (.xlsx) first.")
|
| 129 |
-
if sensitivity is None:
|
| 130 |
-
raise gr.Error("Please enter the Receiver Optical Power Sensitivity.")
|
| 131 |
-
|
| 132 |
-
plt.close("all")
|
| 133 |
-
timestamps, values = read_report(dataset)
|
| 134 |
-
|
| 135 |
-
t0 = timestamps[0]
|
| 136 |
-
x = np.array([(t - t0).total_seconds() / 86400.0
|
| 137 |
-
for t in timestamps]).reshape(-1, 1)
|
| 138 |
-
y = np.array(values)
|
| 139 |
-
|
| 140 |
-
lr = LinearRegression()
|
| 141 |
-
lr.fit(x, y)
|
| 142 |
-
w = lr.coef_[0]
|
| 143 |
-
b = lr.intercept_
|
| 144 |
-
r2 = lr.score(x, y)
|
| 145 |
-
|
| 146 |
-
x_at_threshold = None
|
| 147 |
-
predicted_date = None
|
| 148 |
-
if w == 0:
|
| 149 |
-
verdict = f"The trend is flat, the KPI will never reach **{sensitivity}**."
|
| 150 |
-
else:
|
| 151 |
-
x_at_threshold = (sensitivity - b) / w
|
| 152 |
-
predicted_date = t0 + timedelta(days=x_at_threshold)
|
| 153 |
-
if predicted_date < timestamps[-1]:
|
| 154 |
-
verdict = (f"The KPI already crossed **{sensitivity}** on "
|
| 155 |
-
f"**{predicted_date.strftime(FMT)}** "
|
| 156 |
-
f"(the crossing is inside the observed window).")
|
| 157 |
-
else:
|
| 158 |
-
days_ahead = (predicted_date - timestamps[-1]).total_seconds() / 86400.0
|
| 159 |
-
verdict = (f"The KPI will reach **{sensitivity}** at "
|
| 160 |
-
f"**{predicted_date.strftime(FMT)}** "
|
| 161 |
-
f"({days_ahead:,.2f} days after the last sample).")
|
| 162 |
-
|
| 163 |
-
summary = "\n".join([
|
| 164 |
-
f"- **Samples:** {len(values)}",
|
| 165 |
-
f"- **Observed window:** {timestamps[0].strftime(FMT)} "
|
| 166 |
-
f"to {timestamps[-1].strftime(FMT)}",
|
| 167 |
-
f"- **Slope (w):** {w:.6f} units/day",
|
| 168 |
-
f"- **Bias (b):** {b:.6f}",
|
| 169 |
-
f"- **R²:** {r2:.4f}",
|
| 170 |
-
"",
|
| 171 |
-
verdict,
|
| 172 |
-
])
|
| 173 |
-
|
| 174 |
-
return (summary,
|
| 175 |
-
observed_figure(timestamps, y),
|
| 176 |
-
fit_figure(timestamps, y, x, w, b),
|
| 177 |
-
forecast_figure(timestamps, y, x, w, b, sensitivity, t0,
|
| 178 |
-
x_at_threshold, predicted_date))
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
with gr.Blocks(title="DWDM KPI Trend Forecast") as demo:
|
| 182 |
-
gr.Markdown(
|
| 183 |
-
"# Linear Regression Trend Forecast for DWDM KPI's\n"
|
| 184 |
-
"Upload an Optical Power Report (.xlsx with the columns **End Time** and "
|
| 185 |
-
"**Value**), enter the Receiver Optical Power Sensitivity and get the "
|
| 186 |
-
"forecast of when the Optical Power will reach it."
|
| 187 |
-
)
|
| 188 |
-
|
| 189 |
-
with gr.Row():
|
| 190 |
-
with gr.Column(scale=1):
|
| 191 |
-
dataset = gr.File(
|
| 192 |
-
label="Optical Power Report (.xlsx)",
|
| 193 |
-
file_types=[".xlsx", ".xls"],
|
| 194 |
-
type="filepath",
|
| 195 |
-
value=DEFAULT_FILE if os.path.exists(DEFAULT_FILE) else None,
|
| 196 |
-
)
|
| 197 |
-
sensitivity = gr.Number(
|
| 198 |
-
label="Receiver Optical Power Sensitivity",
|
| 199 |
-
value=-28.0,
|
| 200 |
-
step=0.1,
|
| 201 |
-
)
|
| 202 |
-
run = gr.Button("Forecast", variant="primary")
|
| 203 |
-
with gr.Column(scale=2):
|
| 204 |
-
summary = gr.Markdown(label="Result")
|
| 205 |
-
|
| 206 |
-
with gr.Tabs():
|
| 207 |
-
with gr.Tab("Forecast"):
|
| 208 |
-
forecast_plot = gr.Plot(label="Trend Forecast")
|
| 209 |
-
with gr.Tab("Fit"):
|
| 210 |
-
fit_plot = gr.Plot(label="Linear Regression Fit")
|
| 211 |
-
with gr.Tab("Observed"):
|
| 212 |
-
observed_plot = gr.Plot(label="Observed KPI")
|
| 213 |
-
|
| 214 |
-
run.click(
|
| 215 |
-
fn=forecast,
|
| 216 |
-
inputs=[dataset, sensitivity],
|
| 217 |
-
outputs=[summary, observed_plot, fit_plot, forecast_plot],
|
| 218 |
-
)
|
| 219 |
-
|
| 220 |
-
if __name__ == "__main__":
|
| 221 |
-
demo.launch()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|