

rm(list = ls())

T_model <- function(t,x,params){
  with(as.list(x),{   
    # Set current state values
    
    Tp  = x[1]
    Pp  = x[2]
    NSp = x[3]
    NSp2 = x[4]
    
    T  = x[5]
    P  = x[6]
    NS = x[7]
    
    S  = x[8]
    M  = x[9]
    E  = x[10]
    

    
    ddt_Tp   =  -ke*Tp
    ddt_Pp   =  ke*Tp + rp*(1-(NS+NSp+NSp2+S+M+E)/Kp)*Pp
    ddt_NSp  =  lambdapns*Pp - dns*NSp+ lambdasns*NSp2
    ddt_NSp2 =  lambdanss*NSp  + rs*(1-(NS+NSp+NSp2+S+M+E)/Ks)*NSp2
    
    
    ddt_T   =  -ke*T
    ddt_P   =  ke*T + rp*(1-(NS+NSp+NSp2+S+M+E)/Kp)*P
    
    ddt_NS  =  lambdapns*P  - dns*NS  + lambdasns*S
    ddt_S   =  lambdanss*NS + rs*(1-(NS+NSp+NSp2+S+M+E)/Ks)*S
    
    ddt_M   =  lambdapm*(P+Pp) + rm*(1-(NS+NSp+NSp2+S+M+E)/Km)*M
    ddt_E   =  lambdame*M + re*(1-(NS+NSp+NSp2+S+M+E)/Ke)*E
    

    
    der <- c(ddt_Tp,ddt_Pp,ddt_NSp,ddt_NSp2,ddt_T,ddt_P,ddt_NS,ddt_S,ddt_M,ddt_E)
   
     #print(x)
    list(der)
  })       
}



#load R library for ordinary differential equation solvers
library(deSolve)
library(rstudioapi)
###########################
# Reading the data
###########################

setwd(dirname(getActiveDocumentContext()$path ))
data <- read.csv("Figure 2-source data.csv", header=TRUE,stringsAsFactors=FALSE)

IDs = unique(data[,"ID"])
ytypes = unique(data[,"ytype_def"])
pchID = c(21,22,23,24,25,21,22,23,24,25,21,22,23,24,25,21,22,23,24,25,21,22)

coloresID = c("steelblue4","slateblue3","navy","lightsteelblue4","dodgerblue2", 
              "salmon4","indianred3","brown2","coral1","chocolate2",
              "aquamarine3","darkolivegreen3","cadetblue4","chartreuse3","forestgreen","seagreen3",
              "palegreen3","springgreen4","darkseagreen4","green4","greenyellow","lightgreen")



###########################
# Reading estimates
###########################
estimates <- read.table("Figure 3-source data 5.txt", header=TRUE,stringsAsFactors=FALSE,row.names = "parameter",sep=",")

ke	= estimates["ke_pop","value"]
rp	= estimates["rp_pop","value"]
rs	= estimates["rs_pop","value"]
rm	= estimates["rm_pop","value"]
re	= estimates["re_pop","value"]

re_NT = re
re_T = re
re_TP = re

qdns	= estimates["qdns_pop","value"]

lambdap	= estimates["lambdap_pop","value"]
lambdanss	= estimates["lambdanss_pop","value"]
lambdasns	= estimates["lambdasns_pop","value"]
lambdame	= estimates["lambdame_pop","value"]

log10Kp	= estimates["log10Kp_pop","value"]
log10Kps	= estimates["log10Kps_pop","value"]
log10Kpm	= estimates["log10Kpm_pop","value"]
log10Kpe	= estimates["log10Kpe_pop","value"]

log10P0	= estimates["log10P0_pop","value"]
log10NS0	= estimates["log10NS0_pop","value"]
log10S0	= estimates["log10S0_pop","value"]
log10M0	= estimates["log10M0_pop","value"]
log10E0	= estimates["log10E0_pop","value"]

lambdapns= lambdap
lambdapm = lambdap

dns = (qdns+1)*lambdanss
dnsp = qdns*lambdanss

W = 5
pb = 1
VolB = 60*W*1e3

Kp = 10^log10Kp
Ks = 10^(log10Kp-log10Kps)
Km = 10^(log10Kp-log10Kpm)
Ke = 10^(log10Kp-log10Kpe)

