Bits & Flames bitsandflames/fyron

Survival Reference

Kaplan-Meier curves, RMST, Cox models, proportional hazards diagnostics, AFT models, and survival boosting.

For workflow context, see Survival module guide.

Functions And Classes

fyron.survival.boosting.train_gradient_survival_boosting

Train a gradient boosting survival model.

Import path: fyron.survival.boosting.train_gradient_survival_boosting

python
train_gradient_survival_boosting(X_train: ArrayLikeInput, duration_train: ArrayLike, event_train: ArrayLike, X_test: ArrayLikeInput | None = None, duration_test: ArrayLike | None = None, event_test: ArrayLike | None = None, *, random_state: int = 42, **model_params: Any) -> SurvivalBoostingResult

Parameters

ParameterRequiredTypeDefaultDescription
X_trainyesArrayLikeInputFeature matrix.
duration_trainyesArrayLikeSee signature.
event_trainyesArrayLikeSurvival time and event indicator for the training set.
X_testnoArrayLikeInput or NoneNoneSee signature.
duration_testnoArrayLike or NoneNoneSee signature.
event_testnoArrayLike or NoneNoneOptional held-out data. When supplied, the returned risk scores and concordance index are computed on this set; otherwise in-sample scores are returned.
random_statenoint42Random seed passed to the estimator. **model_params Additional parameters passed to `GradientBoostingSurvivalAnalysis`.
model_paramsyesAnySee signature.

Returns

dict - `model, risk_score, concordance_index, train_concordance_index`, and the structured survival arrays used for fitting/evaluation.

See also: Survival module guide.

fyron.survival.cox.fit_multivariate_cox

Fit a multivariate Cox model.

Import path: fyron.survival.cox.fit_multivariate_cox

python
fit_multivariate_cox(df: pd.DataFrame, duration_col: str, event_col: str, *, covariates: Sequence[str] | None = None, formula: str | None = None, strata: str | Sequence[str] | None = None, robust: bool = False) -> dict[str, Any]

Parameters

ParameterRequiredTypeDefaultDescription
dfyespd.DataFrameSee signature.
duration_colyesstrSee signature.
event_colyesstrSee signature.
covariatesnoSequence[str] or NoneNoneSee signature.
formulanostr or NoneNoneSee signature.
stratanostr or Sequence[str] or NoneNoneSee signature.
robustnoboolFalseSee signature.

Returns

dict[str, Any]

See also: Survival module guide.

fyron.survival.cox.fit_univariate_cox

Fit separate univariate Cox models for one or more covariates.

Import path: fyron.survival.cox.fit_univariate_cox

python
fit_univariate_cox(df: pd.DataFrame, duration_col: str, event_col: str, covariates: str | Sequence[str], *, strata: str | Sequence[str] | None = None, robust: bool = False) -> dict[str, Any]

Parameters

ParameterRequiredTypeDefaultDescription
dfyespd.DataFrameSurvival dataset.
duration_colyesstrSee signature.
event_colyesstrFollow-up time and event indicator (1 = event).
covariatesyesstr or Sequence[str]Column name(s) modeled one at a time (each produces its own fit).
stratanostr or Sequence[str] or NoneNonePassed through to `lifelines.CoxPHFitter.fit`.
robustnoboolFalseIf True, use robust sandwich errors (cluster-robust when combined with `cluster_col` in lifelines).

Returns

dict - `results — stacked summary table with model identifying the covariate used; fitters — list of fitted CoxPHFitter objects in the same order; n_excluded / n_used per fit (included as columns n_excluded, n_used` on each slice).

See also: Survival module guide.

fyron.survival.groups.create_survival_groups

Add a survival/stratification group column to a copy of `df`.

Import path: fyron.survival.groups.create_survival_groups

python
create_survival_groups(df: pd.DataFrame, column: str, method: SplitMethod, group_col: str, *, bins: int | Sequence[float] | None = None, labels: Sequence[str] | bool | None = None, duplicates: Literal['raise', 'drop'] = 'drop') -> pd.DataFrame

