##################################################
## Wiener process
##################################################
dt <- 0.01
T <- 10
t <- seq(0,T,by=dt)
n <- length(t)-1
W <- cumsum(c(0,rnorm(n,sd=sqrt(dt))))
plot(t,W,type="l")

## Simulated properties
k <- 1e3
dw <- matrix(rnorm(k*n)*sqrt(dt),ncol=k)
W <- rbind(0,apply(dw,2,cumsum))
V <- apply(W,1,var)
E <- apply(W,1,mean)

plot(t,E,type="l")
plot(t,V,type="l")

## Covariance
cov(W[t==4,],W[t==6,])


## Ito or Stratonivich
par(mfrow=c(1,2))
Ito <- apply(W[-(n+1), ]*dw,1,cumsum)
hist(Ito,freq=FALSE)
mean(Ito)

Stra <- apply((W[-(n+1), ]+W[-1, ])/2*dw,1,cumsum)
hist(Stra,freq=FALSE)
mean(Stra)

##################################################
## Example: Simple
##################################################
k <- 1e3
dt <- 0.001
T <- 10
t <- seq(0,T,by=dt)

b <- 2
sigma <- 2
x0 <- 0

x <- matrix(ncol=k,nrow=length(t))
x[1, ] <- x0

for(i in 2:length(t)){
    x[i, ] <- x[i-1, ] + b*dt + sigma * rnorm(k) * sqrt(dt)
}


par(mfrow=c(1,1))
matplot(t,x[ ,1:3],type="l")
lines(t,t*b,lwd=2,lty=2)

t1 <- 5
hist(x[t==t1, ],freq=FALSE)
xplot <- seq(b*t1-4*sigma*sqrt(t1),b*t1+4*sigma*sqrt(t1),length=200)
lines(xplot,dnorm(xplot,mean=b*t1,sd=sigma*sqrt(t1)),col=2,lwd=2)

t2 <- 10
var(t(x[t==t1 | t==t2, ]))
c(t1,t2)*sigma^2

rowMeans(x[t==t1 | t==t2, ])
b * c(t1,t2)


##################################################
## Example OU
##################################################

k <- 1e3
dt <- 0.01
T <- 10
t <- seq(0,T,by=dt)


x0 <- 0
theta <- 1
mu <- 1
sigma <- 0.25

x <- matrix(ncol=k,nrow=length(t))
x[1, ] <- x0
y <- x

for(i in 2:length(t)){
    B <- rnorm(k)
    x[i, ] <- x[i-1, ] + theta * (mu - x[i-1, ])*dt + sigma * B * sqrt(dt)
    y[i, ] <- y[i-1, ] + theta * mu *exp(theta * t[i]) * dt  +
        sigma * exp(theta * t[i]) * B * sqrt(dt)
}


par(mfrow=c(3,1))
matplot(t,x[ ,1:3],type="l")
lines(t,x0*exp(-theta*t) + mu*(1-exp(-theta*t)),lwd=2,lty=2)

matplot(t,y[ ,1:3],type="l")
lines(t,x0 + mu*(exp(theta*t)-1),lwd=2,lty=2)

matplot(t,exp(-theta*t)*y[ ,1:3],type="l")
lines(t,x0*exp(-theta*t) + mu*(1-exp(-theta*t)),lwd=2,lty=2)

## Difference
par(mfrow=c(1,1))
matplot(t,x[ ,1:3]-exp(-theta*t)*y[ ,1:3],type="l")


##################################################
## Example: 1 compartment
##################################################

## Process, parameter choices
set.seed(245)
k <- 1000
dt <- 0.001
t <- seq(0,30,by=dt)
K <- 0.25
sigma <- 0.05
x0 <- 1
s <- 0.05
x <- matrix(nrow=length(t),ncol=k)
x[1, ] <- x0


## Simulation (Euler)
for(i in 2:length(t)){
    x[i,] <- x[i-1,] - K * x[i-1,] * dt + sigma * rnorm(k) * sqrt(dt)
}

## Observations
by <- 300
y <- x[seq(by,dim(x)[1],by=by), ]
dim(y)
y <- y +rnorm(prod(dim(y)),sd=s)
ty <- t[seq(by,length(t),by=by)]

