Skip to content

Hazards, medians and the area under the curve

Connect the moment-to-moment hazard to the survival curve, then choose between the median, survival at a time point, and restricted mean survival.

Applied ~11 min7 steps

What runs in CodeSplash

You will be able to

  • Explain how a hazard builds up into a survival curve
  • Read median survival, survival at a chosen time, and restricted mean survival from a curve
  • Say when the median can't be estimated and what to report instead

Read first

01

Risk now, survival so far

Read

Two curves describe the same waiting time.

The survival functionSurvival functionThe probability of remaining free of the event beyond time t. It starts at 1 and can only fall. S(t)S(t) is the chance of getting past time tt. It can only fall.

The hazardHazardThe moment-to-moment risk of the event among those still at risk. h(t)h(t) is the event rate right now among those still event-free. It can rise, fall or wobble.

S(t)=exp⁡(−∫0th(u) du)S(t) = \exp\left(-\int_0^t h(u)\,du\right)

Every moment's risk adds up, and survival is what is left.

02

Move the hazard

Explore

The shape controls how risk changes over time: below 1 risk falls, above 1 it rises. Predict what happens to each survival curve before you drag.

FExplorable · From hazard to survival

How does the moment-to-moment risk build up into a survival curve?

What share of group A is still event-free at this time?

0.50
How sure?
1.50

Below 1 risk falls with time; above 1 it rises.

10.0
1.50
15.0
10.0

Hazard: risk at each moment

Survival: still event-free

Commit your prediction above to see the result

Make your prediction first; the figure appears when you commit.

Make your prediction to see the result.

Now make the hazards cross by changing one group's shape. Watch what a single "hazard ratio" would have to average over.

03

Three ways to summarize

Predict

Predict first

A trial ends after two years with 70% of patients still event-free. What can you say about the median survival time?

The median can't be estimatedThe median is the last event timeThe median is half the follow-up
Reveal

It can't be estimated: the curve never reached 50%. This is common in good-prognosis groups, and it's a reason to report survival at fixed times or a restricted mean as well. A software result of "NA" here isn't a failure.

04

The restricted mean

Read

Restricted mean survival timeRestricted mean survival timeThe average event-free time up to a horizon τ, the area under the survival curve; a difference in RMST is a difference in time. is the area under the curve up to a horizon τ\tau: the average time lived during that window.

In the lung data, over the first 365 days, patients lived 263 days on average (standard error 7.8).

Unlike the median, it exists whenever you have follow-up to τ\tau, and "a difference of 30 days lived over the first year" is a sentence anyone can act on. Choose τ\tau before looking at the curves, and keep it inside the follow-up you really have.

Kaplan–Meier curveWhat fraction survives (is event-free) over time, and do groups differ?
View data
monthssurvivallowerupperarmn.riskn.censor
0111standard600
0.10000.98330.88750.9976standard600
0.20000.96670.87320.9916standard590
0.50000.95000.85290.9836standard580
0.60000.93330.83210.9744standard570
0.90000.91670.81130.9644standard560
1.4000.90000.79090.9538standard550
1.9000.88330.77080.9426standard540
2.2000.86670.75100.9310standard530
2.4000.85000.73160.9190standard520
2.6000.83330.71240.9066standard510
2.9000.81670.69350.8940standard500
3.6000.78330.65630.8680standard490
40.76670.63810.8546standard470
4.9000.75000.62000.8410standard460
50.71670.58450.8133standard450
5.5000.70000.56690.7992standard430
60.68330.54960.7849standard420
6.2000.68330.54960.7849standard411
6.3000.66620.53180.7702standard400
6.6000.64920.51420.7553standard390
6.8000.63210.49680.7402standard380
7.7000.61500.47960.7250standard370
7.7000.61500.47960.7250standard361
7.9000.61500.47960.7250standard351
8.1000.61500.47960.7250standard341
9.1000.59640.46050.7086standard330
9.5000.57770.44160.6919standard320
9.8000.57770.44160.6919standard311
10.2000.55850.42210.6747standard300
11.1000.55850.42210.6747standard291
11.4000.55850.42210.6747standard281
11.9000.53780.40100.6563standard270
12.1000.51710.38030.6377standard260
12.3000.49640.35990.6188standard250
13.2000.47570.33980.5997standard240
13.5000.45500.32010.5803standard230
13.7000.43440.30060.5607standard220
14.2000.41370.28150.5408standard210
14.7000.39300.26270.5207standard200
15.3000.39300.26270.5207standard191
15.8000.37120.24280.4996standard180
16.1000.34930.22340.4781standard170
17.7000.34930.22340.4781standard161
17.7000.32600.20260.4553standard150
18.5000.32600.20260.4553standard141
19.5000.30100.18040.4309standard130
19.7000.27590.15890.4059standard120
21.9000.25080.13820.3804standard110
22.5000.22570.11820.3543standard100
23.3000.20060.09910.3275standard90
24.2000.20060.09910.3275standard81
26.5000.17200.07740.2978standard70
28.1000.14330.05740.2669standard60
28.4000.11470.03940.2344standard50
28.7000.08600.02370.2002standard40
330.05730.01090.1639standard30
44.3000.05730.01090.1639standard21
44.5000——standard10
0111new therapy600