Parameters

ParameterRequiredTypeDefaultDescription
dfyespd.DataFrameInput table.
columnyesstrColumn used to derive groups (categorical levels or numeric for splits).
methodyesSplitMethod`"categorical" copies stringified levels from column. "median", "tertile", and "quartile" use pandas.qcut. "custom" uses pandas.cut with bins` (required).
group_colyesstrName of the new column to create.
binsnoint or Sequence[float] or NoneNoneFor `method="custom": edges passed to pandas.cut (sequence of bin edges or an integer number of equal-width bins). Ignored for quantile methods unless you rely on pandas defaults for integer bins with cut` (not used here).
labelsnoSequence[str] or bool or NoneNoneOptional labels for `qcut/cut` groups. Must match the number of resulting bins.
duplicatesnoLiteral['raise', 'drop']'drop'Quantile method duplicate policy. `"drop" matches pandas.qcut; "raise" surfaces ValueError` when quantiles are not distinct.

Returns

pandas.DataFrame - A copy of `df including group_col`.

See also: Survival module guide.

fyron.survival.groups.default_tau_from_observed_times

Default RMST truncation: minimum of per-group maximum observed times.

Import path: fyron.survival.groups.default_tau_from_observed_times

python
default_tau_from_observed_times(df: pd.DataFrame, duration_col: str, group_col: str | None = None) -> float

Parameters

ParameterRequiredTypeDefaultDescription
dfyespd.DataFrameSee signature.
duration_colyesstrSee signature.
group_colnostr or NoneNoneSee signature.

Returns

float

See also: Survival module guide.

fyron.survival.kaplan_meier.KaplanMeierPlotResult

Outputs from :func:plot_kaplan_meier.

Import path: fyron.survival.kaplan_meier.KaplanMeierPlotResult

python
KaplanMeierPlotResult()

Parameters

No parameters documented.

Returns

Class constructor.

See also: Survival module guide.

fyron.survival.kaplan_meier.plot_kaplan_meier

Fit Kaplan–Meier curves, optionally compare groups, and plot.

Import path: fyron.survival.kaplan_meier.plot_kaplan_meier

python
plot_kaplan_meier(df: pd.DataFrame, duration_col: str, event_col: str, group_col: str | None = None, *, split_column: str | None = None, split_method: SplitMethod | None = None, split_bins: int | Sequence[float] | None = None, split_labels: Sequence[str] | bool | None = None, confidence_interval: bool = True, ci_alpha: float = 0.05, at_risk_counts: bool = False, show_censors: bool = False, censor_styles: Mapping[str, Any] | None = None, xlim: tuple[float, float] | None = None, annotate_logrank: bool = False, palette: str | Sequence[str] | None = None, colors: Mapping[str, str] | Sequence[str] | None = None, linestyles: str | Sequence[str] | None = None, title: str | None = None, xlabel: str | None = None, ylabel: str = 'Survival probability', legend_title: str | None = None, legend_kwargs: MutableMapping[str, Any] | None = None, figsize: tuple[float, float] | None = None, save_path: str | Path | None = None, save_format: Literal['png', 'pdf', 'svg'] | None = None, dpi: int | None = None, annotate_rmst: bool = False, rmst_tau: float | None = None, rmst_group_col: str | None = None) -> KaplanMeierPlotResult

Parameters

