Aside from the stop Button[]
example in the docs that Carl pointed out, here are a couple of ways.
The first saves the result periodically using NDSolve`ProcessSolutions[]
.
ClearAll[sol0];
NDSolve[{y''[x] == -y[x], y[0] == 1, y'[0] == 0,
WhenEvent[Mod[x, 10] == 0,
sol0 = NDSolve`ProcessSolutions[NDSolve`Self]; {}]},
y, {x, 0, 1000000}]
(* $Aborted <-- because I aborted evalutation *)
sol0
Another way to advance the integration bit by bit using NDSolve`Iterate[]
. This has the advantage that after being aborted, one can continue iterating without any further setup.
ClearAll[sol0];
{state} = NDSolve`ProcessEquations[{y''[x] == -y[x], y[0] == 1, y'[0] == 0},
y, {x, 0, 1000000}];
Do[NDSolve`Iterate[state, tt], {tt, 10, 1000000, 10}]
(* $Aborted <-- because I aborted evalutation *)
state
(* NDSolve`StateData[< 0., 12740.>] <-- shows how far it got (12740.) *)
sol = NDSolve`ProcessSolutions[state]
Here's a way that saves every 1000 steps:
ClearAll[sol0];
nsteps = 0;
NDSolve[{y''[x] == -(1 + x/100) y[x], y[0] == 1, y'[0] == 0,
WhenEvent[Mod[nsteps, 1000] == 0,
sol0 = NDSolve`ProcessSolutions[NDSolve`Self]; {}]},
y, {x, 0, 1000000}, StepMonitor :> ++nsteps]
(* $Aborted <-- because I aborted evalutation *)
y["Grid"] /. sol0 // Length
nsteps
(*
49001
49602
*)
WhenEvent
example from the documentation? $\endgroup$