Friday, August 6, 2021

Linear Least-Squares Regression

Problem 14.14.


An investigator has reported the data tabulated below for an experiment to determine the growth rate of bacteria k (per d) as a function of oxygen concentration c (mg/L). It is known that such data can be modeled by the following equation: 


 Eq.(14.14(a))


where cs and kmax are parameters. Use a transformation to linearize this equation. Then use linear regression to estimate cs and kmax and predict the growth rate at c = 2 mg/L.

Solution:


Equation (14.14(a)), which is in the format of saturation-growth-rate model can be linearized by inverting it to give:





Thus, a plot of 1/k (y) versus 1/c2 (x) will yield a straight line with a slope of cs/kmax and an intercept of 1/kmax. The data can be set up in tabular form and the necessary sums computed as in table below.












The means can be computed as:




The slope and intercept can then be calculated with Eqs (14.15) and (14.16) as in textbook.






The least-squares fit of the transformed data is 1/k = 0.09666 + 0.20201(1/c2).

The model coefficients can then be calculated as:
kmax = 1/0.09666 = 10.34554
cs = 0.20201 x 10.34554 = 2.0899

The growth rate at c = 2 mg/L can be predicted as:
1/k = 0.09666 + 0.20201(1/4) = 0.1471625
k = 6.7952 per day

*The linregr M-file can also be used to determine the least-squares fit:
>> format long
>> c = [0.5 0.8 1.5 2.5 4];
>> k = [1.1 2.5 5.3 7.6 8.9];
>> [a,r2,syx] = linregr(1./c.^2,1./k)

a =

   0.202005196520525   0.096665700618091


r2 =

   0.999569288346182


syx =

   0.007995513530533

The model coefficients can then be calculated as:
>> kmax = 1/a(2)

kmax =

  10.344930969370603

>> cs = kmax*a(1)

cs =

   2.089729813458969

Thursday, August 5, 2021

Linear Least-Squares Regression

Here is an M-file to implement linear regression. 

Linear Regression M-file

function [a,r2,syx] = linregr(x,y)
% linregr: linear regression curve fitting
%   [a, r2] = linregr(x,y): Least squares fit of straight line to data by solving the normal equations
% input:
%   x = independent variable
%   y = dependent variable
% output:
%   a = vector of slope, a(1), and intercept, a(2)
%   r2 = coefficient of determination
%   syx = standard error of estimate

n = length(x); % show number of data
if length(y)~=n, error('x and y must be same length'); end
% error checking to have complete number of data points
x = x(:); y = y(:); % convert to column vectors
sx = sum(x); sy = sum(y);
sx2 = sum(x.*x); sxy = sum(x.*y); sy2 = sum(y.*y);
a(1) = (n*sxy-sx*sy)/(n*sx2-sx^2); % a(1) = slope
a(2) = sy/n-a(1)*sx/n; % a(2) = intercept
r2 = ((n*sxy-sx*sy)/sqrt(n*sx2-sx^2)/sqrt(n*sy2-sy^2))^2;
Sr = sum((y-a(2)-a(1)*x).^2);
St = sum((y-mean(y)).^2);
syx = sqrt(Sr/(n-2)); 

% create plot of data and best fit line
xp = linspace(min(x),max(x),2);
yp = a(1)*xp+a(2);
% best fit line equation
plot(x,y,'o',xp,yp),xlabel('x'),ylabel('y')
% to generate plot of x vs y with circle marker and plot for best fit line
grid on

Linear Least-Squares Regression

Problem 14.9.


The concentration of E.coli bacteria in a swimming area is monitored after a storm:
The time is measured in hours following the end of the storm and the unit CFU is a "colony forming unit". Use this data to estimate (a) the concentration at the end of the storm (t = 0) and (b) the time at which the concentration will reach 200 CFU/100 mL. Note that your choice of model should be consistent with the fact that negative concentrations are impossible and that the bacteria concentration always decreases with time. 

Solution:


Based on the clues provided (underlined), we can expect the model best describes the given data should be exponential model.




The above equation can be linearized by taking its natural logarithm to yield:




Thus, a plot of ln c (y) versus t (x) will yield a straight line with a slope of β and an intercept of ln α.

The data can be set up in tabular form and the necessary sums computed as in table follow.










The mean can be computed as: 




The slope and intercept can then be calculated with Eq.(14.15) and (14.16) as in textbook:





Hence, the least-squares fit of transformed data is ln c = 7.5936 - 0.053506t.