ParameterRequiredTypeDefaultDescription
dfyespd.DataFrameSurvival dataset.
duration_colyesstrSee signature.
event_colyesstrFollow-up time and event indicator (1 = event, 0 = censored).
group_colnostr or NoneNoneOptional categorical column defining cohorts.
split_columnnostr or NoneNoneSee signature.
split_methodnoSplitMethod or NoneNoneSee signature.
split_binsnoint or Sequence[float] or NoneNoneSee signature.
split_labelsnoSequence[str] or bool or NoneNoneWhen `split_column is set, groups are created with :func:fyron.survival.create_survival_groups into a temporary column (split_method must be "median", "tertile", "quartile", or "custom" with split_bins` for custom edges).
confidence_intervalnoboolTrueIf True, shaded pointwise intervals are drawn.
ci_alphanofloat0.05See signature.
at_risk_countsnoboolFalseIf True, lifelines' at-risk table is drawn under the x-axis.
show_censorsnoboolFalseIf True, censor marks are drawn on the survival curves.
censor_stylesnoMapping[str, Any] or NoneNoneSee signature.
xlimnotuple[float, float] or NoneNoneOptional x-axis limits.
annotate_logranknoboolFalseIf True, annotate the plot with the log-rank p-value when groups are present.
palettenostr or Sequence[str] or NoneNoneNamed Fyron palette or explicit colors used when `colors` is not supplied.
colorsnoMapping[str, str] or Sequence[str] or NoneNonePer-group colors as a dict `{label: color}` or a list applied in sorted label order.
linestylesnostr or Sequence[str] or NoneNoneMatplotlib linestyle or one linestyle per sorted group label.
titlenostr or NoneNoneSee signature.
xlabelnostr or NoneNoneSee signature.
ylabelnostr'Survival probability'See signature.
legend_titlenostr or NoneNoneSee signature.
legend_kwargsnoMutableMapping[str, Any] or NoneNoneSee signature.
figsizenotuple[float, float] or NoneNoneSee signature.
save_pathnostr or Path or NoneNoneSee signature.
save_formatnoLiteral['png', 'pdf', 'svg'] or NoneNoneSee signature.
dpinoint or NoneNoneSee signature.
annotate_rmstnoboolFalseIf True, draw a vertical line at `rmst_tau` (default from data) and annotate RMST.
rmst_taunofloat or NoneNoneTruncation time for RMST text; defaults to :func:fyron.survival.default_tau_from_observed_times.
rmst_group_colnostr or NoneNoneGroup column passed to RMST helper when annotating (defaults to effective group column).

Returns

KaplanMeierPlotResult

See also: Survival module guide.

fyron.survival.outputs.cox_forest_table

Extract hazard ratios and confidence intervals for forest plots.

Import path: fyron.survival.outputs.cox_forest_table

python
cox_forest_table(cox_result: Any, *, covariate_col: str = 'covariate') -> pd.DataFrame

Parameters

ParameterRequiredTypeDefaultDescription
cox_resultyesAnyOutput from `fit_multivariate_cox / fit_univariate_cox, a lifelines CoxPHFitter`, or a DataFrame with Cox summary columns.
covariate_colnostr'covariate'Name for the covariate column in the returned table.

Returns

pandas.DataFrame - Columns include covariate, hazard ratio, confidence interval, p-value, and a formatted label.

See also: Survival module guide.

fyron.survival.outputs.survival_prediction_table

Create fixed-time survival/risk predictions for supported survival models.

Import path: fyron.survival.outputs.survival_prediction_table

python
survival_prediction_table(model: Any, df: pd.DataFrame, times: Sequence[float], *, id_col: str | None = None) -> pd.DataFrame

Parameters

ParameterRequiredTypeDefaultDescription
modelyesAnyFitted model with `predict_survival_function or predict` support.
dfyespd.DataFrameFeature rows to score.
timesyesSequence[float]Positive time horizons.
id_colnostr or NoneNoneOptional identifier column copied into the output.

Returns

pandas.DataFrame - Long table with one row per input row and time horizon.

See also: Survival module guide.

fyron.survival.ph_diagnostics.check_ph_assumptions

Schoenfeld-based proportional hazards diagnostics.

Import path: fyron.survival.ph_diagnostics.check_ph_assumptions

python
check_ph_assumptions(training_df: pd.DataFrame, fitter: CoxPHFitter, *, p_value_threshold: float = 0.05, show_plots: bool = False, columns: Sequence[str] | None = None, advice: bool = False, p_adjust: str | None = 'fdr_bh', include_residuals: bool = False) -> dict[str, Any]