qNSS = (rs/lambdanss)*(Kp/Ks-1)
qPS  = (1/lambdapns)*(dns*qNSS-lambdasns)
qPM  = (rm/lambdapm)*(Kp/Km-1)
qME  = (re/lambdame)*(Kp/Ke-1)

Ei  = Kp/(qNSS*qPM*qME/qPS + qPM*qME/qPS + qME +1)
Mi  = qME*Ei
Si  = (qPM/qPS)*Mi
NSi = qNSS*Si
Pi  = qPS*Si


###############################

tstart=0
tend=27


nrows = 2
ncolumns =2

par(mfrow = c(nrows,ncolumns),     
    oma = c(0, 0, 0, 0), # 
    mar = c(4.0, 5.0, 0.0, 0.5), 
    mgp = c(3.0, 1, 0),    
    xpd = FALSE)



T01 = 7e6

############################
# Plotting CCR5+
############################

for(ID in IDs[c(6:22)]){
  ##########################
  # 1. Reading T cell counts
  ##########################
  
  i = which(IDs %in% ID)
  
  #Cd4+CCR5+
  CD4CCR5pd = 10^as.numeric(data[which(ID==data[,"ID"]& data[,"ytype_def"]=="cd4+ccr5+"),"y"])
  tCD4CCR5pd = as.numeric(data[which(ID==data[,"ID"] & data[,"ytype_def"]=="cd4+ccr5+"),"time"])
  

  ################################
  # 2. Plotting data and simulation
  ################################
  
  xlabel=""
  
  if (i==6){
    ylabel = expression(paste("CD4"^"+"~"CCR5"^"+"~"T cells/",mu,"L"))
  }
  else{
    ylabel=""
  }
  
  
  if (i==6){
    plot(tCD4CCR5pd/7,CD4CCR5pd,
         xlab=xlabel,ylim = range(10^0,15000),xlim =  c(tstart,tend),
         ylab=ylabel,bty="n",log="y",
         main="",yaxt="n",xaxt="n",
         cex.main=1.5,cex.axis=1.5,cex.lab=1.5,
         type="l",col="gray",lwd=2)
    
    axis(2,at=c(1,10,100,1000,10000),labels=expression(bold("1"),bold("10"),bold("10"^"2"),bold("10"^"3"),bold("10"^"4")),
         cex.axis=1.3,font=2,lwd=2)

    axis(1,at=axTicks(1),labels=as.character(axTicks(1)),cex.axis=1.3,font=2,lwd=2,las=1)
    
  }
  else{
    points(tCD4CCR5pd/7,CD4CCR5pd,
           type="l",col="gray",lwd=2)
    
    
    
    ##################################
    # Plotting population estimates
    ##################################
    
    if(i==22){
      if(i==5){
        T0  = 0
        P0  = Pi
        NS0 = NSi
        S0  = Si
        M0  = Mi
        E0  = Ei
        color="steelblue"
        fp = 0
        re=re_NT
      }
      if(i==10 || i==22){
        T0 = T01*W
        P0  = 10^log10P0
        S0  = 10^log10S0
        NS0 = 10^log10NS0
        M0  = 10^log10M0
        E0  = 10^log10E0
        if(i==10)
        {
          re = re_T
          color="indianred1"
          fp = 0
        }
        else{
          fp = 0.4
          re = re_TP
          color="gray25"
        }
        
      }
      
      Tp_0 = fp*T0
      Pp_0 = 0
      NSp_0 = 0
      NSp2_0 = 0
      T_0 = (1-fp)*T0
      P_0 = P0
      NS_0 = NS0
      S_0 = S0
      M_0 = M0
      E_0 = E0
      
      params=c()
      t.out <- seq(tstart,tend*7,by=1)
      init.x <- c(Tp_0,Pp_0,NSp_0,NSp2_0,T_0,P_0,NS_0,S_0,M_0,E_0)
      out <- as.data.frame(lsodar(init.x,t.out,T_model,params)) 
      
      t.out = out[,1]
      Tp = out[,2]
      Pp  = out[,3]
      NSp = out[,4]
      NSp2 = out[,5]
      T  = out[,6]
      P  = out[,7]
      NS = out[,8]
      S = out[,9]
      M =  out[,10]
      E =  out[,11]
      
      S_b = pb*(S)/VolB
      NS_b = pb*(NS+NSp+NSp2)/VolB
      CD8_b =pb*(M+E)/VolB
      E_b = pb*(E)/VolB
      M_b = pb*(M)/VolB
      
      lines(t.out/7,S_b,col=color,lwd=2)
    }
    
    
  }
  

  
}

