#Slash density
s = function(x)
{
  (1-exp(-x^2/2))/(x^2*sqrt(2*pi))
}

#h=function(x){
#  x+0.2*x^2
#}

#h=function(x){
#  x+0.2*cos(2*pi*x)
#}


h=function(x){
  sin(x)+0.2*cos(2*pi*x)
}



## show ratio
x = seq(-5,5,length=100)
par(mfrow=c(1,1))
plot(x, dnorm(x),type="l")
lines(x,s(x),type="l")

par(mfrow=c(1,2))
plot(x,s(x)/dnorm(x),type="l")
plot(x,dnorm(x)/s(x),type="l")



## show mean
m = 1000
x=rnorm(m)
y =rnorm(m)/runif(m)
show(c(mean(x), mean(h(x)), mean(y), mean(h(y))))

m = 100000
x=rnorm(m)
y =rnorm(m)/runif(m)
show(c(mean(x), mean(h(x)), mean(y), mean(h(y))))

m = 10000000
x=rnorm(m)
y =rnorm(m)/runif(m)
show(c(mean(x), mean(h(x)), mean(y), mean(h(y))))

## show std
m = 1000
x=rnorm(m)
y =rnorm(m)/runif(m)
show(c(sd(x), sd(h(x)), sd(y), sd(h(y))))

m = 100000
x=rnorm(m)
y =rnorm(m)/runif(m)
show(c(sd(x), sd(h(x)), sd(y), sd(h(y))))

m = 10000000
x=rnorm(m)
y =rnorm(m)/runif(m)
show(c(sd(x), sd(h(x)), sd(y), sd(h(y))))




## rejection sampling
y =rnorm(m)/runif(m)
U=runif(m)
accept = dnorm(y)/(s(y)*2)
sample = y[U<accept]

length(sample)/m
max(accept)
min(accept)
hist(sample)

## importance sampling: normal by sampling slash
m=100000

y =rnorm(m)/runif(m)
w1 = dnorm(y)/s(y)
wn1 = w1/sum(w1)
mean(w1)


neff = 1/sum(wn1^2)
show(neff/m)


t=h(y)*w1
mean(t)

par(mfrow=c(1,2))
hist(w1,20,freq=F)
hist(t,20,freq=F)

## importance sampling: slash by sampling normal
m=100000
y =rnorm(m)
w1 = s(y)/dnorm(y)
wn1 = w1/sum(w1)
mean(w1)

max(wn1)

neff = 1/sum(wn1^2)
show(neff/m)


t=h(y)*w1
mean(t)

par(mfrow=c(1,2))

hist(w1,20000,freq=F,xlim=c(0,10))
hist(t,20000,freq=F,xlim=c(-5,5))


par(mfrow=c(1,2))

hist(w1[w1>10],200,freq=F)
hist(t[abs(t)>5],200,freq=F)








## SIR resample normal by sampling slash

n = 1000
y =rnorm(m)/runif(m)
w1 = dnorm(y)/s(y)
wn1 = w1/sum(w1)
x = sample(y,n,replace=T,prob=wn1)
par(mfrow=c(1,2))
hist(y,1000000,xlim=c(-5 ,5))
hist(x,40,xlim=c(-5 ,5))


## SIR resample   slash by sampling normal :-(
y =rnorm(m)
w1 = s(y)/dnorm(y)
wn1 = w1/sum(w1)
n = 1000
x = sample(y,n,replace=T,prob=wn1)
par(mfrow=c(1,2))
hist(y,100,xlim=c(-8 ,8))
hist(x,40,xlim=c(-8 ,8))




## SIR resample  figures

par(mfrow=c(1,2))

y =rnorm(m)/runif(m)
w = dnorm(y)/s(y)
x = sample(y,n,replace=T,prob=w)
x = sort(x)
hist(x,20,freq=F,xlim=c(-8,8))
xp=seq(-8,8,by=0.1)
lines(xp,dnorm(xp),col=2)

y = rnorm(m)
w = s(y)/dnorm(y)
x = sample(y,n,replace=T,prob=w)
x = sort(x)
hist(x,20,freq=F,xlim=c(-8,8))
lines(xp,s(xp),col=2)





