{"data":{"slug":"github-aipoch-medical-research-skills-awesome-med-research-skills-data-analysis-external-model-validation-ab483584a889","title":"External Model Validation for Prognostic Risk Signatures","summary":"Validate a pre-existing prognostic risk signature on an external bulk expression cohort with survival outcomes, generating risk scores, Kaplan-Meier curves, and time-dependent ROC curves. The deliverable includes a risk table, Kaplan-Meier curve, risk score plot, and time-dependent ROC curves.","url":"https:\/\/skillshunter.net\/skills\/github-aipoch-medical-research-skills-awesome-med-research-skills-data-analysis-external-model-validation-ab483584a889","json_url":"https:\/\/skillshunter.net\/api\/public\/v1\/skills\/github-aipoch-medical-research-skills-awesome-med-research-skills-data-analysis-external-model-validation-ab483584a889","markdown_url":"https:\/\/skillshunter.net\/skills\/github-aipoch-medical-research-skills-awesome-med-research-skills-data-analysis-external-model-validation-ab483584a889.md","download_url":"https:\/\/skillshunter.net\/skills\/github-aipoch-medical-research-skills-awesome-med-research-skills-data-analysis-external-model-validation-ab483584a889\/download","category":{"slug":"data-research","name":"Data & Research"},"editor_note":"Ensure the input files are correctly formatted: the expression matrix must have genes as rows and samples as columns, with the first column containing gene identifiers. The clinical file must include `OS` (encoded as 0\/1) and `OS.time` (positive values compatible with the specified `--time_unit`). The model file must contain `Gene` and `Coef` columns. Additionally, ensure that the cohort has sufficient survival events (at least 5) for reliable Kaplan-Meier and ROC results.","instructions":"---\nname: external-model-validation\ndescription: \"Use when validating an existing prognostic risk signature on an external bulk expression cohort with survival outcomes, producing risk scores, Kaplan-Meier curves, risk distribution plots, heatmap, and time-dependent ROC curves. NOT for: model training, feature selection, nomogram construction, calibration analysis, or single-cell data.\"\nlicense: MIT\nskill-author: AIPOCH\n---\n\n# External Model Validation\n\n## Input Validation\n\nThis skill accepts: an existing prognostic gene signature (model coefficient file with `Gene` and `Coef` columns), a bulk expression matrix in CSV format (genes as rows, samples as columns), and a clinical file with `OS` and `OS.time` survival columns.\n\nIf the user's request does not involve validating a pre-existing prognostic model on an external cohort \u2014 for example, asking to train a new model, perform feature selection, build a nomogram, run calibration curves, analyze single-cell data, or process data without survival endpoints \u2014 do not proceed with the workflow. Instead respond:\n\n> \"external-model-validation is designed to validate an existing prognostic risk signature on an external bulk expression cohort with survival outcomes. Your request appears to be outside this scope. Please provide a fixed model coefficient file plus expression and clinical data with OS\/OS.time columns, or use a more appropriate tool for model training, nomogram construction, or single-cell analysis.\"\n\n## When to Read External Files\n\n| Situation | File to Read | Purpose |\n|-----------|--------------|---------|\n| **Need to run the analysis** | `scripts\/main.R` | Execute: `Rscript scripts\/main.R --exp_file ... --cli_file ... --model_file ...` |\n| **Need workflow order or output generation steps** | `scripts\/run_analysis.R` | Review the 4-step orchestration of loading, scoring, plotting, and metadata export |\n| **Need risk score or sample matching logic** | `scripts\/functions.R` | Inspect core data preparation and validation logic |\n| **Need output writing or metadata export details** | `scripts\/io.R` | Inspect output directory creation and file-writing helpers |\n| **Need plotting implementation details** | `scripts\/plotting.R` | Inspect Kaplan-Meier, risk, heatmap, and ROC plot generation |\n| **Need input validation, logging, timeout, or dependency logic** | `scripts\/utils.R` | Review validation helpers, `SKILL_*` error handling, logging, and runtime safeguards |\n| **Need statistical assumptions or method details** | `references\/algorithm.md` | Risk score formula, group cutoff, survival analysis, ROC, and heatmap assumptions |\n| **Need troubleshooting help** | `references\/troubleshooting.md` | Common failures, warnings, and concrete fixes |\n| **Need CLI usage examples** | `references\/cli-guide.md` | Parameter explanations, examples, and command patterns |\n| **Need expected outputs or benchmark run** | `references\/baseline-run.md` | Real-data baseline command, runtime, memory checkpoints, and output inventory |\n| **Need test inputs** | `tests\/data\/` | Example expression, clinical, and model files for validation |\n| **Need to refresh the retained example output** | `tests\/refresh_example_output.R` | Rebuild `tests\/output\/` with `--overwrite` using the bundled test data |\n\n---\n\n## Usage\n\n```bash\nRscript scripts\/main.R \\\n  --exp_file .\/expression.csv \\\n  --cli_file .\/clinical.csv \\\n  --model_file .\/model.csv \\\n  --output_dir .\/output\/ \\\n  --time_unit month \\\n  --seed 42\n```\n\n---\n\n## Arguments\n\n| Short | Long | Type | Default | Description |\n|-------|------|------|---------|-------------|\n| `-e` | `--exp_file` | character | **required** | Expression matrix CSV with genes as rows and samples as columns |\n| `-c` | `--cli_file` | character | **required** | Clinical CSV with sample IDs as row names and `OS`, `OS.time` columns |\n| `-m` | `--model_file` | character | **required** | Model coefficient CSV with `Gene` and `Coef` columns |\n| `-o` | `--output_dir` | character | `.\/output\/` | Output directory |\n|  | `--overwrite` | flag | `FALSE` | Allow writing into a non-empty output directory |\n| `-u` | `--time_unit` | character | `month` | Survival time unit in input clinical file: `day`, `month`, `year` |\n|  | `--col_high` | character | `#E64B35` | Color for high-risk samples |\n|  | `--col_low` | character | `#4DBBD5` | Color for low-risk samples |\n|  | `--roc_cols` | character | `#E64B35,#00A087,#3C5488` | Comma-separated colors for ROC curves |\n|  | `--roc_times` | character | `1,3,5` | Comma-separated ROC time points **always in years**, regardless of `--time_unit`. When follow-up is in days or months, still provide `--roc_times` in years (e.g., `1,3,5` for 1, 3, and 5 years). |\n|  | `--roc_pos` | character | `bottomright` | ROC legend position |\n|  | `--km_breaks` | integer | `0` | Kaplan-Meier x-axis break in years; `0` selects automatically |\n| `-s` | `--seed` | integer | `42` | Random seed for reproducibility |\n|  | `--timeout_seconds` | integer | `3600` | Elapsed timeout limit in seconds |\n\n---\n\n## When to Use\n\n- You already have a fixed prognostic gene signature and coefficients.\n- You need to test that model on an independent cohort with bulk expression and survival data.\n- You want standard outputs for external validation: risk table, Kaplan-Meier curve, risk score plot, survival status plot, expression heatmap, and time-dependent ROC.\n\n## When Not to Use\n\n- Do not use this skill to train or re-fit a prognostic model.\n- Do not use it for nomogram construction, calibration curves, DCA, or diagnostic classification.\n- Do not use it for single-cell expression matrices or cohorts without survival endpoints.\n- Do not use identifiable patient data without de-identification and local compliance approval.\n- Do not use for cohorts with very few events (fewer than 5 events may produce unreliable Kaplan-Meier and ROC results).\n\n## Research Use Notice\n\n- This skill is for research and validation workflows only.\n- It does not provide diagnosis, treatment recommendations, or clinical decision support.\n- Use de-identified data and follow IRB, ethics, and data-use requirements before running on human cohorts.\n\n---\n\n## Input Format\n\n### Expression Matrix (`exp_file`)\n\nCSV with genes as rows and samples as columns. The first column must contain gene identifiers.\n\n```csv\n\"\",\"Sample_1\",\"Sample_2\",\"Sample_3\"\n\"TSPAN6\",3.87,4.54,8.12\n\"TNMD\",9.98,5.86,5.38\n\"DPM1\",7.95,6.11,5.41\n```\n\n### Clinical File (`cli_file`)\n\nCSV with sample IDs as row names and at least `OS` and `OS.time` columns.\n\n```csv\n,Age,OS,OS.time\nSample_1,59,0,133.5\nSample_2,60,0,49.13\nSample_3,59,1,22.40\n```\n\n- `OS` must use `0\/1` encoding.\n- `OS.time` must be positive and interpretable under `--time_unit`.\n\n### Model Coefficient File (`model_file`)\n\nCSV with two required columns: `Gene` and `Coef`.\n\n```csv\nGene,Coef\nTSPAN6,-0.25\nTNMD,0.15\nDPM1,0.32\n```\n\n---\n\n## Output Files\n\n| File | Description |\n|------|-------------|\n| `data\/risk_data.rds` | Serialized analysis dataset containing survival data, model gene expression, risk scores, and risk groups |\n| `table\/out_varifyRisk.txt` | Tab-delimited risk table for all matched samples |\n| `plot\/out_varifySurv.pdf` | Kaplan-Meier survival curve with risk table |\n| `plot\/out_varify.riskScore.pdf` | Ordered risk score plot |\n| `plot\/out_varify.survStat.pdf` | Survival status plot |\n| `plot\/out_varify.heatmap.pdf` | Heatmap of model genes across ordered samples |\n| `plot\/out_varify.ROC.pdf` | Time-dependent ROC curve PDF |\n| `analysis.log` | Runtime log including memory checkpoints and processing steps |\n| `run_parameters.tsv` | Exact parameter values used for the run |\n| `session_info.txt` | R version, platform, and package session information |\n\n---\n\n## Workflow\n\n### Step 1: Validate Inputs\n- Check required files and CSV extensions.\n- Validate color strings, timeout, seed, KM break setting, and time unit choice.\n- Parse `--roc_times` and `--roc_cols`.\n\n### Step 2: Build Matched Validation Dataset\n- Read expression, clinical, and model files.\n- Match samples shared by expression columns and clinical row names.\n- Check all model genes exist in the expression matrix.\n- Remove incomplete cases before downstream analysis.\n\n### Step 3: Calculate Risk Scores and Groups\n- Compute risk scores with the supplied linear predictor.\n- Convert follow-up time into years.\n- Split patients into `low` and `high` groups using the median risk score.\n\n### Step 4: Generate Validation Outputs\n- Save the full risk table and RDS object.\n- Produce Kaplan-Meier, risk score, survival status, heatmap, and time-dependent ROC plots.\n- Save session metadata and exact run parameters.\n\n---\n\n## Methods\n\n### Risk Score Formula\n\nFor sample `i`, the skill computes:\n\n```text\nriskScore_i = sum(expression_ig * coefficient_g)\n```\n\nusing all genes listed in `model_file`.\n\n### Risk Stratification\n\n- Samples are ordered by `riskScore`.\n- The median risk score is used as the cutoff.\n- Samples with scores above the median are labeled `high`; the others are labeled `low`.\n\n### Survival Analysis\n\n- Kaplan-Meier curves are fit with `survival::survfit`.\n- Group difference is shown with the default log-rank p-value in `survminer::ggsurvplot`.\n\n### Time-Dependent ROC\n\n- ROC analysis is performed with `timeROC::timeROC` using follow-up time in years.\n- All `--roc_times` values must be smaller than the maximum observed follow-up time.\n- `--roc_times` is always interpreted in years, regardless of `--time_unit`.\n\n---\n\n## Examples\n\n### Basic Usage\n\n```bash\nRscript scripts\/main.R \\\n  -e tests\/data\/BRCA_data.csv \\\n  -c tests\/data\/BRCA_clinic.csv \\\n  -m tests\/data\/BRCA_coef.csv \\\n  -o .\/output\/\n```\n\n### Input Follow-up Recorded in Days\n\n```bash\nRscript scripts\/main.R \\\n  -e expression.csv \\\n  -c clinical.csv \\\n  -m model.csv \\\n  -o .\/output \\\n  -u day \\\n  --roc_times 1,2,3\n```\n\nNote: `--roc_times 1,2,3` means 1, 2, and 3 years \u2014 even though `--time_unit day` was supplied. The skill converts `OS.time` from days to years internally before ROC computation.\n\n### Custom Plot Colors and ROC Settings\n\n```bash\nRscript scripts\/main.R \\\n  -e expression.csv \\\n  -c clinical.csv \\\n  -m model.csv \\\n  -o .\/output \\\n  --col_high '#B2182B' \\\n  --col_low '#2166AC' \\\n  --roc_cols '#B2182B,#4D9221,#2166AC' \\\n  --roc_pos topleft \\\n  --km_breaks 2\n```\n\n---\n\n## Error Handling\n\n### Common Errors\n\n| Error | Cause | Solution |\n|-------|-------|----------|\n| `SKILL_FILE_NOT_FOUND` | Input path is missing or wrong | Check file path and permissions |\n| `SKILL_MISSING_COLUMNS` | Clinical or model file lacks required columns | Ensure `OS`, `OS.time`, `Gene`, and `Coef` exist |\n| `SKILL_SAMPLE_MISMATCH` | No overlapping samples between expression and clinical data | Align sample IDs exactly |\n| `SKILL_EMPTY_DATA` | An input file is empty after loading | Verify the CSV contains at least one row and one column of usable data |\n| `SKILL_INVALID_DATA` | Duplicate genes, empty data, non-numeric coefficients, or invalid survival values. For duplicate genes: deduplicate with `dplyr::distinct()` or keep the row with highest mean expression (e.g., `mat[order(-rowMeans(mat[,-1])),] %>% distinct(Gene, .keep_all=TRUE)`) | Clean input tables and verify formats |\n| `SKILL_ANALYSIS_ERROR` | Risk groups collapse or event count is too low | Use a valid signature and cohort with enough events (minimum ~5) |\n| `SKILL_INVALID_PARAMETER` | Bad `--time_unit`, invalid color, or impossible ROC time point | Correct the parameter value |\n| `SKILL_DEPENDENCY_MISSING` | Required R package is not installed | Install the missing package |\n| `SKILL_PKG_VERSION` | Installed package version is below the required minimum | Upgrade the package to the required version |\n\n**IF error persists**, READ: `references\/troubleshooting.md`\n\n---\n\n## Testing\n\n### Test with Included Data\n\n```bash\n# Check CLI\nRscript scripts\/main.R --help\n\n# Run with bundled test data in a fresh output directory\nRscript scripts\/main.R \\\n  -e tests\/data\/BRCA_data.csv \\\n  -c tests\/data\/BRCA_clinic.csv \\\n  -m tests\/data\/BRCA_coef.csv \\\n  -o .\/output\/\n```\n\n### Validation Commands\n\n```bash\n# Run R tests\nRscript tests\/testthat.R\n\n# Refresh the retained example output bundle\nRscript tests\/refresh_example_output.R\n\n# Inspect the generated risk table\nwc -l tests\/output\/table\/out_varifyRisk.txt\n\n# Review the retained example outputs\nls -la tests\/output\/\n```\n\n### Real-data Baseline\n\nThe repository stores a documented real-data baseline summary in `references\/baseline-run.md`.\n\n**IF you need exact benchmark outputs or runtime expectations**, READ: `references\/baseline-run.md`\n\n\u2192 Directory structure and implementation details: [references\/project-structure.md](references\/project-structure.md)\n","use_cases":["Validate a pre-existing gene signature on an independent cohort with survival data","Generate standard outputs for external model validation: risk table, Kaplan-Meier curve, risk score plot, and time-dependent ROC curves"],"limitations":[],"compatibility":[],"setup_tip":null,"sample_input":null,"sample_output":null,"source_url":"https:\/\/github.com\/aipoch\/medical-research-skills\/blob\/686e09dfdb45d9fa1a08664f06bb93769b3c9d91\/awesome-med-research-skills\/Data%20Analysis\/external-model-validation\/SKILL.md","source_commit":"686e09dfdb45d9fa1a08664f06bb93769b3c9d91","license":"MIT","version":null,"listing_approved_at":"2026-11-24","created_at":"2026-11-23T07:07:16.000000Z","updated_at":"2026-11-24T07:13:04.000000Z","seo_title":"External Model Validation for Prognostic Risk Signatures","seo_description":"Validate prognostic risk signatures on external bulk expression cohorts with survival outcomes. Generate risk scores, Kaplan-Meier curves, and time-dependent ROC curves.","seo_keywords":["external model validation","prognostic risk signature validation","survival analysis","Kaplan-Meier curves","time-dependent ROC curves"]}}