############################
# Plotting CCR5-
############################
for(ID in IDs[c(6:22)]){
  ##########################
  # 1. Reading T cell counts
  ##########################
  
  i = which(IDs %in% ID)
  

  #Cd4+CCR5-
  CD4CCR5nd = 10^as.numeric(data[which(ID==data[,"ID"]& data[,"ytype_def"]=="cd4+ccr5-"),"y"])
  tCD4CCR5nd = as.numeric(data[which(ID==data[,"ID"] & data[,"ytype_def"]=="cd4+ccr5-"),"time"])
  
  ##################################
  # 2. Plotting CCR5- and simulation
  ##################################

  xlabel=""
  
  if (i==6){
    ylabel = expression(paste("CD4"^"+"~"CCR5"^"-"~"T cells/",mu,"L"))
  }
  else{
    ylabel=""
  }
  
  
  if (i==6){
    plot(tCD4CCR5nd/7,CD4CCR5nd,
         xlab=xlabel,ylim = range(10^0,15000),xlim =  c(tstart,tend),
         ylab=ylabel,bty="n",log="y",
         main="",yaxt="n",xaxt="n",
         
         cex.main=1.5,cex.axis=1.5,cex.lab=1.5,
         type="l",col="gray",lwd=2)
    axis(2,at=c(1,10,100,1000,10000),labels=expression(bold("1"),bold("10"),bold("10"^"2"),bold("10"^"3"),bold("10"^"4")),
         cex.axis=1.3,font=2,lwd=2)#,las=1)
    
    axis(1,at=axTicks(1),labels=as.character(axTicks(1)),cex.axis=1.3,font=2,lwd=2,las=1)
    
  }
  else{
    points(tCD4CCR5nd/7,CD4CCR5nd,
           type="l",col="gray",lwd=2)
    
    ##################################
    # Plotting population estimates
    ##################################
    
    if(i==22){
      if(i==5){
        T0  = 0
        P0  = Pi
        NS0 = NSi
        S0  = Si
        M0  = Mi
        E0  = Ei
        color="steelblue"
        fp = 0
        re=re_NT
      }
      if(i==10 || i==22){
        T0 = T01*W
        P0  = 10^log10P0
        S0  = 10^log10S0
        NS0 = 10^log10NS0
        M0  = 10^log10M0
        E0  = 10^log10E0
        if(i==10)
        {
          re = re_T
          color="indianred1"
          fp = 0
        }
        if(i==22){
          fp = 0.4
          re = re_TP
          color="gray25"
        }
        
      }
      
      Pp_0 = 0
      NSp_0 = 0
      NSp2_0 = 0
      Tp_0 = fp*T0
      T_0 = (1-fp)*T0
      P_0 = P0
      NS_0 = NS0
      S_0 = S0
      M_0 = M0
      E_0 = E0
      
      params=c()
      t.out <- seq(tstart,tend*7,by=1)
      init.x <- c(Tp_0,Pp_0,NSp_0,NSp2_0,T_0,P_0,NS_0,S_0,M_0,E_0)
      out <- as.data.frame(lsodar(init.x,t.out,T_model,params)) 
      
      t.out = out[,1]
      Tp = out[,2]
      Pp  = out[,3]
      NSp = out[,4]
      NSp2 = out[,5]
      T  = out[,6]
      P  = out[,7]
      NS = out[,8]
      S = out[,9]
      M =  out[,10]
      E =  out[,11]
      
      S_b = pb*(S)/VolB
      NS_b = pb*(NS+NSp+NSp2)/VolB
      CD8_b =pb*(M+E)/VolB
      E_b = pb*(E)/VolB
      M_b = pb*(M)/VolB
      
      lines(t.out/7,NS_b,col=color,lwd=2)
    }
    
  }
  
  
}

############################
# Plotting CD8s
############################

