# [R] optimize integer function parameters

Enrico Schumann es at enricoschumann.net
Tue Jul 23 17:27:46 CEST 2013

```On Tue, 23 Jul 2013, Christof Kluß <ckluss at email.uni-kiel.de> writes:

> Am 23-07-2013 13:20, schrieb Enrico Schumann:
>
>> On Tue, 23 Jul 2013, Christof Kluß <ckluss at email.uni-kiel.de> writes:
>>
>>>
>>> I have "observations" obs <- (11455, 11536, 11582, 11825, 11900,  ...)
>>>
>>> and a simulation function f(A,B,C,D,E,F), so sim <- f(A,B,C,D,E,F)
>>>
>>> e.g. sim = c(11464, 11554, 11603, 11831, 11907, ...)
>>>
>>> now I would like to fit A,B,C,D,E,F such that "obs" and f(A,B,C,D,E,F)
>>> match as well as possible. A,..,F should be integers and have bounds.
>>>
>>> How would you solve this problem without bruteforce in an acceptable time?
>>>
>>
>>
>> That depends on what your "simulation function" looks like.  Could you
>> post a (small) self-contained example?
>>
>>
>
> the integer values in the vectors sim and obs are dates
>
> when I set sim <- f(TS0,TS1,TS2,TB0,TB1,TB2) my A,..,F below
> then TS0 and TB0 are depend (and so on)
>
>
> the main thing in f(...) is something like
>
>  for (i in c(1:length(temperature))) {
>       Temp <- temperature[i]
>       if (DS < 0) {
>         DS <- DS + max(Temp-TB0,0) / TS0
>       } else if (DS < 1) {
>         ... date0 <- i
>         DS <- DS + max(Temp-TB1,0) / TS1
>       } else if (DS < 2) {
>         ... date1 <- i
>         DS <- DS + max(Temp-TB2,0) / TS2
>       } else {
>         ... date2 <- i
>         break
>       }
>     }
>
>
> this produced a vector sim = c(date0,date1,date2,...)
>
>
> now I would like to minimize RMSE(sim,obs) or something like that
>
> thx
> Christof
>
>
>
> for brute force I would do something like
>
> obs <- ...
> act <- 1000
>
>   for (TS0 in seq(50,100,10))
>     for (TS1 in seq(750,850,10))
>       for (TS2 in seq(400,600,10))
>         for (TB0 in c(5:7))
>           for (TB1 in c(5:7))
>             for (TB2 in c(4:9)) {
>               sim <- foosim(dat,TS0,TS1,TS2,TB0,TB1,TB2)
>               rmse <- sqrt(mean((sim - obs)^2, na.rm = TRUE))
>
>               if (rmse < act) {
>                 print(paste(rmse,TS0,TS1,TS2,TB0,TB1,TB2))
>                 act <- rmse
>               }
>             }
>

Sorry, but that is not what I meant by "a (small) self-contained
example".

In any case, if brute force is feasible -- ie, your function can be
evaluated quickly enough and there are no further parameters -- then why
not do brute force?  (In the NMOF package there is a function
'gridSearch' that allows you to distribute the function evaluations.
Disclosure: I am the package author.)

If that does not work, you might try a Local Search or one of its
variants (see for instance 'LSopt' in the NMOF package).  But it is
difficult to say anything specific without knowing your actual function.

Regards,
Enrico

--
Enrico Schumann
Lucerne, Switzerland
http://enricoschumann.net

```