I want to find the minimum of the function r[x,p]
subject to the constraint w[x,p,t]==0
(t
is a fixed parameter).
To find the minimum I use the function NMinimize
.
The constraint w[x,p,t]==0
is a rather complicated numerical function. It depends on the function evolve[x,p,t]
which is the numerical solution of some ordinary differential equation.
I use a For
loop to find the minima for different values of the constraint parameter t
.
My problem is the following: At certain instants of time, the kernel Local quits without errors or warnings before the loop is finished. The error message is "The kernel Local has quit (exited) during the course of an evaluation". The time when the kernel quits is always different, sometimes it happens very early, sometimes rather late. When I evaluate NMinimize
for the parameter t
where the kernel crashed (and also for parameters beyond that point), it works well without any error.
First I thought the reason for the crash could be a lack of memory, but if I monitor the memory during the calculation, everything looks fine.
Here is the code of a simplified version of my problem.
(*definition of the constraint*)
h[x_, p_] := -x^2 + p^2 + x^4;
evolve[ xini_, pini_, time_] :=
Module[{x, p, t},
Hold[{x[time], p[time]} /.
NDSolve[{x'[t] == p[t], p'[t] == -x[t], x[0] == xini, p[0] == pini}, {x, p},
{t, 0, time}, MaxSteps -> Infinity][[1]]
]];
w[x_?NumericQ, p_?NumericQ, t_?NumericQ] := h @@ ReleaseHold[evolve[x, p, t]] - h[x, p];
(*definition of the function which should be minimized*)
r[x_, p_] := {x - 1, p}.{{0.1, 0}, {0, 0.1}}.{x - 1, p};
fct = First[{Print[#];
NMinimize[{r[x, p], w[x, p, #] == 0}, {x, p},
Method -> "NelderMead", MaxIterations -> 10^3]}] &;
(*loop over different parameters t*)
dt := 0.05;
tmin := 0;
tmax := 40;
maxt := Floor[(tmax - tmin)/dt];
times = Table[tmin + dt*n, {n, 0, maxt}];
positions = Table[0, {Length[times]}];
values = Table[0, {Length[times]}];
For[n = 1, n <= Length[times], n++,
tmp = fct@times[[n]];
positions[[n]] = {x, p} /. (tmp[[2]]);
values[[n]] = tmp[[1]];
];
When I replace the loop over t
by
fct/@times;
I get the same error.
I am using Mathematica 9.0.1.0