Parameters

ParameterRequiredTypeDefaultDescription
training_dfyespd.DataFrameThe same (or row-aligned) dataframe used in `fitter.fit`.
fitteryesCoxPHFitterA fitted `CoxPHFitter`.
p_value_thresholdnofloat0.05Flag covariates whose minimum p-value across time transforms falls below this level.
show_plotsnoboolFalseIf True, scaled Schoenfeld residual plots are produced (can be slow).
columnsnoSequence[str] or NoneNoneOptional subset of covariates to summarize.
advicenoboolFalseForwarded to lifelines `check_assumptions when show_plots` is True (verbose console advice).
p_adjustnostr or None'fdr_bh'See signature.
include_residualsnoboolFalseSee signature.

Returns

dict - `summary — long-form test table; violations — covariates failing the threshold; warnings / suggestions` — narrative guidance.

See also: Survival module guide.

fyron.survival.ph_diagnostics.plot_schoenfeld_residuals

Plot Schoenfeld residuals for selected covariates.

Import path: fyron.survival.ph_diagnostics.plot_schoenfeld_residuals

python
plot_schoenfeld_residuals(residuals: pd.DataFrame, *, covariates: Sequence[str] | None = None, time_col: str = 'time', residual_col: str = 'residual', covariate_col: str = 'covariate', title: str = 'Schoenfeld residuals', ax: Any | None = None, save_path: str | Path | None = None, fmt: str = 'png') -> PlotReturn

Parameters

ParameterRequiredTypeDefaultDescription
residualsyespd.DataFrameSee signature.
covariatesnoSequence[str] or NoneNoneSee signature.
time_colnostr'time'See signature.
residual_colnostr'residual'See signature.
covariate_colnostr'covariate'See signature.
titlenostr'Schoenfeld residuals'See signature.
axnoAny or NoneNoneSee signature.
save_pathnostr or Path or NoneNoneSee signature.
fmtnostr'png'See signature.

Returns

PlotReturn

See also: Survival module guide.

fyron.survival.ph_diagnostics.schoenfeld_residuals_table

Return Schoenfeld residuals in long tabular form.

Import path: fyron.survival.ph_diagnostics.schoenfeld_residuals_table

python
schoenfeld_residuals_table(fitter: CoxPHFitter, training_df: pd.DataFrame, *, scaled: bool = True) -> pd.DataFrame

Parameters

ParameterRequiredTypeDefaultDescription
fitteryesCoxPHFitterFitted lifelines `CoxPHFitter`.
training_dfyespd.DataFrameRow-aligned DataFrame used for fitting.
scalednoboolTrueIf True, use scaled Schoenfeld residuals; otherwise raw residuals.

Returns

pandas.DataFrame - Long table with event row index, covariate, residual, and event time.

See also: Survival module guide.

fyron.survival.ph_diagnostics.schoenfeld_test_table

Run Schoenfeld proportional-hazards tests and return a clean table.

Import path: fyron.survival.ph_diagnostics.schoenfeld_test_table

python
schoenfeld_test_table(fitter: CoxPHFitter, training_df: pd.DataFrame, *, method: str | Sequence[str] = 'rank', p_adjust: str | None = 'fdr_bh', alpha: float = 0.05) -> pd.DataFrame

Parameters

ParameterRequiredTypeDefaultDescription
fitteryesCoxPHFitterSee signature.
training_dfyespd.DataFrameSee signature.
methodnostr or Sequence[str]'rank'See signature.
p_adjustnostr or None'fdr_bh'See signature.
alphanofloat0.05See signature.

Returns

pd.DataFrame

See also: Survival module guide.

fyron.survival.rmst.calculate_rmst

Compute RMST at truncation `tau` using Kaplan–Meier integration.

Import path: fyron.survival.rmst.calculate_rmst

