------ R code ------- library(rstan) # Reading dataset data <- read.table("p1_data_001.txt",header=T) y <- data[,10] # Constructing addtive relationship matrix ped <- data n.ped <- length(ped[,1]) a.mat <- matrix(0,n.ped,n.ped) a.inv <- matrix(0,n.ped,n.ped) f <- array(0,n.ped) tt <- c(1.0,-0.5,-0.5) for(i in 1:n.ped){ a.mat[i,i] <- 1 if(ped[i,2]!=0 && ped[i,3]!=0){ a.mat[i,i] <- a.mat[i,i]+0.5*a.mat[ped[i,2],ped[i,3]] a.mat[1:i-1,i] <- 0.5*(a.mat[1:i-1,ped[i,2]]+a.mat[1:i-1,ped[i,3]]) }else if(ped[i,2]==0 && ped[i,3]!=0){ a.mat[1:i-1,i] <- 0.5*(a.mat[1:i-1,ped[i,3]]) }else if(ped[i,2]!=0 && ped[i,3]==0){ a.mat[1:i-1,i] <- 0.5*(a.mat[1:i-1,ped[i,2]]) } a.mat[i,1:i-1] <- a.mat[1:i-1,i] f[i] <- a.mat[i,i]-1 } # Setting fixed effect n.fixed <- 2 n <- length(data[,1]) sex <- matrix(0,n,1) for(i in 1:n){ if(data[i,4]=='M'){ sex[i] <- 1 } else if(data[i,4]=='F'){ sex[i] <- 2 } } # Setting incident matrix X <- matrix(0,n,n.fixed) Z <- matrix(0,n,n.ped) for(i in 1:n){ X[i,sex[i]] <- 1 Z[i,data[i,1]] <- 1 } # Implementing NUTS by Stan data_stan <- list(J=n.fixed, N=n, K=n.ped, X=X, Z=Z, Y=y, A=a.mat) fit <- stan(file='test.stan', data=data_stan, seed=1234, chain = 1, iter = 10000, warmup = 1000) ------ test.stan file------ data { int J; // number of fixed effects int K; // number of all animals int N; // number of observations matrix[N,J] X; // Fixed effects design matrix matrix[N,K] Z; // Random effects design matrix vector[N] Y; // response variable matrix[K,K] A; // relationship matrix } transformed data{ matrix[K,K] LA; LA = cholesky_decompose(A); } parameters { vector[K] a_decompose; // breeding values vector[J] b; // fixed effects real sigma_G; // genetic standard deviation real sigma_R; // residual standard deviation } model { vector[N] mu; vector[K] a; a_decompose ~ normal(0, 1); a = sigma_G * (LA * a_decompose); mu = X * b + Z * a; Y ~ normal(mu, sigma_R); to_vector(b) ~ normal(0, 1); sigma_G ~ student_t(4, 0, 1); sigma_R ~ student_t(4, 0, 1); } generated quantities{ real sigma_U; real sigma_E; sigma_U = sigma_G * sigma_G; // genetic variance sigma_E = sigma_R * sigma_R; // residual variance }