I have a problem I am attempting to solve with NMinimize.
I have a scoring function, which will give me a final score. The problem has many variables, so instead of having them as parameters, they are assembled by variable name. Here is a simple example:
scoreResults = Function[
Module[{temp, i},
temp = 0;
Print["Checkpoint 0: " <> ToString[temp]];
For[i = 0, i < 2, i++,
temp = temp + ToExpression["aaa" <> ToString[i]];
If[ToExpression["aaa" <> ToString[i]] > 300,
temp = temp + 100000;
];
Print["Checkpoint 1: " <> ToString[Evaluate[temp]]];
];
Return[temp, Module];
]
];
Notice the If condition. Now, when I evaluate with a ReplaceAll, I get the following:
scoreResults[] /. {aaa0 -> 123, aaa1 -> 456}
Checkpoint 0: 0
Checkpoint 1: aaa0
Checkpoint 1: aaa0 + aaa1
579
That is not correct! I believe what's happening is the function is being evaluated before the ReplaceAll. Is it possible to get around this without having input parameters? My problem has many variables, and the scoring function will have many nested for loops, so assembling variable names on the fly inside the scoring function is key. Even if I do use input parameters for the function, I'm finding that my ToExpression["aaa"<>ToString[i]] is not effective.
Ultimately, I would like to use this scoring function with NMinimize like such:
NMinimize[{scoreResults[], {aaa0 > 222, aaa1 > 333}}, {aaa0, aaa1}]
Currently the answer it gives me is wrong:
{555., {aaa0 -> 222., aaa1 -> 333.}}
Thank you in advance for your help, I have been trying to figure this out for a while now. I understand that when I get to the NMinimize part, I'll probably have to use NumericQ, but for now, I just need to get past the initial problem I'm having just getting the function to produce the correct value, including the If statement.
ReplaceAll
does not have any Hold attributes so it will evaluate the first argument before doing any replacements. If it didn't, something likescoreResults[] /. {aaa0 -> 123, aaa1 -> 456}
could never work because the first argument would just bescoreResults[]
and there would be nothing to replace in that because it's just aSymbol
and nothing else. What you can try, is(scoreResults /. {...})[]
, but this won't work in your code because the thing you're trying to replace doesn't exist in your function yet. $\endgroup$