for(ID in IDs[c(6:22)]){
  ##########################
  # 1. Reading T cell counts
  ##########################
  
  i = which(IDs %in% ID)
  
  #Cd8+
  CD8d = 10^as.numeric(data[which(ID==data[,"ID"]& data[,"ytype_def"]=="cd8+"),"y"])
  tCD8d = as.numeric(data[which(ID==data[,"ID"] & data[,"ytype_def"]=="cd8+"),"time"])

  ##################################
  # 2. Plotting CD8s and simulation
  ##################################

  xlabel=expression("weeks after transplant")
  
  if (i==6 ){
    ylabel = expression(paste("Total CD8"^"+"~"T cells/",mu,"L"))
  }
  else{
    ylabel=""
  }
  
  
  if (i==6){
    plot(tCD8d/7,CD8d,
         xlab=xlabel,ylim = range(10^0,15000),xlim =  c(tstart,tend),
         ylab=ylabel,bty="n",log="y",
         main="",yaxt="n",xaxt="n",
         cex.main=1.5,cex.axis=1.5,cex.lab=1.5,
         type="l",col="gray",lwd=2)
    
    aty <- axTicks(2)
    labels <- sapply(aty,function(k){
      if (log10(k)%%1==0){
        toString(k)
      }
      else{
        paste("")
      }}
    )
    
    axis(2,at=c(1,10,100,1000,10000),labels=expression(bold("1"),bold("10"),bold("10"^"2"),bold("10"^"3"),bold("10"^"4")),
         cex.axis=1.3,font=2,lwd=2)
    axis(1,at=axTicks(1),labels=as.character(axTicks(1)),cex.axis=1.3,font=2,lwd=2,las=1)
    
  }
  else{
    points(tCD8d/7,CD8d,
           type="l",col="gray",lwd=2)
    
    ##################################
    # Plotting population estimates
    ##################################
    
    if(i==22){
      if(i==5){
        T0  = 0
        P0  = Pi
        NS0 = NSi
        S0  = Si
        M0  = Mi
        E0  = Ei
        color="steelblue"
        fp = 0.0
        re=re_NT
      }
      if(i==10 || i==22){
        T0 = T01*W
        P0  = 10^log10P0
        S0  = 10^log10S0
        NS0 = 10^log10NS0
        M0  = 10^log10M0
        E0  = 10^log10E0
        if(i==10)
        {
          re = re_T
          color="indianred1"
          fp = 0
        }
        else{
          fp = 0.4
          re = re_TP
          color="gray25"
        }
        
      }
      
      Tp_0 = fp*T0
      Pp_0 = 0
      NSp_0 = 0
      NSp2_0 = 0
      
      T_0 = (1-fp)*T0
      P_0 = P0
      NS_0 = NS0
      S_0 = S0
      M_0 = M0
      E_0 = E0
      
      params=c()
      t.out <- seq(tstart,tend*7,by=1)
      init.x <- c(Tp_0,Pp_0,NSp_0,NSp2_0,T_0,P_0,NS_0,S_0,M_0,E_0)
      out <- as.data.frame(lsodar(init.x,t.out,T_model,params)) 
      
      Tp = out[,2]
      Pp  = out[,3]
      NSp = out[,4]
      NSp2 = out[,5]
      T  = out[,6]
      P  = out[,7]
      NS = out[,8]
      S = out[,9]
      M =  out[,10]
      E =  out[,11]
      
      S_b = pb*(S)/VolB
      NS_b = pb*(NS+NSp+NSp2)/VolB
      CD8_b =pb*(M+E)/VolB
      E_b = pb*(E)/VolB
      M_b = pb*(M)/VolB
      
      lines(t.out/7,CD8_b,col=color,lwd=2)
    }
    
  }
  
  
}

############################
# Plotting CD8 subsets
############################

