JAGS bayesian MCMC but came into this: Error parsing model file: syntax error on line 5 near "=" - bayesian

when I run my jags model, I got this error message :
module glm loaded
Error in jags.model(model.file, data = data, inits = init.values, n.chains = n.chains, :
Error parsing model file:
syntax error on line 5 near "="
And here is my code:
install.packages('R2jags')
install.packages('rjags')
library(rjags)
library('R2jags')
library(lattice)
binomial.model.JAGS = function(){
y ~ dbin(p,n)
p=lambda*mu+rho*(1-mu)
lambda ~ dunif(min = 0.2,max = 1.4)
mu ~ dunif(min = 0,max = 1)
rho ~ dunif(min = 0.1,max = 1.7)
}
n = 100000
y = 30000
data.JAGS = list(y = y, n = n)
inits.JAGS = list(list(lambda=0.8,mu=0.5,rho=0.9))
para.JAGS = c("p", "lambda", "mu", "rho")
fit.JAGS = jags(
data=data.JAGS,inits=inits.JAGS,
parameters.to.save=para.JAGS,
n.chains=1,
n.iter=9000,
n.burnin = 1000,
model.file = binomial.model.JAGS)
I really don't know where it went wrong. Does anybody could help me please? Thank you a lot!!

Just remove all the argument naming in your priors and you should be good to go.
binomial.model.JAGS = function(){
y ~ dbin(p,n)
p=lambda*mu+rho*(1-mu)
lambda ~ dunif(0.2,1.4)
mu ~ dunif(0,1)
rho ~ dunif(0.1,1.7)
}
n = 100000
y = 30000
data.JAGS = list(y = y, n = n)
inits.JAGS = list(list(lambda=0.8,mu=0.5,rho=0.9))
para.JAGS = c("p", "lambda", "mu", "rho")
fit.JAGS = jags(
data=data.JAGS,inits=inits.JAGS,
parameters.to.save=para.JAGS,
n.chains=1,
n.iter=9000,
n.burnin = 1000,
model.file = binomial.model.JAGS)
mu.vect sd.vect 2.5% 25% 50% 75% 97.5%
lambda 0.286 0.025 0.239 0.270 0.287 0.298 0.351
mu 0.936 0.064 0.758 0.930 0.957 0.977 0.996
p 0.300 0.001 0.297 0.299 0.300 0.301 0.303
rho 0.794 0.459 0.114 0.355 0.774 1.166 1.611
deviance 12.799 1.403 11.791 11.883 12.230 13.105 16.491
DIC info (using the rule, pD = var(deviance)/2)
pD = 1.0 and DIC = 13.8
DIC is an estimate of expected predictive error (lower deviance is better).

Related

Error with continuous time simulation. 'Index exceeds the number of array elements (2).'

Im attempting to model a the following continuous time simulation but do not understand why there is an indexing error.
clear all
global Bsm Bsf Jm Jg1 Jf Gc GR Ke Kf Kg Kr Ks Kt L lf mf R g Va Tf
%Model Paramaters
Bsm=0.01; Bsf=1.5; Jm=0.002; Jg1=0.001; Jf=0.0204; Gc=9.95; GR=1.7; R=4; g=9.81;
Ke=0.35; Kf=0.5; Kg=2.0; Kr=0.9; Ks=0.9; Kt=0.35; L=0.1; lf=0.35; mf=0.5; Va=1;
% Define parameters for the simulation
stepsize = 0.1;
comminterval = 0.1;
EndTime = 20;
i = 0;
% Initial conditions
u = 0;
x = [0,0]';
xdot = [0,0]';
for time = 0:stepsize:EndTime
if rem(time,comminterval)==0
i = i+1;
tout(i) = time;
xout(i,:) = x;
xdout(i,:) = xdot;
end
xdot = derivitive(x,u);
x = eulerint(xdot, stepsize, x);
end
figure(1)
clf % clear figure
plot(tout,xout(:,1),'bo-')
xlabel('time [s]')
ylabel('states')
hold on
grid on
plot(tout,xout(:,2),'ro-')
hold off
Index exceeds the number of array elements (2).
Error in derivitive (line 5)
xdot(1,1) = -R/L*x(1)-Ke/L*x(3)+Va/L;`
The function 'derivative' for my dynamic equations I'm attempting to call is as follows:
function xdot = derivitive(x,u);
global Bsm Bsf Jm Jg1 Jf Gc GR Ke Kf Kg Kr Ks Kt L lf mf R g Va Tf
xdot(1,1) = -(R/L)*x(1)-(Ke/L)*x(3)+(Va/L);
xdot(2,1) = x(3);
xdot(3,1) = -Bsm/Jm*x(3)+Bsm/Jm*x(5)+Kt/Jm*x(1);
xdot(4,1) = x(5);
xdot(5,1) = Bsm/Jg1*x(3)-Bsm/Jg1*x(5);
xdot(6,1) = x(7);
xdot(7,1) = -Bsf/Jf*x(7)-mf*lf*g/(2*Jf)*x(4)-mf*lf*g/(2*Jf)*x(6)+Tf/Jf``
Do not understand why there is an indexing error, any help appreciated.

Solve MLE for Vasicek Interest model but constantly run into an error "Error in if (!all(lower[isfixed] <= fixed[isfixed] & fixed[isfixed]..."

I tried to obtain MLEs of the Vasicek function using the following function.
I am running into into the following error constantly and I have no way to solve it. Please help me. Thanks!
Error in if (!all(lower[isfixed] <= fixed[isfixed] & fixed[isfixed] <= :
missing value where TRUE/FALSE needed
Here is the background:
Likelihood function
likehood.Vasicek<-function (theta, kappa, sigma, rt){
n <- NROW(rt)
y <- rt[2:n,] # Take rates other than r0
dt <- 1/12 # Simulated data is monthly
mu <- rt[1:(n-1),]* exp(-kappa*dt) + theta* (1- exp(-kappa*dt)) #Take prior rates for mu calculation
sd <- sqrt((sigma^2)*(1-exp(-2*kappa*dt))/(2*kappa))
pdf_yt <- dnorm(y, mu, sd, log = FALSE)
- sum(log(pdf_yt))
}
Simulating scenarios
IRModeling.Vasicek = function(r0, theta, kappa, sigma, T, N){
M <- T*12 # monthly time step
t <- 1/12 # time interval is monthly
rt = matrix(0, M+1, N) # N sets of scenarios with M months of time steps
rt[1,] <- r0 # set the initial value for each of the N scenarios
for (i in 1:N){
for (j in 1:M){
rt[j+1,i] = rt[j,i] + kappa*(theta - rt[j,i])*t + sigma*rnorm(1,mean=0,sd=1)*sqrt(t)
}
}
rt # Return the values
}
MLE
r0 = 0.03
theta = 0.03
kappa = 0.3
sigma = 0.03
T = 5 # years
N = 500
rt = IRModeling.Vasicek (r0, theta, kappa, sigma, T, N)
theta.est <- 0.04
kappa.est <- 0.5
sigma.est <- 0.02
parameters.est <- c(theta.est, kappa.est, sigma.est)
library(stats4)
bound.lower <- parameters.est*0.1
bound.upper <- parameters.est*2
est.mle<-mle(likelihood.Vasicek, start= list(theta = theta.est, kappa = kappa.est, sigma = sigma.est),
method="L-BFGS-B", lower=bound.lower, upper= bound.upper, fixed = list(rt = rt))
summary(est.mle)
Error
Error in if (!all(lower[isfixed] <= fixed[isfixed] & fixed[isfixed] <= :
missing value where TRUE/FALSE needed

RuntimeWarning: invalid value encountered

I'm trying to make my Philips hue lights change colors based on the Hz of a played song. But i faced a RuntimeWarning and can't figure out whats going on. I'd highly appreciate it if anyone could help me out here :)
wf = wave.open('visualize.wav', 'rb')
swidth = wf.getsampwidth()
RATE = wf.getframerate()
window = np.blackman(chunk)
p = pyaudio.PyAudio()
channels = wf.getnchannels()
stream = p.open(format =
p.get_format_from_width(wf.getsampwidth()),
channels = channels,
rate = RATE,
output = True)
data = wf.readframes(chunk)
print('switdth {} chunk {} data {} ch {}'.format(swidth,chunk,len(data), channels))
while len(data) == chunk*swidth*channels:
stream.write(data)
indata = np.fromstring(data, dtype='int16')
channel0 = indata[0::channels]
fftData=abs(np.fft.rfft(indata))**2
which = fftData[1:].argmax() + 1
if which != len(fftData)-1:
y0,y1,y2 = np.log(fftData[which-1:which+2:])
x1 = (y2 - y0) * .5 / (2 * y1 - y2 - y0)
thefreq = (which+x1)*RATE/chunk
print ("The freq is %f Hz." % (thefreq))
elif thefreq > 4000:
for i in cycle(color_list):
change_light_color(room, *color_list[i])
time.sleep(0.5)
else:
if thefreq < 4000:
for i in cycle(color_list_2):
change_light_color(room, *color_list_2[i])
time.sleep(0.5)
if data:
stream.write(data)
stream.close()
p.terminate()
This is what i end up with:
/usr/local/bin/python3 /Users/Sem/Desktop/hue_visualizer/visualize.py
Sem#Sems-MacBook-Pro hue_visualizer % /usr/local/bin/python3 /Users/Sem/Desktop/hue_visualizer/visualize.py
switdth 2 chunk 1024 data 4096 ch 2
/Users/Sem/Desktop/hue_visualizer/visualize.py:69: DeprecationWarning: The binary mode of fromstring is deprecated, as it behaves surprisingly on unicode inputs. Use frombuffer instead
indata = np.fromstring(data, dtype='int16')
/Users/Sem/Desktop/hue_visualizer/visualize.py:74: RuntimeWarning: divide by zero encountered in log
y0,y1,y2 = np.log(fftData[which-1:which+2:])
/Users/Sem/Desktop/hue_visualizer/visualize.py:75: RuntimeWarning: invalid value encountered in double_scalars
x1 = (y2 - y0) * .5 / (2 * y1 - y2 - y0)
The freq is nan Hz.
The freq is nan Hz.
The freq is nan Hz.
The freq is nan Hz.
The freq is nan Hz.

RGB to HSV in numpy

I'm trying to implement RGB to HSV conversion from opencv in pure numpy using formula from here:
def rgb2hsv_opencv(img_rgb):
img_hsv = cv2.cvtColor(img_rgb, cv2.COLOR_RGB2HSV)
return img_hsv
def rgb2hsv_np(img_rgb):
assert img_rgb.dtype == np.float32
height, width, c = img_rgb.shape
r, g, b = img_rgb[:,:,0], img_rgb[:,:,1], img_rgb[:,:,2]
t = np.min(img_rgb, axis=-1)
v = np.max(img_rgb, axis=-1)
s = (v - t) / (v + 1e-6)
s[v==0] = 0
# v==r
hr = 60 * (g - b) / (v - t + 1e-6)
# v==g
hg = 120 + 60 * (b - r) / (v - t + 1e-6)
# v==b
hb = 240 + 60 * (r - g) / (v - t + 1e-6)
h = np.zeros((height, width), np.float32)
h = h.flatten()
hr = hr.flatten()
hg = hg.flatten()
hb = hb.flatten()
h[(v==r).flatten()] = hr[(v==r).flatten()]
h[(v==g).flatten()] = hg[(v==g).flatten()]
h[(v==b).flatten()] = hb[(v==b).flatten()]
h[h<0] += 360
h = h.reshape((height, width))
img_hsv = np.stack([h, s, v], axis=-1)
return img_hsv
img_bgr = cv2.imread('00000.png')
img_rgb = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2RGB)
img_rgb = img_rgb / 255.0
img_rgb = img_rgb.astype(np.float32)
img_hsv1 = rgb2hsv_np(img_rgb)
img_hsv2 = rgb2hsv_opencv(img_rgb)
print('max diff:', np.max(np.fabs(img_hsv1 - img_hsv2)))
print('min diff:', np.min(np.fabs(img_hsv1 - img_hsv2)))
print('mean diff:', np.mean(np.fabs(img_hsv1 - img_hsv2)))
But I get big diff:
max diff: 240.0
min diff: 0.0
mean diff: 0.18085355
Do I missing something?
Also maybe it's possible to write numpy code more efficient, for example without flatten?
Also I have hard time finding original C++ code for cvtColor function, as I understand it should be actually function cvCvtColor from C code, but I can't find actual source code with formula.
From the fact that the max difference is exactly 240, I'm pretty sure that what's happening is in the case when both or either of v==r, v==g are simultaneously true alongside v==b, which gets executed last.
If you change the order from:
h[(v==r).flatten()] = hr[(v==r).flatten()]
h[(v==g).flatten()] = hg[(v==g).flatten()]
h[(v==b).flatten()] = hb[(v==b).flatten()]
To:
h[(v==r).flatten()] = hr[(v==r).flatten()]
h[(v==b).flatten()] = hb[(v==b).flatten()]
h[(v==g).flatten()] = hg[(v==g).flatten()]
The max difference may start showing up as 120, because of that added 120 in that equation. So ideally, you would want to execute these three lines in the order b->g->r. The difference should be negligible then (still noticing a max difference of 0.01~, chalking it up to some round off somewhere).
h[(v==b).flatten()] = hb[(v==b).flatten()]
h[(v==g).flatten()] = hg[(v==g).flatten()]
h[(v==r).flatten()] = hr[(v==r).flatten()]

Can't figure out, why script on Jython working differently from script on Pascal

Long story short: I'm writing script, which should move mouse and do clicks like human (it's a bot, actually), using SikuliX. SikuliX uses Jython 2.7 as lang for scritps.
I found nice lib for my purposes (moving mouse like human): mouse.simba written in Pascal-like lang, and rewrite function _humanWindMouse() in jython. It works, but not like I expected it would be.
Test run of my script, drawing rectangle:
https://prtscr.cx.ua/storage/5b/5b2203.jpg
Result of using original function with same coords:
https://prtscr.cx.ua/storage/bb/bb3ff5.jpg
sorry for links, I can't post images yet (
My code:
import random
import time
import math
from time import sleep
from math import sqrt
from math import ceil
from math import hypot
from java.awt import Robot
def distance(x1, y1, x2, y2):
return math.hypot(x2 - x1, y2 - y1)
def myrandom(x):
return random.randint(0, x-1)
def myround(x):
return int(round(x))
# function MMouseMove (MyMouseMove) for moving mouse using only coord
def MMouseMove(x,y):
robot = Robot()
robot.mouseMove(x,y)
# function HumanWindMouse by BenLand100 & Flight, python implementation
def humanWindMouse(xs, ys, xe, ye, gravity, wind):
veloX = veloY = windX=windY=veloMag=dist=randomDist=lastDist=D=0
lastX=lastY=MSP=W=TDist=0
mouseSpeed = 20
MSP = mouseSpeed
sqrt2 = sqrt(2)
sqrt3 = sqrt(3)
sqrt5 = sqrt(5)
TDist = distance(myround(xs), myround(ys), myround(xe), myround(ye))
t = time.time() + 10000
while True:
if time.time() > t:
break
dist = hypot(xs - xe, ys - ye)
wind = min(wind, dist)
if dist < 1:
dist = 1
D = (myround((myround(TDist)*0.3))/7)
if D > 25:
D = 25
if D < 5:
D = 5
rCnc = myrandom(6)
if rCnc == 1:
D = random.randint(2,3)
if D <= myround(dist):
maxStep = D
else:
maxStep = myround(dist)
windX= windX / sqrt2
windY= windY / sqrt2
veloX= veloX + windX
veloY= veloY + windY
veloX= veloX + gravity * (xe - xs) / dist
veloY= veloY + gravity * (ye - ys) / dist
if hypot(veloX, veloY) > maxStep:
temp = int(myround(maxStep) // 2)
if temp == 0:
temp = 1
randomDist= maxStep / 2.0 + myrandom(temp)
veloMag= sqrt(veloX * veloX + veloY * veloY)
veloX= (veloX / veloMag) * randomDist
veloY= (veloY / veloMag) * randomDist
lastX= myround(xs)
lastY= myround(ys)
xs= xs + veloX
ys= ys + veloY
if lastX <> myround(xs) or lastY <> myround(ys):
MMouseMove(myround(xs), myround(ys))
W = (myrandom((myround(100/MSP)))*6)
if W < 5:
W = 5
W = myround(W*0.9)
sleep(W/1000.0)
lastdist= dist
if hypot(xs - xe, ys - ye) < 1:
break
if myround(xe) <> myround(xs) or myround(ye) <> myround(ys):
MMouseMove(myround(xe), myround(ye))
mouseSpeed = MSP
return;
def MMouse(x,y):
mouseSpeed = 20
randSpeed = (myrandom(mouseSpeed) / 2.0 + mouseSpeed) / 10.0
curPos = Mouse.at()
x1 = curPos.x
y1 = curPos.y
humanWindMouse(x1, y1, x, y, 5, 10.0/randSpeed)
return;
And I used this in such a way:
MMouseMove(227, 146)
mouseDown(Button.LEFT)
MMouse(396, 146)
MMouse(396, 252)
MMouse(227, 252)
MMouse(227, 146)
mouseUp(Button.LEFT)
exit()
mouseDown() and mouseUp() are built-in functions in SikuliX
And I didn't use built-in mouseMove(), because with it going from A to B is too slow.
Any help would be appreciated
After few hours of debugging i figured out the problem: in source code for unknowing reason author passed constant called MOUSE_HUMAN to variable named gravity when caling his function _humanWindMouse(), this looks like an error to me. Thats why I decided to fix this in my code, and throw out one argument of the function and a few lines of code (and that was wrong move). After re-adding needed code my function working, as I expected.
So, here's the working code:
# function HumanWindMouse by BenLand100 & Flight,
# python implementation by Nokse
def humanWindMouse(xs, ys, xe, ye, gravity, wind, targetArea):
veloX = veloY = windX=windY=veloMag=dist=randomDist=lastDist=D=0
lastX=lastY=MSP=W=TDist=0
mouseSpeed = 20
MSP = mouseSpeed
sqrt2 = sqrt(2)
sqrt3 = sqrt(3)
sqrt5 = sqrt(5)
TDist = distance(myround(xs), myround(ys), myround(xe), myround(ye))
t = time.time() + 10000
while True:
if time.time() > t:
break
dist = hypot(xs - xe, ys - ye)
wind = min(wind, dist)
if dist < 1:
dist = 1
D = (myround((myround(TDist)*0.3))/7)
if D > 25:
D = 25
if D < 5:
D = 5
rCnc = myrandom(6)
if rCnc == 1:
D = random.randint(2,3)
if D <= myround(dist):
maxStep = D
else:
maxStep = myround(dist)
if dist >= targetArea:
windX = windX / sqrt3 + (myrandom(myround(wind) * 2 + 1) - wind) / sqrt5
windY = windY / sqrt3 + (myrandom(myround(wind) * 2 + 1) - wind) / sqrt5
else:
windX = windX / sqrt2
windY = windY / sqrt2
veloX = veloX + windX
veloY = veloY + windY
veloX = veloX + gravity * (xe - xs) / dist
veloY = veloY + gravity * (ye - ys) / dist
if hypot(veloX, veloY) > maxStep:
halfSteps = int(myround(maxStep) // 2)
if halfSteps == 0:
halfSteps = 1
randomDist = maxStep / 2.0 + myrandom(halfSteps)
veloMag = sqrt(veloX * veloX + veloY * veloY)
veloX = (veloX / veloMag) * randomDist
veloY = (veloY / veloMag) * randomDist
lastX = myround(xs)
lastY = myround(ys)
xs = xs + veloX
ys = ys + veloY
if lastX <> myround(xs) or lastY <> myround(ys):
MMouseMove(myround(xs), myround(ys))
W = (myrandom((myround(100/MSP)))*6)
if W < 5:
W = 5
W = myround(W*0.9)
sleep(W/1000.0)
lastdist = dist
#condition for exiting while loop
if hypot(xs - xe, ys - ye) < 1:
break
if myround(xe) <> myround(xs) or myround(ye) <> myround(ys):
MMouseMove(myround(xe), myround(ye))
mouseSpeed = MSP
return;
I tested it with different parameters, and choose this one:
humanWindMouse(xs, ys, x, y, 9, 10.0/randSpeed, 10.0*randSpeed)
but I recommend to play with parameters first, to understand, how do they affect the behavior of the mouse.
How to calc randSpeed, what should be imported, and sub-functions, such as myround(), could be found at my first post.
Hope, this code will help somebody someday)