Documentation for the R (http://cran.rproject.org/) package allowing interaction with a Simile model
Documentaion in R formats (PDF and local HTML) are available as part of the installation package but HTML R documentation hard to find on the web . Sodocumentation for the R package allowing interaction with a Simile model is made available here.
Interface to executable Simile models
This package loads, parameterizes, executes and interrogates executable models saved by Simile.
Package:  Simile 
Type:  Package 
Version:  1.2 
Date:  20121011 
License:  Unrestricted 
LazyLoad:  yes 
The package loads some Simile libraries into R's tcltk extension, so you need Simile installed to use it. Initialize the package by calling use.simile.at() to tell it where to find Simile in the file system. Tell it where to find the saved executable model with load.model() which returns a handle to the loaded model. This can be used to interrogate static model info via list.objects() and get.model.property(), and to create executable instances with create.model(), which returns their handles.
An executable instance can be parameterized either by loading a Simile parameter metafile with consult.parameter.metafile(), or directly from R arrays with create.param.array() and set.model.parameter(). The functions set.model.step(), reset.model() and execute.model() control execution. get.model.time() returns the time at which execution finished. Use get.value.array() to get the values from any model component as an R array, or get.value.list() to get them as an R list.
This version works with Simile versions 5.94 on.
Simulistics Ltd
Simile modelling environment: http://simulistics.com
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.spiro < tcl("tk_getOpenFile",
"title", "Compiled binary for Spiro example:",
"initialfile", paste("spiro",exec.extn,sep=""))
mHandle < load.model(path.to.spiro)
objs < list.objects(mHandle)
for (obj in objs) {
print(c(obj, get.model.property(mHandle, obj, "Class")))
}
iHandle < create.model(mHandle)
# model step is 0.1 by default but spiro only needs 1.0
set.model.step(iHandle, 1, 1)
# initialize the model, including default slider values
reset.model(iHandle, 2)
xs < list(get.value.list(iHandle, "/runs/x"))
ys < list(get.value.list(iHandle, "/runs/y"))
for (count in 1:1739) {
execute.model(iHandle, count)
xs[[count+1]] < get.value.list(iHandle, "/runs/x")
ys[[count+1]] < get.value.list(iHandle, "/runs/y")
}
xs < mapply(c,xs)
ys < mapply(c,ys)
print("View default pattern  now try to plot dancer")
plot(xs, ys, type="l")
# now we are going to parameterize it using a state file for the slider helper
#  to make this work we load the mime library, which is needed only because
# the dancer.spf in Simile v5.94 is an older v4.x format file.
tcl("package","require","mime")
pFile < tcl("file", "join", path.to.installation, "Examples", "dancer.spf")
consult.parameter.metafile(iHandle, pFile)
# also the file from the distribution has no value for "Wheel outside?"
# so we set this boolean directly
pHandle < create.param.array(iHandle, "/start/Wheel outside?")
set.model.parameter(pHandle, FALSE)
# apply reset at level 0 to propagate input values
reset.model(iHandle, 0)
xs < list(get.value.list(iHandle, "/runs/x"))
ys < list(get.value.list(iHandle, "/runs/y"))
for (count in 1:419) {
execute.model(iHandle, count)
xs[[count+1]] < get.value.list(iHandle, "/runs/x")
ys[[count+1]] < get.value.list(iHandle, "/runs/y")
}
xs < mapply(c,xs)
ys < mapply(c,ys)
print("OK, but that's not how it looks on Simile is it? Try this...")
plot(xs, ys, type="l")
xs < aperm(xs, c(2,1))
ys < aperm(ys, c(2,1))
plot(xs, ys, type="l")
Parameter metafiles (.spf) saved from within Simile can contain information about a model's parameter values, either locally or as references to other files. They may refer to the whole model or a submodel.
consult.parameter.metafile(instance.handle,param.file,target.submodel="")
instance.handle 
The handle returned by create.model() identifying the model instance. 
param.file 
Location of the parameter metafile. 
target.submodel 
Pathname of the submodel into which the parameters are to be loaded. Default is the top level. 
None
Jasper Taylor
consult.parameter.metafile(instance.handle, "../data/base_vals.spf")
Loads a simile model saved as a compiled binary ( a .dll, .so or .dylib file depending on platform)
load.model(path.to.binary)
path.to.binary 
Absolute or relative path to file to be loaded 
Handle to be used for querying or instantiating model, as a Tcl object
Jasper Taylor
This package loads, parameterizes, executes and interrogates executable models saved by Simile.
Package:  Simile 
Type:  Package 
Version:  1.2 
Date:  20121011 
License:  Unrestricted 
LazyLoad:  yes 
The package loads some Simile libraries into R's tcltk extension, so you need Simile installed to use it. Initialize the package by calling use.simile.at() to tell it where to find Simile in the file system. Tell it where to find the saved executable model with load.model() which returns a handle to the loaded model. This can be used to interrogate static model info via list.objects() and get.model.property(), and to create executable instances with create.model(), which returns their handles.
An executable instance can be parameterized either by loading a Simile parameter metafile with consult.parameter.metafile(), or directly from R arrays with create.param.array() and set.model.parameter(). The functions set.model.step(), reset.model() and execute.model() control execution. get.model.time() returns the time at which execution finished. Use get.value.array() to get the values from any model component as an R array, or get.value.list() to get them as an R list.
This version works with Simile versions 5.94 on.
Simulistics Ltd
Simile modelling environment: http://simulistics.com
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.spiro < tcl("tk_getOpenFile",
"title", "Compiled binary for Spiro example:",
"initialfile", paste("spiro",exec.extn,sep=""))
mHandle < load.model(path.to.spiro)
objs < list.objects(mHandle)
for (obj in objs) {
print(c(obj, get.model.property(mHandle, obj, "Class")))
}
iHandle < create.model(mHandle)
# model step is 0.1 by default but spiro only needs 1.0
set.model.step(iHandle, 1, 1)
# initialize the model, including default slider values
reset.model(iHandle, 2)
xs < list(get.value.list(iHandle, "/runs/x"))
ys < list(get.value.list(iHandle, "/runs/y"))
for (count in 1:1739) {
execute.model(iHandle, count)
xs[[count+1]] < get.value.list(iHandle, "/runs/x")
ys[[count+1]] < get.value.list(iHandle, "/runs/y")
}
xs < mapply(c,xs)
ys < mapply(c,ys)
print("View default pattern  now try to plot dancer")
plot(xs, ys, type="l")
# now we are going to parameterize it using a state file for the slider helper
#  to make this work we load the mime library, which is needed only because
# the dancer.spf in Simile v5.94 is an older v4.x format file.
tcl("package","require","mime")
pFile < tcl("file", "join", path.to.installation, "Examples", "dancer.spf")
consult.parameter.metafile(iHandle, pFile)
# also the file from the distribution has no value for "Wheel outside?"
# so we set this boolean directly
pHandle < create.param.array(iHandle, "/start/Wheel outside?")
set.model.parameter(pHandle, FALSE)
# apply reset at level 0 to propagate input values
reset.model(iHandle, 0)
xs < list(get.value.list(iHandle, "/runs/x"))
ys < list(get.value.list(iHandle, "/runs/y"))
for (count in 1:419) {
execute.model(iHandle, count)
xs[[count+1]] < get.value.list(iHandle, "/runs/x")
ys[[count+1]] < get.value.list(iHandle, "/runs/y")
}
xs < mapply(c,xs)
ys < mapply(c,ys)
print("OK, but that's not how it looks on Simile is it? Try this...")
plot(xs, ys, type="l")
xs < aperm(xs, c(2,1))
ys < aperm(ys, c(2,1))
plot(xs, ys, type="l")
A script can create many independent instances of the same model description, each with its own execution state.
create.model(model.handle)
model.handle 
The handle returned by load.model() identifying the model type. 
A handle to a new instance of the model, which will have its own component values, parameter values and execution settings
Jasper Taylor
If a script is to provide values directly for a Simile model parameter, this command must be called first to set up a location for the parameters to be held
create.param.array(instance.handle,param.name)
instance.handle 
The handle returned by create.model() identifying the model instance. 
param.name 
Caption path to the model component whose value is to be specified 
A handle to the location that has been created.
Jasper Taylor
The model will be executed using the time steps specified by earlier calling set.model.step until either the finish.time is reached or an exception occurs.
execute.model(instance.handle, finish.time, integration.method,
start.time, error.limit, pause.on.event)
instance.handle 
The handle returned by create.model(), identifying an executable model instance. 
finish.time 
Time returned by functions in the model on the last execution step, when incrementing the time takes it to or beyond this value. 
integration.method 
One of "Euler" or "RungeKutta", the latter being 4thorder. Default is "Euler". 
start.time 
Time returned by functions in the model on the first execution step. On each subsequent step this will be incremented by the value specified by earlier calling set.model.step. Default is NA, which starts the model at the time to which it was previously reset or executed. 
error.limit 
Maximum integration error allowed by adaptive step size variation, as a fraction of the allowed range of each model compartment value. The integration error is estimated by comparing each compartment's rate of change with that predicted on the previous time step (equal to its previous rate of change if integration method is Euler). If error limit is exceeded, the time step is temporarily shortened and the model reexecuted from the end of the last time step. Default is 0, in which case no adaptive step size variation is done. 
pause.on.event 
Reserved for future Simile versions with discrete event handling. Default is FALSE. 
Result code: value of system error (ve), userdefined interruption (+ve) or 0 if model runs to finish.time
This function can return any of several pieces of static information about a component in a loaded Simile model
get.model.property(model.handle,caption.path,requested.property)
model.handle 
Model handle created when calling load.model() 
caption.path 
Path made from submodel and component captions separated by forward slashes, like a member of the list returned by list.objects() 
requested.property 
One of the following strings:

Form of returned value depends on the requested.property as described above.
For Class it is one of SUBMODEL VARIABLE COMPARTMENT FLOW CONDITION CREATION REPRODUCTION IMMIGRATION LOSS ALARM EVENT SQUIRT STATE
For Type: one of VALUELESS REAL INTEGER FLAG EXTERNAL or ENUM(n), where n is the index of a set of enumerated type values.
For Eval: one of EXOGENOUS DERIVED TABLE INPUT SPLIT GHOST. Fixed parameters have TABLE and variable parameters INPUT for this property.
For Dims it is a list containing integers or the special types RECORDS MEMBERS SEPARATE START_VM END_VM for components in submodels without a preset member count.
For MinVal and MaxVal it is a number of the same type as the component.
For Desc and Comment it is a character string.
Jasper Taylor
This function returns the current time in a model instance
get.model.time(instance.handle)
instance.handle 
Instance handle created when calling create.model() 
A floatingpoint number giving the model time
Jasper Taylor
The function optimize
searches the interval from lower
to upper
for a minimum or maximum of the function f
with respect to its first argument.
optimise
is an alias for optimize
.
optimize(f = , interval = , ..., lower = min(interval),
upper = max(interval), maximum = FALSE,
tol = .Machine$double.eps^0.25)
optimise(f = , interval = , ..., lower = min(interval),
upper = max(interval), maximum = FALSE,
tol = .Machine$double.eps^0.25)
f 
the function to be optimized. The function is either minimized or maximized over its first argument depending on the value of 
interval 
a vector containing the endpoints of the interval to be searched for the minimum. 
... 
additional named or unnamed arguments to be passed to 
lower 
the lower end point of the interval to be searched. 
upper 
the upper end point of the interval to be searched. 
maximum 
logical. Should we maximize or minimize (the default)? 
tol 
the desired accuracy. 
Note that arguments after ...
must be matched exactly.
The method used is a combination of golden section search and successive parabolic interpolation, and was designed for use with continuous functions. Convergence is never much slower than that for a Fibonacci search. If f
has a continuous second derivative which is positive at the minimum (which is not at lower
or upper
), then convergence is superlinear, and usually of the order of about 1.324.
The function f
is never evaluated at two points closer together than eps * x_0 + (tol/3), where eps is approximately sqrt(.Machine$double.eps)
and x_0 is the final abscissa optimize()$minimum
.
If f
is a unimodal function and the computed values of f
are always unimodal when separated by at least eps * x + (tol/3), then x_0 approximates the abscissa of the global minimum of f
on the interval lower,upper
with an error less than eps * x_0+ tol.
If f
is not unimodal, then optimize()
may approximate a local, but perhaps nonglobal, minimum to the same accuracy.
The first evaluation of f
is always at x_1 = a + (1φ)(ba) where (a,b) = (lower, upper)
and phi = (sqrt(5)  1)/2 = 0.61803.. is the golden section ratio. Almost always, the second evaluation is at x_2 = a + phi(ba). Note that a local minimum inside [x_1,x_2] will be found as solution, even when f
is constant in there, see the last example.
f
will be called as f(x, ...)
for a numeric value of x.
A list with components minimum
(or maximum
) and objective
which give the location of the minimum (or maximum) and the value of the function at that point.
A C translation of Fortran code http://www.netlib.org/fmm/fmin.f based on the Algol 60 procedure localmin
given in the reference.
Brent, R. (1973) Algorithms for Minimization without Derivatives. Englewood Cliffs N.J.: PrenticeHall.
require(graphics)
f < function (x,a) (xa)^2
xmin < optimize(f, c(0, 1), tol = 0.0001, a = 1/3)
xmin
## See where the function is evaluated:
optimize(function(x) x^2*(print(x)1), lower=0, upper=10)
## "wrong" solution with unlucky interval and piecewise constant f():
f < function(x) ifelse(x > 1, ifelse(x < 4, exp(1/abs(x  1)), 10), 10)
fp < function(x) { print(x); f(x) }
plot(f, 2,5, ylim = 0:1, col = 2)
optimize(fp, c(4, 20))# doesn't see the minimum
optimize(fp, c(7, 20))# ok
Retrieves data from the model, as either a single quantity or a possibly nested list of values
get.value.list(instance.handle, value.name, as.enum.types)
instance.handle 
The handle returned by create.model(), identifying an executable model instance. 
value.name 
Caption path to the model component whose values are required 
as.enum.types 
Logical: whether to supply indices and values as character strings, using enumerated type members if applicable. Default is false: indices are integers and values are numerical. 
A value or indexvalue list, from the model
Jasper Taylor
> get.value.list(iHandle, "/runs/x", "FALSE")
[[1]]
[1] 40.76668
[[2]]
[1] 37.52907
[[3]]
[1] 33.82021
[[4]]
[1] 29.69413
Lists all the model components with values. Components are specified by path, i.e., a string made from their caption preceded by the caption of their parent submodel, its parent and so on, separated by forwardslashes like a directory path.
list.objects(model.handle)
model.handle 
Model handle created when calling load.model() 
List of component paths as described above, in tree traversal order
Jasper Taylor
A model parameter may be a single value or an array of values. This function allows it to be set.
set.model.parameter(param.handle,data, as.enum.types)
param.handle 
The handle returned by create.param.array() identifying the location to send the data. 
data 
The data to be used in the model, either a single value or an array with the appropriate dimensions 
as.enum.types 
Logical: whether the values are supplied using enumerated type names if applicable. Default is false: values are numerical. 
None
Jasper Taylor
The time step is the amount by which the model time advances each time the state variables are updated. A model may have more than one time step.
set.model.step(instance.handle,step.index,step.size)
instance.handle 
The handle returned by create.model(), identifying an executable model instance. 
step.index 
The level of the time step to be set. If a model only has one time step, this is step 1. Higher levels are set to shorter steps. 
step.size 
The duration for the time step. 
None
Jasper Taylor
Convert a set of values from a Simile model component from a nested list of alternating indices and values to an R array structure
tcl.paired.to.array(paired, dims, as.enum.types)
paired 
Nested list of alternating indices and values 
dims 
Dimensions of R array structure 
as.enum.types 
If TRUE, values will be converted to R character strings, otherwise they are numeric 
A numerical value or array of numerical values, from the Tcl value or array
Note that the dimensions of the array returned will be in the opposite order from those supplied in the 'dims' argument. This is because Simile's convention is to list the outermost dimension first, whereas R's is to list the outermost dimension last.
Jasper Taylor
Simile:::tcl.paired.to.array("1 {1 7 2 4} 2 {1 8 2 6} 3 {1 9 2 1}",
c(3,2), FALSE)
# [,1] [,2] [,3]
#[1,] 7 8 9
#[2,] 4 6 1
This tells the package where to find an installed copy of Simile. It then loads the Tcl command implementations in the Simile installation to enable R's tcltk package to communicate with Simile's saved executable models. It should be called only once in a session.
use.simile.at(path.to.installation)
path.to.installation 
Absolute or realtive path to top directory of Simile installation 
undefined.
Simulistics Ltd