for(ID in IDs[c(6:22)]){
  ##########################
  # 1. Reading T cell counts
  ##########################
  
  i = which(IDs %in% ID)
  
  
  #Cd8+ Tcm
  CD8Tmd = 10^as.numeric(data[which(ID==data[,"ID"]& data[,"ytype_def"]=="CD8Tm"),"y"])
  tCD8Tmd = as.numeric(data[which(ID==data[,"ID"] & data[,"ytype_def"]=="CD8Tm"),"time"])
  
  #Cd8+ Tem
  CD8Temd = 10^as.numeric(data[which(ID==data[,"ID"]& data[,"ytype_def"]=="CD8Tem"),"y"])
  tCD8Temd = as.numeric(data[which(ID==data[,"ID"] & data[,"ytype_def"]=="CD8Tem"),"time"])
  
  
  ################################################
  # 2. Plotting CD8Tem, Tn+Tcm and simulations
  ################################################

  xlabel=expression("weeks after transplant")
  
  if (i==6 ){
    ylabel = expression(paste("CD8"^"+"~"T cells/",mu,"L"))
  }
  else{
    ylabel=""
  }
  
  
  if (i==6){
    plot(tCD8Tmd/7,CD8Tmd,
         xlab=xlabel,ylim = range(10^0,15000),xlim =  c(tstart,tend),
         ylab=ylabel,bty="n",log="y",
         main="",yaxt="n",xaxt="n",
         cex.main=1.5,cex.axis=1.5,cex.lab=1.5,
         type="l",col="gray",lwd=2)
    
    aty <- axTicks(2)
    labels <- sapply(aty,function(k){
      if (log10(k)%%1==0){
        toString(k)
      }
      else{
        paste("")
      }}
    )
    
    axis(2,at=c(1,10,100,1000,10000),labels=expression(bold("1"),bold("10"),bold("10"^"2"),bold("10"^"3"),bold("10"^"4")),
         cex.axis=1.3,font=2,lwd=2)
    axis(1,at=axTicks(1),labels=as.character(axTicks(1)),cex.axis=1.3,font=2,lwd=2,las=1)
    
    
    lines(tCD8Temd/7,CD8Temd,
          type="l",col="gray",lwd=2)
  }
  else{
    lines(tCD8Tmd/7,CD8Tmd,
           type="l",col="gray",lwd=2)
    lines(tCD8Temd/7,CD8Temd,
          type="l",col="gray",lwd=2)
    
    ##################################
    # Plotting population estimates
    ##################################
    
    if(i==22){
      if(i==5){
        T0  = 0
        P0  = Pi
        NS0 = NSi
        S0  = Si
        M0  = Mi
        E0  = Ei
        color="steelblue"
        fp = 0.0
        re=re_NT
      }
      if(i==10 || i==22){
        T0 = T01*W
        P0  = 10^log10P0
        S0  = 10^log10S0
        NS0 = 10^log10NS0
        M0  = 10^log10M0
        E0  = 10^log10E0
        if(i==10)
        {
          re = re_T
          color="indianred1"
          fp = 0
        }
        else{
          fp = 0.4
          re = re_TP
          color="gray25"
        }
        
      }
      
      Tp_0 = fp*T0
      Pp_0 = 0
      NSp_0 = 0
      NSp2_0 = 0
      
      T_0 = (1-fp)*T0
      P_0 = P0
      NS_0 = NS0
      S_0 = S0
      M_0 = M0
      E_0 = E0
      
      params=c()
      t.out <- seq(tstart,tend*7,by=1)
      init.x <- c(Tp_0,Pp_0,NSp_0,NSp2_0,T_0,P_0,NS_0,S_0,M_0,E_0)
      out <- as.data.frame(lsodar(init.x,t.out,T_model,params)) 
      
      Tp = out[,2]
      Pp  = out[,3]
      NSp = out[,4]
      NSp2 = out[,5]
      T  = out[,6]
      P  = out[,7]
      NS = out[,8]
      S = out[,9]
      M =  out[,10]
      E =  out[,11]
      
      S_b = pb*(S)/VolB
      NS_b = pb*(NS+NSp+NSp2)/VolB
      CD8_b =pb*(M+E)/VolB
      E_b = pb*(E)/VolB
      M_b = pb*(M)/VolB
      
      lines(t.out/7,E_b,col=color,lwd=2)
      lines(t.out/7,M_b,col=color,lwd=2)
      
      
      text(15,1000,expression(T[EM]),cex=1.2)
      text(22,10,expression(T[N]+T[CM]),cex=1.2)
    }
    
  }
  
  
}


nrows = 1
ncolumns =1

par(mfrow = c(nrows,ncolumns),     
    oma = c(0, 0, 0, 0), # 
    mar = c(4.0, 5.0, 0.0, 0.5), 
    mgp = c(3.0, 1, 0),    
    xpd = FALSE)