python
calculate_rmst(df: pd.DataFrame, duration_col: str, event_col: str, *, group_col: str | None = None, tau: float | None = None) -> pd.DataFrame

Parameters

ParameterRequiredTypeDefaultDescription
dfyespd.DataFrameSurvival data.
duration_colyesstrSee signature.
event_colyesstrTime and event columns (1 = event, 0 = censored).
group_colnostr or NoneNoneOptional categorical column; one RMST row per level plus `n` counts.
taunofloat or NoneNoneUpper integration limit. Must be positive.

Returns

pandas.DataFrame - Columns: `group, n, rmst, rmst_se, rmst_lower, rmst_upper, tau. Normal-based 95% intervals use rmst ± 1.96 * rmst_se` when variance is available.

See also: Survival module guide.

fyron.survival.rmst.compare_rmst

Pairwise RMST differences versus a reference group.

Import path: fyron.survival.rmst.compare_rmst

python
compare_rmst(df: pd.DataFrame, duration_col: str, event_col: str, group_col: str, reference: str, *, tau: float | None = None) -> pd.DataFrame

Parameters

ParameterRequiredTypeDefaultDescription
dfyespd.DataFrameSee signature.
duration_colyesstrSee signature.
event_colyesstrSee signature.
group_colyesstrSame conventions as :func:calculate_rmst.
referenceyesstrReference level of `group_col` (string-coerced).
taunofloat or NoneNoneTruncation time; defaults like :func:calculate_rmst.

Returns

pandas.DataFrame - Columns include `group, reference, rmst_group, rmst_reference, difference, diff_lower, diff_upper, p_value, tau`.

See also: Survival module guide.

fyron.survival.weibull_aft.fit_weibull_aft

Fit a Weibull AFT model with `lifelines.WeibullAFTFitter`.

Import path: fyron.survival.weibull_aft.fit_weibull_aft

python
fit_weibull_aft(df: pd.DataFrame, duration_col: str, event_col: str, *, covariates: Sequence[str] | None = None, formula: str | None = None, robust: bool = False) -> dict[str, Any]

Parameters

ParameterRequiredTypeDefaultDescription
dfyespd.DataFrameSee signature.
duration_colyesstrSee signature.
event_colyesstrSurvival data.
covariatesnoSequence[str] or NoneNoneList of column names joined into a formula.
formulanostr or NoneNonePatsy-like lifelines formula string.
robustnoboolFalsePassed through to `fit` when supported.

Returns

dict - `results — coefficient table; fitter; AIC; concordance_index (if available); n_excluded / n_used`.

See also: Survival module guide.

fyron.survival.weibull_aft.plot_aft_survival_curves

Plot predicted survival curves for covariate profiles (partial effects).

Import path: fyron.survival.weibull_aft.plot_aft_survival_curves

python
plot_aft_survival_curves(fitter: WeibullAFTFitter, covariates: str | Sequence[str], profiles: Sequence[Mapping[str, float]], *, plot_baseline: bool = True, figsize: tuple[float, float] | None = None, ax: plt.Axes | None = None, plot_kwargs: MutableMapping[str, Any] | None = None) -> dict[str, Any]

Parameters

ParameterRequiredTypeDefaultDescription
fitteryesWeibullAFTFitterFitted `WeibullAFTFitter`.
covariatesyesstr or Sequence[str]Names to vary (order must match each profile mapping).
profilesyesSequence[Mapping[str, float]]Iterable of dicts mapping covariate name to numeric level.
plot_baselinenoboolTrueInclude the baseline curve at central values.
figsizenotuple[float, float] or NoneNoneUsed when `ax` is not provided.
axnoplt.Axes or NoneNoneOptional matplotlib axes.
plot_kwargsnoMutableMapping[str, Any] or NoneNoneExtra kwargs forwarded to `plot_partial_effects_on_outcome`.

Returns

dict - `figure, axes, fitter`.

See also: Survival module guide.