# app.py — ST_Log_GR (Gamma Ray) — UI aligned with TS/Tc apps
import io, json, os, base64, math
from pathlib import Path
import streamlit as st
import pandas as pd
import numpy as np
import joblib
from datetime import datetime
# Matplotlib (static plots: preview, cross-plot)
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from matplotlib.ticker import FuncFormatter
import plotly.graph_objects as go
from sklearn.metrics import mean_squared_error, mean_absolute_error
# =========================
# Constants (GR)
# =========================
APP_NAME = "ST_Log_GR"
TAGLINE = "Real-Time Gamma Ray Prediction"
FEATURES = ["GPM", "SPP", "RPM", "WOB", "T", "ROP"]
# Target used during training
TARGET = "log(GR)" # set to your training target column name if different
# Inverse transform used to map predictions/target back to API
TARGET_TRANSFORM = "log10" # "log10" for log10(GR); "ln" for ln(GR); "none" for raw
# Column with actual GR in API units (if present)
ACTUAL_COL = "GR"
MODELS_DIR = Path("models")
DEFAULT_MODEL = MODELS_DIR / "gr_rf.joblib"
MODEL_FALLBACKS = [MODELS_DIR / "model.joblib", MODELS_DIR / "model.pkl"]
COLORS = {"pred": "#1f77b4", "actual": "#f2b702", "ref": "#5a5a5a"}
# ---- Plot sizing controls ----
CROSS_W = 350
CROSS_H = 350
TRACK_H = 1000
TRACK_W = 500
FONT_SZ = 13
BOLD_FONT = "Arial Black, Arial, sans-serif"
# =========================
# Page / CSS
# =========================
st.set_page_config(page_title=APP_NAME, page_icon="logo.png", layout="wide")
st.markdown("""
""", unsafe_allow_html=True)
TABLE_CENTER_CSS = [
dict(selector="th", props=[("text-align", "center")]),
dict(selector="td", props=[("text-align", "center")]),
]
# =========================
# Password gate
# =========================
def inline_logo(path="logo.png") -> str:
try:
p = Path(path)
if not p.exists(): return ""
return f"data:image/png;base64,{base64.b64encode(p.read_bytes()).decode('ascii')}"
except Exception:
return ""
def add_password_gate() -> None:
try:
required = st.secrets.get("APP_PASSWORD", "")
except Exception:
required = os.environ.get("APP_PASSWORD", "")
if not required:
st.warning("Set APP_PASSWORD in Secrets (or environment) and restart.")
st.stop()
if st.session_state.get("auth_ok", False):
return
st.sidebar.markdown(f"""
{APP_NAME}
Smart Thinking • Secure Access
""", unsafe_allow_html=True
)
pwd = st.sidebar.text_input("Access key", type="password", placeholder="••••••••")
if st.sidebar.button("Unlock", type="primary"):
if pwd == required:
st.session_state.auth_ok = True
st.rerun()
else:
st.error("Incorrect key.")
st.stop()
add_password_gate()
# =========================
# Utilities
# =========================
def rmse(y_true, y_pred) -> float:
return float(np.sqrt(mean_squared_error(y_true, y_pred)))
def pearson_r(y_true, y_pred) -> float:
a = np.asarray(y_true, dtype=float)
p = np.asarray(y_pred, dtype=float)
if a.size < 2 or np.all(a == a[0]) or np.all(p == p[0]): return float("nan")
return float(np.corrcoef(a, p)[0, 1])
@st.cache_resource(show_spinner=False)
def load_model(model_path: str):
return joblib.load(model_path)
@st.cache_data(show_spinner=False)
def parse_excel(data_bytes: bytes):
bio = io.BytesIO(data_bytes)
xl = pd.ExcelFile(bio)
return {sh: xl.parse(sh) for sh in xl.sheet_names}
def read_book_bytes(b: bytes):
return parse_excel(b) if b else {}
def normalize_df(df: pd.DataFrame) -> pd.DataFrame:
out = df.copy()
out.columns = [str(c).strip().replace(" ", " ") for c in out.columns]
return out
def ensure_cols(df: pd.DataFrame, cols: list[str]) -> bool:
miss = [c for c in cols if c not in df.columns]
if miss:
st.error(f"Missing columns: {miss}\nFound: {list(df.columns)}")
return False
return True
def find_sheet(book, names):
low2orig = {k.lower(): k for k in book.keys()}
for nm in names:
if nm.lower() in low2orig: return low2orig[nm.lower()]
return None
def _nice_tick0(xmin: float, step: int = 5) -> float:
return step * math.floor(xmin / step) if np.isfinite(xmin) else xmin
def df_centered_rounded(df: pd.DataFrame, hide_index=True):
out = df.copy()
numcols = out.select_dtypes(include=[np.number]).columns
styler = (
out.style
.format({c: "{:.2f}" for c in numcols})
.set_properties(**{"text-align": "center"})
.set_table_styles(TABLE_CENTER_CSS)
)
st.dataframe(styler, use_container_width=True, hide_index=hide_index)
# --- target transform helpers (to support models trained on log(GR)) ---
def inverse_target(x: np.ndarray, transform: str) -> np.ndarray:
t = (transform or "none").lower()
if t in ["log10", "log_10", "log10()"]:
return np.power(10.0, x)
if t in ["ln", "log", "log_e", "natural"]:
return np.exp(x)
return x # "none"
def to_actual_series(df: pd.DataFrame, target_col: str, actual_col_hint: str, transform: str) -> pd.Series:
# Prefer explicit GR column if available; else invert target
if actual_col_hint and actual_col_hint in df.columns:
return pd.Series(df[actual_col_hint], dtype=float)
if target_col in df.columns:
return pd.Series(inverse_target(np.asarray(df[target_col], dtype=float), transform), dtype=float)
if "GR" in df.columns:
return pd.Series(df["GR"], dtype=float)
raise ValueError("Cannot find actual GR column or target to invert.")
# === Excel export helpers (TS/Tc-style multiselect) =======================
def _excel_engine() -> str:
try:
import xlsxwriter # noqa: F401
return "xlsxwriter"
except Exception:
return "openpyxl"
def _excel_safe_name(name: str) -> str:
bad = '[]:*?/\\'
safe = ''.join('_' if ch in bad else ch for ch in str(name))
return safe[:31]
def _round_numeric(df: pd.DataFrame, ndigits: int = 2) -> pd.DataFrame:
out = df.copy()
for c in out.columns:
if pd.api.types.is_float_dtype(out[c]) or pd.api.types.is_integer_dtype(out[c]):
out[c] = pd.to_numeric(out[c], errors="coerce").round(ndigits)
return out
def _summary_table(df: pd.DataFrame, cols: list[str]) -> pd.DataFrame:
cols = [c for c in cols if c in df.columns]
if not cols: return pd.DataFrame()
tbl = (df[cols]
.agg(['min','max','mean','std'])
.T.rename(columns={"min":"Min","max":"Max","mean":"Mean","std":"Std"})
.reset_index(names="Field"))
return _round_numeric(tbl, 2)
def _train_ranges_df(ranges: dict[str, tuple[float, float]]) -> pd.DataFrame:
if not ranges: return pd.DataFrame()
df = pd.DataFrame(ranges).T.reset_index()
df.columns = ["Feature", "Min", "Max"]
return _round_numeric(df, 2)
def _excel_autofit(writer, sheet_name: str, df: pd.DataFrame, min_w: int = 8, max_w: int = 40):
try:
import xlsxwriter # noqa: F401
except Exception:
return
ws = writer.sheets[sheet_name]
for i, col in enumerate(df.columns):
series = df[col].astype(str)
max_len = max([len(str(col))] + series.map(len).tolist())
ws.set_column(i, i, max(min_w, min(max_len + 2, max_w)))
ws.freeze_panes(1, 0)
def _available_sections() -> list[str]:
res = st.session_state.get("results", {})
sections = []
if "Train" in res: sections += ["Training","Training_Metrics","Training_Summary"]
if "Test" in res: sections += ["Testing","Testing_Metrics","Testing_Summary"]
if "Validate" in res: sections += ["Validation","Validation_Metrics","Validation_Summary","Validation_OOR"]
if "PredictOnly" in res: sections += ["Prediction","Prediction_Summary","Prediction_OOR"]
if st.session_state.get("train_ranges"): sections += ["Training_Ranges"]
sections += ["Info"]
return sections
def build_export_workbook(selected: list[str], ndigits: int = 2, do_autofit: bool = True) -> tuple[bytes|None, str|None, list[str]]:
res = st.session_state.get("results", {})
if not res: return None, None, []
sheets: dict[str, pd.DataFrame] = {}
order: list[str] = []
# Training
if "Training" in selected and "Train" in res:
sheets["Training"] = _round_numeric(res["Train"], ndigits); order.append("Training")
if "Training_Metrics" in selected and res.get("m_train"):
sheets["Training_Metrics"] = _round_numeric(pd.DataFrame([res["m_train"]]), ndigits); order.append("Training_Metrics")
if "Training_Summary" in selected and "Train" in res:
tr_cols = FEATURES + [c for c in ["GR_Actual","GR_Pred"] if c in res["Train"].columns]
s = _summary_table(res["Train"], tr_cols)
if not s.empty:
sheets["Training_Summary"] = s; order.append("Training_Summary")
# Testing
if "Testing" in selected and "Test" in res:
sheets["Testing"] = _round_numeric(res["Test"], ndigits); order.append("Testing")
if "Testing_Metrics" in selected and res.get("m_test"):
sheets["Testing_Metrics"] = _round_numeric(pd.DataFrame([res["m_test"]]), ndigits); order.append("Testing_Metrics")
if "Testing_Summary" in selected and "Test" in res:
te_cols = FEATURES + [c for c in ["GR_Actual","GR_Pred"] if c in res["Test"].columns]
s = _summary_table(res["Test"], te_cols)
if not s.empty:
sheets["Testing_Summary"] = s; order.append("Testing_Summary")
# Validation
if "Validation" in selected and "Validate" in res:
sheets["Validation"] = _round_numeric(res["Validate"], ndigits); order.append("Validation")
if "Validation_Metrics" in selected and res.get("m_val"):
sheets["Validation_Metrics"] = _round_numeric(pd.DataFrame([res["m_val"]]), ndigits); order.append("Validation_Metrics")
if "Validation_Summary" in selected and res.get("sv_val"):
sheets["Validation_Summary"] = _round_numeric(pd.DataFrame([res["sv_val"]]), ndigits); order.append("Validation_Summary")
if "Validation_OOR" in selected and isinstance(res.get("oor_tbl"), pd.DataFrame) and not res["oor_tbl"].empty:
sheets["Validation_OOR"] = _round_numeric(res["oor_tbl"].reset_index(drop=True), ndigits); order.append("Validation_OOR")
# Prediction
if "Prediction" in selected and "PredictOnly" in res:
sheets["Prediction"] = _round_numeric(res["PredictOnly"], ndigits); order.append("Prediction")
if "Prediction_Summary" in selected and res.get("sv_pred"):
sheets["Prediction_Summary"] = _round_numeric(pd.DataFrame([res["sv_pred"]]), ndigits); order.append("Prediction_Summary")
if "Prediction_OOR" in selected and isinstance(res.get("oor_tbl_pred"), pd.DataFrame) and not res["oor_tbl_pred"].empty:
sheets["Prediction_OOR"] = _round_numeric(res["oor_tbl_pred"].reset_index(drop=True), ndigits); order.append("Prediction_OOR")
# Training ranges
if "Training_Ranges" in selected and st.session_state.get("train_ranges"):
sheets["Training_Ranges"] = _train_ranges_df(st.session_state["train_ranges"]); order.append("Training_Ranges")
# Info
if "Info" in selected:
info = pd.DataFrame([
{"Key": "AppName", "Value": APP_NAME},
{"Key": "Tagline", "Value": TAGLINE},
{"Key": "Target", "Value": TARGET},
{"Key": "TargetTransform", "Value": TARGET_TRANSFORM},
{"Key": "ActualColumn", "Value": ACTUAL_COL},
{"Key": "Features", "Value": ", ".join(FEATURES)},
{"Key": "ExportedAt", "Value": datetime.now().strftime("%Y-%m-%d %H:%M:%S")},
])
sheets["Info"] = info; order.append("Info")
if not order: return None, None, []
bio = io.BytesIO()
engine = _excel_engine()
with pd.ExcelWriter(bio, engine=engine) as writer:
for name in order:
df = sheets[name]
sheet = _excel_safe_name(name)
df.to_excel(writer, sheet_name=sheet, index=False)
_excel_autofit(writer, sheet, df)
bio.seek(0)
fname = f"GR_Export_{datetime.now().strftime('%Y%m%d_%H%M%S')}.xlsx"
return bio.getvalue(), fname, order
def render_export_button(phase_key: str) -> None:
res = st.session_state.get("results", {})
if not res: return
st.divider()
st.markdown("### Export to Excel")
options = _available_sections()
selected_sheets = st.multiselect(
"Sheets to include",
options=options,
default=[],
placeholder="Choose option(s)",
help="Pick the sheets you want to include in the Excel export.",
key=f"sheets_{phase_key}",
)
if not selected_sheets:
st.caption("Select one or more sheets above to enable the export.")
st.download_button("⬇️ Export Excel", data=b"", file_name="GR_Export.xlsx",
mime="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
disabled=True, key=f"download_{phase_key}")
return
data, fname, names = build_export_workbook(selected=selected_sheets, ndigits=2, do_autofit=True)
if names:
st.caption("Will include: " + ", ".join(names))
st.download_button(
"⬇️ Export Excel",
data=(data or b""),
file_name=(fname or "GR_Export.xlsx"),
mime="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
disabled=(data is None),
key=f"download_{phase_key}",
)
# =========================
# Cross plot (Matplotlib)
# =========================
def _nice_bounds(arr_min, arr_max, n_ticks=6):
if not np.isfinite(arr_min) or not np.isfinite(arr_max):
return 0.0, 100.0, 20.0
span = arr_max - arr_min
if span <= 0:
return max(arr_min-5, 0), arr_max+5, 5.0
raw_step = span / max(n_ticks, 1)
mag = 10 ** math.floor(math.log10(raw_step))
steps = np.array([1, 2, 2.5, 5, 10]) * mag
step = steps[np.argmin(np.abs(steps - raw_step))]
lo = step * math.floor(arr_min / step)
hi = step * math.ceil(arr_max / step)
return float(lo), float(hi), float(step)
def cross_plot_static(actual, pred):
a = pd.Series(actual, dtype=float)
p = pd.Series(pred, dtype=float)
lo = min(a.min(), p.min())
hi = max(a.max(), p.max())
fixed_min, fixed_max, step = _nice_bounds(lo, hi, n_ticks=6)
ticks = np.arange(fixed_min, fixed_max + step, step)
dpi = 110
fig, ax = plt.subplots(figsize=(CROSS_W / dpi, CROSS_H / dpi), dpi=dpi, constrained_layout=False)
ax.scatter(a, p, s=14, c=COLORS["pred"], alpha=0.9, linewidths=0)
ax.plot([fixed_min, fixed_max], [fixed_min, fixed_max],
linestyle="--", linewidth=1.2, color=COLORS["ref"])
ax.set_xlim(fixed_min, fixed_max)
ax.set_ylim(fixed_min, fixed_max)
ax.set_xticks(ticks); ax.set_yticks(ticks)
ax.set_aspect("equal", adjustable="box")
fmt = FuncFormatter(lambda x, _: f"{int(x):,}")
ax.xaxis.set_major_formatter(fmt); ax.yaxis.set_major_formatter(fmt)
ax.set_xlabel("Actual GR (API)", fontweight="bold", fontsize=10, color="black")
ax.set_ylabel("Predicted GR (API)", fontweight="bold", fontsize=10, color="black")
ax.tick_params(labelsize=8, colors="black")
ax.grid(True, linestyle=":", alpha=0.3)
for spine in ax.spines.values():
spine.set_linewidth(1.1); spine.set_color("#444")
fig.subplots_adjust(left=0.16, bottom=0.16, right=0.98, top=0.98)
return fig
# =========================
# Track plot (Plotly) — y-axis reversed
# =========================
def track_plot(df, include_actual=True, pred_col="GR_Pred", actual_col="GR"):
def _col_1d(frame: pd.DataFrame, col: str) -> pd.Series:
if col not in frame.columns: return pd.Series(dtype=float)
v = frame[col]
if isinstance(v, pd.DataFrame): v = v.iloc[:, 0]
return pd.Series(v, dtype=float)
depth_col = next((c for c in df.columns if 'depth' in str(c).lower()), None)
if depth_col is not None:
y = pd.Series(df[depth_col]).astype(float); ylab = depth_col
else:
y = pd.Series(np.arange(1, len(df) + 1), dtype=float); ylab = "Point Index"
x_pred = _col_1d(df, pred_col)
if include_actual and actual_col in df.columns:
x_act = _col_1d(df, actual_col)
x_series = pd.concat([x_pred, x_act], ignore_index=True)
else:
x_act = None
x_series = x_pred
x_lo, x_hi = float(x_series.min()), float(x_series.max())
x_pad = 0.03 * (x_hi - x_lo if x_hi > x_lo else 1.0)
xmin, xmax = x_lo - x_pad, x_hi + x_pad
tick0 = _nice_tick0(xmin, step=5)
fig = go.Figure()
fig.add_trace(go.Scatter(
x=x_pred, y=y, mode="lines",
line=dict(color=COLORS["pred"], width=1.8),
name=pred_col,
hovertemplate="GR_Pred: %{x:.0f}
"+ylab+": %{y}"
))
if include_actual and x_act is not None:
fig.add_trace(go.Scatter(
x=x_act, y=y, mode="lines",
line=dict(color=COLORS["actual"], width=2.0, dash="dot"),
name="GR (actual)",
hovertemplate="GR (actual): %{x:.0f}
"+ylab+": %{y}"
))
fig.update_layout(
height=TRACK_H, width=TRACK_W, autosize=False,
paper_bgcolor="#fff", plot_bgcolor="#fff",
margin=dict(l=64, r=16, t=36, b=48), hovermode="closest",
font=dict(size=FONT_SZ, color="#000"),
legend=dict(x=0.98, y=0.05, xanchor="right", yanchor="bottom",
bgcolor="rgba(255,255,255,0.75)", bordercolor="#ccc", borderwidth=1),
legend_title_text=""
)
fig.update_xaxes(
title_text="GR (API)",
title_font=dict(size=20, family=BOLD_FONT, color="#000"),
tickfont=dict(size=15, family=BOLD_FONT, color="#000"),
side="top", range=[xmin, xmax],
ticks="outside",
tickformat=",.0f",
tickmode="auto",
tick0=tick0,
showline=True, linewidth=1.2, linecolor="#444", mirror=True,
showgrid=True, gridcolor="rgba(0,0,0,0.12)", automargin=True,
)
fig.update_yaxes(
title_text=ylab,
title_font=dict(size=20, family=BOLD_FONT, color="#000"),
tickfont=dict(size=15, family=BOLD_FONT, color="#000"),
autorange="reversed",
ticks="outside",
showline=True, linewidth=1.2, linecolor="#444", mirror=True,
showgrid=True, gridcolor="rgba(0,0,0,0.12)", automargin=True,
)
return fig
# ---------- Preview (Matplotlib) — colorful tracks; shared Y; ticks only left ----------
def preview_tracks(df: pd.DataFrame, cols: list[str]):
cols = [c for c in cols if c in df.columns]
n = len(cols)
if n == 0:
fig, ax = plt.subplots(figsize=(4, 2))
ax.text(0.5, 0.5, "No selected columns", ha="center", va="center")
ax.axis("off")
return fig
depth_col = next((c for c in df.columns if 'depth' in str(c).lower()), None)
if depth_col is not None:
y = pd.to_numeric(df[depth_col], errors="coerce")
ylab = depth_col
else:
y = pd.Series(np.arange(1, len(df) + 1), dtype=float)
ylab = "Point Index"
# Stable qualitative colors
cmap = plt.get_cmap("tab20")
col_colors = {col: cmap(i % cmap.N) for i, col in enumerate(cols)}
fig, axes = plt.subplots(1, n, figsize=(2.3 * n, 7.0), sharey=True, dpi=100)
if n == 1:
axes = [axes]
y_min, y_max = float(np.nanmin(y)), float(np.nanmax(y))
for i, (ax, col) in enumerate(zip(axes, cols)):
x = pd.to_numeric(df[col], errors="coerce")
ax.plot(x, y, '-', lw=1.8, color=col_colors[col])
ax.set_xlabel(col)
ax.xaxis.set_label_position('top'); ax.xaxis.tick_top()
ax.set_ylim(y_max, y_min) # reverse Y (Depth down)
ax.grid(True, linestyle=":", alpha=0.3)
if i == 0:
ax.set_ylabel(ylab)
else:
# Hide Y ticks and labels for non-left tracks
ax.tick_params(axis='y', left=False, labelleft=False)
fig.tight_layout()
return fig
# =========================
# Load model + meta
# =========================
def ensure_model() -> Path|None:
for p in [DEFAULT_MODEL, *MODEL_FALLBACKS]:
if p.exists() and p.stat().st_size > 0:
return p
url = os.environ.get("MODEL_URL", "")
if not url:
return None
try:
import requests
DEFAULT_MODEL.parent.mkdir(parents=True, exist_ok=True)
with requests.get(url, stream=True, timeout=30) as r:
r.raise_for_status()
with open(DEFAULT_MODEL, "wb") as f:
for chunk in r.iter_content(1<<20):
if chunk: f.write(chunk)
return DEFAULT_MODEL
except Exception:
return None
mpath = ensure_model()
if not mpath:
st.error("Model not found. Upload models/gr_rf.joblib (or set MODEL_URL).")
st.stop()
try:
model = load_model(str(mpath))
except Exception as e:
st.error(f"Failed to load model: {e}")
st.stop()
meta_path = MODELS_DIR / "meta.json"
if meta_path.exists():
try:
meta = json.loads(meta_path.read_text(encoding="utf-8"))
FEATURES = meta.get("features", FEATURES)
TARGET = meta.get("target", TARGET)
TARGET_TRANSFORM = meta.get("target_transform", TARGET_TRANSFORM)
ACTUAL_COL = meta.get("actual_col", ACTUAL_COL)
except Exception:
pass
# =========================
# Session state
# =========================
st.session_state.setdefault("app_step", "intro")
st.session_state.setdefault("results", {})
st.session_state.setdefault("train_ranges", None)
st.session_state.setdefault("dev_file_name","")
st.session_state.setdefault("dev_file_bytes",b"")
st.session_state.setdefault("dev_file_loaded",False)
st.session_state.setdefault("dev_preview",False)
st.session_state.setdefault("show_preview_modal", False)
# =========================
# Sidebar branding
# =========================
st.sidebar.markdown(f"""
{APP_NAME}
{TAGLINE}
""", unsafe_allow_html=True
)
def sticky_header(title, message):
st.markdown(
f"""
""",
unsafe_allow_html=True
)
# =========================
# INTRO
# =========================
if st.session_state.app_step == "intro":
st.header("Welcome!")
st.markdown("This software is developed by *Smart Thinking AI-Solutions Team* to estimate **Gamma Ray (GR)** from drilling data.")
st.subheader("How It Works")
st.markdown(
"1) **Upload your data to build the case and preview model performance.** \n"
"2) Click **Run Model** to compute metrics and plots. \n"
"3) **Proceed to Validation** (with actual GR) or **Proceed to Prediction** (no GR)."
)
if st.button("Start Showcase", type="primary"):
st.session_state.app_step = "dev"; st.rerun()
# =========================
# CASE BUILDING
# =========================
if st.session_state.app_step == "dev":
st.sidebar.header("Case Building")
up = st.sidebar.file_uploader("Upload Your Data File", type=["xlsx","xls"])
if up is not None:
st.session_state.dev_file_bytes = up.getvalue()
st.session_state.dev_file_name = up.name
st.session_state.dev_file_loaded = True
st.session_state.dev_preview = False
if st.session_state.dev_file_loaded:
tmp = read_book_bytes(st.session_state.dev_file_bytes)
if tmp:
df0 = next(iter(tmp.values()))
st.sidebar.caption(f"**Data loaded:** {st.session_state.dev_file_name} • {df0.shape[0]} rows × {df0.shape[1]} cols")
if st.sidebar.button("Preview data", use_container_width=True, disabled=not st.session_state.dev_file_loaded):
st.session_state.show_preview_modal = True
st.session_state.dev_preview = True
run = st.sidebar.button("Run Model", type="primary", use_container_width=True)
if st.sidebar.button("Proceed to Validation ▶", use_container_width=True): st.session_state.app_step="validate"; st.rerun()
if st.sidebar.button("Proceed to Prediction ▶", use_container_width=True): st.session_state.app_step="predict"; st.rerun()
if st.session_state.dev_file_loaded and st.session_state.dev_preview:
sticky_header("Case Building", "Previewed ✓ — now click **Run Model**.")
elif st.session_state.dev_file_loaded:
sticky_header("Case Building", "📄 **Preview uploaded data**, then click **Run Model**.")
else:
sticky_header("Case Building", "Upload your data to build a case, then run the model to review development performance.")
if run and st.session_state.dev_file_bytes:
book = read_book_bytes(st.session_state.dev_file_bytes)
sh_train = find_sheet(book, ["Train","Training","training2","train","training"])
sh_test = find_sheet(book, ["Test","Testing","testing2","test","testing"])
if sh_train is None or sh_test is None:
st.markdown('Workbook must include Train/Training and Test/Testing sheets.
', unsafe_allow_html=True)
st.stop()
tr = normalize_df(book[sh_train].copy())
te = normalize_df(book[sh_test].copy())
if not (ensure_cols(tr, FEATURES) and ensure_cols(te, FEATURES)):
st.markdown('Missing required feature columns.
', unsafe_allow_html=True)
st.stop()
# Predict (model trained on transformed target)
tr_pred_raw = model.predict(tr[FEATURES])
te_pred_raw = model.predict(te[FEATURES])
tr["GR_Pred"] = inverse_target(np.asarray(tr_pred_raw, dtype=float), TARGET_TRANSFORM)
te["GR_Pred"] = inverse_target(np.asarray(te_pred_raw, dtype=float), TARGET_TRANSFORM)
# Actual GR for metrics/plots
tr["GR_Actual"] = to_actual_series(tr, TARGET, ACTUAL_COL, TARGET_TRANSFORM)
te["GR_Actual"] = to_actual_series(te, TARGET, ACTUAL_COL, TARGET_TRANSFORM)
st.session_state.results["Train"]=tr; st.session_state.results["Test"]=te
st.session_state.results["m_train"]={
"R": pearson_r(tr["GR_Actual"], tr["GR_Pred"]),
"RMSE": rmse(tr["GR_Actual"], tr["GR_Pred"]),
"MAE": mean_absolute_error(tr["GR_Actual"], tr["GR_Pred"])
}
st.session_state.results["m_test"]={
"R": pearson_r(te["GR_Actual"], te["GR_Pred"]),
"RMSE": rmse(te["GR_Actual"], te["GR_Pred"]),
"MAE": mean_absolute_error(te["GR_Actual"], te["GR_Pred"])
}
tr_min = tr[FEATURES].min().to_dict(); tr_max = tr[FEATURES].max().to_dict()
st.session_state.train_ranges = {f:(float(tr_min[f]), float(tr_max[f])) for f in FEATURES}
st.markdown('Case has been built and results are displayed below.
', unsafe_allow_html=True)
def _dev_block(df, m):
c1, c2, c3 = st.columns(3)
c1.metric("R", f"{m['R']:.3f}")
c2.metric("RMSE", f"{m['RMSE']:.3f}")
c3.metric("MAE", f"{m['MAE']:.3f}")
st.markdown("""
R: Pearson Correlation Coefficient
RMSE: Root Mean Square Error
MAE: Mean Absolute Error
""", unsafe_allow_html=True)
col_track, col_cross = st.columns([2, 3], gap="large")
with col_track:
st.plotly_chart(
track_plot(df, include_actual=True, pred_col="GR_Pred", actual_col="GR_Actual"),
use_container_width=False,
config={"displayModeBar": False, "scrollZoom": True},
)
with col_cross:
st.pyplot(cross_plot_static(df["GR_Actual"], df["GR_Pred"]), use_container_width=False)
if "Train" in st.session_state.results or "Test" in st.session_state.results:
tab1, tab2 = st.tabs(["Training", "Testing"])
if "Train" in st.session_state.results:
with tab1: _dev_block(st.session_state.results["Train"], st.session_state.results["m_train"])
if "Test" in st.session_state.results:
with tab2: _dev_block(st.session_state.results["Test"], st.session_state.results["m_test"])
render_export_button(phase_key="dev")
# =========================
# VALIDATION (with actual GR)
# =========================
if st.session_state.app_step == "validate":
st.sidebar.header("Validate the Model")
up = st.sidebar.file_uploader("Upload Validation Excel", type=["xlsx","xls"])
if up is not None:
book = read_book_bytes(up.getvalue())
if book:
df0 = next(iter(book.values()))
st.sidebar.caption(f"**Data loaded:** {up.name} • {df0.shape[0]} rows × {df0.shape[1]} cols")
if st.sidebar.button("Preview data", use_container_width=True, disabled=(up is None)):
st.session_state.show_preview_modal = True
go_btn = st.sidebar.button("Predict & Validate", type="primary", use_container_width=True)
if st.sidebar.button("⬅ Back to Case Building", use_container_width=True): st.session_state.app_step="dev"; st.rerun()
if st.sidebar.button("Proceed to Prediction ▶", use_container_width=True): st.session_state.app_step="predict"; st.rerun()
sticky_header("Validate the Model", "Upload a dataset with the same **features** and **GR** to evaluate performance.")
if go_btn and up is not None:
book = read_book_bytes(up.getvalue())
name = find_sheet(book, ["Validation","Validate","validation2","Val","val"]) or list(book.keys())[0]
df = normalize_df(book[name].copy())
if not ensure_cols(df, FEATURES):
st.markdown('Missing required feature columns.
', unsafe_allow_html=True); st.stop()
pred_raw = model.predict(df[FEATURES])
df["GR_Pred"] = inverse_target(np.asarray(pred_raw, dtype=float), TARGET_TRANSFORM)
try:
df["GR_Actual"] = to_actual_series(df, TARGET, ACTUAL_COL, TARGET_TRANSFORM)
except Exception:
st.markdown('Validation sheet must include actual GR (or a target column that can be inverse-transformed).
', unsafe_allow_html=True)
st.stop()
st.session_state.results["Validate"]=df
ranges = st.session_state.train_ranges; oor_pct = 0.0; tbl=None
if ranges:
any_viol = pd.DataFrame({f:(df[f]ranges[f][1]) for f in FEATURES}).any(axis=1)
oor_pct = float(any_viol.mean()*100.0)
if any_viol.any():
tbl = df.loc[any_viol, FEATURES].copy()
for c in FEATURES:
if pd.api.types.is_numeric_dtype(tbl[c]): tbl[c] = tbl[c].round(2)
tbl["Violations"] = pd.DataFrame({f:(df[f]ranges[f][1]) for f in FEATURES}).loc[any_viol].apply(
lambda r:", ".join([c for c,v in r.items() if v]), axis=1
)
st.session_state.results["m_val"]={
"R": pearson_r(df["GR_Actual"], df["GR_Pred"]),
"RMSE": rmse(df["GR_Actual"], df["GR_Pred"]),
"MAE": mean_absolute_error(df["GR_Actual"], df["GR_Pred"])
}
st.session_state.results["sv_val"]={"n":len(df),"pred_min":float(df["GR_Pred"].min()),"pred_max":float(df["GR_Pred"].max()),"oor":oor_pct}
st.session_state.results["oor_tbl"]=tbl
if "Validate" in st.session_state.results:
m = st.session_state.results["m_val"]
c1,c2,c3 = st.columns(3)
c1.metric("R", f"{m['R']:.3f}"); c2.metric("RMSE", f"{m['RMSE']:.2f}"); c3.metric("MAE", f"{m['MAE']:.2f}")
st.markdown("""
R: Pearson Correlation Coefficient
RMSE: Root Mean Square Error
MAE: Mean Absolute Error
""", unsafe_allow_html=True)
col_track, col_cross = st.columns([2, 3], gap="large")
with col_track:
st.plotly_chart(
track_plot(st.session_state.results["Validate"], include_actual=True, pred_col="GR_Pred", actual_col="GR_Actual"),
use_container_width=False, config={"displayModeBar": False, "scrollZoom": True}
)
with col_cross:
st.pyplot(cross_plot_static(st.session_state.results["Validate"]["GR_Actual"],
st.session_state.results["Validate"]["GR_Pred"]),
use_container_width=False)
render_export_button(phase_key="validate")
sv = st.session_state.results["sv_val"]
if sv["oor"] > 0: st.markdown('Some inputs fall outside **training min–max** ranges.
', unsafe_allow_html=True)
if st.session_state.results["oor_tbl"] is not None:
st.write("*Out-of-range rows (vs. Training min–max):*")
df_centered_rounded(st.session_state.results["oor_tbl"])
# =========================
# PREDICTION (no actual GR)
# =========================
if st.session_state.app_step == "predict":
st.sidebar.header("Prediction (No Actual GR)")
up = st.sidebar.file_uploader("Upload Prediction Excel", type=["xlsx","xls"])
if up is not None:
book = read_book_bytes(up.getvalue())
if book:
df0 = next(iter(book.values()))
st.sidebar.caption(f"**Data loaded:** {up.name} • {df0.shape[0]} rows × {df0.shape[1]} cols")
if st.sidebar.button("Preview data", use_container_width=True, disabled=(up is None)):
st.session_state.show_preview_modal = True
go_btn = st.sidebar.button("Predict", type="primary", use_container_width=True)
if st.sidebar.button("⬅ Back to Case Building", use_container_width=True): st.session_state.app_step="dev"; st.rerun()
sticky_header("Prediction", "Upload a dataset with the feature columns (no **GR**).")
if go_btn and up is not None:
book = read_book_bytes(up.getvalue()); name = list(book.keys())[0]
df = normalize_df(book[name].copy())
if not ensure_cols(df, FEATURES):
st.markdown('Missing required feature columns.
', unsafe_allow_html=True); st.stop()
pred_raw = model.predict(df[FEATURES])
df["GR_Pred"] = inverse_target(np.asarray(pred_raw, dtype=float), TARGET_TRANSFORM)
st.session_state.results["PredictOnly"]=df
ranges = st.session_state.train_ranges; oor_pct = 0.0; oor_tbl=None
if ranges:
any_viol = pd.DataFrame({f:(df[f]ranges[f][1]) for f in FEATURES}).any(axis=1)
oor_pct = float(any_viol.mean()*100.0)
if any_viol.any():
oor_tbl = df.loc[any_viol, FEATURES].copy()
for c in FEATURES:
if pd.api.types.is_numeric_dtype(oor_tbl[c]): oor_tbl[c] = oor_tbl[c].round(2)
oor_tbl["Violations"] = pd.DataFrame({f:(df[f]ranges[f][1]) for f in FEATURES}).loc[any_viol].apply(
lambda r:", ".join([c for c,v in r.items() if v]), axis=1
)
st.session_state.results["sv_pred"]={
"n":len(df),
"pred_min":float(df["GR_Pred"].min()),
"pred_max":float(df["GR_Pred"].max()),
"pred_mean":float(df["GR_Pred"].mean()),
"pred_std":float(df["GR_Pred"].std(ddof=0)),
"oor":oor_pct
}
st.session_state.results["oor_tbl_pred"] = oor_tbl
if "PredictOnly" in st.session_state.results:
df = st.session_state.results["PredictOnly"]; sv = st.session_state.results["sv_pred"]
col_left, col_right = st.columns([2,3], gap="large")
with col_left:
table = pd.DataFrame({
"Metric": ["# points","Pred min","Pred max","Pred mean","Pred std","OOR %"],
"Value": [sv["n"], round(sv["pred_min"],2), round(sv["pred_max"],2),
round(sv["pred_mean"],2), round(sv["pred_std"],2), f'{sv["oor"]:.1f}%']
})
st.markdown('Predictions ready ✓
', unsafe_allow_html=True)
df_centered_rounded(table, hide_index=True)
st.caption("**★ OOR** = % of rows whose input features fall outside the training min–max range.")
if st.session_state.results.get("oor_tbl_pred") is not None:
st.markdown('Some inputs fall outside **training min–max** ranges.
', unsafe_allow_html=True)
st.write("*Out-of-range rows (vs. Training min–max):*")
df_centered_rounded(st.session_state.results["oor_tbl_pred"])
with col_right:
st.plotly_chart(
track_plot(df, include_actual=False, pred_col="GR_Pred", actual_col="GR"),
use_container_width=False, config={"displayModeBar": False, "scrollZoom": True}
)
render_export_button(phase_key="predict")
# =========================
# Preview modal (re-usable)
# =========================
if st.session_state.show_preview_modal:
book_to_preview = {}
if st.session_state.app_step == "dev":
book_to_preview = read_book_bytes(st.session_state.dev_file_bytes)
elif st.session_state.app_step in ["validate", "predict"] and 'up' in locals() and up is not None:
book_to_preview = read_book_bytes(up.getvalue())
with st.expander("Preview data", expanded=True):
if not book_to_preview:
st.markdown('No data loaded yet.
', unsafe_allow_html=True)
else:
names = list(book_to_preview.keys())
tabs = st.tabs(names)
for t, name in zip(tabs, names):
with t:
df = normalize_df(book_to_preview[name])
t1, t2 = st.tabs(["Tracks", "Summary"])
with t1:
present = [c for c in FEATURES if c in df.columns]
if present:
st.pyplot(preview_tracks(df, present), use_container_width=True)
else:
st.info(f"No expected feature columns found. Expected any of: {FEATURES}. Found: {list(df.columns)}")
with t2:
present = [c for c in FEATURES if c in df.columns]
if present:
tbl = (df[present]
.agg(['min','max','mean','std'])
.T.rename(columns={"min":"Min","max":"Max","mean":"Mean","std":"Std"})
.reset_index(names="Feature"))
df_centered_rounded(tbl)
else:
st.info("No expected feature columns found to summarize.")
st.session_state.show_preview_modal = False
# =========================
# Footer
# =========================
st.markdown("""
""", unsafe_allow_html=True)