Generators¶
The eleven models, grouped by module. Each function returns a
pandas.DataFrame; see Output schemas for what
the columns mean.
Cox proportional hazards¶
cphm
¶
Cox Proportional Hazards Model (CPHM) data generation.
This module provides functions to generate survival data following the Cox Proportional Hazards Model with various censoring mechanisms.
generate_cphm_data
¶
generate_cphm_data(
n: int,
rfunc: CensoringFunc,
cens_par: float,
beta: float,
covariate_range: float,
seed: int | None = None,
) -> NDArray[float64]
Generate data from a Cox Proportional Hazards Model (CPHM).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n
|
int
|
Number of samples to generate. |
required |
rfunc
|
callable
|
Function to generate censoring times, must accept (size, cens_par). |
required |
cens_par
|
float
|
Parameter passed to the censoring function. |
required |
beta
|
float
|
Coefficient for the covariate. |
required |
covariate_range
|
float
|
Range for the covariate (uniformly sampled from [0, covariate_range]). |
required |
seed
|
int
|
Random seed for reproducibility. |
None
|
Returns:
| Type | Description |
|---|---|
NDArray[float64]
|
Array with shape |
Source code in gen_surv/cphm.py
gen_cphm
¶
gen_cphm(
n: int,
model_cens: Literal["uniform", "exponential"],
cens_par: float,
beta: float,
covariate_range: float,
seed: int | None = None,
) -> DataFrame
Generate survival data following a Cox Proportional Hazards Model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n
|
int
|
Number of observations. |
required |
model_cens
|
(uniform, exponential)
|
Type of censoring mechanism. |
"uniform"
|
cens_par
|
float
|
Parameter for the censoring model. |
required |
beta
|
float
|
Coefficient for the covariate. |
required |
covariate_range
|
float
|
Upper bound for the covariate values (uniform between 0 and covariate_range). |
required |
seed
|
int
|
Random seed for reproducibility. |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame with columns ["time", "status", "X0"] - time: observed event or censoring time - status: event indicator (1=event, 0=censored) - X0: predictor variable |
Examples:
>>> from gen_surv.cphm import gen_cphm
>>> df = gen_cphm(n=100, model_cens="uniform", cens_par=1.0, beta=0.5, covariate_range=2.0)
>>> df.head()
time status X0
0 0.23 1.0 1.42
1 0.78 0.0 0.89
...
Source code in gen_surv/cphm.py
Accelerated failure time¶
aft
¶
Accelerated Failure Time (AFT) models including Weibull, Log-Normal, and Log-Logistic distributions.
gen_aft_log_normal
¶
gen_aft_log_normal(
n: int,
beta: List[float],
sigma: float,
model_cens: Literal["uniform", "exponential"],
cens_par: float,
seed: int | None = None,
) -> DataFrame
Simulate survival data under a Log-Normal Accelerated Failure Time (AFT) model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n
|
int
|
Number of individuals |
required |
beta
|
list of float
|
Coefficients for covariates |
required |
sigma
|
float
|
Standard deviation of the log-error term |
required |
model_cens
|
(uniform, exponential)
|
Censoring mechanism |
"uniform"
|
cens_par
|
float
|
Parameter for censoring distribution |
required |
seed
|
int
|
Random seed for reproducibility |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame with columns ['id', 'time', 'status', 'X0', ..., 'Xp'] |
Examples:
>>> from gen_surv.aft import gen_aft_log_normal
>>> df = gen_aft_log_normal(
... n=100,
... beta=[0.5, -0.3],
... sigma=1.0,
... model_cens="uniform",
... cens_par=2.0,
... seed=42,
... )
>>> df.head()
Source code in gen_surv/aft.py
gen_aft_weibull
¶
gen_aft_weibull(
n: int,
beta: List[float],
shape: float,
scale: float,
model_cens: Literal["uniform", "exponential"],
cens_par: float,
seed: int | None = None,
) -> DataFrame
Simulate survival data under a Weibull Accelerated Failure Time (AFT) model.
The Weibull AFT model has survival function: S(t|X) = exp(-(t/scale)^shape * exp(-X*beta))
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n
|
int
|
Number of individuals |
required |
beta
|
list of float
|
Coefficients for covariates |
required |
shape
|
float
|
Weibull shape parameter (k > 0) |
required |
scale
|
float
|
Weibull scale parameter (λ > 0) |
required |
model_cens
|
(uniform, exponential)
|
Censoring mechanism |
"uniform"
|
cens_par
|
float
|
Parameter for censoring distribution |
required |
seed
|
int
|
Random seed for reproducibility |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame with columns ['id', 'time', 'status', 'X0', ..., 'Xp'] |
Examples:
>>> from gen_surv.aft import gen_aft_weibull
>>> df = gen_aft_weibull(
... n=100,
... beta=[0.5, -0.3],
... shape=1.2,
... scale=2.0,
... model_cens="uniform",
... cens_par=2.0,
... seed=42,
... )
>>> df.head()
Source code in gen_surv/aft.py
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 | |
gen_aft_log_logistic
¶
gen_aft_log_logistic(
n: int,
beta: List[float],
shape: float,
scale: float,
model_cens: Literal["uniform", "exponential"],
cens_par: float,
seed: int | None = None,
) -> DataFrame
Simulate survival data under a Log-Logistic Accelerated Failure Time (AFT) model.
The Log-Logistic AFT model has survival function: S(t|X) = 1 / (1 + (t/scale)^shape * exp(X*beta))
Log-logistic distribution is useful when the hazard rate first increases and then decreases.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n
|
int
|
Number of individuals |
required |
beta
|
list of float
|
Coefficients for covariates |
required |
shape
|
float
|
Log-logistic shape parameter (α > 0) |
required |
scale
|
float
|
Log-logistic scale parameter (β > 0) |
required |
model_cens
|
(uniform, exponential)
|
Censoring mechanism |
"uniform"
|
cens_par
|
float
|
Parameter for censoring distribution |
required |
seed
|
int
|
Random seed for reproducibility |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame with columns ['id', 'time', 'status', 'X0', ..., 'Xp'] |
Examples:
>>> from gen_surv.aft import gen_aft_log_logistic
>>> df = gen_aft_log_logistic(
... n=100,
... beta=[0.5, -0.3],
... shape=1.2,
... scale=2.0,
... model_cens="uniform",
... cens_par=2.0,
... seed=42,
... )
>>> df.head()
Source code in gen_surv/aft.py
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 | |
Piecewise exponential¶
piecewise
¶
Piecewise Exponential survival models.
This module provides functions for generating survival data from piecewise exponential distributions with time-dependent hazards.
gen_piecewise_exponential
¶
gen_piecewise_exponential(
n: int,
breakpoints: list[float],
hazard_rates: list[float],
betas: list[float] | NDArray[float64] | None = None,
n_covariates: int = 2,
covariate_dist: Literal[
"normal", "uniform", "binary"
] = "normal",
covariate_params: dict[str, float] | None = None,
model_cens: Literal[
"uniform", "exponential"
] = "uniform",
cens_par: float = 5.0,
seed: int | None = None,
) -> DataFrame
Generate survival data using a piecewise exponential distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n
|
int
|
Number of subjects. |
required |
breakpoints
|
list of float
|
Time points where hazard rates change. Must be in ascending order. The first interval is [0, breakpoints[0]), the second is [breakpoints[0], breakpoints[1]), etc. |
required |
hazard_rates
|
list of float
|
Hazard rates for each interval. Length should be len(breakpoints) + 1. |
required |
betas
|
list or array
|
Coefficients for covariates. If None, generates random coefficients. |
None
|
n_covariates
|
int
|
Number of covariates to generate if betas is None. |
2
|
covariate_dist
|
(normal, uniform, binary)
|
Distribution to generate covariates from. |
"normal"
|
covariate_params
|
dict
|
Parameters for covariate distribution: - "normal": {"mean": float, "std": float} - "uniform": {"low": float, "high": float} - "binary": {"p": float} If None, uses defaults based on distribution. |
None
|
model_cens
|
(uniform, exponential)
|
Censoring mechanism. |
"uniform"
|
cens_par
|
float
|
Parameter for censoring distribution. |
5.0
|
seed
|
int
|
Random seed for reproducibility. |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame with columns: - "id": Subject identifier - "time": Time to event or censoring - "status": Event indicator (1=event, 0=censored) - "X0", "X1", ...: Covariates |
Examples:
>>> from gen_surv.piecewise import gen_piecewise_exponential
>>>
>>> # Generate data with 3 intervals (increasing hazard)
>>> df = gen_piecewise_exponential(
... n=100,
... breakpoints=[1.0, 3.0],
... hazard_rates=[0.2, 0.5, 1.0],
... betas=[0.8, -0.5],
... seed=42
... )
Source code in gen_surv/piecewise.py
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 | |
piecewise_hazard_function
¶
piecewise_hazard_function(
t: float | NDArray[float64],
breakpoints: list[float],
hazard_rates: list[float],
) -> float | NDArray[float64]
Calculate the hazard function value at time t for a piecewise exponential distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
t
|
float or array
|
Time point(s) at which to evaluate the hazard function. |
required |
breakpoints
|
list of float
|
Time points where hazard rates change. |
required |
hazard_rates
|
list of float
|
Hazard rates for each interval. |
required |
Returns:
| Type | Description |
|---|---|
float or array
|
Hazard function value(s) at time t. |
Source code in gen_surv/piecewise.py
piecewise_survival_function
¶
piecewise_survival_function(
t: float | NDArray[float64],
breakpoints: list[float],
hazard_rates: list[float],
) -> float | NDArray[float64]
Calculate the survival function at time t for a piecewise exponential distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
t
|
float or array
|
Time point(s) at which to evaluate the survival function. |
required |
breakpoints
|
list of float
|
Time points where hazard rates change. |
required |
hazard_rates
|
list of float
|
Hazard rates for each interval. |
required |
Returns:
| Type | Description |
|---|---|
float or array
|
Survival function value(s) at time t. |
Source code in gen_surv/piecewise.py
Competing risks¶
competing_risks
¶
Competing Risks models for survival data simulation.
This module provides functions to generate survival data with competing risks under different hazard specifications.
gen_competing_risks
¶
gen_competing_risks(
n: int,
n_risks: int = 2,
baseline_hazards: (
Union[List[float], ndarray] | None
) = None,
betas: Union[List[List[float]], ndarray] | None = None,
covariate_dist: Literal[
"normal", "uniform", "binary"
] = "normal",
covariate_params: Dict[str, float] | None = None,
max_time: float | None = 10.0,
model_cens: Literal[
"uniform", "exponential"
] = "uniform",
cens_par: float = 5.0,
seed: int | None = None,
) -> DataFrame
Generate survival data with competing risks.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n
|
int
|
Number of subjects. |
required |
n_risks
|
int
|
Number of competing risks. |
2
|
baseline_hazards
|
list of float or array
|
Baseline hazard rates for each risk. If None, uses [0.5, 0.3, ...] with decreasing values for subsequent risks. |
None
|
betas
|
list of list of float or array
|
Coefficients for covariates, one list per risk. Shape should be (n_risks, n_covariates). If None, generates random coefficients. |
None
|
covariate_dist
|
(normal, uniform, binary)
|
Distribution to generate covariates from. |
"normal"
|
covariate_params
|
dict
|
Parameters for covariate distribution: - "normal": {"mean": float, "std": float} - "uniform": {"low": float, "high": float} - "binary": {"p": float} If None, uses defaults based on distribution. |
None
|
max_time
|
float
|
Maximum simulation time. Set to None for no limit. |
10.0
|
model_cens
|
(uniform, exponential)
|
Censoring mechanism. |
"uniform"
|
cens_par
|
float
|
Parameter for censoring distribution. |
5.0
|
seed
|
int
|
Random seed for reproducibility. |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame with columns: - "id": Subject identifier - "time": Time to event or censoring - "status": Event indicator (0=censored, 1,2,...=competing events) - "X0", "X1", ...: Covariates |
Examples:
>>> from gen_surv.competing_risks import gen_competing_risks
>>>
>>> # Simple example with 2 competing risks
>>> df = gen_competing_risks(
... n=100,
... n_risks=2,
... baseline_hazards=[0.5, 0.3],
... betas=[[0.8, -0.5], [0.2, 0.7]],
... seed=42
... )
>>>
>>> # Distribution of event types
>>> df["status"].value_counts()
Source code in gen_surv/competing_risks.py
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 | |
gen_competing_risks_weibull
¶
gen_competing_risks_weibull(
n: int,
n_risks: int = 2,
shape_params: Union[List[float], ndarray] | None = None,
scale_params: Union[List[float], ndarray] | None = None,
betas: Union[List[List[float]], ndarray] | None = None,
covariate_dist: Literal[
"normal", "uniform", "binary"
] = "normal",
covariate_params: Dict[str, float] | None = None,
max_time: float | None = 10.0,
model_cens: Literal[
"uniform", "exponential"
] = "uniform",
cens_par: float = 5.0,
seed: int | None = None,
) -> DataFrame
Generate survival data with competing risks using Weibull hazards.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n
|
int
|
Number of subjects. |
required |
n_risks
|
int
|
Number of competing risks. |
2
|
shape_params
|
list of float or array
|
Shape parameters for Weibull distribution, one per risk. If None, uses [1.2, 0.8, ...] alternating values. |
None
|
scale_params
|
list of float or array
|
Scale parameters for Weibull distribution, one per risk. If None, uses [2.0, 3.0, ...] increasing values. |
None
|
betas
|
list of list of float or array
|
Coefficients for covariates, one list per risk. Shape should be (n_risks, n_covariates). If None, generates random coefficients. |
None
|
covariate_dist
|
(normal, uniform, binary)
|
Distribution to generate covariates from. |
"normal"
|
covariate_params
|
dict
|
Parameters for covariate distribution: - "normal": {"mean": float, "std": float} - "uniform": {"low": float, "high": float} - "binary": {"p": float} If None, uses defaults based on distribution. |
None
|
max_time
|
float
|
Maximum simulation time. Set to None for no limit. |
10.0
|
model_cens
|
(uniform, exponential)
|
Censoring mechanism. |
"uniform"
|
cens_par
|
float
|
Parameter for censoring distribution. |
5.0
|
seed
|
int
|
Random seed for reproducibility. |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame with columns: - "id": Subject identifier - "time": Time to event or censoring - "status": Event indicator (0=censored, 1,2,...=competing events) - "X0", "X1", ...: Covariates |
Examples:
>>> from gen_surv.competing_risks import gen_competing_risks_weibull
>>>
>>> # Example with 2 competing risks with different shapes
>>> df = gen_competing_risks_weibull(
... n=100,
... n_risks=2,
... shape_params=[0.8, 1.5], # Decreasing vs increasing hazard
... scale_params=[2.0, 3.0],
... betas=[[0.8, -0.5], [0.2, 0.7]],
... seed=42
... )
Source code in gen_surv/competing_risks.py
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 | |
cause_specific_cumulative_incidence
¶
cause_specific_cumulative_incidence(
data: DataFrame,
time_points: Union[List[float], ndarray],
time_col: str = "time",
status_col: str = "status",
cause: int = 1,
) -> DataFrame
Calculate the cause-specific cumulative incidence function at specified time points.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
DataFrame with competing risks data. |
required |
time_points
|
list of float or array
|
Time points at which to calculate the cumulative incidence. |
required |
time_col
|
str
|
Name of the time column. |
"time"
|
status_col
|
str
|
Name of the status column (0=censored, 1,2,...=competing events). |
"status"
|
cause
|
int
|
The cause/event type for which to calculate the incidence. |
1
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame with time points and corresponding cumulative incidence values. |
Notes
The cumulative incidence function for cause j is defined as: F_j(t) = P(T <= t, cause = j)
This is the probability of experiencing the event of type j before time t.
Source code in gen_surv/competing_risks.py
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 | |
competing_risks_summary
¶
competing_risks_summary(
data: DataFrame,
time_col: str = "time",
status_col: str = "status",
covariate_cols: list[str] | None = None,
) -> dict[str, Any]
Provide a summary of a competing risks dataset.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
DataFrame with competing risks data. |
required |
time_col
|
str
|
Name of the time column. |
"time"
|
status_col
|
str
|
Name of the status column (0=censored, 1,2,...=competing events). |
"status"
|
covariate_cols
|
list of str
|
List of covariate columns to include in the summary. If None, all columns except time_col and status_col are considered. |
None
|
Returns:
| Type | Description |
|---|---|
Dict[str, Any]
|
Dictionary with summary statistics. |
Examples:
>>> from gen_surv.competing_risks import gen_competing_risks, competing_risks_summary
>>>
>>> # Generate data
>>> df = gen_competing_risks(n=100, n_risks=3, seed=42)
>>>
>>> # Get summary
>>> summary = competing_risks_summary(df)
>>> print(f"Number of events by cause: {summary['events_by_cause']}")
>>> print(f"Median time to first event: {summary['median_time']}")
Source code in gen_surv/competing_risks.py
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 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 | |
plot_cause_specific_hazards
¶
plot_cause_specific_hazards(
data: DataFrame,
time_points: ndarray | None = None,
time_col: str = "time",
status_col: str = "status",
bandwidth: float = 0.5,
figsize: tuple[float, float] = (10, 6),
) -> tuple[Figure, Axes]
Plot cause-specific hazard functions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
DataFrame with competing risks data. |
required |
time_points
|
array
|
Time points at which to estimate hazards. If None, uses 100 equally spaced points from 0 to max time. |
None
|
time_col
|
str
|
Name of the time column. |
"time"
|
status_col
|
str
|
Name of the status column (0=censored, 1,2,...=competing events). |
"status"
|
bandwidth
|
float
|
Bandwidth for kernel density estimation. |
0.5
|
figsize
|
tuple
|
Figure size (width, height) in inches. |
(10, 6)
|
Returns:
| Type | Description |
|---|---|
tuple
|
Figure and axes objects. |
Notes
This function requires matplotlib and scipy.
Source code in gen_surv/competing_risks.py
538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 | |
Mixture cure¶
mixture
¶
Mixture Cure Models for survival data simulation.
This module provides functions to generate survival data with a cure fraction, i.e., a proportion of subjects who are immune to the event of interest.
gen_mixture_cure
¶
gen_mixture_cure(
n: int,
cure_fraction: float,
baseline_hazard: float = 0.5,
betas_survival: list[float] | None = None,
betas_cure: list[float] | None = None,
n_covariates: int = 2,
covariate_dist: Literal[
"normal", "uniform", "binary"
] = "normal",
covariate_params: dict[str, float] | None = None,
model_cens: Literal[
"uniform", "exponential"
] = "uniform",
cens_par: float = 5.0,
max_time: float | None = 10.0,
seed: int | None = None,
) -> DataFrame
Generate survival data with a cure fraction using a mixture cure model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n
|
int
|
Number of subjects. |
required |
cure_fraction
|
float
|
Baseline probability of being cured (immune to the event). Should be between 0 and 1. |
required |
baseline_hazard
|
float
|
Baseline hazard rate for the non-cured population. |
0.5
|
betas_survival
|
list of float
|
Coefficients for covariates in the survival component. If None, generates random coefficients. |
None
|
betas_cure
|
list of float
|
Coefficients for covariates in the cure component. If None, generates random coefficients. |
None
|
n_covariates
|
int
|
Number of covariates to generate if betas is None. |
2
|
covariate_dist
|
(normal, uniform, binary)
|
Distribution to generate covariates from. |
"normal"
|
covariate_params
|
dict
|
Parameters for covariate distribution: - "normal": {"mean": float, "std": float} - "uniform": {"low": float, "high": float} - "binary": {"p": float} If None, uses defaults based on distribution. |
None
|
model_cens
|
(uniform, exponential)
|
Censoring mechanism. |
"uniform"
|
cens_par
|
float
|
Parameter for censoring distribution. |
5.0
|
max_time
|
float
|
Maximum simulation time. Set to None for no limit. |
10.0
|
seed
|
int
|
Random seed for reproducibility. |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame with columns: - "id": Subject identifier - "time": Time to event or censoring - "status": Event indicator (1=event, 0=censored) - "cured": Indicator of cure status (1=cured, 0=not cured) - "X0", "X1", ...: Covariates |
Examples:
>>> from gen_surv.mixture import gen_mixture_cure
>>>
>>> # Generate data with 30% baseline cure fraction
>>> df = gen_mixture_cure(
... n=100,
... cure_fraction=0.3,
... betas_survival=[0.8, -0.5],
... betas_cure=[-0.5, 0.8],
... seed=42
... )
>>>
>>> # Check cure proportion
>>> print(f"Cured subjects: {df['cured'].mean():.2%}")
Source code in gen_surv/mixture.py
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 | |
cure_fraction_estimate
¶
cure_fraction_estimate(
data: DataFrame,
time_col: str = "time",
status_col: str = "status",
bandwidth: float = 0.1,
) -> float
Estimate the cure fraction from observed data using non-parametric methods.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
DataFrame with survival data. |
required |
time_col
|
str
|
Name of the time column. |
"time"
|
status_col
|
str
|
Name of the status column (1=event, 0=censored). |
"status"
|
bandwidth
|
float
|
Bandwidth parameter for smoothing the tail of the survival curve. |
0.1
|
Returns:
| Type | Description |
|---|---|
float
|
Estimated cure fraction. |
Notes
This function uses a non-parametric approach to estimate the cure fraction based on the plateau of the survival curve. It may not be accurate for small sample sizes or heavy censoring.
Source code in gen_surv/mixture.py
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 | |
Illness-death, intervals¶
cmm
¶
generate_event_times
¶
generate_event_times(
z1: float,
beta: Sequence[float],
rate: Sequence[float],
rng: Generator | None = None,
) -> EventTimes
Generate event times for a continuous-time multi-state Markov model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
z1
|
float
|
Covariate value. |
required |
beta
|
Sequence[float]
|
List of 3 beta coefficients. |
required |
rate
|
Sequence[float]
|
List of 6 transition rate parameters. |
required |
rng
|
Generator
|
Random number generator to use. Defaults to |
None
|
Returns:
| Type | Description |
|---|---|
EventTimes
|
Dictionary with keys |
Examples:
>>> from gen_surv.cmm import generate_event_times
>>> ev = generate_event_times(0.2, [0.1, -0.2, 0.3],
... [0.5, 1.0, 0.7, 1.2, 0.4, 1.5])
>>> sorted(ev.keys())
['t12', 't13', 't23']
Source code in gen_surv/cmm.py
gen_cmm
¶
gen_cmm(
n: int,
model_cens: str,
cens_par: float,
beta: Sequence[float],
covariate_range: float,
rate: Sequence[float],
seed: RandomStateLike = None,
) -> DataFrame
Generate survival data using a continuous-time Markov model (CMM).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n
|
int
|
Number of individuals. |
required |
model_cens
|
str
|
|
required |
cens_par
|
float
|
Parameter for censoring. |
required |
beta
|
Sequence[float]
|
Regression coefficients (length 3). |
required |
covariate_range
|
float
|
Upper bound for the covariate values. |
required |
rate
|
Sequence[float]
|
Transition rates (length 6). |
required |
seed
|
int
|
Random seed for reproducibility. |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Counting-process records with columns States are 1 (healthy), 2 (illness) and 3 (death). While a subject
occupies state 1 it is simultaneously at risk of |
Notes
Sojourn times are drawn on a reset clock, so the model is semi-Markov: the
2 -> 3 row spans t12 to t12 + t23 where t23 is an
independent draw. This matches genCMM in the R package.
Examples:
>>> from gen_surv.cmm import gen_cmm
>>> df = gen_cmm(
... n=50,
... model_cens="uniform",
... cens_par=2.0,
... beta=[0.3, -0.2, 0.1],
... covariate_range=1.0,
... rate=[0.1, 1.0, 0.2, 1.2, 0.3, 1.5],
... seed=42,
... )
>>> list(df.columns)
['id', 'start', 'stop', 'from_state', 'to_state', 'status', 'X0']
Source code in gen_surv/cmm.py
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 | |
Illness-death, panel¶
thmm
¶
calculate_transitions
¶
calculate_transitions(
z1: float,
cens_par: float,
beta: Sequence[float],
rate: Sequence[float],
rfunc: CensoringFunc,
seed: RandomStateLike = None,
) -> TransitionTimes
Calculate transition and censoring times for THMM.
Parameters: - z1 (float): Covariate value. - cens_par (float): Censoring parameter. - beta (list of float): Coefficients for rate modification (length 3). - rate (list of float): Base rates (length 3). - rfunc (callable): Censoring function, e.g. runifcens or rexpocens. - seed (int, Generator or None): Seed or generator for reproducibility.
Returns: - dict with keys 'c', 't12', 't13', 't23'
Source code in gen_surv/thmm.py
gen_thmm
¶
gen_thmm(
n: int,
model_cens: str,
cens_par: float,
beta: Sequence[float],
covariate_range: float,
rate: Sequence[float],
seed: RandomStateLike = None,
) -> DataFrame
Generate THMM (Time-Homogeneous Markov Model) survival data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n
|
int
|
Number of individuals. |
required |
model_cens
|
(uniform, exponential)
|
Censoring model. |
"uniform"
|
cens_par
|
float
|
Censoring parameter. |
required |
beta
|
Sequence[float]
|
Length-3 regression coefficients. |
required |
covariate_range
|
float
|
Upper bound for the covariate values. |
required |
rate
|
Sequence[float]
|
Length-3 transition rates. |
required |
seed
|
int or Generator
|
Seed or generator for reproducibility. |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Columns = States are 1 (healthy), 2 (illness) and 3 (death). Every subject starts with an observation in state 1 at time 0, then contributes one or two further observations, so subjects yield two or three rows each rather than one. A subject still in state 1 or 2 when censoring occurs has a final observation in that state at the censoring time. |
Notes
This panel layout -- a state recorded at each observation time -- matches
genTHMM in the R package, and differs deliberately from
:func:gen_surv.cmm.gen_cmm, which emits counting-process intervals.
All transition intensities are constant in time, so sojourn times are exponential and the reset and forward clocks coincide.
Examples:
>>> from gen_surv.thmm import gen_thmm
>>> df = gen_thmm(
... n=3,
... model_cens="uniform",
... cens_par=5.0,
... beta=[0.1, 0.2, 0.3],
... covariate_range=1.0,
... rate=[0.1, 0.1, 0.2],
... seed=42,
... )
Source code in gen_surv/thmm.py
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 | |
Time-dependent covariates¶
tdcm
¶
generate_censored_observations
¶
generate_censored_observations(
n: int,
dist_par: Sequence[float],
model_cens: str,
cens_par: float,
beta: Sequence[float],
lam: float,
b: NDArray[float64],
seed: RandomStateLike = None,
) -> NDArray[float64]
Generate censored TDCM observations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n
|
int
|
Number of individuals. |
required |
dist_par
|
Sequence[float]
|
Not directly used here (kept for API compatibility). |
required |
model_cens
|
(uniform, exponential)
|
Censoring model. |
"uniform"
|
cens_par
|
float
|
Parameter for the censoring model. |
required |
beta
|
Sequence[float]
|
Length-2 list of regression coefficients. |
required |
lam
|
float
|
Rate parameter. |
required |
b
|
NDArray[float64]
|
Covariate matrix with two columns |
required |
seed
|
int or Generator
|
Seed or generator for reproducibility. |
None
|
Returns:
| Type | Description |
|---|---|
NDArray[float64]
|
Array of shape |
Source code in gen_surv/tdcm.py
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 | |
gen_tdcm
¶
gen_tdcm(
n: int,
dist: str,
corr: float,
dist_par: Sequence[float],
model_cens: str,
cens_par: float,
beta: Sequence[float],
lam: float,
seed: RandomStateLike = None,
) -> DataFrame
Generate TDCM (Time-Dependent Covariate Model) survival data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n
|
int
|
Number of individuals. |
required |
dist
|
(weibull, exponential)
|
Type of marginal distributions. |
"weibull"
|
corr
|
float
|
Correlation between the baseline covariate and the crossover time, on
the latent normal scale. Must be in |
required |
dist_par
|
Sequence[float]
|
Distribution parameters. |
required |
model_cens
|
(uniform, exponential)
|
Censoring model. |
"uniform"
|
cens_par
|
float
|
Censoring parameter. |
required |
beta
|
Sequence[float]
|
Length-2 regression coefficients: the baseline covariate effect and the effect of the time-dependent covariate. |
required |
lam
|
float
|
Lambda rate parameter. |
required |
seed
|
int or Generator
|
Seed or generator for reproducibility. |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Columns are |
Examples:
>>> from gen_surv.tdcm import gen_tdcm
>>> df = gen_tdcm(
... n=5,
... dist="exponential",
... corr=0.3,
... dist_par=[0.5, 1.0],
... model_cens="uniform",
... cens_par=2.0,
... beta=[0.1, 0.2],
... lam=0.5,
... seed=42,
... )
Source code in gen_surv/tdcm.py
Recurrent events¶
recurrent
¶
Recurrent event data generation.
Subjects may experience the same event repeatedly during follow-up. The three processes here correspond to the models the data is usually analysed with:
ag
Andersen-Gill. The intensity depends on the covariates but not on how many
events have already happened, and the clock runs forward from entry. A
non-homogeneous Poisson process.
pwp_tt
Prentice-Williams-Peterson in total time. As Andersen-Gill, but the
intensity is scaled by a factor specific to the event number, so the risk of
a second event may differ from the risk of a first. The clock still runs
forward from entry.
pwp_gt
Prentice-Williams-Peterson in gap time. As pwp_tt, but the clock resets
after every event, so the baseline hazard is a function of time since the
previous event rather than time since entry.
All three return counting-process intervals, the canonical layout for transition data in this package.
gen_recurrent_events
¶
gen_recurrent_events(
n: int,
process: Process = "ag",
baseline: Baseline | BaselineHazard = "exponential",
baseline_params: dict[str, float] | None = None,
betas: Sequence[float] | None = None,
n_covariates: int = 2,
covariate_dist: Literal[
"normal", "uniform", "binary"
] = "normal",
covariate_params: dict[str, float] | None = None,
stratum_effects: Sequence[float] | None = None,
max_events: int | None = None,
followup_time: float = 10.0,
model_cens: Literal[
"uniform", "exponential"
] = "uniform",
cens_par: float = 20.0,
seed: RandomStateLike = None,
) -> DataFrame
Generate recurrent event data in counting-process form.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n
|
int
|
Number of subjects. Each contributes one row per at-risk interval, so
the frame is longer than |
required |
process
|
(ag, pwp_tt, pwp_gt)
|
Event process. |
"ag"
|
baseline
|
(exponential, weibull, gompertz)
|
Baseline hazard family. Exponential is constant, Weibull is monotone, Gompertz is exponentially increasing or decreasing. |
"exponential"
|
baseline_params
|
dict[str, float]
|
Parameters of the baseline. |
None
|
betas
|
Sequence[float]
|
Coefficients acting on the log intensity, one per covariate. Drawn at random when omitted, which is convenient for a smoke test and unusable for validation. |
None
|
n_covariates
|
int
|
Number of covariates when |
2
|
covariate_dist
|
(normal, uniform, binary)
|
Distribution the covariates are drawn from. |
"normal"
|
covariate_params
|
dict[str, float]
|
Parameters of that distribution. Defaults are filled in when omitted. |
None
|
stratum_effects
|
Sequence[float]
|
Multiplicative intensity factors by event number, for the two PWP
processes. The final entry applies to all later events, so
|
None
|
max_events
|
int
|
Stop following a subject once it has this many events. |
None
|
followup_time
|
float
|
Administrative end of follow-up, applied to every subject. |
10.0
|
model_cens
|
(uniform, exponential)
|
Random dropout mechanism, applied on top of |
"uniform"
|
cens_par
|
float
|
Parameter of the dropout distribution: the upper bound for |
20.0
|
seed
|
int or Generator
|
Seed or generator for reproducibility. |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Counting-process intervals with columns |
Raises:
| Type | Description |
|---|---|
ValidationError
|
If any parameter is outside its allowed range. |
Examples:
>>> from gen_surv.recurrent import gen_recurrent_events
>>> df = gen_recurrent_events(
... n=50,
... process="ag",
... baseline_params={"rate": 0.5},
... betas=[0.4, -0.2],
... followup_time=5.0,
... seed=42,
... )
>>> list(df.columns)
['id', 'start', 'stop', 'status', 'enum', 'X0', 'X1']
Source code in gen_surv/recurrent.py
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 | |
The multistate engine¶
multistate
¶
A general multistate engine.
A subject moves through a graph of states. Each edge carries its own baseline
hazard and its own coefficients, so the intensity of the i -> j transition
is
.. math::
\alpha_{ij}(t \mid X) = h_{0,ij}(t)\exp(X^\top\beta_{ij}).
Two clocks are supported, and the choice is what separates a Markov process from a semi-Markov one:
clock="forward"
The hazard is a function of time since entry to the study. The process is
Markov: where a subject has been does not matter, only where it is and how
long the study has run.
clock="reset"
The hazard restarts at each entry to a state, so it is a function of time
in the current state. The process is semi-Markov.
With an exponential baseline the two coincide, because a constant hazard is memoryless.
Both canonical layouts are available. layout="intervals" gives
counting-process rows -- one per transition a subject was at risk of, over the
interval it was at risk -- and layout="panel" gives one row per observation
of the subject's state. See :doc:the output schemas page </getting-started/schemas>.
Examples:
An illness-death process with Weibull sojourns:
>>> from gen_surv import Transition, WeibullBaseline, gen_multistate
>>> transitions = [
... Transition(1, 2, WeibullBaseline(shape=1.0, scale=3.0), [0.3]),
... Transition(1, 3, WeibullBaseline(shape=1.0, scale=5.0), [0.1]),
... Transition(2, 3, WeibullBaseline(shape=1.2, scale=2.0), [0.2]),
... ]
>>> frame = gen_multistate(n=100, transitions=transitions, clock="reset", seed=1)
>>> list(frame.columns)
['id', 'start', 'stop', 'from_state', 'to_state', 'status', 'X0']
Transition
dataclass
¶
Transition(
origin: int,
destination: int,
baseline: BaselineHazard,
coefficients: Sequence[float] = tuple(),
)
One edge of the transition graph.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
origin
|
int
|
The state a subject moves from. |
required |
destination
|
int
|
The state it moves to. Must differ from |
required |
baseline
|
BaselineHazard
|
The baseline hazard for this transition. Any object implementing the protocol works, so the shape is a parameter rather than a fork in the code. |
required |
coefficients
|
Sequence[float]
|
One coefficient per covariate, acting on the log intensity. Empty means the transition does not depend on the covariates. |
tuple()
|
gen_multistate
¶
gen_multistate(
n: int,
transitions: Sequence[Transition],
clock: Clock = "forward",
initial_state: int = 1,
covariate_dist: Literal[
"normal", "uniform", "binary"
] = "normal",
covariate_params: dict[str, float] | None = None,
model_cens: Literal[
"uniform", "exponential"
] = "uniform",
cens_par: float = 5.0,
max_time: float | None = None,
layout: Layout = "intervals",
seed: RandomStateLike = None,
) -> DataFrame
Simulate a multistate process over an arbitrary transition graph.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n
|
int
|
Number of subjects. Each contributes several rows, so the frame is
longer than |
required |
transitions
|
Sequence[Transition]
|
The graph. Every edge carries its own baseline hazard and coefficients. A state with no outgoing transition is absorbing. |
required |
clock
|
('forward', 'reset')
|
|
"forward"
|
initial_state
|
int
|
The state every subject starts in, at time zero. |
1
|
covariate_dist
|
('normal', 'uniform', 'binary')
|
Distribution the covariates are drawn from. |
"normal"
|
covariate_params
|
dict[str, float]
|
Parameters of that distribution; defaults are filled in. |
None
|
model_cens
|
('uniform', 'exponential')
|
Random censoring mechanism. |
"uniform"
|
cens_par
|
float
|
Parameter of the censoring distribution. |
5.0
|
max_time
|
float
|
Administrative end of follow-up, applied on top of random censoring. |
None
|
layout
|
('intervals', 'panel')
|
|
"intervals"
|
seed
|
int or Generator
|
Seed or generator for reproducibility. |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
For |
Raises:
| Type | Description |
|---|---|
ValidationError
|
If the graph is malformed or any parameter is out of range. |
Source code in gen_surv/multistate.py
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 470 | |