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"
Total rows: {stats['total']}
Valid predictions: {stats['valid']}
Rows with errors: {stats['invalid']}
Above threshold: {stats['above']} | Below threshold: {stats['below']}
Average model score: {stats['avg_probability']:.1f}%
{warning_html}Please upload a CSV file to begin analysis.
", 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"Error: Unable to read CSV file ({exc}).
", go.Figure(), go.Figure(), go.Figure(), go.Figure(), None, ) if raw_df.empty: empty_df = pd.DataFrame() return ( empty_df, "Error: CSV file is empty.
", 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"Error: Missing required columns: {missing_list}
", 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), )