Reputation: 65
I have a function that calculates the 'value' of a model based on the inputs.
ModelValue <- function(x, y, z) {
#long, most likely non-linear stuff
return(Value)}
x takes is a number between 0-1, and is fixed based on the model I'm testing. Ie, x will just happen to be 0.56.
y and z are groups of 4 thresholds that I want to optimize to maximize Value.
y=c(pa, pb, pc, pd) and z=c(ta, tb, tc, td), subject to:
all are => 0.001,
all are =<0.997,
pa + pb + pc + pd == 1; and
ta + tb + tc + td == 1
I've tried looking at optimx and spg; (this is as far as I could get) but no matter what I do, I can't seem to create an optimization function that doesn't freak out as soon as I try and mention pa, pb, pc etc. I don't understand how to tell the model what variables its meant to be optimizing...
OptimizeModel <- function(x) {
p0=1 #initial guess
fn = ModelValue(x, y, z)
lo <- c(0.001, 0.001, 0.001, 0.001,
0.001, 0.001, 0.001, 0.001) # lower limits for parameters
hi <- c(0.997, 0.997, 0.997, 0.997,
0.997, 0.997, 0.997, 0.997) # upper limits for parameters
y<- c(pa, pb, pc, pd)
z<- c(ta, tb, tc, td)
pa + pb + pc + pd = 1
ta + tb + tc + td = 1
# pa > 0.001
# pb > 0.001
# pc > 0.001
# pd > 0.001
# ta > 0.001
# tb > 0.001
# tc > 0.001
# td > 0.001
ans1 <- spg(par=p0,
fn=fn,
lower=lo,
upper=hi,
control=list(maximize=TRUE, trace=FALSE))
return (ans1)
}
When I try it:
OptimizeModel(0.56)
#Error in OptimizeModel(0.56) : object 'pa' not found
Upvotes: 1
Views: 89
Reputation: 16724
Just pass on pa,pb,pc to spg and use them in the function evaluation. The documentation of spg is showing an example where this is done:
valley.f <- function(x, cons) {
...}
Here x
are the decision variables and cons
is extra data (constants).
The call to spg looks like:
ans.spg2 <- spg(par=p0, fn=valley.f, cons=k, method=2)
You see cons=k
is specified. This argument is not for spg
itself but is passed on to the function evaluation (and gradient evaluation) functions. You need to do the same for pa,pb,pc.
See: https://www.rdocumentation.org/packages/BB/versions/2019.10-1/topics/spg
Upvotes: 1