First 60 of 114 rows.

05

Read a card

In the app

Here is the card for men and women in the lung data, with a 500-day horizon. Find each group's median, its survival at the listed times, and its restricted mean.

Kaplan–Meier survival by sexRecorded · Python and R agreeRecorded 2026-11-17 · 62 values compared
R

median survival = 310; log-rank χ²(1) = 10.33, p = .001

Events
165
Median survival
310
95% CI
[285, 363]
Log-rank p
.001

Plots

Kaplan–Meier curve by sexWhat fraction survives (is event-free) over time, and do groups differ?
View data
upperlowerCensoredAt risksexSurvival probabilitytime
110138male10
10.95420138male0.978311
0.99940.94340135male0.971012
0.99120.92310134male0.956513
0.98660.91340132male0.949315
0.98180.90380131male0.942026
0.97690.89450130male0.934830
0.97180.88530129male0.927531
0.96130.86720128male0.913053
0.95590.85830126male0.905854
0.95040.84960125male0.898659
0.94480.84090124male0.891360
0.93340.82370123male0.876865
0.92760.81520121male0.869671
0.92180.80670120male0.862381
0.90990.79000119male0.847888
0.90390.78170117male0.840692
0.89790.77340116male0.833393
0.89180.76520115male0.826195
0.88570.75700114male0.8188105
0.87950.74890113male0.8116107
0.87330.74080112male0.8043110
0.86710.73280111male0.7971116
0.86080.72470110male0.7899118
0.85450.71670109male0.7826131
0.84190.70080108male0.7681132
0.83550.69290106male0.7609135
0.82910.68510105male0.7536142
0.82260.67720104male0.7464144
0.81610.66940103male0.7391147
0.80310.65380102male0.7246156
0.78340.63060100male0.7029163
0.77680.6230097male0.6957166
0.77020.6153096male0.6884170
0.77020.6153195male0.6884174
0.76350.6076094male0.6811175
0.75670.5999093male0.6738176
0.75000.5922092male0.6664177
0.73640.5769091male0.6518179
0.72960.5693089male0.6445180
0.71590.5541088male0.6298181
0.70900.5466086male0.6225183
0.70900.5466185male0.6225185
0.70900.5466184male0.6225188
0.70200.5388083male0.6150189
0.70200.5388182male0.6150191
0.70200.5388181male0.6150196
0.69480.5309180male0.6073197
0.68750.5228078male0.5995202
0.68020.5148077male0.5917207
0.67280.5068076male0.5839210
0.66550.4988075male0.5762212
0.65810.4909074male0.5684218
0.65810.4909173male0.5684221
0.65060.4829172male0.5605222
0.64300.4747070male0.5525223
0.64300.4747269male0.5525225
0.63520.4663067male0.5442229
0.62740.4579066male0.5360230
0.62740.4579165male0.5360237

First 60 of 208 rows.

