###############################################################
########## Probabilities of extended illness-death model assuming constant hazards

# Function to calculate the transition probabilities of an extended illness-death model
# with constant hazards

# possible plug-in values: the cause-specific hazard rates alpha01, alpha02,
# alpha03, alpha14 and alpha15 and the time-scale

# Default values: alpha01=0.005, alpha02=0.02, alpha03=0.01, alpha14=0.02, 
# alpha15=0.01, t=1:100 (Nullmodel, both hazard ratios are 1)


# The function returns a matrix with the transition probabilities
# P00, P01, P02, P03, P04, P05, P11, P14, P15, P(D(t)=1|E(t)=0),
# P(D(t)=1|E(t)=1), P(D(t)=1) as well as the attributable mortality (AM)
# and the population attributable fraction (PAF) estimated as proposed by Schumacher et al.
# (Schumacher, M., Wangler, M., Wolkewitz, M., Beyersmann, J.: Attributable mortality due 
# to nosocomial infections. a simple and useful application of multistate models. 
# Methods of information in medicine 46(5), 595 (2007))

calc_transProbs_constHaz<-function(alpha01=0.005, alpha02=0.02, alpha03=0.01, alpha14=0.02, 
                                   alpha15=0.01, t=0:100){
  
alpha0<-(alpha01+alpha02+alpha03)
alpha1<-(alpha14+alpha15)


P00<-exp(-alpha0*t)
P02<-alpha02/alpha0*(1-exp(-alpha0*t))
P03<-alpha03/alpha0*(1-exp(-alpha0*t))

if(alpha0!=alpha1){
P01<-alpha01/(alpha1-alpha0)*(exp(-alpha0*t)-exp(-alpha1*t))

P04<-alpha01*alpha14/(alpha0*alpha1)-(alpha01*alpha14/(alpha0*(alpha1-alpha0))*exp(-alpha0*t))+
  alpha01*alpha14/(alpha1*(alpha1-alpha0))*exp(-alpha1*t)

P05<-alpha01*alpha15/(alpha0*alpha1)-(alpha01*alpha15/(alpha0*(alpha1-alpha0))*exp(-alpha0*t))+
  alpha01*alpha15/(alpha1*(alpha1-alpha0))*exp(-alpha1*t)
}else{
  P01<-alpha01*t*exp(-alpha1*t)
  P04<-alpha01*alpha14/(alpha0*alpha1)*(1-exp(-alpha0*t)-alpha0*t*exp(-alpha1*t))
  P05<-alpha01*alpha15/(alpha0*alpha1)*(1-exp(-alpha0*t)-alpha0*t*exp(-alpha1*t))
}


P11<-exp(-alpha1*t)
P14<-alpha14/alpha1*(1-exp(-alpha1*t))
P15<-alpha15/alpha1*(1-exp(-alpha1*t))

D1<-P05+P03
D1E0<-P03/(P00+P02+P03)
D1E1<-P05/(P01+P04+P05)

PAF<-(D1-D1E0)/(D1E1)
AM<-D1E1-D1E0

transProbs_constHaz<- matrix(FALSE, ncol = 14, nrow = length(t))
colnames(transProbs_constHaz) <- c("P00", "P01", "P02", "P03", "P04", "P05", 
                                   "P11", "P14", "P15", "AM","PAF","P(D(t)=1|E(t)=0)",
                                   "P(D(t)=1|E(t)=1)", "P(D(t)=1)")
transProbs_constHaz[,1:14]<-c(P00, P01, P02, P03, P04, P05, P11, P14, P15, AM, PAF,
                              D1E0, D1E1, D1)

return(transProbs_constHaz)
}


#x<-calc_transProbs_constHaz()
#t<-0:100
#plot(t, x[,"P01"], xlab="time", ylab="P01", type="l", lwd=3, main="Transition probability")