library(rootSolve)
library(ggplot2)
########Import of experimental data
input<-read.table("input file", header=TRUE, fill = FALSE) #####"input file" is the input data text file
input.data <- as.data.frame(input)
data_unique <- unique(input.data)
########Mathematical model
ODE<-function(t,x,parms){
  with(as.list(c(x,parms)),{
    
    dprecusor <- v - k1_v2*precusor - (kdegr + u)*precusor
    
    dsplicedintermediate <- k1_v2*precusor - (k1_v3*splicedintermediate) - (kdegr*(transcript_length[i]/z) +u)*splicedintermediate
    
    dmRNA <- k1_v3*splicedintermediate - (kdegr_v6 + u)*mRNA
    
    
    der <- c(dprecusor,dsplicedintermediate,dmRNA)
    list(der)
  })
  
}
#######Parameters 
parms <-c(v=0.24, kdegr=0.08, z=600, u=0.0019)

######Model input data
splicing_half-time <- splicing_half_times ##splicing_half_times are the splicing half_times for the transcripts
polyadenylation_half-time = poly_half_times ###poly_half-time is the splicing half time of transcript at the 3' end of the transcript of interest
transcript_length <-data_unique$mRNA_L ###mRNA_L is the transcript length
HLmRNA <- data_unique$mRNA_HL ###mRNA_HL is the mature mRNA half-life
#####loop for mRNA abundance prediction
for(i in 1:nrow(data_unique)){

  k1_v2 <- log(2)/splicing_half[i]
  k1_v3 <- log(2)/polyadenylation_half[i]
  kdegr_v6 <- log(2)/HLmRNA[i]

  out <-as.data.frame(steady(y = c(precusor=0, splicedintermediate=0, mRNA=0), time = c(0, 2e5), func = ODE, parms = parms, method = "runsteady"))

  ifelse(i==1,pl<-c(out[3,1]),pl<-rbind(pl,out[3,1]))

}

row.names(pl) <- c(GeneIDs) ###GeneIDs are the names of the respective transcripts
pd<-data.frame(pl)
pl_og <- log(pd,2)
pl_all <- cbind(pl,pl_og)
colnames(pl_all)<-c("mRNA/cell","log(2)_mRNA/cell")
data_all <- cbind(data_unique, pl_all)

write.table(data_all,file="mRNA_per_cell.csv")

######Plot Experimental against Simulated data
# RUN REGRESSION AND APPEND PREDICTION INTERVALS
lm_fit  = lm(Exp~Sim,data=data_all) ###Exp = log(2) of Experimental mRNA abundance and Sim = log(2) of predicted mRNA abundance
tips_with_pred = data.frame(data_all, predict(lm_fit, interval = 'prediction'))

png("Exp_vs_Sim.png")    
# PLOT WITH REGRESSION LINE, CONFIDENCE INTERVAL AND PREDICTION INTERVAL
ggplot(tips_with_pred, aes(x = Sim, y = Exp) ) + 
  geom_point() +
  labs(x="log2(Simulated data)", y="log2(Experimental data)") +
  geom_smooth(method = 'lm', aes(fill = 'confidence'), alpha = 0.5) +
  geom_ribbon(aes(y = tips_with_pred[,10], ymin = tips_with_pred[,11], ymax = tips_with_pred[,12], fill = 'prediction'),
              alpha = 0.2) +
  scale_fill_manual('Interval', values = c('green', 'blue', 'magenta')) +
  theme(legend.position = c(0.20, 0.85))
dev.off()