Cumulative hazard by sexHow has risk built up over time?
View data
sexSurvival probabilitytime
male10
male0.978311
male0.971012
male0.956513
male0.949315
male0.942026
male0.934830
male0.927531
male0.913053
male0.905854
male0.898659
male0.891360
male0.876865
male0.869671
male0.862381
male0.847888
male0.840692
male0.833393
male0.826195
male0.8188105
male0.8116107
male0.8043110
male0.7971116
male0.7899118
male0.7826131
male0.7681132
male0.7609135
male0.7536142
male0.7464144
male0.7391147
male0.7246156
male0.7029163
male0.6957166
male0.6884170
male0.6884174
male0.6811175
male0.6738176
male0.6664177
male0.6518179
male0.6445180
male0.6298181
male0.6225183
male0.6225185
male0.6225188
male0.6150189
male0.6150191
male0.6150196
male0.6073197
male0.5995202
male0.5917207
male0.5839210
male0.5762212
male0.5684218
male0.5684221
male0.5605222
male0.5525223
male0.5525225
male0.5442229
male0.5360230
male0.5360237

First 60 of 208 rows.

Log–log survival by sexAre the hazards proportional, and could the times be Weibull?
View data
sexSurvival probabilitytime
male10
male0.978311
male0.971012
male0.956513
male0.949315
male0.942026
male0.934830
male0.927531
male0.913053
male0.905854
male0.898659
male0.891360
male0.876865
male0.869671
male0.862381
male0.847888
male0.840692
male0.833393
male0.826195
male0.8188105
male0.8116107
male0.8043110
male0.7971116
male0.7899118
male0.7826131
male0.7681132
male0.7609135
male0.7536142
male0.7464144
male0.7391147
male0.7246156
male0.7029163
male0.6957166
male0.6884170
male0.6884174
male0.6811175
male0.6738176
male0.6664177
male0.6518179
male0.6445180
male0.6298181
male0.6225183
male0.6225185
male0.6225188
male0.6150189
male0.6150191
male0.6150196
male0.6073197
male0.5995202
male0.5917207
male0.5839210
male0.5762212
male0.5684218
male0.5684221
male0.5605222
male0.5525223
male0.5525225
male0.5442229
male0.5360230
male0.5360237

First 60 of 208 rows.

Assumptions

  • Non-informative censoring — 63 of 228 observations are censored; censoring must be unrelated to prognosis.
  • Number of events — At least 10 events per curve.

Survival summary

sexnEventsMedian95% CI low95% CI highRMST (τ = 500)SE
All228165310285363310.3311.246
male138112270212310278.7614.355
female9053426348550360.9116.801

Survival at chosen times

sexTimeAt riskSurvival95% CI low95% CI high
All2601130.59670.53490.6656
All510410.29330.23200.3707
All77090.08810.04980.1560
male260610.51920.44090.6114
male510200.22320.15690.3176
male77070.07810.03900.1563
female260520.71860.62870.8214
female510210.41100.30500.5540
female77020.08320.02570.2697

log intervals; Greenwood standard errors.

  • Event: status = 2. Intervals: log transformation (Greenwood SE); median limits from the interval curves (Brookmeyer–Crowley).
The exact R script · R R version 4.5.1 (2025-06-13)
# Kaplan–Meier survival curves
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method survival.km 1.0.1 · spec 97d5cf030ef37e8c
# Dataset: lung (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(survival)
library(codesplashr)

# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/lung.parquet", col_select = c("time", "status", "sex")))
n_input <- nrow(df)
df[["sex"]] <- factor(df[["sex"]], levels = c("male", "female"))  # stored level order
df <- df[stats::complete.cases(df[c("time", "status", "sex")]), , drop = FALSE]  # listwise deletion
df[] <- lapply(df, function(x) if (is.factor(x)) droplevels(x) else x)
n_dropped <- n_input - nrow(df)
warnings <- list()
if (n_dropped > 0) {
  warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_dropped, total = n_input))
}
if (n_input > 0 && nrow(df) == 0) cs_error("CS_E_NO_ROWS")
cs_check_finite_columns(df, c("time", "status", "sex"))  # infinite values stop the run (registry/errors.yaml)

# %% Event coding
tcol <- "time"
ecol <- "status"
tt <- as.numeric(df[[tcol]])
if (any(tt < 0)) cs_error("CS_E_INVALID_VALUES", column = tcol, requirement = "zero or positive (survival times)", count = sum(tt < 0))
codes <- sort(unique(df[[ecol]]))
if (all(codes %in% c(0, 1))) {
  event_code <- 1  # 0 = censored, 1 = event
} else if (all(codes %in% c(1, 2))) {
  event_code <- 2  # 1 = censored, 2 = event (survival::Surv convention)
} else {
  stop(sprintf("%s must be coded 0/1 or 1/2 (the larger code is the event), or be a yes/no or categorical column", ecol))
}
ev <- df[[ecol]] == event_code
event_label <- sprintf("%s = %s", ecol, format(event_code))
if (!any(ev)) cs_error("CS_E_NO_EVENTS", event = event_label)

