Survival Analysis (Kaplan-Meier)
Kaplan-Meier survival analysis tool for clinical and biological research. Generates publication-ready survival curves with statistical tests.
Features
- Kaplan-Meier Curve Generation: Publication-quality survival plots with confidence intervals
- Statistical Tests: Log-rank test, Wilcoxon test, Peto-Peto test
- Hazard Ratios: Cox proportional hazards regression with 95% CI
- Summary Statistics: Median survival time, restricted mean survival time (RMST)
- Multi-group Analysis: Supports 2+ comparison groups
- Risk Tables: Optional at-risk table below curves
Usage
Python Script
python scripts/main.py --input data.csv --time time_col --event event_col --group group_col --output results/
Arguments
| Argument |
Description |
Required |
--input |
Input CSV file path |
Yes |
--time |
Column name for survival time |
Yes |
--event |
Column name for event indicator (1=event, 0=censored) |
Yes |
--group |
Column name for grouping variable |
Optional |
--output |
Output directory for results |
Yes |
--conf-level |
Confidence level (default: 0.95) |
Optional |
--risk-table |
Include risk table in plot |
Optional |
Input Format
CSV with columns:
- Time column: Numeric, time to event or censoring
- Event column: Binary (1 = event occurred, 0 = censored/right-censored)
- Group column: Categorical variable for stratification
Example:
patient_id,time_months,death,treatment_group
P001,24.5,1,Drug_A
P002,36.2,0,Drug_A
P003,18.7,1,Placebo
Output Files
km_curve.png: Kaplan-Meier survival curve
km_curve.pdf: Vector version for publications
survival_stats.csv: Statistical summary (median survival, confidence intervals)
hazard_ratios.csv: Cox regression results with HR and 95% CI
- `logrank_test.csv**: Pairwise comparison p-values
- `report.txt**: Human-readable summary report
Technical Details
Statistical Methods
Kaplan-Meier Estimator: Non-parametric maximum likelihood estimate of survival function
- Product-limit estimator: Ŝ(t) = Π(tᵢ≤t) (1 - dᵢ/nᵢ)
- Greenwood's formula for variance estimation
Log-Rank Test: Most widely used test for comparing survival curves
- Null hypothesis: No difference between groups
- Weighted by number at risk at each event time
Cox Proportional Hazards: Semi-parametric regression model
- h(t|X) = h₀(t) × exp(β₁X₁ + β₂X₂ + ...)
- Proportional hazards assumption checked via Schoenfeld residuals
Dependencies
lifelines: Core survival analysis library
matplotlib, seaborn: Visualization
pandas, numpy: Data handling
scipy: Statistical tests
Technical Difficulty: High ⚠️
This skill involves advanced statistical modeling. Results should be reviewed by a biostatistician, especially for:
- Proportional hazards assumption violations
- Small sample sizes (< 30 per group)
- Heavy censoring (> 50%)
- Time-varying covariates
References
See references/ folder for:
- Kaplan EL, Meier P (1958) original paper
- Cox DR (1972) regression models paper
- Sample datasets for testing
- Clinical reporting guidelines (ATN, CONSORT)
Parameters
| Parameter |
Type |
Default |
Description |
--input |
str |
Required |
Input CSV file path |
--time |
str |
Required |
Column name for survival time |
--event |
str |
Required |
|
--group |
str |
Required |
|
--output |
str |
Required |
Output directory for results |
--conf-level |
float |
0.95 |
|
--risk-table |
str |
Required |
Include risk table in plot |
--figsize |
str |
'10 |
|
--dpi |
int |
300 |
|
Example
# Basic survival curve
python scripts/main.py \
--input clinical_data.csv \
--time overall_survival_months \
--event death \
--group treatment_arm \
--output ./results/ \
--risk-table
Output includes:
- Survival curves with 95% confidence bands
- Median survival: Drug A = 28.4 months (95% CI: 24.1-32.7), Placebo = 18.2 months (95% CI: 15.3-21.1)
- Log-rank test p-value: 0.0023
- Hazard ratio: 0.62 (95% CI: 0.45-0.85), p = 0.003
Risk Assessment
| Risk Indicator |
Assessment |
Level |
| Code Execution |
Python/R scripts executed locally |
Medium |
| Network Access |
No external API calls |
Low |
| File System Access |
Read input files, write output files |
Medium |
| Instruction Tampering |
Standard prompt guidelines |
Low |
| Data Exposure |
Output files saved to workspace |
Low |
Security Checklist
Prerequisites
# Python dependencies
pip install -r requirements.txt
Evaluation Criteria
Success Metrics
Test Cases
- Basic Functionality: Standard input → Expected output
- Edge Case: Invalid input → Graceful error handling
- Performance: Large dataset → Acceptable processing time
Lifecycle Status
- Current Stage: Draft
- Next Review Date: 2026-03-06
- Known Issues: None
- Planned Improvements:
- Performance optimization
- Additional feature support
1---
2name: survival-analysis-km
3description: Generates Kaplan-Meier survival curves, calculates survival statistics
4 (log-rank test, median survival time), and estimates hazard ratios for clinical
5 and biological survival data analysis. Triggered when user requests survival analysis,
6 Kaplan-Meier plots, time-to-event analysis, or asks about survival statistics in
7 biomedical contexts.
8version: 1.0.0
9category: Bioinfo
10tags: []
11author: AIPOCH
12license: MIT
13status: Draft
14risk_level: Medium
15skill_type: Tool/Script
16owner: AIPOCH
17reviewer: ''
18last_updated: '2026-02-06'
19metadata:
20 source: https://skillmd.com/skills/modbender/survival-analysis-km
21---
22
23# Survival Analysis (Kaplan-Meier)
24
25Kaplan-Meier survival analysis tool for clinical and biological research. Generates publication-ready survival curves with statistical tests.
26
27## Features
28
29- **Kaplan-Meier Curve Generation**: Publication-quality survival plots with confidence intervals
30- **Statistical Tests**: Log-rank test, Wilcoxon test, Peto-Peto test
31- **Hazard Ratios**: Cox proportional hazards regression with 95% CI
32- **Summary Statistics**: Median survival time, restricted mean survival time (RMST)
33- **Multi-group Analysis**: Supports 2+ comparison groups
34- **Risk Tables**: Optional at-risk table below curves
35
36## Usage
37
38### Python Script
39
40```bash
41python scripts/main.py --input data.csv --time time_col --event event_col --group group_col --output results/
42```
43
44### Arguments
45
46| Argument | Description | Required |
47|----------|-------------|----------|
48| `--input` | Input CSV file path | Yes |
49| `--time` | Column name for survival time | Yes |
50| `--event` | Column name for event indicator (1=event, 0=censored) | Yes |
51| `--group` | Column name for grouping variable | Optional |
52| `--output` | Output directory for results | Yes |
53| `--conf-level` | Confidence level (default: 0.95) | Optional |
54| `--risk-table` | Include risk table in plot | Optional |
55
56### Input Format
57
58CSV with columns:
59- **Time column**: Numeric, time to event or censoring
60- **Event column**: Binary (1 = event occurred, 0 = censored/right-censored)
61- **Group column**: Categorical variable for stratification
62
63Example:
64```csv
65patient_id,time_months,death,treatment_group
66P001,24.5,1,Drug_A
67P002,36.2,0,Drug_A
68P003,18.7,1,Placebo
69```
70
71### Output Files
72
73- `km_curve.png`: Kaplan-Meier survival curve
74- `km_curve.pdf`: Vector version for publications
75- `survival_stats.csv`: Statistical summary (median survival, confidence intervals)
76- `hazard_ratios.csv`: Cox regression results with HR and 95% CI
77- `logrank_test.csv**: Pairwise comparison p-values
78- `report.txt**: Human-readable summary report
79
80## Technical Details
81
82### Statistical Methods
83
841. **Kaplan-Meier Estimator**: Non-parametric maximum likelihood estimate of survival function
85 - Product-limit estimator: Ŝ(t) = Π(tᵢ≤t) (1 - dᵢ/nᵢ)
86 - Greenwood's formula for variance estimation
87
882. **Log-Rank Test**: Most widely used test for comparing survival curves
89 - Null hypothesis: No difference between groups
90 - Weighted by number at risk at each event time
91
923. **Cox Proportional Hazards**: Semi-parametric regression model
93 - h(t|X) = h₀(t) × exp(β₁X₁ + β₂X₂ + ...)
94 - Proportional hazards assumption checked via Schoenfeld residuals
95
96### Dependencies
97
98- `lifelines`: Core survival analysis library
99- `matplotlib`, `seaborn`: Visualization
100- `pandas`, `numpy`: Data handling
101- `scipy`: Statistical tests
102
103### Technical Difficulty: High ⚠️
104
105This skill involves advanced statistical modeling. Results should be reviewed by a biostatistician, especially for:
106- Proportional hazards assumption violations
107- Small sample sizes (< 30 per group)
108- Heavy censoring (> 50%)
109- Time-varying covariates
110
111## References
112
113See `references/` folder for:
114- Kaplan EL, Meier P (1958) original paper
115- Cox DR (1972) regression models paper
116- Sample datasets for testing
117- Clinical reporting guidelines (ATN, CONSORT)
118
119
120## Parameters
121
122| Parameter | Type | Default | Description |
123|-----------|------|---------|-------------|
124| `--input` | str | Required | Input CSV file path |
125| `--time` | str | Required | Column name for survival time |
126| `--event` | str | Required | |
127| `--group` | str | Required | |
128| `--output` | str | Required | Output directory for results |
129| `--conf-level` | float | 0.95 | |
130| `--risk-table` | str | Required | Include risk table in plot |
131| `--figsize` | str | '10 | |
132| `--dpi` | int | 300 | |
133
134## Example
135
136```bash
137# Basic survival curve
138python scripts/main.py \
139 --input clinical_data.csv \
140 --time overall_survival_months \
141 --event death \
142 --group treatment_arm \
143 --output ./results/ \
144 --risk-table
145```
146
147Output includes:
148- Survival curves with 95% confidence bands
149- Median survival: Drug A = 28.4 months (95% CI: 24.1-32.7), Placebo = 18.2 months (95% CI: 15.3-21.1)
150- Log-rank test p-value: 0.0023
151- Hazard ratio: 0.62 (95% CI: 0.45-0.85), p = 0.003
152
153## Risk Assessment
154
155| Risk Indicator | Assessment | Level |
156|----------------|------------|-------|
157| Code Execution | Python/R scripts executed locally | Medium |
158| Network Access | No external API calls | Low |
159| File System Access | Read input files, write output files | Medium |
160| Instruction Tampering | Standard prompt guidelines | Low |
161| Data Exposure | Output files saved to workspace | Low |
162
163## Security Checklist
164
165- [ ] No hardcoded credentials or API keys
166- [ ] No unauthorized file system access (../)
167- [ ] Output does not expose sensitive information
168- [ ] Prompt injection protections in place
169- [ ] Input file paths validated (no ../ traversal)
170- [ ] Output directory restricted to workspace
171- [ ] Script execution in sandboxed environment
172- [ ] Error messages sanitized (no stack traces exposed)
173- [ ] Dependencies audited
174## Prerequisites
175
176```bash
177# Python dependencies
178pip install -r requirements.txt
179```
180
181## Evaluation Criteria
182
183### Success Metrics
184- [ ] Successfully executes main functionality
185- [ ] Output meets quality standards
186- [ ] Handles edge cases gracefully
187- [ ] Performance is acceptable
188
189### Test Cases
1901. **Basic Functionality**: Standard input → Expected output
1912. **Edge Case**: Invalid input → Graceful error handling
1923. **Performance**: Large dataset → Acceptable processing time
193
194## Lifecycle Status
195
196- **Current Stage**: Draft
197- **Next Review Date**: 2026-03-06
198- **Known Issues**: None
199- **Planned Improvements**:
200 - Performance optimization
201 - Additional feature support