6
$\begingroup$

I would like to solve a system of ODEs numerically using NDSolve on an interval {t,t0,tf}.

For the systems I currently solve, calculations take quite long, and if I pick tf too large, it would be nice to have an option to break at some point without losing all data NDSolve has obtained so far.

Is there a way, say, to break with the press of the button, but without throwing away the data? So I want to stop the thing, but not abort.

$\endgroup$
4

1 Answer 1

3
$\begingroup$

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

enter image description here

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]

enter image description here

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
*)
$\endgroup$
1
  • $\begingroup$ @MichelE2 Brilliant! Thank you so much for outlining all the options in so much detail! : ) $\endgroup$
    – Britzel
    Commented Jun 6, 2019 at 14:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.