# %% Kaplan–Meier
conf <- 0.95
conf_type <- "log"  # pinned: survfit's default is "log"
times <- c()
if (length(times) == 0) times <- cs_default_times(tt)
rmst_tau <- 500  # 0 = no restricted mean
g <- "sex"
levels_g <- levels(df[[g]])
gv <- as.character(df[[g]])
strata <- c(list(All = rep(TRUE, length(tt))), stats::setNames(lapply(levels_g, function(lv) gv == lv), levels_g))
fin <- function(x) if (length(x) == 0 || is.null(x) || !is.finite(x)) NA else unname(x)

values <- list(event_label = event_label, n_groups = if (length(levels_g)) length(levels_g) else NA)
summary_rows <- list()
time_rows <- list()
curve <- list(time = numeric(0), surv = numeric(0), low = numeric(0), high = numeric(0), strata = character(0),
              nrisk = numeric(0), ncensor = numeric(0))
for (name in names(strata)) {
  m <- strata[[name]]
  fit <- survfit(Surv(tt[m], ev[m]) ~ 1, conf.type = conf_type, conf.int = conf)
  tb <- summary(fit, rmean = if (rmst_tau > 0) rmst_tau else "none")$table
  st <- list(n = sum(m), events = sum(ev[m]), median = fin(tb[["median"]]),
             median_low = fin(tb[[grep("LCL$", names(tb))]]), median_high = fin(tb[[grep("UCL$", names(tb))]]),
             rmst = if (rmst_tau > 0) fin(tb[["rmean"]]) else NA, rmst_se = if (rmst_tau > 0) fin(tb[["se(rmean)"]]) else NA)
  for (k in names(st)) values[[if (name == "All") k else sprintf("%s[%s]", k, name)]] <- st[[k]]
  summary_rows[[length(summary_rows) + 1]] <- c(list(group = name), st)
  s_at <- cs_step_at(fit$time, fit$surv, times)
  l_at <- cs_step_at(fit$time, fit$lower, times)
  u_at <- cs_step_at(fit$time, fit$upper, times)
  r_at <- cs_n_risk_at(tt[m], times)
  for (i in seq_along(times)) {
    key <- sprintf("%s@%s", name, cs_key_num(times[i]))
    values[[sprintf("surv[%s]", key)]] <- fin(s_at[i])
    values[[sprintf("surv_low[%s]", key)]] <- fin(l_at[i])
    values[[sprintf("surv_high[%s]", key)]] <- fin(u_at[i])
    values[[sprintf("n_risk[%s]", key)]] <- r_at[i]
    time_rows[[length(time_rows) + 1]] <- list(group = name, time = times[i], n_risk = r_at[i], surv = fin(s_at[i]),
                                               lower = fin(l_at[i]), upper = fin(u_at[i]))
  }
  if ((name == "All") == (length(levels_g) == 0)) {
    curve$time <- c(curve$time, 0, fit$time)
    curve$surv <- c(curve$surv, 1, fit$surv)
    curve$low <- c(curve$low, 1, fit$lower)
    curve$high <- c(curve$high, 1, fit$upper)
    curve$strata <- c(curve$strata, rep(name, length(fit$time) + 1))
    curve$nrisk <- c(curve$nrisk, sum(m), fit$n.risk)
    curve$ncensor <- c(curve$ncensor, 0, fit$n.censor)
  }
}

# %% Log-rank test
if (length(levels_g)) {
  lr <- survdiff(Surv(tt, ev) ~ gv, rho = 0)
  lr_df <- sum(lr$n > 0) - 1
  values$logrank_chisq <- lr$chisq
  values$logrank_df <- lr_df
  values$logrank_p <- stats::pchisq(lr$chisq, lr_df, lower.tail = FALSE)
} else {
  values$logrank_chisq <- NA
  values$logrank_df <- NA
  values$logrank_p <- NA
}

