Não foi possível enviar o arquivo. Será algum problema com as permissões?
Diferenças
Aqui você vê as diferenças entre duas revisões dessa página.
Ambos lados da revisão anterior Revisão anterior Próxima revisão | Revisão anterior Próxima revisão Ambos lados da revisão seguinte | ||
pessoais:eder [2011/06/12 17:36] eder [section 5] |
pessoais:eder [2011/09/25 20:50] eder [Códigos] |
||
---|---|---|---|
Linha 12: | Linha 12: | ||
* Estatística Espacial | * Estatística Espacial | ||
* [[http://www.leg.ufpr.br/doku.php/projetos:gem2|GEM²]] Grupo de estudos em modelos mistos | * [[http://www.leg.ufpr.br/doku.php/projetos:gem2|GEM²]] Grupo de estudos em modelos mistos | ||
+ | * {{:pessoais:inlarrblup.r|GWS}} Seleção Genômica Ampla Via ML REML INLA | ||
+ | * {{:pessoais:reml_inla.r|Script}} Modelo seleção Genótipo ambiente via REML ML INLA | ||
===== Disciplinas 2011/1 ===== | ===== Disciplinas 2011/1 ===== | ||
* [[http://www.leg.ufpr.br/doku.php/disciplinas:ce210-2010-02|CE-210: Inferência estatística II]] | * [[http://www.leg.ufpr.br/doku.php/disciplinas:ce210-2010-02|CE-210: Inferência estatística II]] | ||
Linha 21: | Linha 23: | ||
* [[http://www.leg.ufpr.br/doku.php/pessoais:eder:planejamentofito|Planejamento de experimento PG Produção Vegetal UFPR]] | * [[http://www.leg.ufpr.br/doku.php/pessoais:eder:planejamentofito|Planejamento de experimento PG Produção Vegetal UFPR]] | ||
* [[http://www.leg.ufpr.br/doku.php/pessoais:eder:exptempo| Análise de Experimentos de longa duração]] II Reunião Paranaense Ciência do Solo | * [[http://www.leg.ufpr.br/doku.php/pessoais:eder:exptempo| Análise de Experimentos de longa duração]] II Reunião Paranaense Ciência do Solo | ||
- | ===== Códigos ===== | + | ===== Códigos (Em construção) ===== |
<code R> | <code R> | ||
###-----------------------------------------------------------------### | ###-----------------------------------------------------------------### | ||
- | ### Agulha de buffon | + | ### Reversible jump MCMC |
- | buffon <- function(n,l=1,a=1){ | + | ### Modelo 1 y ~ N(b0+b1*x,sigma) |
- | if(a<l){cat('Erro: a < l, deve ser a > l\n')} | + | ### Modelo 1 y ~ N(b0+b1*x+b2*x²,sigma) |
- | if(a>=l){ | + | #browseURL('http://www.icmc.usp.br/~ehlers/bayes/cap4.pdf') |
- | theta <- runif(n,0,pi) | + | # pg 76 |
- | dist <- runif(n,0,a/2) | + | require(MASS)#mvnorm() |
- | inter <- sum(dist <= l/2*sin(theta)) | + | require(MCMCpack)#rinvgamma() dinvgamma() |
- | phi_est <- round((n/inter)*(2*l/a),12) | + | require(coda)#as.mcmc |
- | cat('Número Simulação',n,'phi_estimado',phi_est,'Erro',round(pi-phi_est,12),'\n') | + | rm(list=ls()) |
- | return(c(n,phi_est)) | + | ### Ajustar Prioris |
- | }} | + | ### conferir jacobiano |
+ | |||
+ | rj.modelo <- function(y,x,b0,b1,sigma,b01,b11,b21,sigma1,model,mu=mu,sd=sd,mu0=mu0, | ||
+ | mu02=mu02,V0=V0,V02=V02,v0=v0,tau0=tau0,v02=v02,tau02=tau02){ | ||
+ | if (model == 1){ | ||
+ | u <- rnorm(1, mu,sd) | ||
+ | b0_n <- b0 | ||
+ | b1_n <- b1 | ||
+ | sigma_n <- sigma | ||
+ | b01_n <- b0 * u | ||
+ | b11_n <- b1 * u | ||
+ | b21_n <- u | ||
+ | sigma1_n <- sigma * (u^2) | ||
+ | } | ||
+ | if (model == 2){ | ||
+ | u <- b21 | ||
+ | b0_n <- b01 / u | ||
+ | b1_n <- b11 / u | ||
+ | sigma_n <- sigma1 / (u^2) | ||
+ | b01_n <- b01 | ||
+ | b11_n <- b11 | ||
+ | b21_n <- b21 | ||
+ | sigma1_n <- sigma1 | ||
+ | } | ||
+ | num <- (sum(dnorm(y,b0_n+b1_n*x,sigma_n,log=TRUE))#+ | ||
+ | # sum(dnorm(y,mu0[1],V0[1,1],log=TRUE))+ | ||
+ | #sum(dnorm(y,mu0[1],V0[2,2],log=TRUE))+ | ||
+ | # sum(log(dinvgamma(y,v0,tau0))) | ||
+ | ) * u^4 | ||
+ | den <- (sum(dnorm(y,b01_n+b11_n*x+b21_n*x^2,sigma1_n,log=TRUE))#+ | ||
+ | # sum(dnorm(y,mu02[1],V02[1,1],log=TRUE))+ | ||
+ | # sum(dnorm(y,mu02[2],V02[2,2],log=TRUE))+ | ||
+ | # sum(dnorm(y,mu02[3],V02[3,3],log=TRUE))+ | ||
+ | # sum(log(dinvgamma(y,v02,tau02))) | ||
+ | ) * dnorm(u,0,2) | ||
+ | u = runif(1, 0, 1) | ||
+ | if (model == 1) { | ||
+ | aceita = min(1, num/den) | ||
+ | if (u < aceita) { | ||
+ | model = 2 | ||
+ | b0 <- b0_n | ||
+ | b1 <- b1_n | ||
+ | sigma <- sigma_n | ||
+ | } | ||
+ | } | ||
+ | if (model == 2){ | ||
+ | aceita = min(1, den/num) | ||
+ | if (u < aceita) { | ||
+ | model = 1 | ||
+ | b01 <- b01_n | ||
+ | b11 <- b11_n | ||
+ | b21 <- b21_n | ||
+ | sigma1 <- sigma1_n | ||
+ | } | ||
+ | } | ||
+ | if (model == 1){return(list(model = model,b0=b0,b1=b1,sigma=sigma))} | ||
+ | if (model == 2){return(list(model = model,b01=b01,b11=b11,b21=b21,sigma1=sigma1))} | ||
+ | } | ||
- | n <- seq(10000,1000000,by=20000) | ||
- | res <- matrix(NA,ncol=2,nrow=length(n)) | ||
- | con <- 1 | ||
- | for (i in n){ | ||
- | res[con,] <- buffon(i) | ||
- | con <- con+1 | ||
- | } | ||
- | plot(res,type='l',ylab=expression(pi),xlab='Simulações') | ||
- | abline(h=pi,col='red') | ||
- | ###-----------------------------------------------------------------### | ||
- | ### MOnte carlo | ||
- | ## Calcula a área via simulação de monte carlo | ||
- | ## args: r= raio, s vetor com numero de simulação, plotS plotar a simulação | ||
- | MCcirculo<-function(r,s,plotS=TRUE){ | ||
- | ns<-area<-s | ||
- | r<-r | ||
- | con <- 1 | ||
- | for (j in ns) { | ||
- | #pontos aleatorios | ||
- | x<-runif(j, min=-r, max=r) | ||
- | y<-runif(j, min=-r, max=r) | ||
- | ponto<-cbind(x,y) | ||
- | cont <- sum(apply(ponto,1,function(x){sqrt(sum(x^2))})<r) | ||
- | #plotando Simulação | ||
- | if(plotS==TRUE){ | ||
- | plot(x,y,col="red",type="p",asp=1,lwd=1,xlim=c(-r,r),ylim=c(-r,r), main="Simulação Monte Carlo",sub=j) | ||
- | ang <- seq(0, 2*pi, length = 100) | ||
- | xx <- r * cos(ang);yy <- r * sin(ang) | ||
- | polygon(xx, yy,border = "dark blue",lwd=2) | ||
- | } | ||
- | #Calculo de Area | ||
- | area[con]<-(cont/j)*(r^2)*4 | ||
- | cat(paste(round(area[con],6),j,'\n')) | ||
- | con <- con+1 | ||
- | } | ||
- | plot(ns,area,main="Simulação Monte Carlo",xlab='Número da amostra',ylab='Area') | ||
- | abline(h=pi*r^2,col='red',lwd=2) | ||
| | ||
+ | rjmcmc <- function(nI, x,y,burnIN,mu=mu,sd=sd) { | ||
+ | chain = matrix(NA, nrow = nI, ncol = 8) | ||
+ | nv <- c(0,0) | ||
+ | chain[1,1:8] = c(1) | ||
+ | model = 1 | ||
+ | n <- length(y) | ||
+ | ###----------------------------------------------------------### | ||
+ | ###MOdel 1 | ||
+ | X <- model.matrix(~x) | ||
+ | k<-ncol(X) | ||
+ | #beta | ||
+ | mu0<-rep(0,k) | ||
+ | V0<-100*diag(k) | ||
+ | #sigma2 | ||
+ | v0<-3 | ||
+ | tau0<-100 | ||
+ | #Valores iniciais | ||
+ | chain[1,3] <-sig2draw<- 3 | ||
+ | invV0 <- solve(V0) | ||
+ | XtX <- crossprod(X,X) | ||
+ | Xty <- crossprod(X,y) | ||
+ | invV0_mu0 <- invV0 %*% mu0 | ||
+ | ###----------------------------------------------------------### | ||
+ | # Model 2 | ||
+ | X2 <- cbind(1,x,x^2) | ||
+ | k2<-ncol(X2) | ||
+ | #beta | ||
+ | mu02<-rep(0,k2) | ||
+ | V02<-100*diag(k2) | ||
+ | #sigma2 | ||
+ | v02<-3 | ||
+ | tau02<-100 | ||
+ | #Valores iniciais | ||
+ | chain[1,7] <- sig2draw2<- 3 | ||
+ | invV02 <- solve(V02) | ||
+ | XtX2 <- crossprod(X2,X2) | ||
+ | Xty2 <- crossprod(X2,y) | ||
+ | invV0_mu02 <- invV02 %*% mu02 | ||
+ | ###----------------------------------------------------------### | ||
+ | for (i in 2:nI) { | ||
+ | if (model == 1){ | ||
+ | # Model 1 | ||
+ | #beta | ||
+ | invsig2draw <- 1/sig2draw | ||
+ | V1<-solve(invV0+(invsig2draw) * XtX) | ||
+ | mu1<-V1 %*% (invV0_mu0 + (invsig2draw)* Xty) | ||
+ | chain[i,1:2]<-mvrnorm(n=1,mu1,V1) | ||
+ | # sigma | ||
+ | v1<-(n+2*v0)/2 | ||
+ | yXb <- (y-X %*% chain[i,1:2]) | ||
+ | tyXb <-t(yXb) | ||
+ | tau1<-(0.5)*(tyXb %*% yXb+2*tau0) | ||
+ | chain[i,3] <- sig2draw <- sqrt(rinvgamma(1,v1,tau1)) | ||
+ | } | ||
+ | if (model == 2){ | ||
+ | # Model 2 | ||
+ | #beta | ||
+ | invsig2draw2 <- 1/sig2draw2 | ||
+ | V12<-solve(invV02+(invsig2draw2) * XtX2) | ||
+ | mu12<-V12 %*% (invV0_mu02 + (invsig2draw2)* Xty2) | ||
+ | chain[i,4:6]<-mvrnorm(n=1,mu12,V12) | ||
+ | # sigma | ||
+ | v12<-(n+2*v02)/2 | ||
+ | yXb2 <- (y-X2 %*% chain[i,4:6]) | ||
+ | tyXb2 <-t(yXb2) | ||
+ | tau12<-(0.5)*(tyXb2 %*% yXb2+2*tau02) | ||
+ | chain[i,7] <- sig2draw2 <- sqrt(rinvgamma(1,v12,tau12)) | ||
+ | } | ||
+ | new <- rj.modelo(y,x,chain[i,1],chain[i,2],chain[i,3],chain[i,4],chain[i,5],chain[i,6],chain[i,7],model,mu=mu,sd=sd) | ||
+ | model <- new$model | ||
+ | if (model == 1) { | ||
+ | chain[i, 1] = new$b0 | ||
+ | chain[i, 2] = new$b1 | ||
+ | chain[i, 3] = new$sigma | ||
+ | nv[1] = nv[1] + 1 | ||
+ | } | ||
+ | if (model == 2) { | ||
+ | chain[i, 4] = new$b01 | ||
+ | chain[i, 5] = new$b11 | ||
+ | chain[i, 6] = new$b21 | ||
+ | chain[i, 7] = new$sigma1 | ||
+ | nv[2] = nv[2] + 1 | ||
+ | } | ||
+ | } | ||
+ | chain[,8] <- 1 | ||
+ | chain[is.na(chain[,1]),8] <- 2 | ||
+ | chain <- chain[- c(1:burnIN),] | ||
+ | colnames(chain) <- c('b0_1','b1_1','sigma_1','b0_2','b1_2','b2_2','sigma_2','model') | ||
+ | return(list(as.mcmc(na.omit(chain[,1:3])), | ||
+ | as.mcmc(na.omit(chain[,4:7])), | ||
+ | as.mcmc(na.omit(chain[,8])))) | ||
} | } | ||
- | MCcirculo(1,seq(5,5000,by=1000),plotS=FALSE) | ||
- | ###-----------------------------------------------------------------### | ||
- | ### Inversão de Probabilidade | ||
- | ### OBJ: gerar x~exp transformando de uma uniforme | ||
- | NS <- 10000 | ||
- | lam <- 0.5 | ||
- | #f(x)=exp(lam) F(x)=1-exp(-lam*x), logo: F^-1(x)= -lam^-1*log(1-x) | ||
- | Gexp <- function(x,lam){-(log(1-U))/lam} | ||
- | |||
- | U <- runif(NS) | ||
- | X <- Gexp(U,lam) | ||
- | Y <- rexp(NS,lam) | ||
- | |||
- | par(mfrow=c(1,3)) | ||
- | hist(U,freq=FALSE,main='Uniforme',col='lightblue') | ||
- | lines(density(U),col='red',lwd=2) | ||
- | |||
- | hist(X,freq=FALSE,main='Expoencial via uniforme',col='lightblue') | ||
- | lines(density(X),col='red',lwd=2) | ||
- | lines(curve(dexp(x,lam),min(X),max(X),add=TRUE),col='blue',lwd=2) | ||
- | hist(Y,freq=FALSE,main='Expoencial do R',col='lightblue') | + | x <- 1:10 |
- | lines(density(Y),col='red',lwd=2) | + | y <- 10+2*x^1+rnorm(x,0,5) |
- | lines(curve(dexp(x,lam),min(Y),max(Y),add=TRUE),col='blue',lwd=2) | + | plot(x,y) |
- | ###-----------------------------------------------------------------### | + | res <- rjmcmc(5000,x,y,1,mu=0,sd=100) |
- | ### Metodos de integração numerica | + | lapply(res,summary) |
- | #Função | + | plot(res[[1]]) |
- | f <- function(x){exp(-x^2)} | + | summary(lm(y~1+I(x))) |
- | a <- -3 | + | plot(res[[2]]) |
- | b <- 3 | + | summary(lm(y~1+I(x)+I(x^2))) |
- | # integrar de -3,3 | + | plot(res[[3]]) |
- | x <- seq(a,b,l=100) | + | ##------------------------------------------------------------------### |
- | plot(x,f(x),type='l',ylim=c(0,1)) | + | |
- | # Integração nativa do R - Gauss–Kronrod quadrature | + | |
- | integrate(f,a,b) | + | |
- | ###Simpson 1/3 - INtervalos par, igualmente espaçados | + | |
- | n <- 1200 | + | |
- | xi <- seq(a,b,l=n+1) | + | |
- | i <- seq(2,n,by=2) | + | |
- | j <- seq(3,n-1,by=2) | + | |
- | ((b-a)/n/3)*(f(a)+4*sum(f(xi[i]))+2*sum(f(xi[j]))+f(b)) | + | |
- | ###Simpson 3/8 - Intervalos divisiveis por 3 | + | |
- | n <- 1200 | + | |
- | xi <- seq(a,b,l=n+1) | + | |
- | i <- seq(2,n,by=3) | + | |
- | j <- seq(4,n-2,by=3) | + | |
- | ((3*(b-a)/n)/8)*(f(a)+3*sum(f(xi[i])+f(xi[i+1]))+2*sum(f(xi[j]))+f(b)) | + | |
- | ### Quadratura gausiana 3º Ordem | + | |
- | w <- c(0.555555,0.888888,0.555555) | + | |
- | xi <- c(-0.77459667,0,0.77459667) | + | |
- | (b-a)/2*sum(f((b-a)/2*xi+(a+b)/2)*w) | + | |
- | ### Quadratura gausiana 4º Ordem | + | |
- | w <- c(0.3478548,0.6521452,0.6521452,0.3478548) | + | |
- | xi <- c(-0.86113631,-0.33998104,0.33998104,0.86113631) | + | |
- | (b-a)/2*sum(f((b-a)/2*xi+(a+b)/2)*w) | + | |
- | ### Quadratura gausiana 6º Ordem | + | |
- | w <- c(0.1713245,0.3607616,0.4679139,0.4679139,0.3607616,0.1713245) | + | |
- | xi <- c(-0.933246951,-0.66120938,-0.23861919,0.23861919,0.66120938,0.933246951) | + | |
- | (b-a)/2*sum(f((b-a)/2*xi+(a+b)/2)*w) | + | |
- | ###Monte Carlo | + | |
- | n <- 10000 | + | |
- | xi <- runif(n,a,b) | + | |
- | Ls <- max(f(seq(a,b,l=100))) | + | |
- | Li <- 0 | + | |
- | yi <- runif(n,Li,Ls) | + | |
- | sum(f(xi)>=yi)/n*((b-a)*(Ls-Li)) | + | |
- | points(xi,yi) | + | |
- | ###Laplace | + | |
- | #f' <- -2*x*exp(-x^2) | + | |
- | D2f <- function(x){(4*x^2-2)*exp(-x^2)} | + | |
- | D2f(0) | + | |
- | ((2*pi)/((-D2f(0))))^0.5*f(0) | + | |
- | ##Avaliando | + | |
- | x <- seq(a,b,l=100) | + | |
- | plot(x,f(x),type='l',ylim=c(0,2)) | + | |
- | lines(x,((2*pi)/((-D2f(0))))^0.5*f(x),col="red") | + | |
###-----------------------------------------------------------------### | ###-----------------------------------------------------------------### | ||
### Regressão Beta | ### Regressão Beta | ||
Linha 166: | Linha 215: | ||
return(ll) | return(ll) | ||
} | } | ||
+ | |||
###-----------------------------------------------------------------### | ###-----------------------------------------------------------------### | ||
opt <- optim(c(B0=-0.5,B1=-0.51,B2=0.11,phi=35),log.vero,y=FoodExpenditure$food/FoodExpenditure$income, | opt <- optim(c(B0=-0.5,B1=-0.51,B2=0.11,phi=35),log.vero,y=FoodExpenditure$food/FoodExpenditure$income, | ||
Linha 177: | Linha 226: | ||
summary(fe_beta) | summary(fe_beta) | ||
###-----------------------------------------------------------------### | ###-----------------------------------------------------------------### | ||
+ | log.veroP <- function(par,phi,y,x1,x2){ | ||
+ | mu <- exp((par[1] + par[2] * x1 + par[3] * x2))/(1+exp((par[1] + par[2] * x1 + par[3] * x2)))##logit^-1 | ||
+ | ll <- sum(dbeta(y, mu* phi, (1-mu)*phi,log = TRUE)) | ||
+ | return(ll) | ||
+ | } | ||
+ | |||
+ | opt <- grid.phi <- seq(20,60,l=150) | ||
+ | con <- 1 | ||
+ | for (i in grid.phi){ | ||
+ | opt[con] <- optim(c(B0=-0.5,B1=-0.51,B2=0.11),log.veroP,phi=i,y=FoodExpenditure$food/FoodExpenditure$income, | ||
+ | x1=FoodExpenditure$income, | ||
+ | x2=FoodExpenditure$persons, | ||
+ | hessian = TRUE, control=(list(fnscale=-1)))$value | ||
+ | con <- con+1 | ||
+ | } | ||
+ | |||
+ | plot(grid.phi,2*(max(opt)-opt),type='l') | ||
+ | abline(h=3.84) | ||
+ | |||
</code> | </code> | ||