require(dbarts)
## Loading required package: dbarts
set.seed(1)

X <- matrix(rnorm(500*2),500,2)
X2 <- matrix(rnorm(500*2),500,2)
X2[,2] = X[,2]

gam <- 0.25*(sin((X[,1]+X[,2])*pi)+X[,1])
Y <- as.numeric(gam+rnorm(500) > 0)

dbf <- dbarts(Y~., data.frame(Y=Y, X=X), test=X2)
bartfit <- dbf$run()

# Current state
str(dbf$state)
## Formal class 'dbartsState' [package "dbarts"] with 6 slots
##   ..@ fit.tree   : num [1:500, 1:200] -0.152 -0.152 -0.152 -0.152 -0.152 ...
##   ..@ fit.total  : num [1:500] -0.264 0.336 -0.109 0.821 0.212 ...
##   ..@ fit.test   : num [1:500] 0.519 0.682 -0.109 0.697 -0.174 ...
##   ..@ sigma      : num 1
##   ..@ runningTime: num 2.55
##   ..@ trees      : chr [1:200] "1 28 .." "0 89 .." "1 27 .." "1 93 0 89 ..." ...
# Update 1st column of train to match test
# Setting updateState != NA doesn't seem to change behavior in the following
dbf$setPredictor(X2[,1], 1, updateState=TRUE)

# fit.test & fit.total should be the same now, but aren't (fit.total hasn't
# been updated)
str(dbf$state)
## Formal class 'dbartsState' [package "dbarts"] with 6 slots
##   ..@ fit.tree   : num [1:500, 1:200] -0.152 -0.152 -0.152 -0.152 -0.152 ...
##   ..@ fit.total  : num [1:500] -0.264 0.336 -0.109 0.821 0.212 ...
##   ..@ fit.test   : num [1:500] 0.519 0.682 -0.109 0.697 -0.174 ...
##   ..@ sigma      : num 1
##   ..@ runningTime: num 2.55
##   ..@ trees      : chr [1:200] "1 28 .." "0 89 .." "1 27 .." "1 93 0 89 ..." ...
# still not (all) the same after one step, even though the MCMC should use
# new fitted values immediately
onestep = dbf$run(0, 1)
str(dbf$state)
## Formal class 'dbartsState' [package "dbarts"] with 6 slots
##   ..@ fit.tree   : num [1:500, 1:200] -0.169 -0.169 -0.169 -0.169 -0.169 ...
##   ..@ fit.total  : num [1:500] -0.5616 0.7299 -0.6426 0.19 0.0758 ...
##   ..@ fit.test   : num [1:500] 0.814 1.069 -0.643 0.316 0.202 ...
##   ..@ sigma      : num 1
##   ..@ runningTime: num 2.55
##   ..@ trees      : chr [1:200] "1 28 .." "0 89 .." "1 27 .." "1 93 0 89 ..." ...
# After a lot of steps the first elements match at least. But the MCMC is 
# doing the wrong thing until all the in sample predicted values are updated

moresteps = dbf$run(0, 1000)
str(dbf$state)
## Formal class 'dbartsState' [package "dbarts"] with 6 slots
##   ..@ fit.tree   : num [1:500, 1:200] -0.116 0.118 0.118 -0.116 -0.116 ...
##   ..@ fit.total  : num [1:500] -0.0265 -0.1176 -0.1957 0.1692 0.1481 ...
##   ..@ fit.test   : num [1:500] -0.0265 -0.1176 -0.1957 0.1692 0.1481 ...
##   ..@ sigma      : num 1
##   ..@ runningTime: num 4.84
##   ..@ trees      : chr [1:200] "1 48 .." "0 71 .." "1 25 1 5 ..." "1 55 .." ...