# %% Assumptions
assumptions <- list(list(key = "censoring", label = "Non-informative censoring", status = "info",
                         detail = sprintf("%d of %d observations are censored; censoring must be unrelated to prognosis.",
                                          sum(!ev), length(ev))))
few <- character(0)
for (r in summary_rows) if (r$events < 10 && (r$group != "All" || length(levels_g) == 0)) few <- c(few, r$group)
assumptions[[2]] <- if (length(few)) {
  list(key = "sample_size", label = "Number of events", status = "warn",
       detail = sprintf("Fewer than 10 events in %s; medians and curves are imprecise.", paste(few, collapse = ", ")))
} else {
  list(key = "sample_size", label = "Number of events", status = "pass", detail = "At least 10 events per curve.")
}

# %% Result
pct <- sprintf("%.0f%%", conf * 100)
med_text <- if (is.na(values$median)) "not reached" else format(signif(values$median, 4))
summary_cols <- list(
  list(key = "group", label = if (length(levels_g)) g else "Curve", type = "string"), list(key = "n", label = "n", type = "integer"),
  list(key = "events", label = "Events", type = "integer"), list(key = "median", label = "Median", type = "number"),
  list(key = "median_low", label = paste(pct, "CI low"), type = "number"), list(key = "median_high", label = paste(pct, "CI high"), type = "number")
)
if (rmst_tau > 0) summary_cols <- c(summary_cols, list(list(key = "rmst", label = sprintf("RMST (τ = %s)", format(rmst_tau)), type = "number"),
                                                       list(key = "rmst_se", label = "SE", type = "number")))
cs_publish(list(
  method = "survival.km",
  methodVersion = "1.0.1",
  title = paste0("Kaplan–Meier survival", if (length(levels_g)) paste(" by", g) else ""),
  engine = cs_engine_info("survival", "codesplashr"),
  n = length(tt),
  summary = paste0(sprintf("%d of %d subjects had the event (%s); median survival %s.", sum(ev), length(ev), event_label, med_text),
                   if (length(levels_g)) sprintf(" Log-rank %s.", cs_fmt_p(values$logrank_p)) else ""),
  apa = paste0("median survival = ", med_text,
               if (length(levels_g)) sprintf("; log-rank χ²(%d) = %s, %s", values$logrank_df, cs_fmt_num(values$logrank_chisq), cs_fmt_p(values$logrank_p)) else ""),
  statistics = c(list(
    list(key = "events", label = "Events", value = values$events, format = "integer"),
    list(key = "median", label = "Median survival", value = values$median),
    list(key = "median_ci", label = paste(pct, "CI"), value = c(values$median_low, values$median_high))
  ), if (length(levels_g)) list(list(key = "logrank_p", label = "Log-rank p", value = values$logrank_p, format = "p"))),
  tables = list(
    list(key = "summary", title = "Survival summary", columns = summary_cols, rows = summary_rows),
    list(key = "survival_at", title = "Survival at chosen times", columns = list(
      list(key = "group", label = if (length(levels_g)) g else "Curve", type = "string"), list(key = "time", label = "Time", type = "number"),
      list(key = "n_risk", label = "At risk", type = "integer"), list(key = "surv", label = "Survival", type = "number"),
      list(key = "lower", label = paste(pct, "CI low"), type = "number"), list(key = "upper", label = paste(pct, "CI high"), type = "number")
    ), rows = time_rows, note = paste(conf_type, "intervals; Greenwood standard errors."))
  ),
  assumptions = assumptions,
  warnings = warnings,
  notes = list(sprintf("Event: %s. Intervals: %s transformation (Greenwood SE); median limits from the interval curves (Brookmeyer–Crowley).", event_label, conf_type)),
  charts = list(cs_chart("km", "km-curve", paste0("Kaplan–Meier curve", if (length(levels_g)) paste(" by", g) else ""), list(
    time = cs_col(tcol, curve$time, "numeric"), surv = cs_col("Survival probability", curve$surv, "numeric"),
    low = cs_col("lower", curve$low, "numeric"), high = cs_col("upper", curve$high, "numeric"),
    strata = if (length(levels_g)) cs_col(g, curve$strata, "categorical", levels = levels_g) else NULL,
    nrisk = cs_col("At risk", curve$nrisk, "numeric"), ncensor = cs_col("Censored", curve$ncensor, "numeric")
  )), cs_chart("cumhaz", "cumhaz", paste0("Cumulative hazard", if (length(levels_g)) paste(" by", g) else ""), list(
    time = cs_col(tcol, curve$time, "numeric"), surv = cs_col("Survival probability", curve$surv, "numeric"),
    strata = if (length(levels_g)) cs_col(g, curve$strata, "categorical", levels = levels_g) else NULL
  )), cs_chart("loglog", "loglog-survival", paste0("Log–log survival", if (length(levels_g)) paste(" by", g) else ""), list(
    time = cs_col(tcol, curve$time, "numeric"), surv = cs_col("Survival probability", curve$surv, "numeric"),
    strata = if (length(levels_g)) cs_col(g, curve$strata, "categorical", levels = levels_g) else NULL
  ))),
  values = values
))
Python

