# This code carries out the analysis of the Lake Constance data in the notes. It comes in several parts:# - reading in data# - drawing plots# - likelihood based analysis
# read in data; z is a vector with the years of freezes since 1300freeze=read.table("constance.txt")$V1z=freeze[freeze>=1300]n=length(z)
# produce plot of dataplot(z,rep(0,n),type="p",ylab="",xlab="Year",bty="n",xlim=c(1300,2000),axes=FALSE,xaxs="i",ylim=c(0,0))#Axis(x=c(1300,1400),side=1,at=13:15*100,xaxp=c(1300,1900,3))axis(1,col.ticks=c("red","green"))rug(z)abline(h=0)
# generate Figure 16 (plot of freeze dates)pdf("ConstanceData.pdf",width=10,height=2)par(mar=c(3,1,1,1)+0.1,mgp=c(1,1,0))plot(z,rep(0,n),type="n",ylab="",xlab="Year",bty="n",xlim=c(1300,1975),axes=FALSE,xaxs="r",ylim=c(-1,1),yaxs="i")segments(1300,0,1975,0)segments(z,rep(0,n),z,rep(0.5,n))ticks=13:19*100m=length(ticks)segments(ticks,rep(0,m),ticks,rep(-0.25,m))text(ticks,rep(-0.5,m),ticks)dev.off()
# generate Figure 17 (histogram)require(MASS)pdf("ConstanceHist.pdf",width=10)par(mar=c(5,4,2,2)+0.1)truehist(z,h=75,x0=1300,prob=FALSE,col="Dark Grey",ylab="Frequency",xlab="Freeze date",cex.lab=1.3,cex.axis=1.3)dev.off()
# generate Figure 18 (QQ plot)pdf("ConstanceQQ.pdf",width=10)par(mar=c(5,4,2,2)+0.1)n<-length(z)qs<-qunif(ppoints(n),1300,1975)plot(z,qs,pch="+",xlab="Freeze Dates",ylab="Uniform quantiles",cex.lab=1.3,cex.axis=1.3)abline(0,1)dev.off()
# define (minus the) log likelihood as functionlogl=function(theta,t1=t,v1=v){ alpha=theta[1] beta=theta[2] alpha*t1+beta*t1^2/2-sum(log(alpha+beta*v1))}
# numerical maximisation of log likelihood
t=7.2 # this is the number of centuries' data (after 1300) to use so 7.20 uses data to 2020v=(z-1300)/100 # this transforms the freeze dates to centuries after 1300results=optim(c(1,0),logl,hessian=TRUE)
# obtain values from maximisation
results$par # this gives the maximum likelihood estimates for alpha and betaj=solve(results$hessian) # this gives the inverse of the Hessian matrix at the maximumsqrt(j[1,1]);sqrt(j[2,2]) # taking square roots of the inverse of the Hessian gives standard errors
# carry out likelihood ratio test
W=-2*(logl(theta=results$par,t1=t,v1=v)-logl(theta=c(length(v)/t,0),t1=t,v1=v))1-pchisq(W,1)