How can I set a random seed using the jags() function? - jags

Each time I run my JAGS model using the jags() function, I get very different values of fitted parameters. However, I want other people to reproduce my results.
I tried to add set.seed(123), but it didn't help. This link describes how to achieve my goal using the run.jags() function. I wonder how I can do similar things using jags(). Thank you!
Below is my model in R:
##------------- read data -------------##
m <- 6
l <- 3
node <- read.csv("answer.csv", header = F)
n <- nrow(node)
# values of nodes
## IG
IG <- c(c(0.0, 1.0, 0.0), c(0.0, 0.0, 1.0), c(1.0, 0.0, 0.0), c(1.0, 0.0, 0.0), c(0.0, 1.0, 0.0), c(0.0, 0.0, 1.0))
IG <- matrix(IG, nrow=6, ncol=3, byrow=T)
V_IG <- array(0, dim=c(n, m, l))
for (i in 1:n){
for (j in 1:m){
for (k in 1:l)
{
V_IG[i,j,k] <- IG[j,k] # alternatively, V[i,j,k] <- PTS[j,k]
}
}
}
## PTS
PTS <- c(c(1.0, 0.5, 0.0), c(1.0, 0.0, 0.5), c(1.0, 1.0, 0.0), c(1.0, 0.0, 1.0), c(0.0, 0.5, 1.0), c(0.0, 1.0, 0.5))
PTS <- matrix(PTS, nrow=m, ncol=3, byrow=T)
V_PTS <- array(0, dim=c(n, m, l))
for (i in 1:n){
for (j in 1:m){
for (k in 1:l)
{
V_PTS[i,j,k] <- PTS[j,k]
}
}
}
##------------- fit model -------------##
set.seed(123)
data <- list("n", "m", "V_IG", "V_PTS", "node")
myinits <- list(list(tau = rep(1,n), theta = rep(0.5,n)))
parameters <- c("tau", "theta")
samples <- jags(data, inits=myinits, parameters,
model.file ="model.txt", n.chains=1, n.iter=10000,
n.burnin=1, n.thin=1, DIC=T)
And my model file model.txt:
model{
# data: which node (1, 2, 3) was chosen by each child in each puzzle
for(i in 1:n) # for each child
{
for (j in 1:m) # for each problem
{
# node chosen
node[i,j] ~ dcat(mu[i,j,1:3])
mu[i,j,1:3] <- exp_v[i,j,1:3] / sum(exp_v[i,j,1:3])
for (k in 1:3) {
exp_v[i,j,k] <- exp((V_IG[i,j,k]*theta[i] + V_PTS[i,j,k]*(1-theta[i]))/tau[i])
}
}
}
# priors on tau and theta
for (i in 1:n)
{
tau[i] ~ dgamma(0.001,0.001)
theta[i] ~ dbeta(1,1)
}
}

I know this is an older question, but for anyone using the jagsUI package, the jags() function has an argument for setting the seed, 'seed = ####'. So for example, a JAGS call could be;
np.sim1 <- jags(data = data1, parameters.to.save = params1, model.file = "mod1_all.txt",
n.chains = nc, n.iter = ni, n.burnin = nb, n.thin = nt, seed = 4879)
summary(np.sim1)

Here is a toy example for linear regression. First the model:
model{
a0 ~ dnorm(0, 0.0001)
a1 ~ dnorm(0, 0.0001)
tau ~ dgamma(0.001,0.001)
for (i in 1:100) {
y[i] ~ dnorm(mu[i], tau)
mu[i] <- a0 + a1 * x[i]
}
}
Now we generate some data and you the set.seed function to generate identical results from multiple calls to the jags function.
# make the data and prepare what we need to fit the model
x <- rnorm(100)
y <- 1 + 1.2 * x + rnorm(100)
data <- list("x", "y")
parameters <- c("a0", "a1", "tau")
inits = list(list(a0 = 1, a1=0.5, tau = 1))
# First fit
set.seed(121)
samples <- jags(data, inits,
parameters,model.file = "./sov/lin_reg.R",
n.chains = 1, n.iter = 5000, n.burnin = 1, n.thin = 1)
# second fit
set.seed(121) # with set.seed at same value
samples2 <- jags(data, inits,
parameters,model.file = "./sov/lin_reg.R",
n.chains = 1, n.iter = 5000, n.burnin = 1, n.thin = 1)
If we pull out the draws for one of the parameters from samples and samples2 we can see that they have generated the same values.
a0_1 <- samples$BUGSoutput$sims.list$a0
a0_2 <- samples2$BUGSoutput$sims.list$a0
head(cbind(a0_1, a0_2))
[,1] [,2]
[1,] 1.0392019 1.0392019
[2,] 0.9155636 0.9155636
[3,] 0.9497509 0.9497509
[4,] 1.0706620 1.0706620
[5,] 0.9901852 0.9901852
[6,] 0.9307072 0.9307072