median survival = 310; log-rank χ²(1) = 10.33, p = .001

Events
165
Median survival
310
95% CI
[285, 363]
Log-rank p
.001

To keep this page light, the plots are shown once, under the R tab.

Assumptions

  • Non-informative censoring — 63 of 228 observations are censored; censoring must be unrelated to prognosis.
  • Number of events — At least 10 events per curve.

Survival summary

sexnEventsMedian95% CI low95% CI highRMST (τ = 500)SE
All228165310285363310.3311.246
male138112270212310278.7614.355
female9053426348550360.9116.801

Survival at chosen times

sexTimeAt riskSurvival95% CI low95% CI high
All2601130.59670.53490.6656
All510410.29330.23200.3707
All77090.08810.04980.1560
male260610.51920.44090.6114
male510200.22320.15690.3176
male77070.07810.03900.1563
female260520.71860.62870.8214
female510210.41100.30500.5540
female77020.08320.02570.2697

log intervals; Greenwood standard errors.

  • Event: status = 2. Intervals: log transformation (Greenwood SE); median limits from the interval curves (Brookmeyer–Crowley).
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Kaplan–Meier survival curves
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method survival.km 1.0.1 · spec 97d5cf030ef37e8c
# Dataset: lung (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
import numpy as np
import pandas as pd

import codesplash as cs
from codesplash.stats import survival as sv  # survfit/survdiff twins (see its docstring)

# %% Data
df = pd.read_parquet("tests/parity/fixtures/lung.parquet", columns=["time", "status", "sex"])
n_input = len(df)
df["sex"] = pd.Categorical(df["sex"], categories=["male", "female"])  # stored level order
df = df.dropna(subset=["time", "status", "sex"])  # listwise deletion over the analysis columns
df["sex"] = df["sex"].cat.remove_unused_categories()
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
    warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
    cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["time", "status", "sex"])  # infinite values stop the run (registry/errors.yaml)

# %% Event coding
tcol = "time"
ecol = "status"
t = df[tcol].to_numpy(dtype=float)
if (t < 0).any():
    cs.cs_error("CS_E_INVALID_VALUES", column=tcol, requirement="zero or positive (survival times)", count=int((t < 0).sum()))
codes = set(np.unique(df[ecol].to_numpy(dtype=float)).tolist())
if codes <= {0.0, 1.0}:
    event_code = 1.0  # 0 = censored, 1 = event
elif codes <= {1.0, 2.0}:
    event_code = 2.0  # 1 = censored, 2 = event (survival::Surv convention)
else:
    raise ValueError(f"{ecol} must be coded 0/1 or 1/2 (the larger code is the event), or be a yes/no or categorical column")
ev = df[ecol].to_numpy(dtype=float) == event_code
event_label = f"{ecol} = {event_code:g}"
if not ev.any():
    cs.cs_error("CS_E_NO_EVENTS", event=event_label)

# %% Kaplan–Meier
conf = 0.95
conf_type = "log"  # pinned: survfit's default is "log"
times = [] or sv.default_times(t)
rmst_tau = 500  # 0 = no restricted mean
g = "sex"
levels = [str(x) for x in df[g].cat.categories]
gv = df[g].astype(str).to_numpy()
strata = [("All", np.ones(len(t), dtype=bool))] + [(lv, gv == lv) for lv in levels]

