Slow time integration of system ODE under specific conditions - matlab

I am trying to solve the system of ODEs below. I am applying the finite differences to z, so I get a system of ODE that I can solve with a solver like ode45.
The problem is that under the conditions that interest me integration is too slow (time step is very small) and I get no result. I would like to know what is the underlying problem and if there is any way to solve it. I have tried:
using different solvers (tried all of them)
using dimensionless variables
using the pdepe function of Matlab to solve the PDE system directly without applying finite differences myself. Same problem occurs.
Full code (using the parameters that do not work)
function transport_model()
global parameter L Di epsb Q Cfeed K tfinal npz npt F ui h
parameter = [0.044511*432.75 432.75]; % isotherm parameters
L = 0.4; % m, column length
epsb = 0.367; % column bulk porosity
ui = 4e4; % m/s, velocity
Cfeed = 200; % feed concentration
K = 0.0782 % s-1, mass transfer coefficient
tfinal = 400; % min, final time for calculation
npz = 50; % number of discretization points in z
npt = 20;
F = (1-epsb)/epsb;
tspan = 0:tfinal/(npt-1):tfinal;
y0 = zeros(2*npz,1);
h = L/(npz-1);
sol = ode15s(#sedo, tspan, y0);
t = sol.x;
C1 = sol.y(1:npz,:);
q1 = sol.y((npz+1):end,:);
plot(t, C1(end,:))
xlim([0 tfinal])
ylim([0 Cfeed])
function DyDt = sedo(t,y)
global Cfeed K npz F ui h
N = npz;
y(1) = Cfeed;
DyDt = zeros(2*N,1);
% Forward finite differences
DyDt(1) = -ui * 1/(2*h)*(-y(3)+4*y(2)-3*y(1)) - F * K * (y(1) - ilangmuir(y(N+1)));
DyDt(N+1) = K * (y(1) - ilangmuir(y(N+1)));
% Central finite differences
for i=2:N-1
DyDt(i) = -ui * 1/(2*h)*(y(i+1)-y(i-1)) - F * K * (y(i) - ilangmuir(y(N+i)));
DyDt(N+i) = K * (y(i) - ilangmuir(y(N+i)));
end
% Backward finite differences
DyDt(N) = -ui * 1/(2*h)*(3*y(N)-4*y(N-1)+y(N-2)) - F * K * (y(N) - ilangmuir(y(N+N)));
DyDt(2*N) = K * (y(N) - ilangmuir(y(N+N)));
function c = ilangmuir(q)
% langmuir solved for c
global parameter
a = parameter(1);
b = parameter(2);
c = q /(a - b * q);
However, if I try to model a different case (different conditions) I get the correct response. So I am assuming this is a numerical problem caused by the conditions I am trying to model and not an error in the model. For instance, if I use the conditions below I get the correct response.
parameter = [0.044511*432.75 432.75]; % isotherm parameters
L = 0.4; % m, column length
epsb = 0.367; % column bulk porosity
ui = 0.0056; % m/s, velocity
Cfeed = 0.0025; % feed concentration
K = 0.0782 % s-1, mass transfer coefficient
tfinal = 4000; % min, final time for calculation
npz = 50; % number of discretization points in z
npt = 20;

Related

Applying ode15s to solve a spatial discretization using finite difference for multiple variables

I am trying to run the following ode15s with three variables, C1, q1 and phi1. However, I keep on receiving the following warning:
Warning: Failure at t=1.163115e-13. Unable to meet integration
tolerances without reducing the step size below the smallest value
allowed (4.038968e-28) at time t.
The simulation runs correctly if I do not include the dq1_over_dt term in the ode15s solver, so issue is definitely there. If the simulation runs correctly, the result is a Y matrix of 486X360 dimensions.
Any practical advice is welcomed.
%-------------------------------------------------------------------------%
% Chromatography Simulation 1
% By Santiago Taguado
% Chromatogram Simulation
%-------------------------------------------------------------------------%
close all; clear variables; clc;
% Global variables (meaning reported below)
global u Dax N h isopar K eps v Dphi phi_in Cin mod_gradient
%-------------------------------------------------------------------------%
% Chromatography with variable boundaries
%-------------------------------------------------------------------------%
L = 25; % Length (cm)
Q = 2.513; % Flow Rate (mL/min)
D = 0.8; % Diameter of Column (cm)
S = pi()*(D/2)^2; % Column Cross Section (cm2)
eps = 0.7; % Void Fraction
u = Q/S; % superficial velocity (cm/min)
v = u/eps; %intersitial velocity
Dax = 0.039/u; % axial dispersion (cm)
Dphi = 0.039/u; % axial dispersion (cm)
N = 120; % number of grid points (-)
alpha1 = 149421.036; % Parameter 1
alpha2 = -3.054; % Sensibility variable 1
alpha3 = 500; % Parameter 2
alpha4 = 500; % Sensibility variable 2
isopar = [alpha1 alpha2 alpha3 alpha4];
K = 3; % Linear Driving Force
eps = 0.7; % Void Fraction
%-------------------------------------------------------------------------%
% Preprocessing
%-------------------------------------------------------------------------%
h = L/(N-1); % grid spacing (cm)
nt = 3000; % number of time steps
t_load = 8; % loading time,min
t_tot = 49;
dt = t_tot/(nt-1);
%-------------------------------------------------------------------------%
% Solution via ode15s solver for Loading Phase
%-------------------------------------------------------------------------%
C1 = [0; zeros(N-1,1)]; % Initial Conditions
q1 = [0;zeros(N-1,1)];
phi = [0;zeros(N-1,1)];
Y = [C1;q1;phi];
phi_in = 0.02;
Cin = 1.085; % initial concentration (mg/mL)
mod_gradient = 0;
tspan = 0:dt:t_load;
[t, Y] = ode15s(#ODESystem, tspan, Y);
%-------------------------------------------------------------------------%
% ODE system
%-------------------------------------------------------------------------%
function dY = ODESystem(t,Y)
global u Dax N h Dphi v phi_in Cin mod_gradient eps isopar
C1 = Y(1:N);
q1 = Y(N+1:N*2);
phi = Y(N*2+1:N*3);
dC1_over_dt = zeros(N,1);
dq1_over_dt = zeros(N,1);
dphi_over_dt = zeros(N,1);
% Boundary # x=0
dC1_over_dt(1) = (Cin(1) + Dax/u/h*C1(2))/(1+Dax/u/h);
dq1_over_dt(1) = 0;
dphi_over_dt(1) = (phi_in + mod_gradient*t + Dphi/v/h*phi(2))/(1+Dphi/v/h);
% Internal points
for i=2:N-1
% Isotherm Value
H1 = isopar(1)*phi(i)^isopar(2); H1(isinf(H1)) = 0;
q_inf1 = isopar(3)*H1/(1+H1); q_inf1(isnan(q_inf1)) = 0;
denom = 1 + C1(i)*H1/q_inf1; denom(isnan(denom)) = 1;
qstar1 = C1(i)*H1/denom;
dq1_over_dt(i) = eps/(1-eps)*(qstar1 - q1(i));
% Species, 1
dC1_over_dx = (C1(i-1)-C1(i))/(h);
d2C1_over_dx2 = (C1(i+1)-2.*C1(i)+C1(i-1))/h^2;
% Modifier,1
dphi_over_dx = (phi(i-1)-phi(i))/(h);
d2phi_over_dx2 = (phi(i+1)-2.*phi(i)+phi(i-1))/h^2;
dphi_over_dt(i) = u*dphi_over_dx + ...
Dphi*d2phi_over_dx2;
dC1_over_dt(i) = v*dC1_over_dx + Dax*d2C1_over_dx2;
end
% Boundary # x=L
dC1_over_dt(N) = dC1_over_dt(N-1);
dq1_over_dt(N) = dq1_over_dt(N-1);
dphi_over_dt(N) = dphi_over_dt(N-1);
dY = [dC1_over_dt;dq1_over_dt;dphi_over_dt];
end

Solving the Damped Harmonic Oscillator ODE as a first order system using midpoint methods

The exact solution of the damped harmonic oscillator
$$x'' + 2\gamma x' + \omega^2 x = 0, \quad x(0)=x_0, \quad x'(0)=-\gamma x_0$$
with $0 < \gamma < \omega$ is
$$x(t)= x_0 e^{-\gamma t} \cos(\beta t) \quad \text{where} \quad \beta:=\sqrt{\omega^2 - \gamma^2}$$
Notice that this second order ODE can be written as a first order system by making the substitutions:
$x' = y$ and,
$y' = -2\gamma y - \omega^2 x$
I want to solve the system using the method:
$$\dfrac{ x_{n+1} - x_{n-1} }{2h} = y_n \quad \quad \dfrac{y_{n+1} - y_{n-1}}{2h} = -2\gamma y_n - \omega^2 x_n.$$
which is an explicit midpoint rule. This is the code that I constructed for the problem, but it is not giving me the correct result. My plot has no harmonic behavior as I would anticipate.
function resonance
omega = 1; % resonant frequency = sqrt(k/m)
a = 0.2; % drag coeficient per unit mass
b = 0.1; % driving amplitude per unit mass
omega0 = 1.2; % driving frequency
tBegin = 0; % time begin
tEnd = 80; % time end
x0 = 0.2; % initial position
v0 = 0.8; % initial velocity
a = omega^2; % calculate a coeficient from resonant frequency
% Use Runge-Kutta 45 integrator to solve the ODE
[t,w] = ode45(#derivatives, [tBegin tEnd], [x0 v0]);
x = w(:,1); % extract positions from first column of w matrix
v = w(:,2); % extract velocities from second column of w matrix
plot(t,x);
title('Damped, Driven Harmonic Oscillator');
ylabel('position (m)');
xlabel('time (s)');
% Function defining derivatives dx/dt and dv/dt
% uses the parameters a, b, A, omega0 in main program but changeth them not
function derivs = derivatives(tf,wf)
xf = wf(1); % wf(1) stores x
vf = wf(2); % wf(2) stores v
dxdt = vf; % set dx/dt = velocity
dvdt = xf + 2 * b * vf + a * tf; % set dv/dt = acceleration
derivs = [dxdt; dvdt]; % return the derivatives
end
end
Also, my apologies about the formatting. I am use to math stackexchange, and the LaTeX style formatting doesn't seem to be applicable here and I do not know how to put my math in the math environment.
You missed a sign, it should be
dvdt = - ( xf + 2 * b * vf + a * tf ); % set dv/dt = acceleration
However, the whole expression is at odds with the previously stated equation,
x'' + 2*b*x' * a*x = 0
should result in
dvdt = - ( 2*b*vf + a*xf ); % set dv/dt = acceleration
But then again you have defined a twice, so change w2=omega^2 to get
dvdt = - ( 2*b*vf + w2*xf + a ); % set dv/dt = acceleration

MATLAB - passing a sinusoidal forcing function to ode45

I'm new to Matlab and am really struggling even to get to grips with the basics.
I've got a function, myspring, that solves position and velocity of a mass/spring system with damping and a driving force. I can specify values for the spring stiffness (k), damping coefficient (c), and mass (m), in the command window prior to running ode45. What I am unable to do is to define a forcing function (even something simple like g = sin(t)) and use that as the forcing function, rather than having it written into the myspring function.
Can anyone help? Here's my function:
function pdot = myspring(t,p,c,k,m)
w = sqrt(k/m);
g = sin(t); % This is the forcing function
pdot = zeros(size(p));
pdot(1) = p(2);
pdot(2) = g - c*p(2) - (w^2)*p(1);
end
and how I'm using it in the command window:
>> k = 2; c = 2; m = 4;
>> tspan = linspace(0,10,100);
>> x0 = [1 0];
>> [t,x] = ode45(#(t,p)myspring(t,p,c,k,m),tspan,x0);
That works, but what I want should look something like this (I imagine):
function pdot = myspring(t,p,c,k,m,g)
w = sqrt(k/m);
pdot = zeros(size(p));
pdot(1) = p(2);
pdot(2) = g - c*p(2) - (w^2)*p(1);
end
Then
g = sin(t);
[t,x] = ode45(#(t,p)myspring(t,p,c,k,m,g),tspan,x0);
But what I get is this
In an assignment A(:) = B, the number of elements in A and B must be the same.
Error in myspring (line 7)
pdot(2) = g - c*p(2) - (w^2)*p(1);
Error in #(t,p)myspring(t,p,c,k,m,g)
Error in odearguments (line 87)
f0 = feval(ode,t0,y0,args{:}); % ODE15I sets args{1} to yp0.
Error in ode45 (line 115)
odearguments(FcnHandlesUsed, solver_name, ode, tspan, y0, options, varargin);
Horchler, thank you for the reply. I can do as you suggested and it works. I am now faced with another problem that I hope you could advise me on.
I have a script that calculates the force on a structure due to wave interaction using Morison's equation. I gave it an arbitrary time span to begin with. I would like to use the force F that script calculates as the input driving force to myspring. Here is my Morison script:
H = 3.69; % Wave height (m)
A = H/2; % Wave amplitude (m)
Tw = 9.87; % Wave period (s)
omega = (2*pi)/Tw; % Angular frequency (rad/s)
lambda = 128.02; % Wavelength (m)
k = (2*pi)/lambda; % Wavenumber (1/m)
dw = 25; % Water depth (m)
Cm = 2; % Mass coefficient (-)
Cd = 0.7; % Drag coefficient (-)
rho = 1025; % Density of water (kg/m^3)
D = 3; % Diameter of structure (m)
x = 0; % Fix the position at x = 0 for simplicity
t = linspace(0,6*pi,n); % Define the vector t with n time steps
eta = A*cos(k*x - omega*t); % Create the surface elevation vector with size equal to t
F_M = zeros(1,n); % Initiate an inertia force vector with same dimension as t
F_D = zeros(1,n); % Initiate a drag force vector with same dimension as t
F = zeros(1,n); % Initiate a total force vector with same dimension as t
fun_inertia = #(z)cosh(k*(z+dw)); % Define the inertia function to be integrated
fun_drag = #(z)(cosh(k*(z+dw)).*abs(cosh(k*(z+dw)))); % Define the drag function to be integrated
for i = 1:n
F_D(i) = abs(((H*pi)/Tw) * (1/sinh(k*dw)) * cos(k*x - omega*t(i))) * ((H*pi)/Tw) * (1/sinh(k*dw)) * cos(k*x - omega*t(i)) * integral(fun_drag,-dw,eta(i));
F_M(i) = (Cm*rho*pi*(D^2)/4) * ((2*H*pi^2)/(Tw^2)) * (1/(sin(k*dw))) * sin(k*x - omega*t(i)) * integral(fun_inertia,-dw,eta(i));
F(i) = F_D(i) + F_M(i);
end
Any further advice would be much appreciated.
You can't pre-calculate your forcing function. It depends on time, which ode45 determines. You need to define g as a function and pass a handle to it into your integration function:
...
g = #(t)sin(t);
[t,x] = ode45(#(t,p)myspring(t,p,c,k,m,g),tspan,x0);
And then call it I n your integration function, passing in the current time:
...
pdot(2) = g(t) - c*p(2) - (w^2)*p(1);
...

Find positive solutions in undetermined system of equations (revisited)

I tried to apply the method posted in Find positive solutions to undetermined linear system of equations to the set
A=[0 0.0992 0.315 0.619 1; 0 0.248 0.315 0.248 0]; b=[0.1266 0.4363].
It is supposed that there exists a positive and constrained solution to this problem. The worst thing is that I have an answer code but I can't make it work because my Matlab version doesn`t recognize the anonymous function call and some instructions are obscure for me.
Here is the code:
% example_pt_source_atmos_setup.m
% determine geometry
D2 = 0.5; % diameter of the observation aperture [m]
wvl = 1e-6; % optical wavelength [m]
k = 2*pi / wvl; % optical wavenumber [rad/m]
Dz = 50e3; % propagation distance [m]
% use sinc to model pt source
DROI = 4 * D2; % diam of obs-plane region of interest [m]
D1 = wvl*Dz / DROI; % width of central lobe [m]
R = Dz; % wavefront radius of curvature [m]
% atmospheric properties
Cn2 = 1e-16; % structure parameter [m^-2/3], constant
% SW and PW coherence diameters [m]
r0sw = (0.423 * k^2 * Cn2 * 3/8 * Dz)^(-3/5);
r0pw = (0.423 * k^2 * Cn2 * Dz)^(-3/5);
p = linspace(0, Dz, 1e3);
% log-amplitude variance
rytov = 0.563 * k^(7/6) * sum(Cn2 * (1-p/Dz).^(5/6) ...
.* p.^(5/6) * (p(2)-p(1)));
% screen properties
nscr = 11; % number of screens
A = zeros(2, nscr); % matrix
alpha = (0:nscr-1) / (nscr-1);
A(1,:) = alpha.^(5/3);
A(2,:) = (1 - alpha).^(5/6) .* alpha.^(5/6);
b = [r0sw.^(-5/3); rytov/1.33*(k/Dz)^(5/6)];
% initial guess
x0 = (nscr/3*r0sw * ones(nscr, 1)).^(-5/3);
% objective function
fun = #(X) sum((A*X(:) - b).^2);
% constraints
x1 = zeros(nscr, 1);
rmax = 0.1; % maximum Rytov number per partial prop
x2 = rmax/1.33*(k/Dz)^(5/6) ./ A(2,:);
x2(A(2,:)==0) = 50^(-5/3)
[X,fval,exitflag,output] ...
= fmincon(fun,x0,[],[],[],[],x1,x2)
% check screen r0s
r0scrn = X.^(-3/5)
r0scrn(isinf(r0scrn)) = 1e6;
% check resulting r0sw & rytov
bp = A*X(:); [bp(1)^(-3/5) bp(2)*1.33*(Dz/k)^(5/6)]
[r0sw rytov]
Thanks for your attention.
Carolina Rickenstorff

Implement finite difference method in matlab

I am trying to implement the finite difference method in matlab. I did some calculations and I got that y(i) is a function of y(i-1) and y(i+1), when I know y(1) and y(n+1). However, I don't know how I can implement this so the values of y are updated the right way. I tried using 2 fors, but it's not going to work that way.
EDIT
This is the script and the result isn't right
n = 10;
m = n+1;
h = 1/m;
x = 0:h:1;
y = zeros(m+1,1);
y(1) = 4;
y(m+1) = 6;
s = y;
for i=2:m
y(i) = y(i-1)*(-1+(-2)*h)+h*h*x(i)*exp(2*x(i));
end
for i=m:-1:2
y(i) = (y(i) + (y(i+1)*(2*h-1)))/(3*h*h-2);
end
The equation is:
y''(x) - 4y'(x) + 3y(x) = x * e ^ (2x),
y(0) = 4,
y(1) = 6
Thanks.
Consider the following code. The central differential quotient is discretized.
% Second order diff. equ.
% y'' - 4*y' + 3*y = x*exp(2*x)
% (y(i+1)-2*y(i)+y(i-1))/h^2-4*(y(i+1)-y(i-1))/(2*h) + 3*y(i) = x(i)*exp(2*x(i));
The solution region is specified.
x = (0:0.01:1)'; % Solution region
h = min(diff(x)); % distance
As said in my comment, using this method, all points have to be solved simultaneously. Therefore, above numerical approximation of the equation is transformed in a linear system of euqations.
% System of equations
% Matrix of coefficients
A = zeros(length(x));
A(1,1) = 1; % known solu for first point
A(end,end) = 1; % known solu for last point
% y(i) y'' y
A(2:end-1,2:end-1) = A(2:end-1,2:end-1)+diag(repmat(-2/h^2+3,[length(x)-2 1]));
% y(i-1) y'' -4*y'
A(1:end-1,1:end-1) = A(1:end-1,1:end-1)+diag(repmat(1/h^2+4/(2*h),[length(x)-2 1]),-1);
% y(i+1) y'' -4*y'
A(2:end,2:end) = A(2:end,2:end)+diag(repmat(1/h^2-4/(2*h),[length(x)-2 1]),+1);
With the rhs of the differential equation. Note that the known values are calculated by 1 in the matrix and the actual value in the solution vector.
Y = x.*exp(2*x);
Y(1) = 4; % known solu for first point
Y(end) = 6; % known solu for last point
y = A\Y;
Having an equation to approximate the first order derivative (see above) you can verify the solution. (note, ddx2 is an own function)
f1 = ddx2(x,y); % first derivative (own function)
f2 = ddx2(x,f1); % second derivative (own function)
figure;
plot(x,y);
saveas(gcf,'solu1','png');
figure;
plot(x,f2-4*f1+3*y,x,x.*exp(2*x),'ko');
ylim([0 10]);
legend('lhs','rhs','Location','nw');
saveas(gcf,'solu2','png');
I hope the solution shown below is correct.