Related

How to generate two sets of distinct points on a sphere in julia language?

I need to apply the PCA at different points of a spherical cap, but I don’t know how to build these sets of different points, I need at least 2 sets.
Here is a picture with the idea of what I need.
Spherical Cap
If I correctly understand, here is how I would do in R.
library(uniformly)
library(pracma)
library(rgl)
# sample points on a spherical cap
points_on_cap1 <- runif_on_sphericalCap(300, r = 2, h = 0.5)
# convert to spherical coordinates
sphcoords1 <- cart2sph(points_on_cap1)
# sample points on a spherical cap
points_on_cap2 <- runif_on_sphericalCap(300, r = 2, h = 0.5)
# rotate them, because this is the same spherical cap as before
points_on_cap2 <- rotate3d(points_on_cap2, 3*pi/4, 1, 1, 1)
# convert to spherical coordinates
sphcoords2 <- cart2sph(points_on_cap2)
# 3D plot
spheres3d(0, 0, 0, radius = 2, alpha = 0.5, color = "yellow")
points3d(points_on_cap1, color = "blue")
points3d(points_on_cap2, color = "red")
# 2D plot (of the spherical coordinates)
plot(
sphcoords1[, 1:2], xlim = c(-pi, pi), ylim = c(-pi/2, pi/2),
pch = 19, col = "blue"
)
points(sphcoords2[, 1:2], pch = 19, col = "red")
Do I understand?
Here is the function runif_on_sphericalCap:
function(n, r = 1, h){
stopifnot(h > 0, h < 2*r)
xy <- runif_in_sphere(n, 2L, 1)
k <- h * apply(xy, 1L, crossprod)
s <- sqrt(h * (2*r - k))
cbind(s*xy, r-k)
}
It always samples on a spherical cap with symmetry axis joining the center of the sphere to the North pole. That is why I do a rotation, to get another spherical cap.
Say me if I understand and I'll try to help you to convert the code to Julia.
EDIT: Julia code
using Random, Distributions, LinearAlgebra
function runif_in_sphere(n::I, d::I, r::R) where {I<:Integer, R<:Number}
G = Normal()
sims = rand(G, n, d)
norms = map(norm, eachrow(sims))
u = rand(n) .^ (1/d)
return r .* u .* broadcast(*, 1 ./ norms, sims)
end
function runif_on_sphericalCap(n::I, r::Number, h::Number) where {I<:Integer}
if h <= 0 || h >= 2*r
error("")
end
xy = runif_in_sphere(n, 2, 1.0)
k = h .* map(x -> dot(x,x), eachrow(xy))
s = sqrt.(h .* (2*r .- k))
return hcat(broadcast(*, s, xy), r .- k)
end

I'm stuck with GurobiError: Unable to convert argument to an expression

Could you help me with the
GurobiError: Unable to convert argument to an expression
I tried to declare variables as single variables (e.g x1, x2, x3 etc.), but then I thought the iterable objects will work better (as there was 'Non-itereable object' error), but still Gurobi cannot convert the expression; It now only throws an error at the #96, but I still can't find What should I do?
My code:
import gurobipy as grb
f = [5.5, 5.2, 5]
s = 3.8
lX = [0, 0, 0]
uX = [45000, 4000, 1000000]
lV = [0, 0]
lY = [0, 0]
uY = [1000000, 30000]
r = [3.25, 3.4]
pProc = 0.35
pConv = 0.25
p = [5.75, 4.0]
OreProcessingModel = grb.Model(name="MIP Model")
OreProcessingModel.ModelSense = grb.GRB.MAXIMIZE
x = {i: OreProcessingModel.addVar(vtype=grb.GRB.CONTINUOUS,
lb=lX[i],
ub= uX[i],
name="x_{0}".format(i))
for i in range(3)}
v = {i: OreProcessingModel.addVar(vtype=grb.GRB.CONTINUOUS,
lb=lV[i],
name="v_{0}".format(i))
for i in range(2)}
y = {i: OreProcessingModel.addVar(vtype=grb.GRB.CONTINUOUS,
lb=lY[i],
ub=uY[i],
name="v_{0}".format(i))
for i in range(2)}
conv = OreProcessingModel.addVar(vtype=grb.GRB.CONTINUOUS, lb=0, ub=50000, name="conv")
vlms2 = [v[0], v[1]]
vlmsitrtr = 2
constraint_1 = {1:
OreProcessingModel.addConstr(
lhs=grb.quicksum(y[i] for i in range(2)),
sense=grb.GRB.LESS_EQUAL,
rhs=100000,
name="constraint_{1}")
}
constraint_2 = {1:
OreProcessingModel.addConstr(
lhs=grb.quicksum(v[i] for i in range(2)),
sense=grb.GRB.LESS_EQUAL,
rhs=50000,
name="constraint_{2}")
}
OreProcessingModel.setObjective(grb.quicksum((f[i] * x[i] + s * v[i]) - (y[i]*r[i] + pProc*(y[i]) + pConv*conv))for i in range(3))
OreProcessingModel.optimize()
print(OreProcessingModel)
You should not work with dictionaries like that. You can turn this code
x = {i: OreProcessingModel.addVar(vtype=grb.GRB.CONTINUOUS,
lb=lX[i],
ub= uX[i],
name="x_{0}".format(i))
for i in range(3)}
into this:
x = OreProcessingModel.addVars(len(lX), vtype=grb.GRB.CONTINUOUS, lb=lX, ub=uX, name="x")
Furthermore, the dimensions of your variables don't match. You are looping over range(3) in the setObjective() call and try to access v[i] and y[i] but these dicts are only of length 2.

