Advertisement
Guest User

Untitled

a guest
Feb 13th, 2016
42
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.84 KB | None | 0 0
  1. rm(list=ls())
  2.  
  3. n=260
  4. x_pars=c(0,1);
  5. y_pars=c(1,.3,7);
  6.  
  7. #observed data follows gamma-shifted distribution
  8. y=rgamma(n,y_pars[1],y_pars[2])-y_pars[3]
  9. sy=sort(y)
  10. #quantiles come from the standard normal distribution
  11. p=pnorm(sy,x_pars[1],x_pars[2])
  12.  
  13. ############################
  14. # Linear Interpolation
  15. ############################
  16. w=abs(diff(sy)) #interval width
  17. dp=abs(diff(p)) #differenced quantiles
  18. fx=dp/w #estimated hight of pdf
  19. windows()
  20. par(mfrow=c(2,1))
  21. plot(sy[-n],fx,typ='l',main="Linear Interpolation",
  22. ylab="density",xlab="y",xlim=c(-3,3),ylim=c(0,.5)) #estimated pdf
  23. points(sy,dnorm(sy,x_pars[1],x_pars[2]),type='l',
  24. col=2,lty=2) #actual pdf
  25. points(sy,dgamma(sy+y_pars[3],y_pars[1],y_pars[2]),
  26. type='l',col=4,lty=4) #pdf of observations
  27. legend("topright",legend=c("Actual PDF","Estimated PDF","Obs. PDF"),
  28. lty=c(2,1,4),col=c(2,1,4))
  29.  
  30. ############################
  31. # Monte Carlo Smoothing
  32. ############################
  33. precision=100 #if this is to high the KDE may have difficulty + longer run-time
  34. m=n*precision
  35.  
  36.  
  37. u=sort(runif(m))
  38.  
  39. ind=which(u>p[1] & u<=p[n]) #throw these out for now (assume 0 density on either side of the observations)
  40. m2=length(ind)
  41. u=u[ind];
  42.  
  43. #simulate from linear interp. cdf using probability integral transform
  44. z=numeric(m2)
  45. st=1
  46. for(i in 1:m2){
  47. for(j in 2:n){
  48. if(u[i]<=p[j]){
  49. st=j;
  50. interp=(u[i]-p[j-1])/dp[j-1]
  51. z[i]=sy[j-1]+w[j-1]*interp
  52. break
  53. }
  54. }
  55. }
  56.  
  57.  
  58. plot(density(z),type='l',main="Linear Interpolation + MC Smoothing",
  59. ylab="density",xlab="y",xlim=c(-3,3),ylim=c(0,.5)) #estimated pdf
  60. points(sy,dnorm(sy,x_pars[1],x_pars[2]),type='l',
  61. col=2,lty=2) #actual pdf
  62. points(sy,dgamma(sy+y_pars[3],y_pars[1],y_pars[2]),
  63. type='l',col=4,lty=4) #pdf of observations
  64. legend("topright",legend=c("Actual PDF","Estimated PDF","Obs. PDF"),
  65. lty=c(2,1,4),col=c(2,1,4))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement