I defined a simulation as a module with simulation parameters as the variables. I want to find optimal simulation parameters using NMinimize method. I noticed that my simulation module will run successfully for any sample parameters, but when used in NMinimize will not execute. Please see below a very simplified version of the code:
demand[n_, k_] := Min[k Vf, n capacity];
supply[n_, k_] := Min[(n Kj - k) w, n capacity];
flo[n_, Ku_, Kd_] := Min[demand[n, Ku], supply[n, Kd]];
dx = Vf*dt; capacity =w*Vf*Kj/(Vf + w); Kj = 150.; w = 20.; Vf = 100.;
n = Round[Flen/dx]; m = Round[SimTime/dt]; p = Round[Rlen/dx]; RMLocation = Round[(2/3) p];
\[Alpha][a1_] := 1800.; \[Beta][a2_] := 0.1; L = 1.; Flen = 4.; Rlen = 3.; delta = 1.; SimTime = 15./60.; dt = 6./3600.;
f[a_] := Module[{k0 = ConstantArray[0, n],kr = Table[Table[0, {i1, 1, p}], {i2, 1, n}], \[Gamma] = ConstantArray[1, n], \[Phi]},
Clear[j]; j = 0;
RM[x_, t_] := 100 a; k = k0;
For[i = 2, i < n, i++, kr[[i, 1]] = \[Alpha][i dx] delta/Vf];
NtwrkTT = TT = Plus @@ (Plus @@ kr);
While[TT > 0,
For[i = 2, i < n, i++,
FQin = If[i == 2, Min[demand[L, k0[[i - 1]]], supply[L, k0[[i]]]],FQout];
dem = demand[L, k0[[i]]]; dem = If[dem == 0, 0.001, dem];
\[Gamma][[i]] = Min[1, supply[L, k0[[i + 1]]]/dem];
\[Phi] = \[Gamma][[i]] demand[1, kr[[i, p]]]/delta;
Qr = (\[Phi] - \[Beta][i dx] FQin) dx;
FQout = Min[demand[L, k0[[i]]], supply[L, k0[[i + 1]]]];
k[[i]] = k0[[i]] + (FQin - FQout + Qr)/Vf; kr0 = kr[[i]];
For[ir = 2, ir <= p, ir++,
MR = If[ir == RMLocation + 1, RM[i dx, j dt], capacity];
RQin = Min[MR, If[ir == 2, flo[1, kr0[[ir - 1]], kr0[[ir]]], RQout]];
MR = If[ir == RMLocation, RM[i dx, j dt], capacity];
RQout = Min[MR, If[ir < p,flo[1, kr0[[ir]], kr0[[ir + 1]]], \[Phi] delta]];
kr[[i, ir]] = kr0[[ir]] + (RQin - RQout)/Vf];
kr[[i, 1]] = If[j <= m, \[Alpha][i dx] delta/Vf, 0]];
TT = Plus @@ (Plus @@ kr);
TT += Plus @@ k;
k0 = k; NtwrkTT += TT; j++];
NtwrkTT dt]
NMinimize[{f[a], 3 <= a <= 12 && Element[a, Integers]}, a, Method -> "SimulatedAnnealing", EvaluationMonitor :> Print["a = ", a]]