par(mfrow=c(1,1))
i <- 4
plot(t,x[ ,i],type="l",col=gray(0.75))
points(ty,y[ ,i],pch=19)
lines(ty,x0*exp(-K*ty))


## Distribution
matplot(ty,t(apply(y,1,quantile,probs=c(0.025,0.5,0.975))),
        pch=19,type="l",col=gray(0.5),lty=2,lwd=2)
lines(ty,x0*exp(-K*ty),lwd=2)
matlines(ty,x0*exp(-K*ty)-1.96*sqrt(s^2+sigma^2/(2*K)*(1-exp(-2*K*ty))),lwd=2,col=2)
matlines(ty,x0*exp(-K*ty)+1.96*sqrt(s^2+sigma^2/(2*K)*(1-exp(-2*K*ty))),lwd=2,col=2)

##################################################
## Filter and likelihood estimation
KF <- function(y,K,sigma,s,x0,ty){
    y.hat <- c(x0,numeric(length(y)))
    sig.yy <- numeric(length(y)+1)
    y <- c(x0,y)
    ty <- c(0,ty)
    sig.xx <- 0
    x.hat <- x0
    Dt <- diff(ty)[2]
    i <- 1
    for(i in 1:(length(ty)-1)){
        ## Prediction step
        x.hat <- x.hat * exp(-K * Dt) 
        y.hat[i+1] <- x.hat 
        sig.xx <- sig.xx * exp(-2 * K * Dt) + sigma^2/(2*K)*(1-exp(-2 * K * Dt))
        sig.yy[i+1] <- sig.xx +s^2
        ## Update step
        Kal <- sig.xx/sig.yy[i+1]
        x.hat <-
            x.hat + Kal * (y[i+1]-y.hat[i+1])
        sig.xx <-  sig.xx -Kal^2*sig.yy[i+1]
    }
    cbind(ty,y.hat,sig.yy)[-1, ]                        
}



y.obs <- y[ ,50]

filt <- KF(y.obs,K,sigma,s,x0,ty)

plot(ty,y.obs,type="p",col=1,pch=19)
lines(ty,x0*exp(-K*ty))
lines(ty,filt[ ,2])
lines(ty,filt[ ,2]-2*sqrt(filt[ ,3]),lty=2)
lines(ty,filt[ ,2]+2*sqrt(filt[ ,3]),lty=2)

##################################################
## likelihood
##################################################


nll <- function(theta,y,ty,x0){
    K <- exp(theta[1])
    sigma <- exp(theta[2])
    s <- exp(theta[3])
    filt <- KF(y,K,sigma,s,x0,ty)
    e <- y - filt[ ,2]
    -sum(dnorm(e,mean=0,sd=sqrt(filt[ ,3]),log=TRUE))
}

nll(c(0,0,0),y=y.obs,ty=ty,x0=x0)

opt <- nlminb(c(0,0,0),objective=nll,y=y.obs,ty=ty,x0=x0)
library(numDeriv)
I <- hessian(nll,opt$par,y=y.obs,ty=ty,x0=x0)
cov2cor(solve(I)) ## Parameter unceartainty

## Parameter table (log-domain)
cbind(theta=opt$par,se=sqrt(diag(solve(I))))

## compare estimates and true values
cbind(c(K,sigma,s),exp(opt$par))

## Validation
filt <- KF(y.obs,exp(opt$par[1]),exp(opt$par[2]),s,x0,ty)

acf((y.obs-filt[ ,2])/sqrt(filt[ ,3]))

## Distribution of parameters
pars <- matrix(ncol=3,nrow=k)
for(i in 1:k){
    y.obs <- y[ ,i]
    pars[i, ] <- nlminb(c(0,0,0),objective=nll,y=y.obs,ty=ty,x0=x0)$par
}


par(mfrow=c(1,3))
hist(exp(pars[ ,1]),freq=FALSE,xlab="K",main="")
rug(K,lwd=3,col=2)
hist(exp(pars[ ,2]),freq=FALSE,xlab="sigma",main="")
rug(sigma,lwd=3,col=2)
hist(exp(pars[ ,3]),freq=FALSE,xlab="s",main="")
rug(sigma,lwd=3,col=2)
##################################################
## The end
##################################################