The coefficients of the exponential model are determined as α = exp(7.5936) = 1985.44 and β = -0.053506. Thus, the least-squares exponential fit is c = 1985.44e-0.053506t. Using this exponential fit, we can solve for:

(a) When t = 0: c = 1985.44 CFU/100 mL. 
(b) When c = 200: t = 42.898 hours. 

Figure below showed the exponential model fit along with the data. 
*MATLAB commands to generate the plot:
>> t = [4 8 12 16 20 24];
>> c = [1600 1320 1000 890 650 560];
>> tp = linspace(min(t),max(t));
>> cp = 1985.44*exp(-0.053506*tp);
>> plot(t,c,'o',tp,cp),grid,xlabel('t (hr)'),ylabel('c (CPU/100 mL)')

Tuesday, August 3, 2021

Linear Least-Squares Regression

Problem 14.7.


The following data were gathered to determine the relationship between pressure and temperature of a fixed volume of 1 kg of nitrogen. The volume is 10 m3.
Employ the ideal gas law pV = nRT to determine R on the basis of these data. Note that for the law, T must be expressed in kelvins. 

Solution:


Step 1: Rearrange ideal gas law with p in terms of T. 
p = (nR/V)T
Note that the above expression is a linear equation (intercept = 0, slope = nR/V).

Step 2: Apply criteria for best-fit line by minimizing the sum of squares of the residuals.
The sum of squares of the residuals can be written as:





To determine the value for a1, the above equation is differentiated with respect to the unknown:




Next, setting the derivative equal to zero will result in minimum Sr:







Therefore, 




Step 3: Set up the data given in tabular form and compute the necessary sums. 











a1 = 20601452.5/693933.5 = 29.688
Thus, the best-fit line is p (N/m2) = 29.688T (K). 

Step 4: Determine R based on the slope of best-fit line. 
First, we need to compute n (no of moles of nitrogen):
n = 1 kg / 28 kg/kmol = 0.035714 kmol
Given volume, V = 10 m3. Since nR/V = slope = 29.688, R = 29.688V/n.




R = 8.3127 J/mol.K
*Try to verify the unit.

Monday, August 2, 2021

Roots Finding: Open Methods

Here are the M-files provided to implement the Newton-Raphson, secant & modified secant method. 

Newton-Raphson M-file

function [root,ea,iter]=newtraph(func,dfunc,xr,es,maxit,varargin)
% newtraph: Newton-Raphson root location zeroes
% [root,ea,iter]=newtraph(func,dfunc,xr,es,maxit,p1,p2,...):
%   uses Newton-Raphson method to find the root of func
% input:
%   func = name of function
%   dfunc = name of derivative of function
%   xr = initial guess
%   es = desired relative error (default = 0.0001%)
%   maxit = maximum allowable iterations (default = 50)
%   p1,p2,... = additional parameters used by function
% output:
%   root = real root
%   ea = approximate relative error (%)
%   iter = number of iterations

if nargin<3,error('at least 3 input arguments required'),end
if nargin<4|isempty(es),es=0.0001;end
if nargin<5|isempty(maxit),maxit=50;end
iter = 0;
while (1)
  xrold = xr;
  xr = xr - func(xr)/dfunc(xr);
  iter = iter + 1;
  if xr ~= 0, ea = abs((xr - xrold)/xr) * 100; end
  if ea <= es | iter >= maxit, break, end
end
root = xr;

Secant M-file

function root = secant(func,xrold,xr,es,maxit)
% secant(func,xrold,xr,es,maxit):
% uses secant method to find the root of a function
% input:
%  func = name of function
%  xrold, xr = initial guesses
%  es = (optional) stopping criterion (%)
%  maxit = (optional) maximum allowable iterations
% output:
%  root = real root
%  if necessary, assign default values
if nargin<5, maxit=50; end %if maxit blank set to 50
if nargin<4, es=0.001; end %if es blank set to 0.001

% Secant method
iter = 0;
while (1)
xrn = xr - func(xr)*(xrold - xr)/(func(xrold) - func(xr));
iter = iter + 1;
if xrn ~= 0, ea = abs((xrn - xr)/xrn)*100; end
if ea <= es | iter >= maxit, break, end
xrold = xr;
xr = xrn;
end
root = xrn;

Modified Secant M-file