##############################
# Plotting CCR5- Turnover
##############################
# Thymic export
plot(t.out/7,lambdapns*P/VolB ,
     type="l",lwd=1,ylim=c(0,6.2),
     ylab=expression(paste("CD4"^"+"," T cells/",mu,"L/day")),
     bty="n",#log="y",
     xlab = "Weeks after transplant",
     main="",yaxt="n",xaxt="n",
     cex.main=1.4,cex.axis=1.4,cex.lab=1.4)

#Downregulation of CCR5
lines(t.out/7, lambdasns*S/VolB,lty=2)
axis(2,at=c(0,1,2,3,4,5,6),labels=c(0,1,2,3,4,5,6),
     cex.axis=1.2,font=2,lwd=2)#,las=1)
atx <- axTicks(1)
axis(1,at=atx,labels=as.character(atx),cex.axis=1.2,font=2,lwd=2,las=1)

text(10,6,expression(paste(bold(" CCR5"^"-"),bold(" T cell"))),cex=1.2)
text(10,5.5,"turnover",font=2,cex=1.2)


text(0,3.7,"Down-regulation \nof CCR5:",adj=0)
text(0,3.0,expression(lambda[s]*S),adj=0)

text(8,1.8,"Thymic export:",adj=0)
text(8,1.3,expression(lambda[f]*P),adj=0)

##############################
# Plotting CCR5+ Turnover
##############################
# CCR5+ proliferation
plot(t.out/7, rs*(1-(NS+NSp+NSp2+S+M+E)/Ks)*S/VolB,
     type="l",lwd=1,ylim=c(0,6.2),
     ylab="",#expression(paste("CD4"^"+"," T cells/",mu,"L/day")),
     bty="n",#log="y",
     xlab = "Weeks after transplant",
     main="",yaxt="n",xaxt="n",
     cex.main=1.4,cex.axis=1.4,cex.lab=1.4)

# CCR5 upregulation
lines(t.out/7,lambdanss*NS/VolB,lty=2,lwd=1)
axis(2,at=c(0,1,2,3,4,5,6),labels=c(0,1,2,3,4,5,6),
      cex.axis=1.2,font=2,lwd=2)#,las=1)
atx <- axTicks(1)
axis(1,at=atx,labels=as.character(atx),cex.axis=1.2,font=2,lwd=2,las=1)
text(18,6,expression(paste(bold(" CCR5"^"+"),bold(" T cell"))),cex=1.2)
text(18,5.5,"turnover",font=2,cex=1.2)

text(8,4,"Proliferation:",adj=0)
text(8,3.5,expression((r[s]-d[s])(1-Total/K[s])*S),adj=0)

text(25,1.45,"CCR5 \nupregulation:",adj=1)
text(25,0.65,expression(paste(lambda[n],"N")),adj=1)


##############################
# Plotting CD8 Tem Turnover
##############################

# CD8 Tem proliferation
plot(t.out/7, re_T*(1-(NS+NSp+NSp2+S+M+E)/Ke)*E/VolB,
     type="l",lwd=1,ylim=c(0,15),
     ylab=expression(paste("CD8"^"+",T[EM]," cells/",mu,"L/day")),
     bty="n",#log="y",
     xlab = "Weeks after transplant",
     main="",yaxt="n",xaxt="n",
     cex.main=1.4,cex.axis=1.4,cex.lab=1.4)

# CD8 Tem differentiation from CD8Tcm
lines(t.out/7,lambdame*M/VolB,lty=2,lwd=1)
axis(2,at=seq(1,15,by=3),labels=seq(1,15,by=3),
     cex.axis=1.2,font=2,lwd=2)#,las=1)
atx <- axTicks(1)
axis(1,at=atx,labels=as.character(atx),cex.axis=1.2,font=2,lwd=2,las=1)
text(18,12,expression(paste(bold(" CD8"^"+"),bold(" T"["EM"]),bold(" cell"))),cex=1.2)
text(18,10.8,"turnover",font=2,cex=1.2)

text(8,8,"Proliferation:",adj=0)
text(8,7,expression((r[e]-d[e])(1-Total/K[e])*E),adj=0)

text(25,3,"Differentiation:",adj=1)
text(25,2,expression(paste(lambda[m],"M")),adj=1)




