Spaces:
Running
Running
File size: 14,883 Bytes
51f1be8 fcfb021 51f1be8 fcfb021 51f1be8 fcfb021 51f1be8 fcfb021 51f1be8 fcfb021 51f1be8 fcfb021 51f1be8 fcfb021 51f1be8 fcfb021 51f1be8 fcfb021 51f1be8 fcfb021 51f1be8 fcfb021 51f1be8 fcfb021 51f1be8 fcfb021 51f1be8 fcfb021 51f1be8 fcfb021 51f1be8 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 | import difflib
from datetime import datetime
from pathlib import Path
from typing import List
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
from plotly.subplots import make_subplots
RET_VARIANTS = [
"K666N",
"L790F",
"Y791F",
"V804M",
"S891A",
"R525W",
"M918T",
"C618S",
"C620Y",
"C630R",
"C634R",
"C634Y",
"C634W",
"C634G",
]
REQUIRED_COLUMNS = [
"patient_id",
"age",
"gender",
"ret_variant",
"calcitonin_level",
]
OPTIONAL_DEFAULTS = {
"cea_level": None,
"thyroid_nodules": False,
"multiple_nodules": False,
"family_history_mtc": False,
"pheochromocytoma": False,
"hyperparathyroidism": False,
}
CALCITONIN_ELEVATED_THRESHOLD = 10.0
def _normalize_column_name(name: str) -> str:
return str(name).strip().lower()
def _normalize_gender(value):
if value is None or (isinstance(value, float) and np.isnan(value)):
return None
text = str(value).strip().lower()
if text in {"male", "m"}:
return "Male"
if text in {"female", "f"}:
return "Female"
return None
def _normalize_bool(value):
if isinstance(value, bool):
return value
if value is None or (isinstance(value, float) and np.isnan(value)):
return None
text = str(value).strip().lower()
if text in {"yes", "true", "1", "y"}:
return True
if text in {"no", "false", "0", "n"}:
return False
return None
def _safe_float(value):
if value is None or (isinstance(value, float) and np.isnan(value)):
return None
try:
return float(value)
except Exception:
return None
def _infer_ret_risk_level(variant: str) -> str:
highest = {"M918T", "A883F"}
high = {"C634R", "C634Y", "C634W", "C634S", "C634G"}
if variant in highest:
return "Highest"
if variant in high:
return "High"
return "Moderate"
def _suggest_variant(value: str) -> str:
matches = difflib.get_close_matches(value, RET_VARIANTS, n=1, cutoff=0.6)
return matches[0] if matches else ""
def _make_recommendations(risk_level: str, probability: float) -> str:
if probability is None:
return "Unable to compute the research model score."
return (
"Research output only; do not use this threshold result for diagnosis, "
"screening, referral, genetic testing, or treatment decisions."
)
def _build_stats(valid_df: pd.DataFrame, invalid_count: int, total: int) -> dict:
above_count = (
int((valid_df["risk_level"] == "Above threshold").sum())
if not valid_df.empty
else 0
)
avg_probability = float(valid_df["probability"].mean()) if not valid_df.empty else 0.0
return {
"total": total,
"valid": len(valid_df),
"invalid": invalid_count,
"above": above_count,
"below": len(valid_df) - above_count,
"avg_probability": avg_probability,
}
def _stats_to_html(stats: dict, warnings: List[str]) -> str:
warning_html = ""
if warnings:
warning_items = "".join(f"<li>{w}</li>" for w in warnings)
warning_html = f"<ul>{warning_items}</ul>"
return f"""
<div>
<h4>Cohort Summary</h4>
<p><strong>Total rows:</strong> {stats['total']}</p>
<p><strong>Valid predictions:</strong> {stats['valid']}</p>
<p><strong>Rows with errors:</strong> {stats['invalid']}</p>
<p><strong>Above threshold:</strong> {stats['above']} | <strong>Below threshold:</strong> {stats['below']}</p>
<p><strong>Average model score:</strong> {stats['avg_probability']:.1f}%</p>
{warning_html}
</div>
"""
def _risk_distribution_chart(valid_df: pd.DataFrame):
if valid_df.empty:
return go.Figure()
counts = valid_df["risk_level"].value_counts().reset_index()
counts.columns = ["risk_level", "count"]
fig = px.pie(
counts,
values="count",
names="risk_level",
title="Benchmark Threshold Distribution",
color="risk_level",
color_discrete_map={
"Above threshold": "#d97706",
"Below threshold": "#2563eb",
},
)
fig.update_traces(textposition="inside", textinfo="percent+label")
fig.update_layout(height=520)
return fig
def _age_probability_scatter(valid_df: pd.DataFrame):
if valid_df.empty:
return go.Figure()
fig = px.scatter(
valid_df,
x="age",
y="probability",
color="risk_level",
title="Age vs Model Score",
hover_data=["patient_id", "ret_variant"],
labels={"probability": "Model Score (%)", "age": "Age"},
color_discrete_map={
"Above threshold": "#d97706",
"Below threshold": "#2563eb",
},
)
fig.update_layout(height=520)
return fig
def _variant_comparison_bar(valid_df: pd.DataFrame):
if valid_df.empty:
return go.Figure()
grouped = (
valid_df.groupby("ret_variant")["probability"]
.mean()
.reset_index()
.sort_values("probability", ascending=False)
)
fig = px.bar(
grouped,
x="ret_variant",
y="probability",
title="Variant Comparison (Average Probability)",
labels={"ret_variant": "RET Variant", "probability": "Avg Probability (%)"},
)
fig.update_layout(xaxis_tickangle=-45)
fig.update_layout(height=520)
return fig
def _biomarker_histograms(valid_df: pd.DataFrame):
if valid_df.empty:
return go.Figure()
fig = make_subplots(rows=1, cols=2, subplot_titles=("Calcitonin", "CEA"))
fig.add_trace(
go.Histogram(x=valid_df["calcitonin_level"], name="Calcitonin (pg/mL)"),
row=1,
col=1,
)
fig.add_trace(
go.Histogram(x=valid_df["cea_level"], name="CEA (ng/mL)", marker_color="#1f77b4"),
row=1,
col=2,
)
fig.update_layout(title_text="Biomarker Distributions", showlegend=False, height=520)
return fig
def process_batch(csv_file, model_key, predictor, output_dir="batch_outputs", progress=None):
if csv_file is None:
empty_df = pd.DataFrame()
return (
empty_df,
"<p>Please upload a CSV file to begin analysis.</p>",
go.Figure(),
go.Figure(),
go.Figure(),
go.Figure(),
None,
)
file_path = csv_file.name if hasattr(csv_file, "name") else str(csv_file)
try:
raw_df = pd.read_csv(file_path)
except Exception as exc:
empty_df = pd.DataFrame()
return (
empty_df,
f"<p><strong>Error:</strong> Unable to read CSV file ({exc}).</p>",
go.Figure(),
go.Figure(),
go.Figure(),
go.Figure(),
None,
)
if raw_df.empty:
empty_df = pd.DataFrame()
return (
empty_df,
"<p><strong>Error:</strong> CSV file is empty.</p>",
go.Figure(),
go.Figure(),
go.Figure(),
go.Figure(),
None,
)
normalized_columns = {_normalize_column_name(c): c for c in raw_df.columns}
df = raw_df.rename(columns={v: k for k, v in normalized_columns.items()})
missing_required = [c for c in REQUIRED_COLUMNS if c not in df.columns]
if missing_required:
empty_df = pd.DataFrame()
missing_list = ", ".join(missing_required)
return (
empty_df,
f"<p><strong>Error:</strong> Missing required columns: {missing_list}</p>",
go.Figure(),
go.Figure(),
go.Figure(),
go.Figure(),
None,
)
for column, default_value in OPTIONAL_DEFAULTS.items():
if column not in df.columns:
df[column] = default_value
if "ret_risk_level" not in df.columns:
df["ret_risk_level"] = None
if "calcitonin_elevated" not in df.columns:
df["calcitonin_elevated"] = None
results = []
warnings = []
total_rows = len(df)
for idx, row in df.iterrows():
if progress is not None and total_rows > 100:
progress((idx + 1) / total_rows, desc="Analyzing patients...")
errors = []
patient_id = row.get("patient_id")
if patient_id is None or str(patient_id).strip() == "":
errors.append("Missing patient_id")
patient_id = f"Row {idx + 1}"
age = _safe_float(row.get("age"))
if age is None:
errors.append("Invalid age")
gender = _normalize_gender(row.get("gender"))
if gender is None:
errors.append("Invalid gender (use Male/Female)")
variant_raw = row.get("ret_variant")
variant = str(variant_raw).strip()
variant_upper = variant.upper()
variant_lookup = {v.upper(): v for v in RET_VARIANTS}
if variant_upper in variant_lookup:
variant = variant_lookup[variant_upper]
else:
suggestion = _suggest_variant(variant)
message = "Invalid ret_variant"
if suggestion:
message += f" (did you mean {suggestion}?)"
errors.append(message)
calcitonin_level = _safe_float(row.get("calcitonin_level"))
if calcitonin_level is None:
errors.append("Invalid calcitonin_level")
cea_level = _safe_float(row.get("cea_level"))
if cea_level is None:
cea_level = OPTIONAL_DEFAULTS["cea_level"]
thyroid_nodules = _normalize_bool(row.get("thyroid_nodules"))
if thyroid_nodules is None:
thyroid_nodules = OPTIONAL_DEFAULTS["thyroid_nodules"]
multiple_nodules = _normalize_bool(row.get("multiple_nodules"))
if multiple_nodules is None:
multiple_nodules = OPTIONAL_DEFAULTS["multiple_nodules"]
family_history = _normalize_bool(row.get("family_history_mtc"))
if family_history is None:
family_history = OPTIONAL_DEFAULTS["family_history_mtc"]
pheochromocytoma = _normalize_bool(row.get("pheochromocytoma"))
if pheochromocytoma is None:
pheochromocytoma = OPTIONAL_DEFAULTS["pheochromocytoma"]
hyperparathyroidism = _normalize_bool(row.get("hyperparathyroidism"))
if hyperparathyroidism is None:
hyperparathyroidism = OPTIONAL_DEFAULTS["hyperparathyroidism"]
ret_risk_level = row.get("ret_risk_level")
if ret_risk_level is None or (isinstance(ret_risk_level, float) and np.isnan(ret_risk_level)):
ret_risk_level = _infer_ret_risk_level(variant)
calcitonin_elevated = _normalize_bool(row.get("calcitonin_elevated"))
if calcitonin_elevated is None and calcitonin_level is not None:
calcitonin_elevated = calcitonin_level >= CALCITONIN_ELEVATED_THRESHOLD
if calcitonin_elevated is None:
calcitonin_elevated = False
patient_data = {
"age": age,
"gender": gender,
"ret_variant": variant,
"ret_risk_level": ret_risk_level,
"calcitonin_elevated": "Yes" if calcitonin_elevated else "No",
"calcitonin_level": calcitonin_level,
"cea_level": cea_level,
"thyroid_nodules": "Yes" if thyroid_nodules else "No",
"multiple_nodules": "Yes" if multiple_nodules else "No",
"family_history": "Yes" if family_history else "No",
"pheochromocytoma": "Yes" if pheochromocytoma else "No",
"hyperparathyroidism": "Yes" if hyperparathyroidism else "No",
}
if errors:
results.append(
{
"patient_id": patient_id,
"risk_level": "Invalid",
"probability": None,
"recommendations": "Unable to score due to input errors.",
"error": "; ".join(errors),
"age": age,
"gender": gender,
"ret_variant": variant,
"calcitonin_level": calcitonin_level,
"cea_level": cea_level,
}
)
continue
try:
prediction = predictor.predict(patient_data, model_key)
probability = prediction["probability"] * 100.0
risk_level = "Above threshold" if prediction["prediction"] == 1 else "Below threshold"
except Exception as exc:
results.append(
{
"patient_id": patient_id,
"risk_level": "Error",
"probability": None,
"recommendations": "Prediction failed. Review inputs or model logs.",
"error": str(exc),
"age": age,
"gender": gender,
"ret_variant": variant,
"calcitonin_level": calcitonin_level,
"cea_level": cea_level,
}
)
continue
results.append(
{
"patient_id": patient_id,
"risk_level": risk_level,
"probability": round(probability, 1),
"recommendations": _make_recommendations(risk_level, probability),
"error": "",
"age": age,
"gender": gender,
"ret_variant": variant,
"calcitonin_level": calcitonin_level,
"cea_level": cea_level,
}
)
results_df = pd.DataFrame(results)
valid_df = results_df[
results_df["risk_level"].isin(["Above threshold", "Below threshold"])
].copy()
invalid_count = len(results_df) - len(valid_df)
stats = _build_stats(valid_df, invalid_count, total_rows)
if total_rows > 100:
warnings.append("Large cohort detected. Progress updates enabled.")
if invalid_count > 0:
warnings.append("Some rows were skipped due to validation errors. Review the Results table.")
stats_html = _stats_to_html(stats, warnings)
charts = {
"risk": _risk_distribution_chart(valid_df),
"age": _age_probability_scatter(valid_df),
"variant": _variant_comparison_bar(valid_df),
"biomarker": _biomarker_histograms(valid_df),
}
output_dir = Path(output_dir)
output_dir.mkdir(parents=True, exist_ok=True)
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
csv_path = output_dir / f"batch_results_{timestamp}.csv"
results_df.to_csv(csv_path, index=False)
return (
results_df,
stats_html,
charts["risk"],
charts["age"],
charts["variant"],
charts["biomarker"],
str(csv_path),
)
|