for loop for time dependent parameter values in ode solver only works for some values of t - matlab

I'm using a simple if loop to change my parameter values within my ode script. Here is an example script I wrote that exhibits the same problem. So first the version which works:
function aah = al(t,x)
if (t>10000 && t<10300)
ab = [0; 150];
else
ab = [150; 0];
end
aah = [ab];
this can be run using
t = [0:1:10400];
x0 = [0,0];
[t,x] = ode23tb(#al, t,x0);
and visualised with
plot(t,x(:,1))
plot(t,x(:,2))
Ok that's the good version. Now if all you do is change t to
t = [0:1:12000];
the whole thing blows up. You might think it's just matlab averaging out the graph but it's not because if you look at
x(10300,2)
the answer should be the same in both cases because the code hasn't changed. but this second version outputs 0, which is wrong!
What on earth is going on? Anyone got an idea?
Thank you so much for any help

Your function is constant (except 10000 < t < 10300), and therefore the internal solver starts to solve the system with very large time step, 10% of total time by default. (In the adaptive ODE solver, if the system is constant, higher order and lower order solution will give the same solution, and the (estimated) error will be zero. So the solver assumes that current time step is good enough.) You can see if you give tspan with just two element, start and end time.
t = [0 12000];
Usually the tspan does not affect to the internal time step of solver. The solvers solve the system with their internal time step, and then just interpolate at tspan given by the user. So if the internal time step unfortunately "leap over" the interval [10000, 10300], the solver won't know about the interval.
So you better set the maximum step size, relatively smaller than 300.
options = odeset('MaxStep', 10);
[t, x] = ode23tb(#al, t, x0, options);
If you don't want to solve with small step size whole time (and if you "know" when the function are not constant), you should solve separately.
t1 = [0 9990];
t2 = [9990 10310];
t3 = [10310 12000];
[T1, x1] = ode23tb(#al, t1, x0);
[T2, x2] = ode23tb(#al, t2, x1(end,:));
[T3, x3] = ode23tb(#al, t3, x2(end,:));
T = [T1; T2(2:end); T3(2:end)];
x = [x1; x2(2:end,:); x3(2:end,:)];

Related

Solving a simple system of differential equations

How would I numerically solve for the following simple system of differential equations using Octave?
Note:
I use the qualifier "simple" as, from my understanding, the system is
first order and is not coupled.
I have tried every
method and script online to try solve this including here,
here and here. In all options, I either get a hanging,
non-responsive Octave, a prompt stating "repeated convergence
failures", an error with recommendation that I manually adjust
the initial and maximum step size (which I did try and do, to no
avail), or something that initially seems like a solution on account of no errors but plotting the solution shows a blank graph
Where Octave provided for equivalent Matlab routines, I tried the various routines ode45, ode23, ode113, ode15s, ode23s, ode23t, ode23tb, ode15i and of course, Octaves own lsode command, all giving the same errors described above.
Let's first replicate the vanilla solution
% z = [x,y]
f = #(t,z) [ z(1).^2+t; z(1).*z(2)-2 ];
z0 = [ 2; 1];
[ T, Z ] = ode45(f, [0, 10], z0);
plot(T,Z); legend(["x";"y"]);
The integrator fails as reported with the warning
warning: Solving was not successful. The iterative integration loop exited at time t = 0.494898 before the endpoint at tend = 10.000000 was reached. This may happen if the stepsize becomes too small. Try to reduce the value of 'InitialStep' and/or 'MaxStep' with the command 'odeset'.
Repeating the integration up to shortly before the critical time
opt = odeset('MaxStep',0.01);
[ T, Z ] = ode45(f, [0, 0.49], z0, opt);
clf; plot(T,Z); legend(["x";"y"]);
results in the graph
where one can see that the quadratic term in the first equation leads to run-away growth. For some reason the solver does only recognize the ever reducing step size, but not the run-away values of the solution.
Indeed the first is a Riccati equation which are known to have poles at finite times. Using the typical parametrization x(t)=-u'(t)/u(t) has by the product/quotient rule the derivative
x' = -u''(t)/u(t) - u'(t)* (-u'(t)/u(t)^2) = -u''(t)/u(t) + x(t)^2
which then results in the ODE for u
u''(t)+t*u(t)=0, u(0)=-1, u'(0)=x(0)=2,
which is an Airy equation with the oscillating branch for t>0. The first root of u is a pole for x, there is no way to extend the solution beyond this point.
g=#(t,u) [u(2); -t.*u(1)]
u0 = [ 1; -2];
function [val,term, dir] = event(t,u)
val = u(1);
term = 0;
dir = 0;
end
opt = odeset('MaxStep',0.1, 'Events', #(t,u) event(t,u));
[T,U,Te,Ue,Ie] = ode45(g,[0,4],u0,opt);
disp(Te)
clf; plot(T,U); legend(["u";"u'"]);
which lists the zeros of u as 0.4949319379979706, 2.886092605590324, again confirming the reason for the warning, and gives the plot

Strange wrong result for (un)coupled PDEs using MATLAB's pdepe, time is doubled

I am trying to solve two coupled reaction diffusion equations in 1d, using pdpe, namely
$\partial_t u_1 = \nabla^2 u_1 + 2k(-u_1^2+u_2)$
$\partial_t u_2 = \nabla^2 u_1 + k(u_1^2-u_2)$
The solution is in the domain $x\in[0,1]$, with initial conditions being two identical Gaussian profiles centered at $x=1/2$. The boundary conditions are absorbing for both components, i.e. $u_1(0)=u_2(0)=u_1(1)=u_2(1)=0$.
Pdepe gives me a solution without prompting any errors. However, I think the solutions must be wrong, because when I set the coupling to zero, i.e. $k=0$ (and also if I set it to be very small, say $k=0.001$), the solutions do not coincide with the solution of the simple diffusion equation
$\partial_t u = \nabla^2 u$
as obtained from pdepe itself.
Strangely enough, the solutions $u_1(t)=u_2(t)$ from the "coupled" case with coupling set to zero, and the solution for the case uncoupled by construction $u(t')$ coincide if we set $t'=2t$, that is, the solution of the "coupled" case evolves twice as fast as the solution of the uncoupled case.
Here's a minimal working example:
Coupled case
function [xmesh,tspan,sol] = coupled(k) %argument is the coupling k
std=0.001; %width of initial gaussian
center=1/2; %center of gaussian
xmesh=linspace(0,1,10000);
tspan=linspace(0,1,1000);
sol = pdepe(0,#pdefun,#icfun,#bcfun,xmesh,tspan);
function [c,f,s] = pdefun(x,t,u,dudx)
c=ones(2,1);
f=zeros(2,1);
f(1) = dudx(1);
f(2) = dudx(2);
s=zeros(2,1);
s(1) = 2*k*(u(2)-u(1)^2);
s(2) = k*(u(1)^2-u(2));
end
function u0 = icfun(x)
u0=ones(2,1);
u0(1) = exp(-(x-center)^2/(2*std^2))/(sqrt(2*pi)*std);
u0(2) = exp(-(x-center)^2/(2*std^2))/(sqrt(2*pi)*std);
end
function [pL,qL,pR,qR] = bcfun(xL,uL,xR,uR,t)
pL=zeros(2,1);
pL(1) = uL(1);
pL(2) = uL(2);
pR=zeros(2,1);
pR(1) = uR(1);
pR(2) = uR(2);
qL = [0 0;0 0];
qR = [0 0;0 0];
end
end
Uncoupled case
function [xmesh,tspan,sol] = uncoupled()
std=0.001; %width of initial gaussian
center=1/2; %center of gaussian
xmesh=linspace(0,1,10000);
tspan=linspace(0,1,1000);
sol = pdepe(0,#pdefun,#icfun,#bcfun,xmesh,tspan);
function [c,f,s] = pdefun(x,t,u,dudx)
c=1;
f = dudx;
s=0;
end
function u0 = icfun(x)
u0=exp(-(x-center)^2/(2*std^2))/(sqrt(2*pi)*std);
end
function [pL,qL,pR,qR] = bcfun(xL,uL,xR,uR,t)
pL=uL;
pR=uR;
qL = 0;
qR = 0;
end
end
Now, suppose we run
[xmesh,tspan,soluncoupled] = uncoupled();
[xmesh,tspan,solcoupled] = coupled(0); %coupling k=0, i.e. uncoupled solutions
One can directly check by plotting the solutions for any time index $it$ that, even if they should be identical, the solutions given by each function are not identical, e.g.
hold all
plot(xmesh,soluncoupled(it+1,:),'b')
plot(xmesh,solcoupled(it+1,:,1),'r')
plot(xmesh,solcoupled(it+1,:,2),'g')
On the other hand, if we double the time of the uncoupled solution, the solutions are identical
hold all
plot(xmesh,soluncoupled(2*it+1,:),'b')
plot(xmesh,solcoupled(it+1,:,1),'r')
plot(xmesh,solcoupled(it+1,:,2),'g')
The case $k=0$ is not singular, one can set $k$ to be small but finite, and the deviations from the case $k=0$ are minimal, i.e. the solution still goes twice as fast as the uncoupled solution.
I really don't understand what is going on. I need to work on the coupled case, but obviously I don't trust the results if it does not give the right limit when $k\to 0$. I don't see where I could be making a mistake. Could it be a bug?
I found the source of the error. The problem lies in the qL and qR variables of bcfun for the coupled() function. The MATLAB documentation, see here and here, is slightly ambiguous on whether the q's should be matrices or column vectors. I had used matrices
qL = [0 0;0 0];
qR = [0 0;0 0];
but in reality I should have used column vectors
qL = [0;0];
qR = [0;0];
Amazingly, pdpe didn't throw an error, and simply gave wrong results. This should perhaps be fixed by the developers.

Solve for simultaneous second order ODE for bioreactor with different stages using MATLAB

I am trying to solve simultaneous second order differential equations to find the concentration of a tracer (molecule) at different stages of a bioreactor. The stages are arranged in series.
Context: Bioreactor that we are working with, is a Rotating Biological Contractor. Here is an example. The tracer molecule is injected at the first stage at time t=0 and our objective is to find how the concentration of the tracer molecule varies with respect to time in each stage.
The second order ODE that we are working with can be found here: https://imgur.com/a/KS4Od
I tried to simplify the equation for 4 stages (2nd and 3rd pic in imgur album) and have tried to solve it using MATLAB. Here is the code for it:
P2 = 1; P3 = 5; C0 = 30; P4 = 2;
f = #(t,x)[x(2); (C0+P4*x(7)-x(1)-P3*x(2))/P2;
x(4); (x(1)-x(3)-P3*x(4))/P2;
x(6); (x(3)-x(5)-P3*x(6))/P2;
x(8); (x(5)-x(7)-P3*x(8))/P2];
t= linspace(0,40); init = [0 0 0 0 0 0 0 0];
[t Y] = ode45(f,t,init);
plot(t,Y(:,1),'r-',t,Y(:,3),'b-',t,Y(:,5),'k-',t,Y(:,7),'m-')
legend('C1','C2','C3','C4')
Our aim is to know how the concentration varies in the 4th stage. It is supposed to look like this Residence time distribution or something similar.
I need to know whether its possible to use "for loop" for "n" stages in series and solve the equation. Ideally, only inputs should be no. of stages, time interval, initial concentration and constants. Assume whatever values for constants, initial conc. and time interval.
Could someone please guide me through solving this? I would really appreciate your help.
Instead of the anonymous/lambda definition of f, use a more traditional function which allows you to employ loops.
n = 4
function dotx = f(t,x)
dotx = zeros(2*n,1)
dotx(1) = x(2);
dotx(2) = (C0+P4*x(7)-x(1)-P3*x(2))/P2
for k = 2:n
dotx(2*k-1) = x(2*k)
dotx(2*k) = (x(2*k-3)-x(2*k-1)-P3*x(2*k))/P2
end
end
init = zeros(2*n,1)
One may have to change row/column format for x, dotx.

ODE 15s with time dependent input parameters

I have a MATLAB code that solves a large scale ODE system of following type
function [F] = myfun(t,C,u)
u here is a time dependent vector used as a input in the function myfun. My current code reads as:-
u = zeros(4,1);
u(1) = 0.1;
u(2) = 0.1;
u(3) = 5.01/36;
u(4) = 0.1;
C0 = zeros(15*4*20+12,1);
options = odeset('Mass',Mf,'RelTol',1e-5,'AbsTol',1e-5);
[T,C] = ode15s(#OCFDonecolumnA, [0,5000] ,C0,options,u);
I would like to have the entire time domain split into 5 different sections and have the elements of u take different values at different times(something like a multiple step function). what would be the best way to code it considering that I later want to solve a optimization problem to determine values of u for each time interval in the domain [0,5000].
Thanks
ode15s expects your model function to accept a parameter t for time and a vector x (or C as you named it) of differential state variables. Since ode15s will not let us pass in another vector u of control inputs, I usually wrap the ODE function ffcn inside a model function:
function [t, x] = model(x0, t_seg, u)
idx_seg = 0;
function y = ffcn(t, x)
% simple example of exponential growth
y(1) = u(idx_seg) * x(1)
end
...
end
In the above, the parameters of model are the initial state values x0, the vector of switching times t_seg, and the vector u of control input values in different segments. You can see that idx_seg is visible from within ffcn. This allows us to integrate the model over all segments (replace ... in the above with the following):
t_start = 0;
t = t_start;
x = x0;
while idx_seg < length(t_seg)
idx_seg = idx_seg + 1;
t_end = t_seg(idx_seg);
[t_sol, x_sol] = ode15s(#ffcn, [t_start, t_end], x(end, :));
t = [t; t_sol(2 : end)];
x = [x; x_sol(2 : end, :)];
t_start = t_end;
end
In the first iteration of the loop, t_start is 0 and t_end is the first switching point. We use ode15s now to only integrate over this interval, and our ffcn evaluates the ODE with u(1). The solution y_sol and the corresponding time points t_sol are appended to our overall solution (t, x).
For the next iteration, we set t_start to the end of the current segment and set the new t_end to the next switching point. You can also see that the last element of t_seg must be the time at which the simulation ends. Importantly, we pass to ode15s the current tail y(end, :) of the simulated trajectory as the initial state vector of the next segment.
In summary, the function model will use ode15s to simulate the model segment by segment and return the overall trajectory y and its time points t. You could convince yourself with an example like
[t, x] = model1(1, [4, 6, 12], [0.4, -0.7, 0.3]);
plot(t, x);
which for my exponential growth example should yield
For your optimization runs, you will need to write an objective function. This objective function can pass u to model, and then calculate the merit associated with u by looking at x.

Euler's approximation in MATLAB

I have a project in MATLAB where I am to approximate the solution of a diff equation. To do that, I use ode45 to get the "real solution" and compare it to Euler's approximation that I perform 3 times with halving the step every time. Here are my issues:
ode45 doesn't seem to work on my computer. I get this message:
No help found for ode45.m.
When I type help ode45 in the commando window and this
Error using ode45
Too many input arguments.
Error in Lab2 (line 51)
[f, u] = ode45(#myode, [pi/6 pi/2], 1);
So I switched to ode23 and got a what I thought to be a quite good result. Problem is though that I noticed that the error in the last approximation becomes slightly smaller which shouldn't happens since the error gets only larger by every step... right?
To makes things worse, I tried to run my code with ode23 on the school computer and got different results (different solution curve). I tried then ode45 and got the same results. When I look at the curve and its values it is totally wrong since in my diff equation values should be decreasing instead of increasing like they do when I run them on the school computer.
I don't understand how the same code can produce two different results on different computers.
I don't understand either why ode45 is missing from my computer. I have tried re-installing the new version and it is still the same.
I am totally confused...
Here is my code:
This is in a function file named myode
function dudf = myode(f,u)
k=1/20;
dudf = (-k*u.^3)/sin(f).^3;
end
This is the program
%Euler's method
f_init = pi/6;
f_final = pi/2;
u_init = 1;
k = 1/20;
n = 10; %number of steps
h(1) = (f_final-f_init)/n;
fh(1) = f_init;
uh(1) = u_init;
%calculate euler's approximation after every step
for i = 2:n+1
fh(i) = fh(i-1)+h;
uh(i) = uh(i-1)+h*(-k*uh(i-1)^3)/(sin(fh(i-1))^3);
end
%save vaules of ode45 at every step for first appr.
step0=pi/30;
fiend = pi/6 + step0;
odeu1 = [1];
step1 = [pi/6];
for i = 1:length(uh)-1
[f, u] = ode23(#myode, [pi/6 fiend], 1);
odeu1 = [odeu1 u(end)];
step1 = [step1 fislut];
fiend = fiend + step0;
end
Any help is appreciated!