# Category: Differential Equations
# Name: Numerically plotting trajectories of ODE systems
#
# Draw trajectories of ODE starting at the mouse pointer.  We plot first order
# systems, and give two examples that are converted second order equations: The
# Duffing equation of chaos fame, and the Van der Pol oscillator.  Then we also
# include the Predator-Prey system.  For autonomous systems this can be done
# more easily when plotting vector fields.  To plot these, uncomment the
# correct lines below, or write your own function sys giving the system,
# t_range is the range, and number_of_points is the number of points to compute
# and plot.

# The Duffing equation
# x'' = -0.5x' - x^3 + 8cos(t)
# Converted to first order ODE system 
# x_1' = x_2, x_2' = -0.05x_2 - x_1^3 + 8cos(t)
function sys(t,x) = [x@(2), -0.05*x@(2)-(x@(1))^3+8*cos(t)];
t_range = [0,30];
LinePlotWindow = [-6,6,-6,6];
number_of_points = 1000;
init_cond = [2,3];

# The Van der Pol oscillator
# x'' = (1-x^2)x' - x
# Converted to first order ODE system 
# x_1' = x_2, x_2' = (1-x_1^2)x_2 - x_1
#function sys(t,x) = [x@(2), (1-x@(1)^2)*x@(2)-x@(1)];
#t_range = [0,30];
#LinePlotWindow = [-4,4,-4,4];
#number_of_points = 500;

# The Predator-Prey (Lotka-Volterra)
# x_1' = (0.4 - 0.01 x_2)x_1,  x_2' = (0.003 x_1 - 0.3) x_2
#function sys(t,x) = [(0.4-0.01*x@(2))*x@(1), (0.003*x@(1)-0.3)*x@(2)]
#t_range = [0,50];
#LinePlotWindow = [0,250,0,90];
#number_of_points = 500;

LinePlotDrawLegends = false;
PlotWindowPresent(); # Make sure the window is raised
LinePlotClear ();

while true do (
	p = LinePlotMouseLocation ();
	if IsNull(p) then break;

	# Compute the points
	pt = RungeKuttaFull(sys,t_range@(1),p,t_range@(2),number_of_points);

	# Flatten the matrix
	pt = ExpandMatrix(pt);

	# Draw the trajectory
	PlotCanvasFreeze();
	LinePlotClear();
	LinePlotDrawLine(pt@(,[2,3]),"color","blue");
	PlotCanvasThaw();
	
	wait(0.03)
);