Random walk simulation in python 3.6

I have been trying to simulate a random walk using the code below
import random
def random_walk(n):
""" Return coordiantes after 'n' block random walk"""
x, y = 0, 0
# y = 0
for i in range(n):
(dx, dy) = random.choice([(0, 1), (0, -1), (1, 0), (-1, 0)])
x = x+dx
y = y+dy
return(x, y)
for i in range(25):
walk = random_walk(10)
print(walk, "Distance from origin:",
abs(walk[0]) + abs(walk[1]))
I am always getting output as 1.No matter how much i increase number of walks or
number of blocks walked.I am not able to figure out what am i doing wrong
Just an indenting problem in the first for loop.
import random
def random_walk(n):
""" Return coordiantes after 'n' block random walk"""
x, y = 0, 0
# y = 0
for i in range(n):
(dx, dy) = random.choice([(0, 1), (0, -1), (1, 0), (-1, 0)])
x = x+dx
y = y+dy
return(x, y)
for i in range(25):
walk = random_walk(10)
print(walk, "Distance from origin:", abs(walk[0]) + abs(walk[1]))

Utilizing Quadratic Equation to Output Roots or Message saying Undefinable

Finding quadratic roots:
import math
def main():
print "Hello! This program finds the real solutions to a quadratic"
print
a, b, c = input("Please enter the coefficients (a, b, c): ")
d = (b**2) - (4*a*c) # finding the discriminant
if d < 0:
d = -d
else:
print "This quadratic equation does not have imaginary roots"
return
dRoot = math.sqrt(d)
root1r = (-b) / (2 * a)
root1i = dRoot / (2 * a)
root2r = root1r
root2i = -root1i
print "%s+%si , %s+%si" % (root1r, root1i, root2r, root2i)
print
main()
sample:::
a, b, c
0.0, 0.0, 0.0
0.0, 0.0, 1.0
0.0, 2.0, 4.0
1.0, 2.0, 1.0
1.0, -5.0, 6.0
1.0, 2.0, 3.0,
Need help making a quadratic equation that can help me find the square root(s) or outputing a message saying that the root cannot be found/ or it is undefinable. Using the given a, b, c as examples to finding root(s) or prompting a message. That is what i have,

Ordered Probit in Jags Using scaled inverse wishart