values = {"event_label": event_label, "n_groups": len(levels) if levels else None}
summary_rows, time_rows, curve = [], [], {"time": [], "surv": [], "low": [], "high": [], "strata": [], "nrisk": [], "ncensor": []}
for name, m in strata:
    fit = sv.km(t[m], ev[m], conf=conf, conf_type=conf_type)
    med, med_lo, med_hi = sv.km_median(fit)
    rm, rm_se = sv.rmst(fit, rmst_tau) if rmst_tau > 0 else (None, None)
    at = sv.km_at(fit, times)
    nan = lambda x: None if x is None or not np.isfinite(x) else float(x)  # noqa: E731
    stats_ = {"n": float(m.sum()), "events": float(ev[m].sum()), "median": nan(med), "median_low": nan(med_lo),
              "median_high": nan(med_hi), "rmst": nan(rm), "rmst_se": nan(rm_se)}
    for k, v in stats_.items():
        values[k if name == "All" else f"{k}[{name}]"] = v
    summary_rows.append({"group": name, **stats_})
    for i, x in enumerate(times):
        key = f"{name}@{sv.key_num(x)}"
        row = {"group": name, "time": x, "n_risk": float(at["n_risk"][i]), "surv": nan(at["surv"][i]),
               "lower": nan(at["lower"][i]), "upper": nan(at["upper"][i])}
        values[f"surv[{key}]"], values[f"surv_low[{key}]"], values[f"surv_high[{key}]"] = row["surv"], row["lower"], row["upper"]
        values[f"n_risk[{key}]"] = row["n_risk"]
        time_rows.append(row)
    if (name == "All") == (not levels):
        curve["time"] += [0.0] + fit["time"].tolist()
        curve["surv"] += [1.0] + fit["surv"].tolist()
        curve["low"] += [1.0] + [nan(x) for x in fit["lower"]]
        curve["high"] += [1.0] + [nan(x) for x in fit["upper"]]
        curve["strata"] += [name] * (len(fit["time"]) + 1)
        curve["nrisk"] += [float(m.sum())] + fit["n_risk"].tolist()
        curve["ncensor"] += [0.0] + fit["n_censor"].tolist()

# %% Log-rank test
if levels:
    codes = np.array([levels.index(x) for x in gv])
    lr = sv.logrank(t, ev, codes, rho=0.0)  # survdiff(Surv(time, event) ~ group)
    values.update({"logrank_chisq": lr["chisq"], "logrank_df": float(lr["df"]), "logrank_p": lr["p"]})
else:
    values.update({"logrank_chisq": None, "logrank_df": None, "logrank_p": None})

# %% Assumptions
assumptions = [{"key": "censoring", "label": "Non-informative censoring", "status": "info",
                "detail": f"{int((~ev).sum())} of {len(ev)} observations are censored; censoring must be unrelated to prognosis."}]
few = [r["group"] for r in summary_rows if r["events"] < 10 and (r["group"] != "All" or not levels)]
if few:
    assumptions.append({"key": "sample_size", "label": "Number of events", "status": "warn",
                        "detail": f"Fewer than 10 events in {', '.join(few)}; medians and curves are imprecise."})
else:
    assumptions.append({"key": "sample_size", "label": "Number of events", "status": "pass", "detail": "At least 10 events per curve."})

