Skip to content

Commit fe44bd8

Browse files
Changed GP Package to DiceKriging
1 parent 5ece4b3 commit fe44bd8

File tree

10 files changed

+164
-99
lines changed

10 files changed

+164
-99
lines changed

R/addIterations.R

Lines changed: 61 additions & 60 deletions
Original file line numberDiff line numberDiff line change
@@ -23,12 +23,12 @@
2323
#' @param gsPoints Same as bayesOpt()
2424
#' @param convThresh Same as bayesOpt()
2525
#' @param acqThresh Same as bayesOpt()
26+
#' @param errorHandling Same as bayesOpt()
2627
#' @param saveFile Same as bayesOpt()
2728
#' @param parallel Same as bayesOpt()
2829
#' @param plotProgress Same as bayesOpt()
2930
#' @param verbose Same as bayesOpt()
3031
#' @param ... Same as bayesOpt()
31-
#' @importFrom crayon make_style red
3232
#' @return A \code{bayesOpt} object.
3333
#' @export
3434
addIterations <- function(
@@ -43,9 +43,10 @@ addIterations <- function(
4343
, gsPoints = optObj$optPars$gsPoints
4444
, convThresh = optObj$optPars$convThresh
4545
, acqThresh = optObj$optPars$acqThresh
46+
, errorHandling = "stop"
4647
, saveFile = optObj$saveFile
4748
, parallel = FALSE
48-
, plotProgress = TRUE
49+
, plotProgress = FALSE
4950
, verbose = 1
5051
, ...
5152
) {
@@ -61,11 +62,13 @@ addIterations <- function(
6162
, otherHalting
6263
, acq
6364
, acqThresh
65+
, errorHandling
6466
, plotProgress
6567
, parallel
6668
, verbose
6769
)
6870

71+
optObj$stopStatus <- "OK"
6972
optObj <- changeSaveFile(optObj,saveFile)
7073
otherHalting <- formatOtherHalting(otherHalting)
7174

@@ -78,7 +81,6 @@ addIterations <- function(
7881
if(parallel) Workers <- getDoParWorkers() else Workers <- 1
7982
iters.s <- nrow(scoreSummary)
8083
iters.t <- iters.n + iters.s
81-
returnEarly <- crayon::make_style("#FF6200")
8284

8385
# Store information we know about the different acquisition functions:
8486
# Display name
@@ -117,33 +119,43 @@ addIterations <- function(
117119

118120
Epoch <- Epoch + 1
119121

120-
if (verbose > 0) cat("\nStarting Epoch",Epoch)
122+
if (verbose > 0) cat("\nStarting Epoch",Epoch,"\n")
121123

122124
# How many runs to make this session
123125
runNew <- pmin(iters.t-nrow(scoreSummary), iters.k)
124126

125127
# Fit GP
126-
if (verbose > 0) cat("\n 1) Fitting Gaussian Process...")
127-
optObj <- updateGP(optObj,bounds = bounds, verbose = 0, ...)
128+
if (verbose > 0) cat(" 1) Fitting Gaussian Process...\n")
129+
optObj <- updateGP(optObj,bounds = bounds, verbose = 0,...)
130+
131+
# See if updateGP altered the stopStatus.
132+
# If so, the km() failed and we need to return optObj
133+
if (optObj$stopStatus != "OK") {
134+
printStopStatus(optObj,verbose)
135+
optObj$elapsedTime <- totalTime(optObj,startT)
136+
return(optObj)
137+
}
128138

129139
# Find local optimums of the acquisition function
130-
if (verbose > 0) cat("\n 2) Running local optimum search...")
140+
if (verbose > 0) cat(" 2) Running local optimum search...")
131141
tm <- system.time(
132142
LocalOptims <- getLocalOptimums(
133143
optObj
134144
, parallel=parallel
135145
, verbose=verbose
136146
)
137147
)[[3]]
138-
if (verbose > 0) cat(" ",tm,"seconds")
148+
if (verbose > 0) cat(" ",tm,"seconds\n")
139149

140150
# Should we continue?
141151
if (otherHalting$minUtility > max(LocalOptims$gpUtility)) {
142-
optObj$stopStatus <- paste0("Could not meet minimum required (",otherHalting$minUtility,") utility.")
152+
optObj$stopStatus <- makeStopEarlyMessage(paste0("Returning Results. Could not meet minimum required (",otherHalting$minUtility,") utility."))
153+
printStopStatus(optObj,verbose)
143154
optObj$elapsedTime <- totalTime(optObj,startT)
144155
return(optObj)
145156
} else if (otherHalting$timeLimit < totalTime(optObj,startT)) {
146-
optObj$stopStatus <- paste0("Time Limit - ",otherHalting$timeLimit," seconds.")
157+
optObj$stopStatus <- makeStopEarlyMessage(paste0("Time Limit - ",otherHalting$timeLimit," seconds."))
158+
printStopStatus(optObj,verbose)
147159
optObj$elapsedTime <- totalTime(optObj,startT)
148160
return(optObj)
149161
}
@@ -164,67 +176,51 @@ addIterations <- function(
164176
, timeGP = optObj$GauProList$timeGP
165177
)
166178
if(any(class(nextPars) == "stopEarlyMsg")) {
167-
cat(returnEarly(nextPars))
168-
optObj$stopStatus <- paste0("Error in getNextParameters: ",nextPars)
179+
optObj$stopStatus <- nextPars
180+
printStopStatus(optObj,verbose)
169181
optObj$elapsedTime <- totalTime(optObj,startT)
170182
return(optObj)
171183
}
172184

173185
# Try to run the scoring function. If not all (but at least 1) new runs fail,
174186
# then foreach cannot call rbind correctly, and an error is thrown.
175-
if (verbose > 0) cat("\n 3) Running FUN",nrow(nextPars),"times in",Workers,"thread(s)...")
187+
if (verbose > 0) cat(" 3) Running FUN",nrow(nextPars),"times in",Workers,"thread(s)...")
176188
sink(file = sinkFile)
177189
tm <- system.time(
178-
NewResults <- tryCatch(
179-
{
180-
foreach(
181-
iter = 1:nrow(nextPars)
182-
, .options.multicore = list(preschedule=FALSE)
183-
, .combine = rbind
184-
, .multicombine = TRUE
185-
, .inorder = FALSE
186-
, .errorhandling = 'pass'
187-
#, .packages = packages
188-
, .verbose = FALSE
189-
#, .export = export
190-
) %op% {
191-
192-
Params <- nextPars[get("iter"),boundsDT$N,with=FALSE]
193-
Elapsed <- system.time(Result <- do.call(what = FUN, args = as.list(Params)))
194-
return(data.table(nextPars[get("iter"),], Elapsed = Elapsed[[3]], as.data.table(Result)))
195-
196-
}
190+
NewResults <- foreach(
191+
iter = 1:nrow(nextPars)
192+
, .options.multicore = list(preschedule=FALSE)
193+
, .combine = rbindFE
194+
, .multicombine = TRUE
195+
, .inorder = FALSE
196+
, .errorhandling = 'stop'
197+
, .verbose = FALSE
198+
) %op% {
199+
200+
Params <- nextPars[get("iter"),boundsDT$N,with=FALSE]
201+
Elapsed <- system.time(
202+
Result <- tryCatch(
203+
{
204+
do.call(what = FUN, args = as.list(Params))
205+
}
206+
, error = function(e) e
207+
)
208+
)
209+
210+
if (!any(class(Result) %in% c("simpleError","error","condition"))) {
211+
return(data.table(nextPars[get("iter"),], Elapsed = Elapsed[[3]], as.data.table(Result),errorMessage = NA))
212+
} else {
213+
return(data.table(nextPars[get("iter"),], Elapsed = Elapsed[[3]],Score = NA, errorMessage = conditionMessage(Result)))
197214
}
198-
, error = function(e) e
199-
)
215+
216+
}
200217
)[[3]]
201218
while (sink.number() > 0) sink()
202219

203-
if (verbose > 0) cat(" ",tm,"seconds\n")
220+
# Leaves room for flexability in the future.
221+
optObj$stopStatus <- getEarlyStoppingErrorStatus(NewResults,scoreSummary,errorHandling,verbose)
204222

205-
# Check for errors.
206-
if (!is.data.table(NewResults)) {
207-
208-
if (class(NewResults) %in% c("simpleError","Error","condition")) {
209-
er <- conditionMessage(NewResults)
210-
if (verbose > 0) {
211-
cat(returnEarly("\nAn error occured in FUN:",er))
212-
cat(returnEarly(" If this error is about inconsist column counts, it may mean that FUN failed in at least 1, but not all runs."))
213-
cat(returnEarly(" If you can verify that this is not an error in FUN, please submit an issue to: https://github.com/AnotherSamWilson/ParBayesianOptimization/issues."))
214-
cat(returnEarly(" Returning results so far."))
215-
}
216-
optObj$stopStatus <- paste0("Error in FUN: ",er)
217-
optObj$elapsedTime <- totalTime(optObj,startT)
218-
return(optObj)
219-
} else if(class(NewResults) == "matrix") {
220-
# foreach returns a matrix of errors if running FUN >1 times.
221-
cat(returnEarly("\nFUN returned all errors: ",NewResults[1,]$message,"."),sep = "")
222-
optObj$stopStatus <- paste0("Error in FUN: ",NewResults[1,]$message)
223-
optObj$elapsedTime <- totalTime(optObj,startT)
224-
return(optObj)
225-
}
226-
227-
}
223+
if (verbose > 0) cat(" ",tm,"seconds\n")
228224

229225
# Print updates on parameter-score search
230226
if (verbose > 1) {
@@ -260,9 +256,14 @@ addIterations <- function(
260256
# Plotting
261257
if(plotProgress) plot(optObj)
262258

263-
}
259+
# Check for change in stop status before we continue.
260+
if (optObj$stopStatus != "OK") {
261+
printStopStatus(optObj,verbose)
262+
optObj$elapsedTime <- totalTime(optObj,startT)
263+
return(optObj)
264+
}
264265

265-
optObj$stopStatus <- "OK"
266+
}
266267

267268
return(optObj)
268269

R/applyNoise.R

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ applyNoise <- function(
99
tries <- 1
1010
noiseAdd <- 0.04
1111

12-
while(tries <= 95) {
12+
while(TRUE) {
1313

1414
noiseAdd <- noiseAdd + 0.01
1515

@@ -31,9 +31,15 @@ applyNoise <- function(
3131

3232
# If we have tried enough times, return a message to stop the process early and return results so far.
3333
if (tries >= 100) {
34-
msg <- "\n\nCould not apply noise to get enough random new parameter sets. Increase noiseAdd or decerase bulkNew. Stopping process and returning results so far."
35-
class(msg) <- "stopEarlyMsg"
36-
return(msg)
34+
return(
35+
makeStopEarlyMessage(
36+
paste0(
37+
"Stopping process and returning results so far. "
38+
, "Could not apply noise to get enough random new parameter sets. "
39+
, "This happens if all of your parameters are integers. Try decreasing iters.k"
40+
)
41+
)
42+
)
3743
}
3844

3945
tries <- tries + 1

R/bayesOpt.R

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,11 @@
6868
#' If 1.0, only the global optimum will be used as a candidate
6969
#' parameter set. If 0.5, only local optimums with 50 percent of the utility
7070
#' of the global optimum will be used.
71+
#' @param errorHandling If FUN returns an error, how to proceed. All errors are
72+
#' stored in \code{scoreSummary}. Can be one of 3 options: "stop" stops the
73+
#' function running and returns results. "continue" keeps the process running.
74+
#' Passing an integer will allow the process to continue until that many errors
75+
#' have occured, after which the results will be returned.
7176
#' @param plotProgress Should the progress of the Bayesian optimization be
7277
#' printed? Top graph shows the score(s) obtained at each iteration.
7378
#' The bottom graph shows the estimated utility of each point.
@@ -190,7 +195,8 @@ bayesOpt <- function(
190195
, gsPoints = pmax(100,length(bounds)^3)
191196
, convThresh = 1e8
192197
, acqThresh = 1.000
193-
, plotProgress = TRUE
198+
, errorHandling = "stop"
199+
, plotProgress = FALSE
194200
, verbose = 1
195201
, ...
196202
) {
@@ -218,6 +224,7 @@ bayesOpt <- function(
218224
, otherHalting
219225
, acq
220226
, acqThresh
227+
, errorHandling
221228
, plotProgress
222229
, parallel
223230
, verbose
@@ -293,6 +300,7 @@ bayesOpt <- function(
293300
scoreSummary[,("Epoch") := rep(0,nrow(scoreSummary))]
294301
scoreSummary[,("Iteration") := 1:nrow(scoreSummary)]
295302
scoreSummary[,("inBounds") := rep(TRUE,nrow(scoreSummary))]
303+
scoreSummary[,("errorMessage") := rep(NA,nrow(scoreSummary))]
296304
extraRet <- setdiff(names(scoreSummary),c("Epoch","Iteration",boundsDT$N,"inBounds","Elapsed","Score","gpUtility","acqOptimum"))
297305
setcolorder(scoreSummary,c("Epoch","Iteration",boundsDT$N,"gpUtility","acqOptimum","inBounds","Elapsed","Score",extraRet))
298306

@@ -314,10 +322,11 @@ bayesOpt <- function(
314322
optObj$scoreSummary <- scoreSummary
315323
optObj$GauProList$gpUpToDate <- FALSE
316324
optObj$iters <- nrow(scoreSummary)
325+
optObj$stopStatus <- "OK"
317326
optObj$elapsedTime <- as.numeric(difftime(Sys.time(),startT,units = "secs"))
318327

319328
# Save Intermediary Output
320-
saveSoFar(optObj,verbose)
329+
saveSoFar(optObj,0)
321330

322331
optObj <- addIterations(
323332
optObj
@@ -326,6 +335,7 @@ bayesOpt <- function(
326335
, iters.k = iters.k
327336
, parallel = parallel
328337
, plotProgress = plotProgress
338+
, errorHandling = errorHandling
329339
, saveFile = saveFile
330340
, verbose = verbose
331341
, ...

R/changeSaveFile.R

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -13,11 +13,6 @@ changeSaveFile <- function(optObj,saveFile = NULL) {
1313
# See if saveFile can be written to.
1414
if (!is.null(saveFile)) {
1515
if (toupper(substr(saveFile, nchar(saveFile)-4+1, nchar(saveFile))) != ".RDS") stop("saveFile is saved as an RDS using saveRDS() - please change file extension in saveFile parameter.")
16-
if (file.access(saveFile,mode=2) != 0) {
17-
message("saveFile is not writeable according to file.access(). Continue? [y/n]")
18-
line <- readline()
19-
if (tolower(line) == "y") invisible() else stop("Process Stopped by User.")
20-
}
2116
}
2217
optObj$saveFile <- saveFile
2318
return(optObj)

R/getLocalOptimums.R

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -99,10 +99,10 @@ getLocalOptimums <- function(
9999

100100
# Checking for convergence
101101
if (tryN >= 4) {
102-
if (verbose > 0) cat("\n - Maximum convergence attempts exceeded - process is probably sampling random points.")
102+
if (verbose > 0) cat("\n - Maximum convergence attempts exceeded - process is probably sampling random points.")
103103
continue <- FALSE
104104
} else if (max(LocalOptims$gpUtility) < acqN$base | !any(LocalOptims$gradCount > 2)) {
105-
if (verbose > 0) cat("\n - Convergence Not Found. Trying again with tighter parameters...")
105+
if (verbose > 0) cat("\n - Convergence Not Found. Trying again with tighter parameters...")
106106
gsPoints <- gsPoints * (tryN + 1)
107107
convThresh <- reduceThresh(convThresh)
108108
continue <- TRUE

R/getNextParameters.R

Lines changed: 15 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -52,29 +52,31 @@ getNextParameters <- function(
5252
while(procure > 0 & tries <= 1000) {
5353

5454
if (tries >= 1000) {
55-
msg <- "\n\nNoise could not be added to find unique parameter set. Stopping process and returning results so far."
56-
class(msg) <- "stopEarlyMsg"
57-
return(msg)
55+
return(
56+
makeStopEarlyMessage("Noise could not be added to find unique parameter set. Stopping process and returning results so far.")
57+
)
5858
}
5959

6060
# Only replace custers that are not duplicates.
6161
fromNoise <- applyNoise(
62-
candidateParameters
63-
, boundsDT
62+
tabl = candidateParameters
63+
, boundsDT = boundsDT
6464
)
6565

6666
# Pass stopping message if that is what applyNoise returned
6767
if(any(class(fromNoise) == "stopEarlyMsg")) return(fromNoise)
6868

6969
# Calculate the utility at these spots.
70-
fromNoise$gpUtility <- calcAcq(
71-
fromNoise[,boundsDT$N,with=FALSE]
72-
, scoreGP
73-
, timeGP
74-
, acq
75-
, 1
76-
, kappa
77-
, eps
70+
fromNoise$gpUtility <- apply(
71+
fromNoise[,boundsDT$N,with=FALSE]
72+
, MARGIN = 1
73+
, calcAcq
74+
, scoreGP = scoreGP
75+
, timeGP = timeGP
76+
, acq = acq
77+
, y_max = 1
78+
, kappa = kappa
79+
, eps = eps
7880
)
7981

8082
fromNoise$gpUtility <- fromNoise$gpUtility - acqN$base

0 commit comments

Comments
 (0)