Optimizing model output using the R project Simile package

Based on the Optimizing model output example using SimileScripting and the Tcllib optimization package math::optimize this post is about reimplmenting the same problem using the R project Simile model package.

 

require("Simile")
path.to.installation <- tcl("tk_chooseDirectory", "-title",
"Folder where Simile is installed:")
use.simile.at(path.to.installation)
 
exec.extn <- as.character(tcl("info","sharedlibextension"))
path.to.dll <- tcl("tk_getOpenFile",
"-title", "Compiled binary for MathOptimize example:",
"-initialfile", paste("spiro",exec.extn,sep=""))
mHandle <- load.model(path.to.dll)
 
objs <- list.objects(mHandle)
for (obj in objs) {
  print(c(obj, get.model.property(mHandle, obj, "Class")))
}
 
hInstance.of.Model <- create.model(mHandle)
# model step is 0.1 by default but MathOptimize only needs 1.0
set.model.step(hInstance.of.Model, 1, 1)
 
# initialize the model, including default slider values
reset.model(hInstance.of.Model, -2)
 
##############################
 
# set up a location for the parameters to be held for x vars
hx <- create.param.array(hInstance.of.Model, "/x") # need to find from helper    todo
set.model.parameter(hx,0.12345)
# apply reset at level 0 to propagate input values
reset.model(hInstance.of.Model, 0)
get.value.array(hInstance.of.Model, "/x")
 
#,hx, hInstance.of.Model
# Create function to run model and return value of variable to optimize
model <- function( val ) {
    set.model.parameter(hx,val)
    
    #reset.model(instance.handle, depth, integration.method, starting.time)
    # last 2 args have default Euler and time 0
    reset.model(hInstance.of.Model, 0)
    
    #execute.model(instance.handle, finish.time, integration.method,start.time,
    #    error.limit, pause.on.event)
    integration.method <- "Euler"
    execute.model(hInstance.of.Model, 1, integration.method)
    y<-get.value.array(hInstance.of.Model, "/y")
    print(val); #y
    return(y)
}
 
# maximise the Simile model output
optimize(model, 1:10, maximum=TRUE)
 

Results


[1] 6.562306
[1] 7.875388
[1] 8.686918
[1] 9.188471
[1] 9.498447
[1] 9.690023
[1] 9.808424
[1] 9.881599
[1] 9.926824
[1] 9.954775
[1] 9.972049
[1] 9.982726
[1] 9.989324
[1] 9.993402
[1] 9.995922
[1] 9.99748
[1] 9.998442
[1] 9.999037
[1] 9.999405
[1] 9.999632
[1] 9.999773
[1] 9.99986
[1] 9.999913
[1] 9.999954
[1] 9.999954
$maximum
[1] 9.999954
 
$objective
[1] 0.04978707