Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Survival function for Cox Time Varying model #1637

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions lifelines/fitters/cox_time_varying_fitter.py
Original file line number Diff line number Diff line change
Expand Up @@ -295,6 +295,15 @@ def _compute_confidence_intervals(self):
index=self.params_.index,
)

def calculate_survival_function(self, X: pd.DataFrame) -> pd.Series:
v = self.predict_partial_hazard(X)
col = utils._get_index(v)
times_ = X.start.values
c_0 = utils.interpolate_at_times(self.baseline_cumulative_hazard_, [times_]).T
cumulative_hazard_ = pd.DataFrame(c_0 * v.values, columns=col, index=times_)
surv_func = pd.Series(np.exp(-cumulative_hazard_).values.diagonal(), index=times_)
return surv_func

@property
def summary(self):
"""Summary statistics describing the fit.
Expand Down
8 changes: 8 additions & 0 deletions lifelines/tests/test_estimation.py
Original file line number Diff line number Diff line change
Expand Up @@ -5134,6 +5134,14 @@ def test_inference_against_known_R_output(self, ctv, dfcv):
npt.assert_almost_equal(ctv.summary["se(coef)"].values, [1.229, 1.206], decimal=3)
npt.assert_almost_equal(ctv.summary["p"].values, [0.14, 0.56], decimal=2)

def test_survival_function(self, ctv, dfcv):
sf_validation = [0.866, 0.866, 0.748, 0.866, 0.866, 0.277, 0.954,
0.977, 0.902, 0.977, 0.977, 0.902, 0.977, 0.954]
ctv.fit(dfcv, id_col="id", start_col="start", stop_col="stop", event_col="event")
sf = ctv.calculate_survival_function(dfcv)
assert sf.index.values is dfcv.start.values
npt.assert_almost_equal(sf.values, sf_validation, decimal=2)

def test_that_id_col_is_optional(self, dfcv):

ctv_with_id = CoxTimeVaryingFitter().fit(dfcv, id_col="id", start_col="start", stop_col="stop", event_col="event")
Expand Down