Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
|
|
|
|
|
| 1 |
import io, json, os, base64, math
|
| 2 |
from pathlib import Path
|
| 3 |
import streamlit as st
|
|
@@ -6,7 +8,7 @@ import numpy as np
|
|
| 6 |
import joblib
|
| 7 |
from datetime import datetime
|
| 8 |
|
| 9 |
-
# Matplotlib
|
| 10 |
import matplotlib
|
| 11 |
matplotlib.use("Agg")
|
| 12 |
import matplotlib.pyplot as plt
|
|
@@ -16,128 +18,70 @@ import plotly.graph_objects as go
|
|
| 16 |
from sklearn.metrics import mean_squared_error, mean_absolute_error
|
| 17 |
|
| 18 |
# =========================
|
| 19 |
-
# Constants
|
| 20 |
# =========================
|
| 21 |
-
|
| 22 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 23 |
MODELS_DIR = Path("models")
|
| 24 |
DEFAULT_MODEL = MODELS_DIR / "ucs_rf.joblib"
|
| 25 |
MODEL_FALLBACKS = [MODELS_DIR / "model.joblib", MODELS_DIR / "model.pkl"]
|
| 26 |
COLORS = {"pred": "#1f77b4", "actual": "#f2b702", "ref": "#5a5a5a"}
|
| 27 |
|
| 28 |
-
|
| 29 |
-
|
|
|
|
|
|
|
| 30 |
CROSS_H = 350
|
| 31 |
-
TRACK_H = 1000
|
| 32 |
-
|
| 33 |
-
TRACK_W = 500 # px (plotly width)
|
| 34 |
FONT_SZ = 13
|
| 35 |
-
BOLD_FONT = "Arial Black, Arial, sans-serif"
|
| 36 |
|
| 37 |
# =========================
|
| 38 |
# Page / CSS
|
| 39 |
# =========================
|
| 40 |
-
st.set_page_config(page_title=
|
| 41 |
-
|
| 42 |
-
# General CSS (logo helpers etc.)
|
| 43 |
st.markdown("""
|
| 44 |
<style>
|
| 45 |
.brand-logo { width: 200px; height: auto; object-fit: contain; }
|
| 46 |
-
.
|
| 47 |
-
.
|
| 48 |
-
.
|
| 49 |
-
.
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 54 |
}
|
| 55 |
</style>
|
| 56 |
""", unsafe_allow_html=True)
|
| 57 |
|
| 58 |
-
# CSS to make sticky headers work correctly by overriding Streamlit's overflow property
|
| 59 |
-
st.markdown("""
|
| 60 |
-
<style>
|
| 61 |
-
/* This targets the main content area */
|
| 62 |
-
.main .block-container {
|
| 63 |
-
overflow: unset !important;
|
| 64 |
-
}
|
| 65 |
-
|
| 66 |
-
/* This targets the vertical block that holds all your elements */
|
| 67 |
-
div[data-testid="stVerticalBlock"] {
|
| 68 |
-
overflow: unset !important;
|
| 69 |
-
}
|
| 70 |
-
</style>
|
| 71 |
-
""", unsafe_allow_html=True)
|
| 72 |
-
|
| 73 |
-
# Hide uploader helper text ("Drag and drop file here", limits, etc.)
|
| 74 |
-
st.markdown("""
|
| 75 |
-
<style>
|
| 76 |
-
/* Older builds (helper wrapped in a Markdown container) */
|
| 77 |
-
section[data-testid="stFileUploader"] div[data-testid="stMarkdownContainer"]{display:none !important;}
|
| 78 |
-
/* 1.31–1.34: helper is the first child in the dropzone */
|
| 79 |
-
section[data-testid="stFileUploader"] [data-testid="stFileUploaderDropzone"] > div:first-child{display:none !important;}
|
| 80 |
-
/* 1.35+: explicit helper container */
|
| 81 |
-
section[data-testid="stFileUploader"] [data-testid="stFileUploaderInstructions"]{display:none !important;}
|
| 82 |
-
/* Fallback: any paragraph/small text inside the uploader */
|
| 83 |
-
section[data-testid="stFileUploader"] p, section[data-testid="stFileUploader"] small{display:none !important;}
|
| 84 |
-
</style>
|
| 85 |
-
""", unsafe_allow_html=True)
|
| 86 |
-
|
| 87 |
-
# Make the Preview expander title & tabs sticky (pinned to the top)
|
| 88 |
-
st.markdown("""
|
| 89 |
-
<style>
|
| 90 |
-
div[data-testid="stExpander"] > details > summary {
|
| 91 |
-
position: sticky;
|
| 92 |
-
top: 0;
|
| 93 |
-
z-index: 10;
|
| 94 |
-
background: #fff;
|
| 95 |
-
border-bottom: 1px solid #eee;
|
| 96 |
-
}
|
| 97 |
-
div[data-testid="stExpander"] div[data-baseweb="tab-list"] {
|
| 98 |
-
position: sticky;
|
| 99 |
-
top: 42px; /* adjust if your expander header height differs */
|
| 100 |
-
z-index: 9;
|
| 101 |
-
background: #fff;
|
| 102 |
-
padding-top: 6px;
|
| 103 |
-
}
|
| 104 |
-
</style>
|
| 105 |
-
""", unsafe_allow_html=True)
|
| 106 |
-
|
| 107 |
-
# Center text in all pandas Styler tables (headers + cells)
|
| 108 |
TABLE_CENTER_CSS = [
|
| 109 |
dict(selector="th", props=[("text-align", "center")]),
|
| 110 |
dict(selector="td", props=[("text-align", "center")]),
|
| 111 |
]
|
| 112 |
|
| 113 |
-
# NEW: CSS for the message box
|
| 114 |
-
st.markdown("""
|
| 115 |
-
<style>
|
| 116 |
-
.st-message-box {
|
| 117 |
-
background-color: #f0f2f6;
|
| 118 |
-
color: #333333;
|
| 119 |
-
padding: 10px;
|
| 120 |
-
border-radius: 10px;
|
| 121 |
-
border: 1px solid #e6e9ef;
|
| 122 |
-
}
|
| 123 |
-
.st-message-box.st-success {
|
| 124 |
-
background-color: #d4edda;
|
| 125 |
-
color: #155724;
|
| 126 |
-
border-color: #c3e6cb;
|
| 127 |
-
}
|
| 128 |
-
.st-message-box.st-warning {
|
| 129 |
-
background-color: #fff3cd;
|
| 130 |
-
color: #856404;
|
| 131 |
-
border-color: #ffeeba;
|
| 132 |
-
}
|
| 133 |
-
.st-message-box.st-error {
|
| 134 |
-
background-color: #f8d7da;
|
| 135 |
-
color: #721c24;
|
| 136 |
-
border-color: #f5c6cb;
|
| 137 |
-
}
|
| 138 |
-
</style>
|
| 139 |
-
""", unsafe_allow_html=True)
|
| 140 |
-
|
| 141 |
# =========================
|
| 142 |
# Password gate
|
| 143 |
# =========================
|
|
@@ -165,7 +109,7 @@ def add_password_gate() -> None:
|
|
| 165 |
st.sidebar.markdown(f"""
|
| 166 |
<div class="centered-container">
|
| 167 |
<img src="{inline_logo('logo.png')}" style="width: 200px; height: auto; object-fit: contain;">
|
| 168 |
-
<div style='font-weight:800;font-size:1.2rem; margin-top: 10px;'>
|
| 169 |
<div style='color:#667085;'>Smart Thinking • Secure Access</div>
|
| 170 |
</div>
|
| 171 |
""", unsafe_allow_html=True
|
|
@@ -191,6 +135,7 @@ def pearson_r(y_true, y_pred) -> float:
|
|
| 191 |
a = np.asarray(y_true, dtype=float)
|
| 192 |
p = np.asarray(y_pred, dtype=float)
|
| 193 |
if a.size < 2: return float("nan")
|
|
|
|
| 194 |
return float(np.corrcoef(a, p)[0, 1])
|
| 195 |
|
| 196 |
@st.cache_resource(show_spinner=False)
|
|
@@ -203,9 +148,55 @@ def parse_excel(data_bytes: bytes):
|
|
| 203 |
xl = pd.ExcelFile(bio)
|
| 204 |
return {sh: xl.parse(sh) for sh in xl.sheet_names}
|
| 205 |
|
| 206 |
-
def read_book_bytes(b: bytes):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 207 |
|
| 208 |
-
def ensure_cols(df, cols):
|
| 209 |
miss = [c for c in cols if c not in df.columns]
|
| 210 |
if miss:
|
| 211 |
st.error(f"Missing columns: {miss}\nFound: {list(df.columns)}")
|
|
@@ -222,20 +213,25 @@ def _nice_tick0(xmin: float, step: int = 100) -> float:
|
|
| 222 |
return step * math.floor(xmin / step) if np.isfinite(xmin) else xmin
|
| 223 |
|
| 224 |
def df_centered_rounded(df: pd.DataFrame, hide_index=True):
|
| 225 |
-
"""Center headers & cells; format numeric columns to 2 decimals."""
|
| 226 |
out = df.copy()
|
| 227 |
numcols = out.select_dtypes(include=[np.number]).columns
|
| 228 |
styler = (
|
| 229 |
out.style
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
| 233 |
)
|
| 234 |
st.dataframe(styler, use_container_width=True, hide_index=hide_index)
|
| 235 |
-
# === NEW: Excel export helpers =================================================
|
| 236 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 237 |
def _excel_engine() -> str:
|
| 238 |
-
"""Prefer xlsxwriter for better formatting; fall back to openpyxl if missing."""
|
| 239 |
try:
|
| 240 |
import xlsxwriter # noqa: F401
|
| 241 |
return "xlsxwriter"
|
|
@@ -243,7 +239,6 @@ def _excel_engine() -> str:
|
|
| 243 |
return "openpyxl"
|
| 244 |
|
| 245 |
def _excel_safe_name(name: str) -> str:
|
| 246 |
-
"""Excel sheet names: max 31 chars, no []:*?/\\."""
|
| 247 |
bad = '[]:*?/\\'
|
| 248 |
safe = ''.join('_' if ch in bad else ch for ch in str(name))
|
| 249 |
return safe[:31]
|
|
@@ -272,44 +267,50 @@ def _train_ranges_df(ranges: dict[str, tuple[float, float]]) -> pd.DataFrame:
|
|
| 272 |
df.columns = ["Feature", "Min", "Max"]
|
| 273 |
return _round_numeric(df)
|
| 274 |
|
| 275 |
-
def
|
| 276 |
-
""
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 280 |
res = st.session_state.get("results", {})
|
| 281 |
-
if not res:
|
| 282 |
-
return None, None, []
|
| 283 |
|
| 284 |
sheets: dict[str, pd.DataFrame] = {}
|
| 285 |
order: list[str] = []
|
| 286 |
|
| 287 |
# Training
|
| 288 |
-
if "Train" in res:
|
| 289 |
tr = _round_numeric(res["Train"])
|
| 290 |
sheets["Training"] = tr; order.append("Training")
|
| 291 |
m = res.get("m_train", {})
|
| 292 |
if m:
|
| 293 |
sheets["Training_Metrics"] = _round_numeric(pd.DataFrame([m])); order.append("Training_Metrics")
|
| 294 |
-
tr_cols = FEATURES +
|
| 295 |
s = _summary_table(tr, tr_cols)
|
| 296 |
if not s.empty:
|
| 297 |
sheets["Training_Summary"] = s; order.append("Training_Summary")
|
| 298 |
|
| 299 |
# Testing
|
| 300 |
-
if "Test" in res:
|
| 301 |
te = _round_numeric(res["Test"])
|
| 302 |
sheets["Testing"] = te; order.append("Testing")
|
| 303 |
m = res.get("m_test", {})
|
| 304 |
if m:
|
| 305 |
sheets["Testing_Metrics"] = _round_numeric(pd.DataFrame([m])); order.append("Testing_Metrics")
|
| 306 |
-
te_cols = FEATURES +
|
| 307 |
s = _summary_table(te, te_cols)
|
| 308 |
if not s.empty:
|
| 309 |
sheets["Testing_Summary"] = s; order.append("Testing_Summary")
|
| 310 |
|
| 311 |
# Validation
|
| 312 |
-
if "Validate" in res:
|
| 313 |
va = _round_numeric(res["Validate"])
|
| 314 |
sheets["Validation"] = va; order.append("Validation")
|
| 315 |
m = res.get("m_val", {})
|
|
@@ -320,32 +321,34 @@ def build_export_workbook() -> tuple[bytes|None, str|None, list[str]]:
|
|
| 320 |
sheets["Validation_Summary"] = _round_numeric(pd.DataFrame([sv])); order.append("Validation_Summary")
|
| 321 |
oor_tbl = res.get("oor_tbl")
|
| 322 |
if oor_tbl is not None and isinstance(oor_tbl, pd.DataFrame) and not oor_tbl.empty:
|
| 323 |
-
sheets["
|
| 324 |
|
| 325 |
-
# Prediction
|
| 326 |
-
if "PredictOnly" in res:
|
| 327 |
pr = _round_numeric(res["PredictOnly"])
|
| 328 |
sheets["Prediction"] = pr; order.append("Prediction")
|
| 329 |
sv = res.get("sv_pred", {})
|
| 330 |
if sv:
|
| 331 |
sheets["Prediction_Summary"] = _round_numeric(pd.DataFrame([sv])); order.append("Prediction_Summary")
|
| 332 |
|
| 333 |
-
#
|
| 334 |
tr_ranges = st.session_state.get("train_ranges")
|
| 335 |
-
if tr_ranges:
|
| 336 |
rr = _train_ranges_df(tr_ranges)
|
| 337 |
if not rr.empty:
|
| 338 |
sheets["Training_Ranges"] = rr; order.append("Training_Ranges")
|
| 339 |
|
| 340 |
-
# Info
|
| 341 |
info = pd.DataFrame([
|
| 342 |
-
{"Key": "
|
| 343 |
-
{"Key": "
|
|
|
|
|
|
|
|
|
|
| 344 |
{"Key": "ExportedAt", "Value": datetime.now().strftime("%Y-%m-%d %H:%M:%S")},
|
| 345 |
])
|
| 346 |
sheets["Info"] = info; order.append("Info")
|
| 347 |
|
| 348 |
-
# Write workbook to memory
|
| 349 |
bio = io.BytesIO()
|
| 350 |
with pd.ExcelWriter(bio, engine=_excel_engine()) as writer:
|
| 351 |
for name in order:
|
|
@@ -356,63 +359,80 @@ def build_export_workbook() -> tuple[bytes|None, str|None, list[str]]:
|
|
| 356 |
fname = f"UCS_Export_{datetime.now().strftime('%Y%m%d_%H%M%S')}.xlsx"
|
| 357 |
return bio.getvalue(), fname, order
|
| 358 |
|
| 359 |
-
def render_export_button(
|
| 360 |
-
|
| 361 |
-
|
| 362 |
st.divider()
|
| 363 |
st.markdown("### Export to Excel")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 364 |
if names:
|
| 365 |
-
st.caption("
|
| 366 |
st.download_button(
|
| 367 |
-
|
| 368 |
data=(data or b""),
|
| 369 |
file_name=(fname or "UCS_Export.xlsx"),
|
| 370 |
mime="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
| 371 |
disabled=(data is None),
|
| 372 |
-
|
| 373 |
-
key=key,
|
| 374 |
)
|
| 375 |
-
# ================================================================================
|
| 376 |
|
| 377 |
# =========================
|
| 378 |
-
# Cross plot (Matplotlib
|
| 379 |
# =========================
|
| 380 |
def cross_plot_static(actual, pred):
|
| 381 |
a = pd.Series(actual, dtype=float)
|
| 382 |
p = pd.Series(pred, dtype=float)
|
| 383 |
|
| 384 |
-
|
| 385 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 386 |
|
| 387 |
dpi = 110
|
| 388 |
-
fig, ax = plt.subplots(
|
| 389 |
-
figsize=(CROSS_W / dpi, CROSS_H / dpi),
|
| 390 |
-
dpi=dpi,
|
| 391 |
-
constrained_layout=False
|
| 392 |
-
)
|
| 393 |
|
| 394 |
ax.scatter(a, p, s=14, c=COLORS["pred"], alpha=0.9, linewidths=0)
|
| 395 |
-
ax.plot([
|
| 396 |
-
linestyle="--", linewidth=1.2, color=COLORS["ref"])
|
| 397 |
|
| 398 |
-
ax.set_xlim(
|
| 399 |
-
ax.
|
| 400 |
-
ax.
|
| 401 |
-
ax.set_yticks(ticks)
|
| 402 |
-
ax.set_aspect("equal", adjustable="box") # true 45°
|
| 403 |
|
| 404 |
-
fmt = FuncFormatter(lambda x, _: f"{
|
| 405 |
-
ax.xaxis.set_major_formatter(fmt)
|
| 406 |
-
ax.yaxis.set_major_formatter(fmt)
|
| 407 |
|
| 408 |
-
ax.set_xlabel("Actual UCS (psi)",
|
| 409 |
ax.set_ylabel("Predicted UCS (psi)", fontweight="bold", fontsize=10, color="black")
|
| 410 |
ax.tick_params(labelsize=6, colors="black")
|
| 411 |
|
| 412 |
ax.grid(True, linestyle=":", alpha=0.3)
|
| 413 |
for spine in ax.spines.values():
|
| 414 |
-
spine.set_linewidth(1.1)
|
| 415 |
-
spine.set_color("#444")
|
| 416 |
|
| 417 |
fig.subplots_adjust(left=0.16, bottom=0.16, right=0.98, top=0.98)
|
| 418 |
return fig
|
|
@@ -423,16 +443,13 @@ def cross_plot_static(actual, pred):
|
|
| 423 |
def track_plot(df, include_actual=True):
|
| 424 |
depth_col = next((c for c in df.columns if 'depth' in str(c).lower()), None)
|
| 425 |
if depth_col is not None:
|
| 426 |
-
y = pd.Series(df[depth_col]).astype(float)
|
| 427 |
-
|
| 428 |
-
y_range = [float(y.max()), float(y.min())] # reverse
|
| 429 |
else:
|
| 430 |
-
y = pd.Series(np.arange(1, len(df) + 1))
|
| 431 |
-
ylab = "Point Index"
|
| 432 |
y_range = [float(y.max()), float(y.min())]
|
| 433 |
|
| 434 |
-
|
| 435 |
-
x_series = pd.Series(df.get("UCS_Pred", pd.Series(dtype=float))).astype(float)
|
| 436 |
if include_actual and TARGET in df.columns:
|
| 437 |
x_series = pd.concat([x_series, pd.Series(df[TARGET]).astype(float)], ignore_index=True)
|
| 438 |
x_lo, x_hi = float(x_series.min()), float(x_series.max())
|
|
@@ -441,45 +458,36 @@ def track_plot(df, include_actual=True):
|
|
| 441 |
tick0 = _nice_tick0(xmin, step=100)
|
| 442 |
|
| 443 |
fig = go.Figure()
|
| 444 |
-
|
| 445 |
-
|
| 446 |
-
|
| 447 |
-
|
| 448 |
-
|
| 449 |
-
|
|
|
|
| 450 |
if include_actual and TARGET in df.columns:
|
| 451 |
fig.add_trace(go.Scatter(
|
| 452 |
x=df[TARGET], y=y, mode="lines",
|
| 453 |
line=dict(color=COLORS["actual"], width=2.0, dash="dot"),
|
| 454 |
-
name="
|
| 455 |
-
hovertemplate="
|
| 456 |
))
|
| 457 |
|
| 458 |
fig.update_layout(
|
| 459 |
-
height=TRACK_H,
|
| 460 |
-
width=TRACK_W, # Set the width here
|
| 461 |
-
autosize=False, # Disable autosizing to respect the width
|
| 462 |
paper_bgcolor="#fff", plot_bgcolor="#fff",
|
| 463 |
margin=dict(l=64, r=16, t=36, b=48), hovermode="closest",
|
| 464 |
font=dict(size=FONT_SZ, color="#000"),
|
| 465 |
-
legend=dict(
|
| 466 |
-
|
| 467 |
-
bgcolor="rgba(255,255,255,0.75)", bordercolor="#ccc", borderwidth=1
|
| 468 |
-
),
|
| 469 |
legend_title_text=""
|
| 470 |
)
|
| 471 |
-
|
| 472 |
-
# Bold, black axis titles & ticks
|
| 473 |
fig.update_xaxes(
|
| 474 |
title_text="UCS (psi)",
|
| 475 |
title_font=dict(size=20, family=BOLD_FONT, color="#000"),
|
| 476 |
tickfont=dict(size=15, family=BOLD_FONT, color="#000"),
|
| 477 |
-
side="top",
|
| 478 |
-
|
| 479 |
-
ticks="outside",
|
| 480 |
-
tickformat=",.0f",
|
| 481 |
-
tickmode="auto",
|
| 482 |
-
tick0=tick0,
|
| 483 |
showline=True, linewidth=1.2, linecolor="#444", mirror=True,
|
| 484 |
showgrid=True, gridcolor="rgba(0,0,0,0.12)", automargin=True
|
| 485 |
)
|
|
@@ -487,64 +495,58 @@ def track_plot(df, include_actual=True):
|
|
| 487 |
title_text=ylab,
|
| 488 |
title_font=dict(size=20, family=BOLD_FONT, color="#000"),
|
| 489 |
tickfont=dict(size=15, family=BOLD_FONT, color="#000"),
|
| 490 |
-
range=y_range,
|
| 491 |
-
ticks="outside",
|
| 492 |
showline=True, linewidth=1.2, linecolor="#444", mirror=True,
|
| 493 |
showgrid=True, gridcolor="rgba(0,0,0,0.12)", automargin=True
|
| 494 |
)
|
| 495 |
-
|
| 496 |
return fig
|
| 497 |
|
| 498 |
-
# ---------- Preview
|
| 499 |
def preview_tracks(df: pd.DataFrame, cols: list[str]):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 500 |
cols = [c for c in cols if c in df.columns]
|
| 501 |
n = len(cols)
|
| 502 |
if n == 0:
|
| 503 |
fig, ax = plt.subplots(figsize=(4, 2))
|
| 504 |
-
ax.text(0.5,0.5,"No selected columns",ha="center",va="center"); ax.axis("off")
|
| 505 |
return fig
|
| 506 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 507 |
if n == 1: axes = [axes]
|
| 508 |
-
|
| 509 |
-
|
| 510 |
-
|
| 511 |
-
|
|
|
|
|
|
|
|
|
|
| 512 |
ax.grid(True, linestyle=":", alpha=0.3)
|
| 513 |
-
|
| 514 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 515 |
return fig
|
| 516 |
|
| 517 |
-
# Modal wrapper (Streamlit compatibility)
|
| 518 |
-
try:
|
| 519 |
-
dialog = st.dialog
|
| 520 |
-
except AttributeError:
|
| 521 |
-
def dialog(title):
|
| 522 |
-
def deco(fn):
|
| 523 |
-
def wrapper(*args, **kwargs):
|
| 524 |
-
with st.expander(title, expanded=True):
|
| 525 |
-
return fn(*args, **kwargs)
|
| 526 |
-
return wrapper
|
| 527 |
-
return deco
|
| 528 |
-
|
| 529 |
-
def preview_modal(book: dict[str, pd.DataFrame]):
|
| 530 |
-
if not book:
|
| 531 |
-
st.info("No data loaded yet."); return
|
| 532 |
-
names = list(book.keys())
|
| 533 |
-
tabs = st.tabs(names)
|
| 534 |
-
for t, name in zip(tabs, names):
|
| 535 |
-
with t:
|
| 536 |
-
df = book[name]
|
| 537 |
-
t1, t2 = st.tabs(["Tracks", "Summary"])
|
| 538 |
-
with t1:
|
| 539 |
-
st.pyplot(preview_tracks(df, FEATURES), use_container_width=True)
|
| 540 |
-
with t2:
|
| 541 |
-
tbl = (df[FEATURES]
|
| 542 |
-
.agg(['min','max','mean','std'])
|
| 543 |
-
.T.rename(columns={"min":"Min","max":"Max","mean":"Mean","std":"Std"}))
|
| 544 |
-
df_centered_rounded(tbl.reset_index(names="Feature"))
|
| 545 |
-
|
| 546 |
# =========================
|
| 547 |
-
# Load model
|
| 548 |
# =========================
|
| 549 |
def ensure_model() -> Path|None:
|
| 550 |
for p in [DEFAULT_MODEL, *MODEL_FALLBACKS]:
|
|
@@ -573,13 +575,29 @@ except Exception as e:
|
|
| 573 |
st.error(f"Failed to load model: {e}")
|
| 574 |
st.stop()
|
| 575 |
|
| 576 |
-
|
| 577 |
-
|
|
|
|
|
|
|
|
|
|
| 578 |
try:
|
| 579 |
meta = json.loads(meta_path.read_text(encoding="utf-8"))
|
| 580 |
-
FEATURES = meta.get("features", FEATURES)
|
| 581 |
-
|
| 582 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 583 |
|
| 584 |
# =========================
|
| 585 |
# Session state
|
|
@@ -591,35 +609,27 @@ st.session_state.setdefault("dev_file_name","")
|
|
| 591 |
st.session_state.setdefault("dev_file_bytes",b"")
|
| 592 |
st.session_state.setdefault("dev_file_loaded",False)
|
| 593 |
st.session_state.setdefault("dev_preview",False)
|
| 594 |
-
st.session_state.setdefault("show_preview_modal", False)
|
| 595 |
|
| 596 |
# =========================
|
| 597 |
-
#
|
| 598 |
# =========================
|
| 599 |
st.sidebar.markdown(f"""
|
| 600 |
<div class="centered-container">
|
| 601 |
<img src="{inline_logo('logo.png')}" style="width: 200px; height: auto; object-fit: contain;">
|
| 602 |
-
<div style='font-weight:800;font-size:1.2rem;'>
|
| 603 |
-
<div style='color:#667085;'>
|
| 604 |
</div>
|
| 605 |
""", unsafe_allow_html=True
|
| 606 |
)
|
| 607 |
|
| 608 |
-
# =========================
|
| 609 |
-
# Reusable Sticky Header Function
|
| 610 |
-
# =========================
|
| 611 |
def sticky_header(title, message):
|
| 612 |
st.markdown(
|
| 613 |
f"""
|
| 614 |
<style>
|
| 615 |
.sticky-container {{
|
| 616 |
-
position: sticky;
|
| 617 |
-
top:
|
| 618 |
-
background-color: white;
|
| 619 |
-
z-index: 100;
|
| 620 |
-
padding-top: 10px;
|
| 621 |
-
padding-bottom: 10px;
|
| 622 |
-
border-bottom: 1px solid #eee;
|
| 623 |
}}
|
| 624 |
</style>
|
| 625 |
<div class="sticky-container">
|
|
@@ -635,10 +645,10 @@ def sticky_header(title, message):
|
|
| 635 |
# =========================
|
| 636 |
if st.session_state.app_step == "intro":
|
| 637 |
st.header("Welcome!")
|
| 638 |
-
st.markdown("This software is developed by *Smart Thinking AI-Solutions Team* to estimate UCS from drilling data.")
|
| 639 |
st.subheader("How It Works")
|
| 640 |
st.markdown(
|
| 641 |
-
"1) **Upload your data to build the case and preview the performance
|
| 642 |
"2) Click **Run Model** to compute metrics and plots. \n"
|
| 643 |
"3) **Proceed to Validation** (with actual UCS) or **Proceed to Prediction** (no UCS)."
|
| 644 |
)
|
|
@@ -663,14 +673,13 @@ if st.session_state.app_step == "dev":
|
|
| 663 |
st.sidebar.caption(f"**Data loaded:** {st.session_state.dev_file_name} • {df0.shape[0]} rows × {df0.shape[1]} cols")
|
| 664 |
|
| 665 |
if st.sidebar.button("Preview data", use_container_width=True, disabled=not st.session_state.dev_file_loaded):
|
| 666 |
-
st.session_state.show_preview_modal = True
|
| 667 |
st.session_state.dev_preview = True
|
| 668 |
|
| 669 |
run = st.sidebar.button("Run Model", type="primary", use_container_width=True)
|
| 670 |
if st.sidebar.button("Proceed to Validation ▶", use_container_width=True): st.session_state.app_step="validate"; st.rerun()
|
| 671 |
if st.sidebar.button("Proceed to Prediction ▶", use_container_width=True): st.session_state.app_step="predict"; st.rerun()
|
| 672 |
|
| 673 |
-
# Apply sticky header
|
| 674 |
if st.session_state.dev_file_loaded and st.session_state.dev_preview:
|
| 675 |
sticky_header("Case Building", "Previewed ✓ — now click **Run Model**.")
|
| 676 |
elif st.session_state.dev_file_loaded:
|
|
@@ -681,27 +690,31 @@ if st.session_state.app_step == "dev":
|
|
| 681 |
if run and st.session_state.dev_file_bytes:
|
| 682 |
book = read_book_bytes(st.session_state.dev_file_bytes)
|
| 683 |
sh_train = find_sheet(book, ["Train","Training","training2","train","training"])
|
| 684 |
-
sh_test
|
| 685 |
if sh_train is None or sh_test is None:
|
| 686 |
st.markdown('<div class="st-message-box st-error">Workbook must include Train/Training/training2 and Test/Testing/testing2 sheets.</div>', unsafe_allow_html=True)
|
| 687 |
st.stop()
|
| 688 |
-
|
|
|
|
|
|
|
|
|
|
| 689 |
if not (ensure_cols(tr, FEATURES+[TARGET]) and ensure_cols(te, FEATURES+[TARGET])):
|
| 690 |
st.markdown('<div class="st-message-box st-error">Missing required columns.</div>', unsafe_allow_html=True)
|
| 691 |
st.stop()
|
| 692 |
-
|
| 693 |
-
|
|
|
|
| 694 |
|
| 695 |
st.session_state.results["Train"]=tr; st.session_state.results["Test"]=te
|
| 696 |
st.session_state.results["m_train"]={
|
| 697 |
-
"R":
|
| 698 |
-
"RMSE": rmse(tr[TARGET], tr[
|
| 699 |
-
"MAE":
|
| 700 |
}
|
| 701 |
st.session_state.results["m_test"]={
|
| 702 |
-
"R":
|
| 703 |
-
"RMSE": rmse(te[TARGET], te[
|
| 704 |
-
"MAE":
|
| 705 |
}
|
| 706 |
|
| 707 |
tr_min = tr[FEATURES].min().to_dict(); tr_max = tr[FEATURES].max().to_dict()
|
|
@@ -710,11 +723,7 @@ if st.session_state.app_step == "dev":
|
|
| 710 |
|
| 711 |
def _dev_block(df, m):
|
| 712 |
c1,c2,c3 = st.columns(3)
|
| 713 |
-
c1.metric("R", f"{m['R']:.2f}")
|
| 714 |
-
c2.metric("RMSE", f"{m['RMSE']:.2f}")
|
| 715 |
-
c3.metric("MAE", f"{m['MAE']:.2f}")
|
| 716 |
-
|
| 717 |
-
# NEW: Footer for metric abbreviations
|
| 718 |
st.markdown("""
|
| 719 |
<div style='text-align: left; font-size: 0.8em; color: #6b7280; margin-top: -16px; margin-bottom: 8px;'>
|
| 720 |
<strong>R:</strong> Pearson Correlation Coefficient<br>
|
|
@@ -722,18 +731,11 @@ if st.session_state.app_step == "dev":
|
|
| 722 |
<strong>MAE:</strong> Mean Absolute Error
|
| 723 |
</div>
|
| 724 |
""", unsafe_allow_html=True)
|
| 725 |
-
|
| 726 |
-
# 2-column layout, big gap (prevents overlap)
|
| 727 |
col_track, col_cross = st.columns([2, 3], gap="large")
|
| 728 |
with col_track:
|
| 729 |
-
st.plotly_chart(
|
| 730 |
-
track_plot(df, include_actual=True),
|
| 731 |
-
use_container_width=False, # Set to False to honor the width in track_plot()
|
| 732 |
-
config={"displayModeBar": False, "scrollZoom": True}
|
| 733 |
-
)
|
| 734 |
with col_cross:
|
| 735 |
-
st.pyplot(cross_plot_static(df[TARGET], df[
|
| 736 |
-
|
| 737 |
|
| 738 |
if "Train" in st.session_state.results or "Test" in st.session_state.results:
|
| 739 |
tab1, tab2 = st.tabs(["Training", "Testing"])
|
|
@@ -741,6 +743,7 @@ if st.session_state.app_step == "dev":
|
|
| 741 |
with tab1: _dev_block(st.session_state.results["Train"], st.session_state.results["m_train"])
|
| 742 |
if "Test" in st.session_state.results:
|
| 743 |
with tab2: _dev_block(st.session_state.results["Test"], st.session_state.results["m_test"])
|
|
|
|
| 744 |
|
| 745 |
# =========================
|
| 746 |
# VALIDATION (with actual UCS)
|
|
@@ -754,7 +757,7 @@ if st.session_state.app_step == "validate":
|
|
| 754 |
df0 = next(iter(book.values()))
|
| 755 |
st.sidebar.caption(f"**Data loaded:** {up.name} • {df0.shape[0]} rows × {df0.shape[1]} cols")
|
| 756 |
if st.sidebar.button("Preview data", use_container_width=True, disabled=(up is None)):
|
| 757 |
-
st.session_state.show_preview_modal = True
|
| 758 |
go_btn = st.sidebar.button("Predict & Validate", type="primary", use_container_width=True)
|
| 759 |
if st.sidebar.button("⬅ Back to Case Building", use_container_width=True): st.session_state.app_step="dev"; st.rerun()
|
| 760 |
if st.sidebar.button("Proceed to Prediction ▶", use_container_width=True): st.session_state.app_step="predict"; st.rerun()
|
|
@@ -764,9 +767,10 @@ if st.session_state.app_step == "validate":
|
|
| 764 |
if go_btn and up is not None:
|
| 765 |
book = read_book_bytes(up.getvalue())
|
| 766 |
name = find_sheet(book, ["Validation","Validate","validation2","Val","val"]) or list(book.keys())[0]
|
| 767 |
-
df = book[name].copy()
|
| 768 |
-
if not ensure_cols(df, FEATURES+[TARGET]):
|
| 769 |
-
|
|
|
|
| 770 |
st.session_state.results["Validate"]=df
|
| 771 |
|
| 772 |
ranges = st.session_state.train_ranges; oor_pct = 0.0; tbl=None
|
|
@@ -777,23 +781,21 @@ if st.session_state.app_step == "validate":
|
|
| 777 |
tbl = df.loc[any_viol, FEATURES].copy()
|
| 778 |
for c in FEATURES:
|
| 779 |
if pd.api.types.is_numeric_dtype(tbl[c]): tbl[c] = tbl[c].round(2)
|
| 780 |
-
tbl["Violations"] = pd.DataFrame({f:(df[f]<ranges[f][0])|(df[f]>ranges[f][1]) for f in FEATURES}).loc[any_viol].apply(
|
|
|
|
|
|
|
| 781 |
st.session_state.results["m_val"]={
|
| 782 |
-
"R": pearson_r(df[TARGET], df[
|
| 783 |
-
"RMSE": rmse(df[TARGET], df[
|
| 784 |
-
"MAE": mean_absolute_error(df[TARGET], df[
|
| 785 |
}
|
| 786 |
-
st.session_state.results["sv_val"]={"n":len(df),"pred_min":float(df[
|
| 787 |
st.session_state.results["oor_tbl"]=tbl
|
| 788 |
|
| 789 |
if "Validate" in st.session_state.results:
|
| 790 |
m = st.session_state.results["m_val"]
|
| 791 |
c1,c2,c3 = st.columns(3)
|
| 792 |
-
c1.metric("R", f"{m['R']:.2f}")
|
| 793 |
-
c2.metric("RMSE", f"{m['RMSE']:.2f}")
|
| 794 |
-
c3.metric("MAE", f"{m['MAE']:.2f}")
|
| 795 |
-
|
| 796 |
-
# NEW: Footer for metric abbreviations
|
| 797 |
st.markdown("""
|
| 798 |
<div style='text-align: left; font-size: 0.8em; color: #6b7280; margin-top: -16px; margin-bottom: 8px;'>
|
| 799 |
<strong>R:</strong> Pearson Correlation Coefficient<br>
|
|
@@ -801,20 +803,17 @@ if st.session_state.app_step == "validate":
|
|
| 801 |
<strong>MAE:</strong> Mean Absolute Error
|
| 802 |
</div>
|
| 803 |
""", unsafe_allow_html=True)
|
| 804 |
-
|
| 805 |
col_track, col_cross = st.columns([2, 3], gap="large")
|
| 806 |
with col_track:
|
| 807 |
-
st.plotly_chart(
|
| 808 |
-
|
| 809 |
-
use_container_width=False, # Set to False to honor the width in track_plot()
|
| 810 |
-
config={"displayModeBar": False, "scrollZoom": True}
|
| 811 |
-
)
|
| 812 |
with col_cross:
|
| 813 |
-
st.pyplot(
|
| 814 |
-
|
| 815 |
-
|
| 816 |
-
|
| 817 |
-
|
| 818 |
|
| 819 |
sv = st.session_state.results["sv_val"]
|
| 820 |
if sv["oor"] > 0: st.markdown('<div class="st-message-box st-warning">Some inputs fall outside **training min–max** ranges.</div>', unsafe_allow_html=True)
|
|
@@ -834,7 +833,7 @@ if st.session_state.app_step == "predict":
|
|
| 834 |
df0 = next(iter(book.values()))
|
| 835 |
st.sidebar.caption(f"**Data loaded:** {up.name} • {df0.shape[0]} rows × {df0.shape[1]} cols")
|
| 836 |
if st.sidebar.button("Preview data", use_container_width=True, disabled=(up is None)):
|
| 837 |
-
st.session_state.show_preview_modal = True
|
| 838 |
go_btn = st.sidebar.button("Predict", type="primary", use_container_width=True)
|
| 839 |
if st.sidebar.button("⬅ Back to Case Building", use_container_width=True): st.session_state.app_step="dev"; st.rerun()
|
| 840 |
|
|
@@ -842,9 +841,10 @@ if st.session_state.app_step == "predict":
|
|
| 842 |
|
| 843 |
if go_btn and up is not None:
|
| 844 |
book = read_book_bytes(up.getvalue()); name = list(book.keys())[0]
|
| 845 |
-
df = book[name].copy()
|
| 846 |
-
if not ensure_cols(df, FEATURES):
|
| 847 |
-
|
|
|
|
| 848 |
st.session_state.results["PredictOnly"]=df
|
| 849 |
|
| 850 |
ranges = st.session_state.train_ranges; oor_pct = 0.0
|
|
@@ -853,10 +853,10 @@ if st.session_state.app_step == "predict":
|
|
| 853 |
oor_pct = float(any_viol.mean()*100.0)
|
| 854 |
st.session_state.results["sv_pred"]={
|
| 855 |
"n":len(df),
|
| 856 |
-
"pred_min":float(df[
|
| 857 |
-
"pred_max":float(df[
|
| 858 |
-
"pred_mean":float(df[
|
| 859 |
-
"pred_std":float(df[
|
| 860 |
"oor":oor_pct
|
| 861 |
}
|
| 862 |
|
|
@@ -867,28 +867,22 @@ if st.session_state.app_step == "predict":
|
|
| 867 |
with col_left:
|
| 868 |
table = pd.DataFrame({
|
| 869 |
"Metric": ["# points","Pred min","Pred max","Pred mean","Pred std","OOR %"],
|
| 870 |
-
"Value": [sv["n"],
|
| 871 |
-
round(sv["
|
| 872 |
-
round(sv["pred_max"],2),
|
| 873 |
-
round(sv["pred_mean"],2),
|
| 874 |
-
round(sv["pred_std"],2),
|
| 875 |
-
f'{sv["oor"]:.1f}%']
|
| 876 |
})
|
| 877 |
st.markdown('<div class="st-message-box st-success">Predictions ready ✓</div>', unsafe_allow_html=True)
|
| 878 |
df_centered_rounded(table, hide_index=True)
|
| 879 |
st.caption("**★ OOR** = % of rows whose input features fall outside the training min–max range.")
|
| 880 |
with col_right:
|
| 881 |
-
st.plotly_chart(
|
| 882 |
-
|
| 883 |
-
|
| 884 |
-
|
| 885 |
-
)
|
| 886 |
|
| 887 |
# =========================
|
| 888 |
-
#
|
| 889 |
# =========================
|
| 890 |
if st.session_state.show_preview_modal:
|
| 891 |
-
# Get the correct book based on the current app step
|
| 892 |
book_to_preview = {}
|
| 893 |
if st.session_state.app_step == "dev":
|
| 894 |
book_to_preview = read_book_bytes(st.session_state.dev_file_bytes)
|
|
@@ -903,28 +897,25 @@ if st.session_state.show_preview_modal:
|
|
| 903 |
tabs = st.tabs(names)
|
| 904 |
for t, name in zip(tabs, names):
|
| 905 |
with t:
|
| 906 |
-
df = book_to_preview[name]
|
| 907 |
t1, t2 = st.tabs(["Tracks", "Summary"])
|
| 908 |
with t1:
|
| 909 |
st.pyplot(preview_tracks(df, FEATURES), use_container_width=True)
|
| 910 |
with t2:
|
| 911 |
-
|
| 912 |
-
|
| 913 |
-
|
| 914 |
-
|
| 915 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 916 |
st.session_state.show_preview_modal = False
|
| 917 |
|
| 918 |
-
# === Bottom-of-page Export (per step) =========================================
|
| 919 |
-
if st.session_state.app_step in ("dev", "validate", "predict"):
|
| 920 |
-
has_results = any(
|
| 921 |
-
k in st.session_state.results
|
| 922 |
-
for k in ("Train", "Test", "Validate", "PredictOnly")
|
| 923 |
-
)
|
| 924 |
-
if has_results:
|
| 925 |
-
# Unique key per step avoids duplicate-widget clashes when switching steps
|
| 926 |
-
render_export_button(key=f"export_{st.session_state.app_step}")
|
| 927 |
-
# ==============================================================================
|
| 928 |
# =========================
|
| 929 |
# Footer
|
| 930 |
# =========================
|
|
|
|
| 1 |
+
# app_ucs.py — ST_GeoMech_UCS (Unified workflow like Tc)
|
| 2 |
+
|
| 3 |
import io, json, os, base64, math
|
| 4 |
from pathlib import Path
|
| 5 |
import streamlit as st
|
|
|
|
| 8 |
import joblib
|
| 9 |
from datetime import datetime
|
| 10 |
|
| 11 |
+
# Matplotlib (preview + cross-plot)
|
| 12 |
import matplotlib
|
| 13 |
matplotlib.use("Agg")
|
| 14 |
import matplotlib.pyplot as plt
|
|
|
|
| 18 |
from sklearn.metrics import mean_squared_error, mean_absolute_error
|
| 19 |
|
| 20 |
# =========================
|
| 21 |
+
# Constants / Defaults
|
| 22 |
# =========================
|
| 23 |
+
APP_NAME = "ST_GeoMech_UCS"
|
| 24 |
+
TAGLINE = "Real-Time UCS Tracking While Drilling"
|
| 25 |
+
|
| 26 |
+
# Default features standardized to match Ts/Tc apps.
|
| 27 |
+
# (Older headers are still accepted via alias map below.)
|
| 28 |
+
FEATURES = [
|
| 29 |
+
"WOB (klbf)",
|
| 30 |
+
"Torque (kft.lbf)",
|
| 31 |
+
"SPP (psi)",
|
| 32 |
+
"RPM (1/min)",
|
| 33 |
+
"ROP (ft/h)",
|
| 34 |
+
"Flow Rate (gpm)",
|
| 35 |
+
]
|
| 36 |
+
TARGET = "UCS"
|
| 37 |
+
PRED_COL = "UCS_Pred"
|
| 38 |
+
|
| 39 |
MODELS_DIR = Path("models")
|
| 40 |
DEFAULT_MODEL = MODELS_DIR / "ucs_rf.joblib"
|
| 41 |
MODEL_FALLBACKS = [MODELS_DIR / "model.joblib", MODELS_DIR / "model.pkl"]
|
| 42 |
COLORS = {"pred": "#1f77b4", "actual": "#f2b702", "ref": "#5a5a5a"}
|
| 43 |
|
| 44 |
+
STRICT_VERSION_CHECK = False # optional env banner
|
| 45 |
+
|
| 46 |
+
# ---- Plot sizing ----
|
| 47 |
+
CROSS_W = 350
|
| 48 |
CROSS_H = 350
|
| 49 |
+
TRACK_H = 1000
|
| 50 |
+
TRACK_W = 500
|
|
|
|
| 51 |
FONT_SZ = 13
|
| 52 |
+
BOLD_FONT = "Arial Black, Arial, sans-serif"
|
| 53 |
|
| 54 |
# =========================
|
| 55 |
# Page / CSS
|
| 56 |
# =========================
|
| 57 |
+
st.set_page_config(page_title=APP_NAME, page_icon="logo.png", layout="wide")
|
|
|
|
|
|
|
| 58 |
st.markdown("""
|
| 59 |
<style>
|
| 60 |
.brand-logo { width: 200px; height: auto; object-fit: contain; }
|
| 61 |
+
.centered-container { display: flex; flex-direction: column; align-items: center; text-align: center; }
|
| 62 |
+
.st-message-box { background-color: #f0f2f6; color: #333; padding: 10px; border-radius: 10px; border: 1px solid #e6e9ef; }
|
| 63 |
+
.st-message-box.st-success { background-color: #d4edda; color: #155724; border-color: #c3e6cb; }
|
| 64 |
+
.st-message-box.st-warning { background-color: #fff3cd; color: #856404; border-color: #ffeeba; }
|
| 65 |
+
.st-message-box.st-error { background-color: #f8d7da; color: #721c24; border-color: #f5c6cb; }
|
| 66 |
+
|
| 67 |
+
.main .block-container { overflow: unset !important; }
|
| 68 |
+
div[data-testid="stVerticalBlock"] { overflow: unset !important; }
|
| 69 |
+
|
| 70 |
+
/* Sticky expander & tab header inside preview modal */
|
| 71 |
+
div[data-testid="stExpander"] > details > summary {
|
| 72 |
+
position: sticky; top: 0; z-index: 10; background: #fff; border-bottom: 1px solid #eee;
|
| 73 |
+
}
|
| 74 |
+
div[data-testid="stExpander"] div[data-baseweb="tab-list"] {
|
| 75 |
+
position: sticky; top: 42px; z-index: 9; background: #fff; padding-top: 6px;
|
| 76 |
}
|
| 77 |
</style>
|
| 78 |
""", unsafe_allow_html=True)
|
| 79 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 80 |
TABLE_CENTER_CSS = [
|
| 81 |
dict(selector="th", props=[("text-align", "center")]),
|
| 82 |
dict(selector="td", props=[("text-align", "center")]),
|
| 83 |
]
|
| 84 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 85 |
# =========================
|
| 86 |
# Password gate
|
| 87 |
# =========================
|
|
|
|
| 109 |
st.sidebar.markdown(f"""
|
| 110 |
<div class="centered-container">
|
| 111 |
<img src="{inline_logo('logo.png')}" style="width: 200px; height: auto; object-fit: contain;">
|
| 112 |
+
<div style='font-weight:800;font-size:1.2rem; margin-top: 10px;'>{APP_NAME}</div>
|
| 113 |
<div style='color:#667085;'>Smart Thinking • Secure Access</div>
|
| 114 |
</div>
|
| 115 |
""", unsafe_allow_html=True
|
|
|
|
| 135 |
a = np.asarray(y_true, dtype=float)
|
| 136 |
p = np.asarray(y_pred, dtype=float)
|
| 137 |
if a.size < 2: return float("nan")
|
| 138 |
+
if np.all(a == a[0]) or np.all(p == p[0]): return float("nan")
|
| 139 |
return float(np.corrcoef(a, p)[0, 1])
|
| 140 |
|
| 141 |
@st.cache_resource(show_spinner=False)
|
|
|
|
| 148 |
xl = pd.ExcelFile(bio)
|
| 149 |
return {sh: xl.parse(sh) for sh in xl.sheet_names}
|
| 150 |
|
| 151 |
+
def read_book_bytes(b: bytes):
|
| 152 |
+
return parse_excel(b) if b else {}
|
| 153 |
+
|
| 154 |
+
# ---- Canonical feature aliasing (accept legacy headers) ----
|
| 155 |
+
def _build_alias_map(canonical_features: list[str], target_name: str) -> dict:
|
| 156 |
+
"""
|
| 157 |
+
Map common header variants -> canonical names (from meta FEATURES).
|
| 158 |
+
"""
|
| 159 |
+
def pick(expected_list, variants):
|
| 160 |
+
for v in variants:
|
| 161 |
+
if v in expected_list:
|
| 162 |
+
return v
|
| 163 |
+
return variants[0]
|
| 164 |
+
|
| 165 |
+
can_WOB = pick(canonical_features, ["WOB (klbf)", "WOB, klbf", "WOB(klbf)", "WOB( klbf)"])
|
| 166 |
+
can_TORQUE = pick(canonical_features, ["Torque (kft.lbf)", "Torque(kft.lbf)", "T (kft.lbf)", "TORQUE(kft.lbf)"])
|
| 167 |
+
can_SPP = pick(canonical_features, ["SPP (psi)", "SPP(psi)"])
|
| 168 |
+
can_RPM = pick(canonical_features, ["RPM (1/min)", "RPM(1/min)"])
|
| 169 |
+
can_ROP = pick(canonical_features, ["ROP (ft/h)", "ROP(ft/h)"])
|
| 170 |
+
can_FR = pick(canonical_features, ["Flow Rate (gpm)", "Q, gpm", "Flow Rate, gpm", "Flow Rate,gpm", "Flow Rate , gpm"])
|
| 171 |
+
can_DEPTH = "Depth (ft)"
|
| 172 |
+
|
| 173 |
+
alias = {
|
| 174 |
+
# Features
|
| 175 |
+
"WOB (klbf)": can_WOB, "WOB, klbf": can_WOB, "WOB(klbf)": can_WOB, "WOB( klbf)": can_WOB,
|
| 176 |
+
"Torque (kft.lbf)": can_TORQUE, "Torque(kft.lbf)": can_TORQUE, "T (kft.lbf)": can_TORQUE, "TORQUE(kft.lbf)": can_TORQUE,
|
| 177 |
+
"SPP (psi)": can_SPP, "SPP(psi)": can_SPP,
|
| 178 |
+
"RPM (1/min)": can_RPM, "RPM(1/min)": can_RPM,
|
| 179 |
+
"ROP (ft/h)": can_ROP, "ROP(ft/h)": can_ROP,
|
| 180 |
+
"Flow Rate (gpm)": can_FR, "Q, gpm": can_FR, "Flow Rate, gpm": can_FR, "Flow Rate,gpm": can_FR, "Flow Rate , gpm": can_FR,
|
| 181 |
+
|
| 182 |
+
# Depth (plot only)
|
| 183 |
+
"Depth (ft)": can_DEPTH, "Depth, ft": can_DEPTH, "Depth(ft)": can_DEPTH, "DEPTH, ft": can_DEPTH,
|
| 184 |
+
|
| 185 |
+
# Target aliases
|
| 186 |
+
"UCS": target_name,
|
| 187 |
+
"UCS (psi)": target_name,
|
| 188 |
+
"UCS_Actual": target_name,
|
| 189 |
+
}
|
| 190 |
+
return alias
|
| 191 |
+
|
| 192 |
+
def _normalize_columns(df: pd.DataFrame, canonical_features: list[str], target_name: str) -> pd.DataFrame:
|
| 193 |
+
out = df.copy()
|
| 194 |
+
out.columns = [str(c).strip().replace(" ,", ",").replace(", ", ", ").replace(" ", " ") for c in out.columns]
|
| 195 |
+
alias = _build_alias_map(canonical_features, target_name)
|
| 196 |
+
actual = {k: v for k, v in alias.items() if k in out.columns and k != v}
|
| 197 |
+
return out.rename(columns=actual)
|
| 198 |
|
| 199 |
+
def ensure_cols(df: pd.DataFrame, cols: list[str]) -> bool:
|
| 200 |
miss = [c for c in cols if c not in df.columns]
|
| 201 |
if miss:
|
| 202 |
st.error(f"Missing columns: {miss}\nFound: {list(df.columns)}")
|
|
|
|
| 213 |
return step * math.floor(xmin / step) if np.isfinite(xmin) else xmin
|
| 214 |
|
| 215 |
def df_centered_rounded(df: pd.DataFrame, hide_index=True):
|
|
|
|
| 216 |
out = df.copy()
|
| 217 |
numcols = out.select_dtypes(include=[np.number]).columns
|
| 218 |
styler = (
|
| 219 |
out.style
|
| 220 |
+
.format({c: "{:.2f}" for c in numcols})
|
| 221 |
+
.set_properties(**{"text-align": "center"})
|
| 222 |
+
.set_table_styles(TABLE_CENTER_CSS)
|
| 223 |
)
|
| 224 |
st.dataframe(styler, use_container_width=True, hide_index=hide_index)
|
|
|
|
| 225 |
|
| 226 |
+
# ---------- Build X exactly as trained ----------
|
| 227 |
+
def _make_X(df: pd.DataFrame, features: list[str]) -> pd.DataFrame:
|
| 228 |
+
X = df.reindex(columns=features, copy=False)
|
| 229 |
+
for c in features:
|
| 230 |
+
X[c] = pd.to_numeric(X[c], errors="coerce")
|
| 231 |
+
return X
|
| 232 |
+
|
| 233 |
+
# === Excel export helpers =================================================
|
| 234 |
def _excel_engine() -> str:
|
|
|
|
| 235 |
try:
|
| 236 |
import xlsxwriter # noqa: F401
|
| 237 |
return "xlsxwriter"
|
|
|
|
| 239 |
return "openpyxl"
|
| 240 |
|
| 241 |
def _excel_safe_name(name: str) -> str:
|
|
|
|
| 242 |
bad = '[]:*?/\\'
|
| 243 |
safe = ''.join('_' if ch in bad else ch for ch in str(name))
|
| 244 |
return safe[:31]
|
|
|
|
| 267 |
df.columns = ["Feature", "Min", "Max"]
|
| 268 |
return _round_numeric(df)
|
| 269 |
|
| 270 |
+
def _available_sections() -> list[str]:
|
| 271 |
+
res = st.session_state.get("results", {})
|
| 272 |
+
sections = []
|
| 273 |
+
if "Train" in res: sections += ["Training","Training_Metrics","Training_Summary"]
|
| 274 |
+
if "Test" in res: sections += ["Testing","Testing_Metrics","Testing_Summary"]
|
| 275 |
+
if "Validate" in res: sections += ["Validation","Validation_Metrics","Validation_Summary","Validation_OOR"]
|
| 276 |
+
if "PredictOnly" in res: sections += ["Prediction","Prediction_Summary"]
|
| 277 |
+
if st.session_state.get("train_ranges"): sections += ["Training_Ranges"]
|
| 278 |
+
sections += ["Info"]
|
| 279 |
+
return sections
|
| 280 |
+
|
| 281 |
+
def build_export_workbook(selected: list[str] | None = None) -> tuple[bytes|None, str|None, list[str]]:
|
| 282 |
res = st.session_state.get("results", {})
|
| 283 |
+
if not res: return None, None, []
|
|
|
|
| 284 |
|
| 285 |
sheets: dict[str, pd.DataFrame] = {}
|
| 286 |
order: list[str] = []
|
| 287 |
|
| 288 |
# Training
|
| 289 |
+
if ("Training" in (selected or _available_sections())) and "Train" in res:
|
| 290 |
tr = _round_numeric(res["Train"])
|
| 291 |
sheets["Training"] = tr; order.append("Training")
|
| 292 |
m = res.get("m_train", {})
|
| 293 |
if m:
|
| 294 |
sheets["Training_Metrics"] = _round_numeric(pd.DataFrame([m])); order.append("Training_Metrics")
|
| 295 |
+
tr_cols = FEATURES + [c for c in [TARGET, PRED_COL] if c in tr.columns]
|
| 296 |
s = _summary_table(tr, tr_cols)
|
| 297 |
if not s.empty:
|
| 298 |
sheets["Training_Summary"] = s; order.append("Training_Summary")
|
| 299 |
|
| 300 |
# Testing
|
| 301 |
+
if ("Testing" in (selected or _available_sections())) and "Test" in res:
|
| 302 |
te = _round_numeric(res["Test"])
|
| 303 |
sheets["Testing"] = te; order.append("Testing")
|
| 304 |
m = res.get("m_test", {})
|
| 305 |
if m:
|
| 306 |
sheets["Testing_Metrics"] = _round_numeric(pd.DataFrame([m])); order.append("Testing_Metrics")
|
| 307 |
+
te_cols = FEATURES + [c for c in [TARGET, PRED_COL] if c in te.columns]
|
| 308 |
s = _summary_table(te, te_cols)
|
| 309 |
if not s.empty:
|
| 310 |
sheets["Testing_Summary"] = s; order.append("Testing_Summary")
|
| 311 |
|
| 312 |
# Validation
|
| 313 |
+
if ("Validation" in (selected or _available_sections())) and "Validate" in res:
|
| 314 |
va = _round_numeric(res["Validate"])
|
| 315 |
sheets["Validation"] = va; order.append("Validation")
|
| 316 |
m = res.get("m_val", {})
|
|
|
|
| 321 |
sheets["Validation_Summary"] = _round_numeric(pd.DataFrame([sv])); order.append("Validation_Summary")
|
| 322 |
oor_tbl = res.get("oor_tbl")
|
| 323 |
if oor_tbl is not None and isinstance(oor_tbl, pd.DataFrame) and not oor_tbl.empty:
|
| 324 |
+
sheets["Validation_ORE"] = _round_numeric(oor_tbl.reset_index(drop=True)); order.append("Validation_ORE")
|
| 325 |
|
| 326 |
+
# Prediction
|
| 327 |
+
if ("Prediction" in (selected or _available_sections())) and "PredictOnly" in res:
|
| 328 |
pr = _round_numeric(res["PredictOnly"])
|
| 329 |
sheets["Prediction"] = pr; order.append("Prediction")
|
| 330 |
sv = res.get("sv_pred", {})
|
| 331 |
if sv:
|
| 332 |
sheets["Prediction_Summary"] = _round_numeric(pd.DataFrame([sv])); order.append("Prediction_Summary")
|
| 333 |
|
| 334 |
+
# Ranges
|
| 335 |
tr_ranges = st.session_state.get("train_ranges")
|
| 336 |
+
if ("Training_Ranges" in (selected or _available_sections())) and tr_ranges:
|
| 337 |
rr = _train_ranges_df(tr_ranges)
|
| 338 |
if not rr.empty:
|
| 339 |
sheets["Training_Ranges"] = rr; order.append("Training_Ranges")
|
| 340 |
|
| 341 |
+
# Info
|
| 342 |
info = pd.DataFrame([
|
| 343 |
+
{"Key": "AppName", "Value": APP_NAME},
|
| 344 |
+
{"Key": "Tagline", "Value": TAGLINE},
|
| 345 |
+
{"Key": "Target", "Value": TARGET},
|
| 346 |
+
{"Key": "PredColumn", "Value": PRED_COL},
|
| 347 |
+
{"Key": "Features", "Value": ", ".join(FEATURES)},
|
| 348 |
{"Key": "ExportedAt", "Value": datetime.now().strftime("%Y-%m-%d %H:%M:%S")},
|
| 349 |
])
|
| 350 |
sheets["Info"] = info; order.append("Info")
|
| 351 |
|
|
|
|
| 352 |
bio = io.BytesIO()
|
| 353 |
with pd.ExcelWriter(bio, engine=_excel_engine()) as writer:
|
| 354 |
for name in order:
|
|
|
|
| 359 |
fname = f"UCS_Export_{datetime.now().strftime('%Y%m%d_%H%M%S')}.xlsx"
|
| 360 |
return bio.getvalue(), fname, order
|
| 361 |
|
| 362 |
+
def render_export_button(phase_key: str) -> None:
|
| 363 |
+
res = st.session_state.get("results", {})
|
| 364 |
+
if not res: return
|
| 365 |
st.divider()
|
| 366 |
st.markdown("### Export to Excel")
|
| 367 |
+
|
| 368 |
+
options = _available_sections()
|
| 369 |
+
selected_sheets = st.multiselect(
|
| 370 |
+
"Sheets to include",
|
| 371 |
+
options=options,
|
| 372 |
+
default=[],
|
| 373 |
+
placeholder="Choose option(s)",
|
| 374 |
+
help="Pick the sheets you want to include in the Excel export.",
|
| 375 |
+
key=f"sheets_{phase_key}",
|
| 376 |
+
)
|
| 377 |
+
|
| 378 |
+
if not selected_sheets:
|
| 379 |
+
st.caption("Select one or more sheets above to enable the export.")
|
| 380 |
+
st.download_button(
|
| 381 |
+
label="⬇️ Export Excel",
|
| 382 |
+
data=b"",
|
| 383 |
+
file_name="UCS_Export.xlsx",
|
| 384 |
+
mime="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
| 385 |
+
disabled=True,
|
| 386 |
+
key=f"download_{phase_key}",
|
| 387 |
+
)
|
| 388 |
+
return
|
| 389 |
+
|
| 390 |
+
data, fname, names = build_export_workbook(selected=selected_sheets)
|
| 391 |
if names:
|
| 392 |
+
st.caption("Will include: " + ", ".join(names))
|
| 393 |
st.download_button(
|
| 394 |
+
"⬇️ Export Excel",
|
| 395 |
data=(data or b""),
|
| 396 |
file_name=(fname or "UCS_Export.xlsx"),
|
| 397 |
mime="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
| 398 |
disabled=(data is None),
|
| 399 |
+
key=f"download_{phase_key}",
|
|
|
|
| 400 |
)
|
|
|
|
| 401 |
|
| 402 |
# =========================
|
| 403 |
+
# Cross plot (Matplotlib)
|
| 404 |
# =========================
|
| 405 |
def cross_plot_static(actual, pred):
|
| 406 |
a = pd.Series(actual, dtype=float)
|
| 407 |
p = pd.Series(pred, dtype=float)
|
| 408 |
|
| 409 |
+
# Use data-driven limits with a small pad (or keep your fixed 6000–10000 if you prefer)
|
| 410 |
+
lo = float(min(a.min(), p.min()))
|
| 411 |
+
hi = float(max(a.max(), p.max()))
|
| 412 |
+
pad = 0.03 * (hi - lo if hi > lo else 1.0)
|
| 413 |
+
lo2, hi2 = lo - pad, hi + pad
|
| 414 |
+
ticks = np.linspace(lo2, hi2, 5)
|
| 415 |
|
| 416 |
dpi = 110
|
| 417 |
+
fig, ax = plt.subplots(figsize=(CROSS_W / dpi, CROSS_H / dpi), dpi=dpi, constrained_layout=False)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 418 |
|
| 419 |
ax.scatter(a, p, s=14, c=COLORS["pred"], alpha=0.9, linewidths=0)
|
| 420 |
+
ax.plot([lo2, hi2], [lo2, hi2], linestyle="--", linewidth=1.2, color=COLORS["ref"])
|
|
|
|
| 421 |
|
| 422 |
+
ax.set_xlim(lo2, hi2); ax.set_ylim(lo2, hi2)
|
| 423 |
+
ax.set_xticks(ticks); ax.set_yticks(ticks)
|
| 424 |
+
ax.set_aspect("equal", adjustable="box")
|
|
|
|
|
|
|
| 425 |
|
| 426 |
+
fmt = FuncFormatter(lambda x, _: f"{x:,.0f}")
|
| 427 |
+
ax.xaxis.set_major_formatter(fmt); ax.yaxis.set_major_formatter(fmt)
|
|
|
|
| 428 |
|
| 429 |
+
ax.set_xlabel("Actual UCS (psi)", fontweight="bold", fontsize=10, color="black")
|
| 430 |
ax.set_ylabel("Predicted UCS (psi)", fontweight="bold", fontsize=10, color="black")
|
| 431 |
ax.tick_params(labelsize=6, colors="black")
|
| 432 |
|
| 433 |
ax.grid(True, linestyle=":", alpha=0.3)
|
| 434 |
for spine in ax.spines.values():
|
| 435 |
+
spine.set_linewidth(1.1); spine.set_color("#444")
|
|
|
|
| 436 |
|
| 437 |
fig.subplots_adjust(left=0.16, bottom=0.16, right=0.98, top=0.98)
|
| 438 |
return fig
|
|
|
|
| 443 |
def track_plot(df, include_actual=True):
|
| 444 |
depth_col = next((c for c in df.columns if 'depth' in str(c).lower()), None)
|
| 445 |
if depth_col is not None:
|
| 446 |
+
y = pd.Series(df[depth_col]).astype(float); ylab = depth_col
|
| 447 |
+
y_range = [float(y.max()), float(y.min())] # reversed
|
|
|
|
| 448 |
else:
|
| 449 |
+
y = pd.Series(np.arange(1, len(df) + 1)); ylab = "Point Index"
|
|
|
|
| 450 |
y_range = [float(y.max()), float(y.min())]
|
| 451 |
|
| 452 |
+
x_series = pd.Series(df.get(PRED_COL, pd.Series(dtype=float))).astype(float)
|
|
|
|
| 453 |
if include_actual and TARGET in df.columns:
|
| 454 |
x_series = pd.concat([x_series, pd.Series(df[TARGET]).astype(float)], ignore_index=True)
|
| 455 |
x_lo, x_hi = float(x_series.min()), float(x_series.max())
|
|
|
|
| 458 |
tick0 = _nice_tick0(xmin, step=100)
|
| 459 |
|
| 460 |
fig = go.Figure()
|
| 461 |
+
if PRED_COL in df.columns:
|
| 462 |
+
fig.add_trace(go.Scatter(
|
| 463 |
+
x=df[PRED_COL], y=y, mode="lines",
|
| 464 |
+
line=dict(color=COLORS["pred"], width=1.8),
|
| 465 |
+
name=PRED_COL,
|
| 466 |
+
hovertemplate=f"{PRED_COL}: "+"%{x:.0f}<br>"+ylab+": %{y}<extra></extra>"
|
| 467 |
+
))
|
| 468 |
if include_actual and TARGET in df.columns:
|
| 469 |
fig.add_trace(go.Scatter(
|
| 470 |
x=df[TARGET], y=y, mode="lines",
|
| 471 |
line=dict(color=COLORS["actual"], width=2.0, dash="dot"),
|
| 472 |
+
name=f"{TARGET} (actual)",
|
| 473 |
+
hovertemplate=f"{TARGET}: "+"%{x:.0f}<br>"+ylab+": %{y}<extra></extra>"
|
| 474 |
))
|
| 475 |
|
| 476 |
fig.update_layout(
|
| 477 |
+
height=TRACK_H, width=TRACK_W, autosize=False,
|
|
|
|
|
|
|
| 478 |
paper_bgcolor="#fff", plot_bgcolor="#fff",
|
| 479 |
margin=dict(l=64, r=16, t=36, b=48), hovermode="closest",
|
| 480 |
font=dict(size=FONT_SZ, color="#000"),
|
| 481 |
+
legend=dict(x=0.98, y=0.05, xanchor="right", yanchor="bottom",
|
| 482 |
+
bgcolor="rgba(255,255,255,0.75)", bordercolor="#ccc", borderwidth=1),
|
|
|
|
|
|
|
| 483 |
legend_title_text=""
|
| 484 |
)
|
|
|
|
|
|
|
| 485 |
fig.update_xaxes(
|
| 486 |
title_text="UCS (psi)",
|
| 487 |
title_font=dict(size=20, family=BOLD_FONT, color="#000"),
|
| 488 |
tickfont=dict(size=15, family=BOLD_FONT, color="#000"),
|
| 489 |
+
side="top", range=[xmin, xmax],
|
| 490 |
+
ticks="outside", tickformat=",.0f", tickmode="auto", tick0=tick0,
|
|
|
|
|
|
|
|
|
|
|
|
|
| 491 |
showline=True, linewidth=1.2, linecolor="#444", mirror=True,
|
| 492 |
showgrid=True, gridcolor="rgba(0,0,0,0.12)", automargin=True
|
| 493 |
)
|
|
|
|
| 495 |
title_text=ylab,
|
| 496 |
title_font=dict(size=20, family=BOLD_FONT, color="#000"),
|
| 497 |
tickfont=dict(size=15, family=BOLD_FONT, color="#000"),
|
| 498 |
+
range=y_range, ticks="outside",
|
|
|
|
| 499 |
showline=True, linewidth=1.2, linecolor="#444", mirror=True,
|
| 500 |
showgrid=True, gridcolor="rgba(0,0,0,0.12)", automargin=True
|
| 501 |
)
|
|
|
|
| 502 |
return fig
|
| 503 |
|
| 504 |
+
# ---------- Preview (Matplotlib) ----------
|
| 505 |
def preview_tracks(df: pd.DataFrame, cols: list[str]):
|
| 506 |
+
"""
|
| 507 |
+
Multi-track quick-look:
|
| 508 |
+
- distinct color per input (stable tab20 palette)
|
| 509 |
+
- shared Y & reversed (Depth down if available)
|
| 510 |
+
"""
|
| 511 |
cols = [c for c in cols if c in df.columns]
|
| 512 |
n = len(cols)
|
| 513 |
if n == 0:
|
| 514 |
fig, ax = plt.subplots(figsize=(4, 2))
|
| 515 |
+
ax.text(0.5, 0.5, "No selected columns", ha="center", va="center"); ax.axis("off")
|
| 516 |
return fig
|
| 517 |
+
|
| 518 |
+
# Depth or fallback
|
| 519 |
+
depth_col = next((c for c in df.columns if 'depth' in str(c).lower()), None)
|
| 520 |
+
if depth_col is not None:
|
| 521 |
+
idx = pd.to_numeric(df[depth_col], errors="coerce")
|
| 522 |
+
y_label = depth_col
|
| 523 |
+
else:
|
| 524 |
+
idx = pd.Series(np.arange(1, len(df) + 1))
|
| 525 |
+
y_label = "Point Index"
|
| 526 |
+
|
| 527 |
+
cmap = plt.get_cmap("tab20")
|
| 528 |
+
col_colors = {col: cmap(i % cmap.N) for i, col in enumerate(cols)}
|
| 529 |
+
|
| 530 |
+
fig, axes = plt.subplots(1, n, figsize=(2.3 * n, 7.0), sharey=True, dpi=100)
|
| 531 |
if n == 1: axes = [axes]
|
| 532 |
+
|
| 533 |
+
y_min, y_max = float(idx.min()), float(idx.max())
|
| 534 |
+
for i, (ax, col) in enumerate(zip(axes, cols)):
|
| 535 |
+
x = pd.to_numeric(df[col], errors="coerce")
|
| 536 |
+
ax.plot(x, idx, '-', lw=1.8, color=col_colors[col])
|
| 537 |
+
ax.set_xlabel(col); ax.xaxis.set_label_position('top'); ax.xaxis.tick_top()
|
| 538 |
+
ax.set_ylim(y_max, y_min) # reversed
|
| 539 |
ax.grid(True, linestyle=":", alpha=0.3)
|
| 540 |
+
if i == 0:
|
| 541 |
+
ax.set_ylabel(y_label)
|
| 542 |
+
else:
|
| 543 |
+
ax.tick_params(labelleft=False)
|
| 544 |
+
ax.set_ylabel("")
|
| 545 |
+
fig.tight_layout()
|
| 546 |
return fig
|
| 547 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 548 |
# =========================
|
| 549 |
+
# Load model + meta
|
| 550 |
# =========================
|
| 551 |
def ensure_model() -> Path|None:
|
| 552 |
for p in [DEFAULT_MODEL, *MODEL_FALLBACKS]:
|
|
|
|
| 575 |
st.error(f"Failed to load model: {e}")
|
| 576 |
st.stop()
|
| 577 |
|
| 578 |
+
# Prefer UCS-specific meta
|
| 579 |
+
meta = {}
|
| 580 |
+
meta_candidates = [MODELS_DIR / "ucs_meta.json", MODELS_DIR / "meta.json"]
|
| 581 |
+
meta_path = next((p for p in meta_candidates if p.exists()), None)
|
| 582 |
+
if meta_path:
|
| 583 |
try:
|
| 584 |
meta = json.loads(meta_path.read_text(encoding="utf-8"))
|
| 585 |
+
FEATURES = meta.get("features", FEATURES)
|
| 586 |
+
TARGET = meta.get("target", TARGET)
|
| 587 |
+
PRED_COL = meta.get("pred_col", PRED_COL)
|
| 588 |
+
except Exception as e:
|
| 589 |
+
st.warning(f"Could not parse meta file ({meta_path.name}): {e}")
|
| 590 |
+
|
| 591 |
+
# Optional: version banner
|
| 592 |
+
if STRICT_VERSION_CHECK and meta.get("versions"):
|
| 593 |
+
import numpy as _np, sklearn as _skl
|
| 594 |
+
mv = meta["versions"]; msg=[]
|
| 595 |
+
if mv.get("numpy") and mv["numpy"] != _np.__version__:
|
| 596 |
+
msg.append(f"NumPy {mv['numpy']} expected, running {_np.__version__}")
|
| 597 |
+
if mv.get("scikit_learn") and mv["scikit_learn"] != _skl.__version__:
|
| 598 |
+
msg.append(f"scikit-learn {mv['scikit_learn']} expected, running {_skl.__version__}")
|
| 599 |
+
if msg:
|
| 600 |
+
st.warning("Environment mismatch: " + " | ".join(msg))
|
| 601 |
|
| 602 |
# =========================
|
| 603 |
# Session state
|
|
|
|
| 609 |
st.session_state.setdefault("dev_file_bytes",b"")
|
| 610 |
st.session_state.setdefault("dev_file_loaded",False)
|
| 611 |
st.session_state.setdefault("dev_preview",False)
|
| 612 |
+
st.session_state.setdefault("show_preview_modal", False)
|
| 613 |
|
| 614 |
# =========================
|
| 615 |
+
# Sidebar branding
|
| 616 |
# =========================
|
| 617 |
st.sidebar.markdown(f"""
|
| 618 |
<div class="centered-container">
|
| 619 |
<img src="{inline_logo('logo.png')}" style="width: 200px; height: auto; object-fit: contain;">
|
| 620 |
+
<div style='font-weight:800;font-size:1.2rem;'>{APP_NAME}</div>
|
| 621 |
+
<div style='color:#667085;'>{TAGLINE}</div>
|
| 622 |
</div>
|
| 623 |
""", unsafe_allow_html=True
|
| 624 |
)
|
| 625 |
|
|
|
|
|
|
|
|
|
|
| 626 |
def sticky_header(title, message):
|
| 627 |
st.markdown(
|
| 628 |
f"""
|
| 629 |
<style>
|
| 630 |
.sticky-container {{
|
| 631 |
+
position: sticky; top: 0; background-color: white; z-index: 100;
|
| 632 |
+
padding-top: 10px; padding-bottom: 10px; border-bottom: 1px solid #eee;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 633 |
}}
|
| 634 |
</style>
|
| 635 |
<div class="sticky-container">
|
|
|
|
| 645 |
# =========================
|
| 646 |
if st.session_state.app_step == "intro":
|
| 647 |
st.header("Welcome!")
|
| 648 |
+
st.markdown("This software is developed by *Smart Thinking AI-Solutions Team* to estimate **UCS** from drilling data.")
|
| 649 |
st.subheader("How It Works")
|
| 650 |
st.markdown(
|
| 651 |
+
"1) **Upload your data to build the case and preview the model performance.** \n"
|
| 652 |
"2) Click **Run Model** to compute metrics and plots. \n"
|
| 653 |
"3) **Proceed to Validation** (with actual UCS) or **Proceed to Prediction** (no UCS)."
|
| 654 |
)
|
|
|
|
| 673 |
st.sidebar.caption(f"**Data loaded:** {st.session_state.dev_file_name} • {df0.shape[0]} rows × {df0.shape[1]} cols")
|
| 674 |
|
| 675 |
if st.sidebar.button("Preview data", use_container_width=True, disabled=not st.session_state.dev_file_loaded):
|
| 676 |
+
st.session_state.show_preview_modal = True
|
| 677 |
st.session_state.dev_preview = True
|
| 678 |
|
| 679 |
run = st.sidebar.button("Run Model", type="primary", use_container_width=True)
|
| 680 |
if st.sidebar.button("Proceed to Validation ▶", use_container_width=True): st.session_state.app_step="validate"; st.rerun()
|
| 681 |
if st.sidebar.button("Proceed to Prediction ▶", use_container_width=True): st.session_state.app_step="predict"; st.rerun()
|
| 682 |
|
|
|
|
| 683 |
if st.session_state.dev_file_loaded and st.session_state.dev_preview:
|
| 684 |
sticky_header("Case Building", "Previewed ✓ — now click **Run Model**.")
|
| 685 |
elif st.session_state.dev_file_loaded:
|
|
|
|
| 690 |
if run and st.session_state.dev_file_bytes:
|
| 691 |
book = read_book_bytes(st.session_state.dev_file_bytes)
|
| 692 |
sh_train = find_sheet(book, ["Train","Training","training2","train","training"])
|
| 693 |
+
sh_test = find_sheet(book, ["Test","Testing","testing2","test","testing"])
|
| 694 |
if sh_train is None or sh_test is None:
|
| 695 |
st.markdown('<div class="st-message-box st-error">Workbook must include Train/Training/training2 and Test/Testing/testing2 sheets.</div>', unsafe_allow_html=True)
|
| 696 |
st.stop()
|
| 697 |
+
|
| 698 |
+
tr = _normalize_columns(book[sh_train].copy(), FEATURES, TARGET)
|
| 699 |
+
te = _normalize_columns(book[sh_test].copy(), FEATURES, TARGET)
|
| 700 |
+
|
| 701 |
if not (ensure_cols(tr, FEATURES+[TARGET]) and ensure_cols(te, FEATURES+[TARGET])):
|
| 702 |
st.markdown('<div class="st-message-box st-error">Missing required columns.</div>', unsafe_allow_html=True)
|
| 703 |
st.stop()
|
| 704 |
+
|
| 705 |
+
tr[PRED_COL] = model.predict(_make_X(tr, FEATURES))
|
| 706 |
+
te[PRED_COL] = model.predict(_make_X(te, FEATURES))
|
| 707 |
|
| 708 |
st.session_state.results["Train"]=tr; st.session_state.results["Test"]=te
|
| 709 |
st.session_state.results["m_train"]={
|
| 710 |
+
"R": pearson_r(tr[TARGET], tr[PRED_COL]),
|
| 711 |
+
"RMSE": rmse(tr[TARGET], tr[PRED_COL]),
|
| 712 |
+
"MAE": mean_absolute_error(tr[TARGET], tr[PRED_COL])
|
| 713 |
}
|
| 714 |
st.session_state.results["m_test"]={
|
| 715 |
+
"R": pearson_r(te[TARGET], te[PRED_COL]),
|
| 716 |
+
"RMSE": rmse(te[TARGET], te[PRED_COL]),
|
| 717 |
+
"MAE": mean_absolute_error(te[TARGET], te[PRED_COL])
|
| 718 |
}
|
| 719 |
|
| 720 |
tr_min = tr[FEATURES].min().to_dict(); tr_max = tr[FEATURES].max().to_dict()
|
|
|
|
| 723 |
|
| 724 |
def _dev_block(df, m):
|
| 725 |
c1,c2,c3 = st.columns(3)
|
| 726 |
+
c1.metric("R", f"{m['R']:.3f}"); c2.metric("RMSE", f"{m['RMSE']:.2f}"); c3.metric("MAE", f"{m['MAE']:.2f}")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 727 |
st.markdown("""
|
| 728 |
<div style='text-align: left; font-size: 0.8em; color: #6b7280; margin-top: -16px; margin-bottom: 8px;'>
|
| 729 |
<strong>R:</strong> Pearson Correlation Coefficient<br>
|
|
|
|
| 731 |
<strong>MAE:</strong> Mean Absolute Error
|
| 732 |
</div>
|
| 733 |
""", unsafe_allow_html=True)
|
|
|
|
|
|
|
| 734 |
col_track, col_cross = st.columns([2, 3], gap="large")
|
| 735 |
with col_track:
|
| 736 |
+
st.plotly_chart(track_plot(df, include_actual=True), use_container_width=False, config={"displayModeBar": False, "scrollZoom": True})
|
|
|
|
|
|
|
|
|
|
|
|
|
| 737 |
with col_cross:
|
| 738 |
+
st.pyplot(cross_plot_static(df[TARGET], df[PRED_COL]), use_container_width=False)
|
|
|
|
| 739 |
|
| 740 |
if "Train" in st.session_state.results or "Test" in st.session_state.results:
|
| 741 |
tab1, tab2 = st.tabs(["Training", "Testing"])
|
|
|
|
| 743 |
with tab1: _dev_block(st.session_state.results["Train"], st.session_state.results["m_train"])
|
| 744 |
if "Test" in st.session_state.results:
|
| 745 |
with tab2: _dev_block(st.session_state.results["Test"], st.session_state.results["m_test"])
|
| 746 |
+
render_export_button(phase_key="dev")
|
| 747 |
|
| 748 |
# =========================
|
| 749 |
# VALIDATION (with actual UCS)
|
|
|
|
| 757 |
df0 = next(iter(book.values()))
|
| 758 |
st.sidebar.caption(f"**Data loaded:** {up.name} • {df0.shape[0]} rows × {df0.shape[1]} cols")
|
| 759 |
if st.sidebar.button("Preview data", use_container_width=True, disabled=(up is None)):
|
| 760 |
+
st.session_state.show_preview_modal = True
|
| 761 |
go_btn = st.sidebar.button("Predict & Validate", type="primary", use_container_width=True)
|
| 762 |
if st.sidebar.button("⬅ Back to Case Building", use_container_width=True): st.session_state.app_step="dev"; st.rerun()
|
| 763 |
if st.sidebar.button("Proceed to Prediction ▶", use_container_width=True): st.session_state.app_step="predict"; st.rerun()
|
|
|
|
| 767 |
if go_btn and up is not None:
|
| 768 |
book = read_book_bytes(up.getvalue())
|
| 769 |
name = find_sheet(book, ["Validation","Validate","validation2","Val","val"]) or list(book.keys())[0]
|
| 770 |
+
df = _normalize_columns(book[name].copy(), FEATURES, TARGET)
|
| 771 |
+
if not ensure_cols(df, FEATURES+[TARGET]):
|
| 772 |
+
st.markdown('<div class="st-message-box st-error">Missing required columns.</div>', unsafe_allow_html=True); st.stop()
|
| 773 |
+
df[PRED_COL] = model.predict(_make_X(df, FEATURES))
|
| 774 |
st.session_state.results["Validate"]=df
|
| 775 |
|
| 776 |
ranges = st.session_state.train_ranges; oor_pct = 0.0; tbl=None
|
|
|
|
| 781 |
tbl = df.loc[any_viol, FEATURES].copy()
|
| 782 |
for c in FEATURES:
|
| 783 |
if pd.api.types.is_numeric_dtype(tbl[c]): tbl[c] = tbl[c].round(2)
|
| 784 |
+
tbl["Violations"] = pd.DataFrame({f:(df[f]<ranges[f][0])|(df[f]>ranges[f][1]) for f in FEATURES}).loc[any_viol].apply(
|
| 785 |
+
lambda r:", ".join([c for c,v in r.items() if v]), axis=1
|
| 786 |
+
)
|
| 787 |
st.session_state.results["m_val"]={
|
| 788 |
+
"R": pearson_r(df[TARGET], df[PRED_COL]),
|
| 789 |
+
"RMSE": rmse(df[TARGET], df[PRED_COL]),
|
| 790 |
+
"MAE": mean_absolute_error(df[TARGET], df[PRED_COL])
|
| 791 |
}
|
| 792 |
+
st.session_state.results["sv_val"]={"n":len(df), "pred_min":float(df[PRED_COL].min()), "pred_max":float(df[PRED_COL].max()), "oor":oor_pct}
|
| 793 |
st.session_state.results["oor_tbl"]=tbl
|
| 794 |
|
| 795 |
if "Validate" in st.session_state.results:
|
| 796 |
m = st.session_state.results["m_val"]
|
| 797 |
c1,c2,c3 = st.columns(3)
|
| 798 |
+
c1.metric("R", f"{m['R']:.3f}"); c2.metric("RMSE", f"{m['RMSE']:.2f}"); c3.metric("MAE", f"{m['MAE']:.2f}")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 799 |
st.markdown("""
|
| 800 |
<div style='text-align: left; font-size: 0.8em; color: #6b7280; margin-top: -16px; margin-bottom: 8px;'>
|
| 801 |
<strong>R:</strong> Pearson Correlation Coefficient<br>
|
|
|
|
| 803 |
<strong>MAE:</strong> Mean Absolute Error
|
| 804 |
</div>
|
| 805 |
""", unsafe_allow_html=True)
|
| 806 |
+
|
| 807 |
col_track, col_cross = st.columns([2, 3], gap="large")
|
| 808 |
with col_track:
|
| 809 |
+
st.plotly_chart(track_plot(st.session_state.results["Validate"], include_actual=True),
|
| 810 |
+
use_container_width=False, config={"displayModeBar": False, "scrollZoom": True})
|
|
|
|
|
|
|
|
|
|
| 811 |
with col_cross:
|
| 812 |
+
st.pyplot(cross_plot_static(st.session_state.results["Validate"][TARGET],
|
| 813 |
+
st.session_state.results["Validate"][PRED_COL]),
|
| 814 |
+
use_container_width=False)
|
| 815 |
+
|
| 816 |
+
render_export_button(phase_key="validate")
|
| 817 |
|
| 818 |
sv = st.session_state.results["sv_val"]
|
| 819 |
if sv["oor"] > 0: st.markdown('<div class="st-message-box st-warning">Some inputs fall outside **training min–max** ranges.</div>', unsafe_allow_html=True)
|
|
|
|
| 833 |
df0 = next(iter(book.values()))
|
| 834 |
st.sidebar.caption(f"**Data loaded:** {up.name} • {df0.shape[0]} rows × {df0.shape[1]} cols")
|
| 835 |
if st.sidebar.button("Preview data", use_container_width=True, disabled=(up is None)):
|
| 836 |
+
st.session_state.show_preview_modal = True
|
| 837 |
go_btn = st.sidebar.button("Predict", type="primary", use_container_width=True)
|
| 838 |
if st.sidebar.button("⬅ Back to Case Building", use_container_width=True): st.session_state.app_step="dev"; st.rerun()
|
| 839 |
|
|
|
|
| 841 |
|
| 842 |
if go_btn and up is not None:
|
| 843 |
book = read_book_bytes(up.getvalue()); name = list(book.keys())[0]
|
| 844 |
+
df = _normalize_columns(book[name].copy(), FEATURES, TARGET)
|
| 845 |
+
if not ensure_cols(df, FEATURES):
|
| 846 |
+
st.markdown('<div class="st-message-box st-error">Missing required columns.</div>', unsafe_allow_html=True); st.stop()
|
| 847 |
+
df[PRED_COL] = model.predict(_make_X(df, FEATURES))
|
| 848 |
st.session_state.results["PredictOnly"]=df
|
| 849 |
|
| 850 |
ranges = st.session_state.train_ranges; oor_pct = 0.0
|
|
|
|
| 853 |
oor_pct = float(any_viol.mean()*100.0)
|
| 854 |
st.session_state.results["sv_pred"]={
|
| 855 |
"n":len(df),
|
| 856 |
+
"pred_min":float(df[PRED_COL].min()),
|
| 857 |
+
"pred_max":float(df[PRED_COL].max()),
|
| 858 |
+
"pred_mean":float(df[PRED_COL].mean()),
|
| 859 |
+
"pred_std":float(df[PRED_COL].std(ddof=0)),
|
| 860 |
"oor":oor_pct
|
| 861 |
}
|
| 862 |
|
|
|
|
| 867 |
with col_left:
|
| 868 |
table = pd.DataFrame({
|
| 869 |
"Metric": ["# points","Pred min","Pred max","Pred mean","Pred std","OOR %"],
|
| 870 |
+
"Value": [sv["n"], round(sv["pred_min"],2), round(sv["pred_max"],2),
|
| 871 |
+
round(sv["pred_mean"],2), round(sv["pred_std"],2), f'{sv["oor"]:.1f}%']
|
|
|
|
|
|
|
|
|
|
|
|
|
| 872 |
})
|
| 873 |
st.markdown('<div class="st-message-box st-success">Predictions ready ✓</div>', unsafe_allow_html=True)
|
| 874 |
df_centered_rounded(table, hide_index=True)
|
| 875 |
st.caption("**★ OOR** = % of rows whose input features fall outside the training min–max range.")
|
| 876 |
with col_right:
|
| 877 |
+
st.plotly_chart(track_plot(df, include_actual=False),
|
| 878 |
+
use_container_width=False, config={"displayModeBar": False, "scrollZoom": True})
|
| 879 |
+
|
| 880 |
+
render_export_button(phase_key="predict")
|
|
|
|
| 881 |
|
| 882 |
# =========================
|
| 883 |
+
# Preview modal
|
| 884 |
# =========================
|
| 885 |
if st.session_state.show_preview_modal:
|
|
|
|
| 886 |
book_to_preview = {}
|
| 887 |
if st.session_state.app_step == "dev":
|
| 888 |
book_to_preview = read_book_bytes(st.session_state.dev_file_bytes)
|
|
|
|
| 897 |
tabs = st.tabs(names)
|
| 898 |
for t, name in zip(tabs, names):
|
| 899 |
with t:
|
| 900 |
+
df = _normalize_columns(book_to_preview[name], FEATURES, TARGET)
|
| 901 |
t1, t2 = st.tabs(["Tracks", "Summary"])
|
| 902 |
with t1:
|
| 903 |
st.pyplot(preview_tracks(df, FEATURES), use_container_width=True)
|
| 904 |
with t2:
|
| 905 |
+
feat_present = [c for c in FEATURES if c in df.columns]
|
| 906 |
+
if not feat_present:
|
| 907 |
+
st.info("No feature columns found to summarize.")
|
| 908 |
+
else:
|
| 909 |
+
tbl = (
|
| 910 |
+
df[feat_present]
|
| 911 |
+
.agg(['min','max','mean','std'])
|
| 912 |
+
.T.rename(columns={"min":"Min","max":"Max","mean":"Mean","std":"Std"})
|
| 913 |
+
.reset_index(names="Feature")
|
| 914 |
+
)
|
| 915 |
+
df_centered_rounded(tbl)
|
| 916 |
+
|
| 917 |
st.session_state.show_preview_modal = False
|
| 918 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 919 |
# =========================
|
| 920 |
# Footer
|
| 921 |
# =========================
|