# %% Result
pct = f"{conf:.0%}"
med_text = "not reached" if values["median"] is None else f"{values['median']:.4g}"
cs.publish({
    "method": "survival.km",
    "methodVersion": "1.0.1",
    "title": "Kaplan–Meier survival" + (f" by {g}" if levels else ""),
    "engine": cs.engine_info("numpy", "scipy", "codesplash"),
    "n": int(len(t)),
    "summary": f"{int(ev.sum())} of {len(t)} subjects had the event ({event_label}); median survival {med_text}."
    + (f" Log-rank {cs.fmt_p(values['logrank_p'])}." if levels else ""),
    "apa": f"median survival = {med_text}" + (f"; log-rank χ²({values['logrank_df']:.0f}) = {cs.fmt_num(values['logrank_chisq'])}, {cs.fmt_p(values['logrank_p'])}" if levels else ""),
    "statistics": [
        {"key": "events", "label": "Events", "value": values["events"], "format": "integer"},
        {"key": "median", "label": "Median survival", "value": values["median"]},
        {"key": "median_ci", "label": f"{pct} CI", "value": [values["median_low"], values["median_high"]]},
    ] + ([{"key": "logrank_p", "label": "Log-rank p", "value": values["logrank_p"], "format": "p"}] if levels else []),
    "tables": [
        {"key": "summary", "title": "Survival summary", "columns": [
            {"key": "group", "label": g if levels else "Curve", "type": "string"}, {"key": "n", "label": "n", "type": "integer"},
            {"key": "events", "label": "Events", "type": "integer"}, {"key": "median", "label": "Median", "type": "number"},
            {"key": "median_low", "label": f"{pct} CI low", "type": "number"}, {"key": "median_high", "label": f"{pct} CI high", "type": "number"},
        ] + ([{"key": "rmst", "label": f"RMST (τ = {rmst_tau:g})", "type": "number"}, {"key": "rmst_se", "label": "SE", "type": "number"}]
             if rmst_tau > 0 else []), "rows": summary_rows},
        {"key": "survival_at", "title": "Survival at chosen times", "columns": [
            {"key": "group", "label": g if levels else "Curve", "type": "string"}, {"key": "time", "label": "Time", "type": "number"},
            {"key": "n_risk", "label": "At risk", "type": "integer"}, {"key": "surv", "label": "Survival", "type": "number"},
            {"key": "lower", "label": f"{pct} CI low", "type": "number"}, {"key": "upper", "label": f"{pct} CI high", "type": "number"},
        ], "rows": time_rows, "note": f"{conf_type} intervals; Greenwood standard errors."},
    ],
    "assumptions": assumptions,
    "warnings": warnings,
    "notes": [f"Event: {event_label}. Intervals: {conf_type} transformation (Greenwood SE); median limits from the interval curves (Brookmeyer–Crowley)."],
    "charts": [cs.chart("km", "km-curve", "Kaplan–Meier curve" + (f" by {g}" if levels else ""), {
        "time": cs.col(tcol, curve["time"], "numeric"), "surv": cs.col("Survival probability", curve["surv"], "numeric"),
        "low": cs.col("lower", curve["low"], "numeric"), "high": cs.col("upper", curve["high"], "numeric"),
        "strata": cs.col(g, curve["strata"], "categorical", levels=levels) if levels else None,
        "nrisk": cs.col("At risk", curve["nrisk"], "numeric"), "ncensor": cs.col("Censored", curve["ncensor"], "numeric"),
    }), cs.chart("cumhaz", "cumhaz", "Cumulative hazard" + (f" by {g}" if levels else ""), {
        "time": cs.col(tcol, curve["time"], "numeric"), "surv": cs.col("Survival probability", curve["surv"], "numeric"),
        "strata": cs.col(g, curve["strata"], "categorical", levels=levels) if levels else None,
    }), cs.chart("loglog", "loglog-survival", "Log–log survival" + (f" by {g}" if levels else ""), {
        "time": cs.col(tcol, curve["time"], "numeric"), "surv": cs.col("Survival probability", curve["surv"], "numeric"),
        "strata": cs.col(g, curve["strata"], "categorical", levels=levels) if levels else None,
    })],
    "values": values,
})

The option Restricted mean up to τ sets the horizon, and Report survival at times chooses the time points.

06

Check your understanding

Checkpoint

Check yourself

Which statement is right?

Show the answer

Answer: b

A falling hazard means the curve falls more slowly, not that it rises. A hazard is a rate, so its value isn't limited to 1 and it isn't a probability.

Check yourself

Group A has a restricted mean of 300 days and group B of 270 days, with a horizon of 365 days. What does this mean?

Show the answer

Answer: b

The restricted mean describes the window up to the horizon and says nothing about what happens after it.

Check yourself

When should you choose the horizon τ\tau?

Show the answer

Answer: a

Picking τ\tau where the gap looks largest inflates the difference, and a horizon past most patients' follow-up rests on very few people.

07

Recap

Recap
  • The hazard is the risk right now; the survival curve is what those risks add up to.
  • The median needs the curve to cross 50%, which may never happen.
  • Survival at fixed times and the restricted mean are well defined when the median isn't, and are easy to explain.

Concepts in this lesson