function root = modsec(func,xr,delta,es,maxit)
% secant(func,xrold,xr,es,maxit):
% uses the modified secant method
% to find the root of a function
% input:
%  func = name of function
%  xr = initial guess
%  delta = perturbation fraction
%  es = (optional) stopping criterion (%)
%  maxit = (optional) maximum allowable iterations
% output:
%  root = real root
%  if necessary, assign default values
if nargin<5, maxit=50; end %if maxit blank set to 50
if nargin<4, es=0.001; end %if es blank set to 0.001
if nargin<3, delta=1E-5; end %if delta blank set to 0.00001

% Secant method
iter = 0;
while (1)
xrold = xr;
xr = xr - delta*xr*func(xr)/(func(xr+delta*xr)-func(xr));
iter = iter + 1;
if xr ~= 0, ea = abs((xr - xrold)/xr)*100; end
if ea <= es | iter >= maxit, break, end
end
root = xr;

Sunday, August 1, 2021

Roots Finding: Bracketing Methods

Here are the M-files provided to implement the bisection & false position method. Overall the scripts are the same, the only difference is the iterative function used to evaluate the root (as highlighted in each M-file). 

Bisection M-file

function [root,fx,ea,iter]=bisect(func,xl,xu,es,maxit,varargin)
%bisect:root location zeroes
% [root,fx,ea,iter]=bisect(func,xl,xu,es,maxit,p1,p2,...):
%   uses bisection method to find the root of func
% varargin = variable number of arguments, can input any number of
% arguments in the func
%input:
%  func:name of function
%  xl,xu=lower and upper guesses
%  es=desired relative error(default=0.0001%)
%  maxit=maximum allowable iterations(default=50)
%  p1,p2,...=additional parameters used by func
%output:
%  root=real root
%  fx=function value at root
%  ea=approximate relative error(%)
%  iter=number of iterations 

if nargin<3,error('at least 3 input arguments required'),end
test = func(xl,varargin{:})*func(xu,varargin{:});
if test>0, error('no sign change'),end
if nargin<4||isempty(es),es=0.0001;end
if nargin<5||isempty(maxit),maxit=50;end
iter=0;xr=xl;ea=100;
while(1)
    xrold=xr;
    xr=(xl+xu)/2;
    iter=iter+1;
    if xr~=0,ea=abs((xr-xrold)/xr)*100;end 
    test=func(xl,varargin{:})*func(xr,varargin{:});
    if test<0
        xu=xr;
    elseif test>0
        xl=xr;
    else
        ea=0;
    end
    if ea<=es||iter>=maxit,break,end
end
root=xr;fx=func(xr,varargin{:});


False Position M-file

function [root,fx,ea,iter]=falsepos(func,xl,xu,es,maxit,varargin)
%falsepos:root location zeroes
% [root,fx,ea,iter]=falsepo(func,xl,xu,es,maxit,p1,p2,...):
%   uses falsepos method to find the root of func
% varargin = variable number of arguments, can input any number of
% arguments in the func
%input:
%  func:name of function
%  xl,xu=lower and upper guesses
%  es=desired relative error(default=0.0001%)
%  maxit=maximum allowable iterations(default=50)
%  p1,p2,...=additional parameters used by func
%output:
%  root=real root
%  fx=function value at root
%  ea=approximate relative error(%)
%  iter=number of iterations 

if nargin<3,error('at least 3 input arguments required'),end
% check for number of arg inp, if less than 3, then error message is printed out
test = func(xl,varargin{:})*func(xu,varargin{:});
if test>0, error('no sign change'),end
% if upper and lower boundary same sign, error message is printed out
if nargin<4|isempty(es),es=0.0001;end
% if no input for es, then matlab set default value as 0.0001%
if nargin<5|isempty(maxit),maxit=50;end
% if no input for maxit, then matlab set default value as 50 iterations
iter=0;xr=xl;ea=100;
% in first iteration, if f(xl)f(xr)>0,replace xl with xr, approximate relative error = 100%
while(1)
    xrold=xr;
    % xrold is xr value of previous iteration
    xr=xu-(func(xu)*(xl-xu))/(func(xl)-func(xu));
    % formula to calculate xr
    iter=iter+1;
    % to display next iteration
    if xr~=0,ea=abs((xr-xrold)/xr)*100;end
    % if xr not equal to zero, calculate ea using the formula 
    test=func(xl,varargin{:})*func(xr,varargin{:});
    % evaluate the root by multiplying f(xl) with f(xr)
    if test<0
        xu=xr;
        % if f(xl)f(xr)<0,replace xu with xr
    elseif test>0
        xl=xr;
        % if f(xl)f(xr)>0,replace xl with xr
    else
        ea=0;
        % if f(xl)f(xr)=0,found root and stop iteration
    end
    if ea<=es|iter>=maxit,break,end
    % if ea less than or equal es, then stop iteration
