Last active
April 12, 2018 01:02
-
-
Save javadnoorb/00c230e535c65e20da100c18e60bd29b to your computer and use it in GitHub Desktop.
Python wrapper for BPCP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from rpy2.robjects import pandas2ri, r | |
import rpy2.robjects.packages as rpackages | |
from rpy2.robjects.vectors import StrVector | |
from rpy2.rinterface import RRuntimeError | |
utils = rpackages.importr('utils') | |
utils.chooseCRANmirror(ind=1); | |
packnames = ['bpcp'] | |
names_to_install = [x for x in packnames if not rpackages.isinstalled(x)] | |
if len(names_to_install) > 0: | |
utils.install_packages(StrVector(names_to_install)) | |
pandas2ri.activate() | |
bpcp = rpackages.importr('bpcp') | |
def bpcp_survival(input_time, event_times, events_status): | |
""" | |
This function calculates the Kaplan-Meier survival rate | |
at a specific time-point | |
The confidence intervals are calculated using | |
`Beta Product Confidence Procedure for Right Censored Data (BPCP)` | |
as described in the following paper: | |
https://www.ncbi.nlm.nih.gov/pmc/articles/PMC3769999/ | |
The function is a wrapper around the following R package: | |
https://cran.r-project.org/web/packages/bpcp/index.html | |
Parameters: | |
input_time: time at which the survival results are | |
calculated | |
event_times: list of times at which the event has occured | |
events_status: list of events' status. 1 corresponds to event | |
having occured and 0 corresponds to censorship. | |
Returns: | |
pandas series containing the following fields: | |
'survival': survival rate at `input_time` | |
'lower': lower 95% CI | |
'upper': upper 95% CI | |
""" | |
try: | |
bfit = bpcp.bpcp(event_times, events_status, Delta=0); | |
except RRuntimeError: | |
return pd.Series(index=['survival', 'lower', 'upper']) | |
surv_results = pandas2ri.ri2py(bpcp.StCI(bfit, input_time)) | |
return surv_results[['survival', 'lower', 'upper']].iloc[0] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment