############################################################################################################## # # Example 7.11 (pages 277) – Figure 7.6 (page 278) # # Multiple try Metropolis and Random walk Metropolis algorithms to sample from # # This example is related to Example 3.7 (pages 102-3). # ############################################################################################################## # # NONLINEAR MODEL MODEL WITH EXPONENTIAL DECAY WITH A FIXED RATE CONSTANT # # Biochemical oxygen demand (BOD) # # Tanner (1996, page 169) # Marske (1967) # Bates and Watts (1988) # # x = time (days) # y = BOD (mg/Liter) # ############################################################################################################## # # Author : Hedibert Freitas Lopes # Graduate School of Business # University of Chicago # 5807 South Woodlawn Avenue # Chicago, Illinois, 60637 # Email : hlopes@ChicagoGSB.edu # ############################################################################################################### quantile025 = function(x){quantile(x,0.025)} quantile975 = function(x){quantile(x,0.975)} post = function(th){sum((y-th[1]*(1-exp(-x*th[2])))^2)^(-2)*dnorm(th[1],20,20)*dnorm(th[2],0,1.5)} # Data # ---- x = c(1,2,3,4,5,7) y = c(8.3,10.3,19,16,15.6,19.8) # Contours of the posterior distribution # -------------------------------------- th1 = seq(0,60,length=100) th2 = seq(0,7,length=100) f = matrix(0,100,100) for (i in 1:100) for (j in 1:100) f[i,j] = post(c(th1[i],th2[j])) f = f/sum(f) # Random Walk Metropolis # ---------------------- set.seed(9023749) M = 10000 ths = matrix(0,M+1,2) sd = c(25,3) th = c(10,0) ths[1,] = th for (iter in 1:M){ # sampling theta1 theta = rnorm(1,th[1],sd[1]) accept = min(1,post(c(theta,th[2]))/post(th)) if (runif(1)