I am trying to use the following code (adapted from the code given in Gelman and Hill's Book) to estimate a varying coefficient/intercept ordered probit model in Jags. However, it is giving me a "Observed node inconsistent with unobserved parents at initialization.Try setting appropriate initial values". Where am I going wrong? Could somebody please help me? Thanks in advance !!
rm(list=ls(all=TRUE));
options(warn=-1)
library(mvtnorm)
library(arm)
library(foreign)
library("R2jags")
library(MCMCpack)
set.seed(1)
standardizeCols = function( dataMat ) {
zDataMat = dataMat
for ( colIdx in 1:NCOL( dataMat ) ) {
mCol = mean( dataMat[,colIdx] )
sdCol = sd( dataMat[,colIdx] )
zDataMat[,colIdx] = ( dataMat[,colIdx] - mCol ) / sdCol
}
return( zDataMat )
}
keep<-1
nobs = 150;
nis<-sample(1:40,nobs,replace=T) # number obs per subject
id<-rep(1:nobs,nis)
N<-length(id)
corr_beta = 0.6;
Sigma_beta = matrix(c(1, corr_beta, corr_beta, corr_beta,
corr_beta, 1, corr_beta, corr_beta,
corr_beta, corr_beta, 1, corr_beta,
corr_beta, corr_beta, corr_beta, 1), ncol=4);
betas <- rmvnorm(n=N, mean=c(-1.45, 0.90, 0.25, -2.3), sigma=Sigma_beta);
#Generate the data
x3 = matrix(0, nrow=N,ncol=3);
y3 = matrix(0, nrow=N,ncol=1);
for (i in 1:N) {
error_v = rnorm(1,0,1);
x3[i,1] = rnorm(1,0,1);
x3[i,2] = rnorm(1,0,1);
x3[i,3] = rnorm(1,0,1);
y3[i,1] = betas[id[i], 1] + betas[id[i], 2]*x3[i,1] + betas[id[i], 3]*x3[i,2] + betas[id[i], 4]*x3[i,3] + error_v;
}
cutoff=c(-100, 0, 1.5, 2.4, 100)
k=length(cutoff)-1;
Y3<-cut(y3, br = cutoff, right=TRUE, include.lowest = TRUE, labels = FALSE)
Y3=Y3
X3=x3
m1=max(Y3)
y = as.vector( Y3 )
n = length(y)
J<-length(unique(id))
X = cbind(1, standardizeCols( X3 ))
nPred = NCOL(X)
subjects<-as.vector(as.numeric(id))
K=nPred
W <- diag (K)
# MCMC settings
ni <- 5000; nb <- 2500; nt <- 6; nc <- 3
tau1u=c(0,1,2)
jags_data <- list ("n", "J", "K", "y", "subjects", "X", "W", "m1")
inits <- function (){
list (B.raw=array(rnorm(J*K),c(J,K)), mu.raw=rnorm(K), sigma.y=runif(1), Tau.B.raw=rwish(K+1,diag(K)), xi=runif(K))
}
params <- c ("B", "mu", "sigma.B", "rho.B", "tau1u")
cat("model {
for (i in 1:n){
y.hat[i] <- inprod(B[subjects[i],],X[i,])
y[i] ~ dcat(p[i,])
estar[i]~dnorm (y.hat[i], tau.y);
for (j in 1:(m1-1)) {
Q1[i,j]<-pnorm(tau1[j]-estar[i],0,1)
}
p[i,1] <- Q1[i,1]
for(j in 2:(m1-1)) {
p[i,j] <- Q1[i,j] - Q1[i,j-1]
}
p[i,m1] <- 1 - Q1[i,m1-1]
}
tau.y <- pow(sigma.y, -2)
sigma.y ~ dunif (0, 100)
# thresholds (unordered priors)
for(j in 1:(m1-1)){
tau1u[j] ~ dnorm(0,.01)
}
# ordered thresholds
tau1 <- sort(tau1u)
for (j in 1:J){
for (k in 1:K){
B[j,k] <- xi[k]*B.raw[j,k]
}
B.raw[j,1:K] ~ dmnorm (mu.raw[], Tau.B.raw[,])
}
for (k in 1:K){
mu[k] <- xi[k]*mu.raw[k]
mu.raw[k] ~ dnorm (0, .0001)
xi[k] ~ dunif (0, 100)
}
Tau.B.raw[1:K,1:K] ~ dwish (W[,], df)
df <- K+1
Sigma.B.raw[1:K,1:K] <- inverse(Tau.B.raw[,])
for (k in 1:K){
for (k.prime in 1:K){
rho.B[k,k.prime] <- Sigma.B.raw[k,k.prime]/sqrt(Sigma.B.raw[k,k]*Sigma.B.raw[k.prime,k.prime])
}
sigma.B[k] <- abs(xi[k])*sqrt(Sigma.B.raw[k,k])
}
}", fill=TRUE, file="wishart2.txt")
# Start Gibbs sampler
outj <- jags(jags_data, inits=inits, parameters.to.save=params, model.file="wishart2.txt", n.thin=nt, n.chains=nc, n.burnin=nb, n.iter=ni)
Your initial values function returns random numbers from normal and uniform distributions, which it appears are not close enough to sensible values to allow a non-0 posterior value to be calculated. I think you need to choose your initial values more carefully, and perhaps based on the values generated in the data, to ensure that the model compiles. Do Gelman and Hill give initial values for their model that you could start with?
Update: you could also try removing your 'inits=inits' argument to allow JAGS to select its own initial values, which works for most (although not all) models. I dont use R2JAGS though so I'm not sure if this is allowed for the jags function (but it is for rjags and runjags).

Resources