end
root=xr;fx=func(xr,varargin{:});
% put the calculated xr value into the function to check the answer

Roots Finding: Bracketing Methods

Problem 5.14.


A reversible chemical reaction 2A + B ⇄ C can be characterized by the equilibrium relationship 
 Eq.(5.14(a))
where the nomenclature ci represents the concentration of constituent i. Suppose that we define a variable x as representing the number of moles of C that are produced. Conservation of mass can be used to reformulate the equilibrium relationship as 
 Eq.(5.14(b))
where subscript 0 designates the initial concentration of each constituent. If K = 0.016, ca,0 = 42, cb,0 = 28, and cc,0 = 4, determine the value of x.
(a) Obtain the solution graphically.
(b) On the basis of (a), solve for the root with initial guesses of xl = 0 and xu = 20 to εs = 0.5%. Choose either bisection or false position to obtain your solution. Justify your choice. 

Solution:


(a) Firstly, substitute the parameters into the Eq.(5.14(b)) to obtain a single function in terms of x:
MATLAB can be used to plot the function:
>> x = linspace(0,20);
>> f = 0.016-(4+x)./(((42-2*x).^2).*(28-x));
>> plot(x,f),grid,xlabel('x'),ylabel('f(x)')
A visual inspection of the plot gives a rough estimate of the root, which is about 15.9 moles. The validity of the graphical estimate can be checked by substituting it into f(x) to yield:
>> f = 0.016-(4+15.9)./((42-2*15.9).^2.*(28-15.9))

f =

   1.9235e-04
which is close to zero. 

(b) In this case, I will choose bisection to solve the problem. This is because false-position is not suitable to find root for a function with significant curvature, as it would lead to poor and slow convergence. We can use bisect M-file below to solve for x:

function [root,fx,ea,iter]=bisect(func,xl,xu,es,maxit,varargin)
%bisect:root location zeroes
% [root,fx,ea,iter]=bisect(func,xl,xu,es,maxit,p1,p2,...):
%   uses bisection method to find the root of func
% varargin = variable number of arguments, can input any number of
% arguments in the func
%input:
%  func:name of function
%  xl,xu=lower and upper guesses
%  es=desired relative error(default=0.0001%)
%  maxit=maximum allowable iterations(default=50)
%  p1,p2,...=additional parameters used by func
%output:
%  root=real root
%  fx=function value at root
%  ea=approximate relative error(%)
%  iter=number of iterations 

if nargin<3,error('at least 3 input arguments required'),end
test = func(xl,varargin{:})*func(xu,varargin{:});
if test>0, error('no sign change'),end
if nargin<4||isempty(es),es=0.0001;end
if nargin<5||isempty(maxit),maxit=50;end
iter=0;xr=xl;ea=100;
while(1)
    xrold=xr;
    xr=(xl+xu)/2;
    iter=iter+1;
    if xr~=0,ea=abs((xr-xrold)/xr)*100;end 
    test=func(xl,varargin{:})*func(xr,varargin{:});
    if test<0
        xu=xr;
    elseif test>0
        xl=xr;
    else
        ea=0;
    end
    if ea<=es||iter>=maxit,break,end
end
root=xr;fx=func(xr,varargin{:});

Plug in the given initial guesses and stopping criterion:

>> f = @(x)0.016-(4+x)./((42-2*x).^2.*(28-x));
>> [root,fx,ea,iter]=bisect(f,0,20,0.5)

root =

   15.8594


fx =

   5.2493e-04


ea =

    0.4926


iter =

     8

Thus, after eight iterations, the x is computed as 15.8594 moles with an approximate relative error of 0.4926%. 

**Additional: Or else we can also use the MATLAB fzero function:

>> f = @(x)0.016-(4+x)./((42-2*x).^2.*(28-x));
>> x = fzero(f,[0,20])

x =

   15.9230

which gives the exact value of 15.9230 moles. 

Numerical Integration Formulas

Here are the M-files to implement composite trapezoidal rule for equally spaced data and unequally spaced data.  Composite Trapezoidal Rule ...