% Least squares fit of straight line to d(z) and z(d).
% auxially variable z and data d
% least squares fit to d(z)
fprintf('d(z): intercept %f slope %f\n', mest(1), mest(2) );
d(z): intercept -0.500000 slope 1.300000
% least squares fit to z(d)
mest2 = (G2'*G2)\(G2'*z);
% convert model parameters for z(d) case to d(z)
mest3(1)=-mest2(1)/mest2(2);
fprintf('dp(zp): intercept %f slope %f\n', mest2(1), mest2(2) );
dp(zp): intercept 0.457143 slope 0.742857
fprintf('zp(dp): intercept %f slope %f\n', mest3(1), mest3(2) );
zp(dp): intercept -0.615385 slope 1.346154
plot( z, d, 'ko', 'LineWidth', 3);
plot( z, dpre, 'r-', 'LineWidth', 3);
plot( d, z, 'ko', 'LineWidth', 3);
plot( d, dpre2, 'g-', 'LineWidth', 3);
% plot z(d) and transformed z(d) cases
plot( z, d, 'ko', 'LineWidth', 3);
plot( z, dpre3, 'g-', 'LineWidth', 3);
plot( z, dpre, 'r-', 'LineWidth', 2);
title('d(z) and inv z(d)');
fprintf('Caption: Linear fits to z(d) to data (circles): (left) fits to d(z),\n');
Caption: Linear fits to z(d) to data (circles): (left) fits to d(z),
fprintf('(middle) fit to z(d), (right) d(z) implied by fit to z(d)\n');
(middle) fit to z(d), (right) d(z) implied by fit to z(d)
% An inverse problem to determine the model parameter
% in a model with an exponential function, d(z)=m1*exp(m2 z)
% using (Case 1) a linearizing transformation
% and (Case 2) Newton's Method.
% data, a exponential d=m1*exp(m2 z)
dtrue = mtrue(1)*exp(mtrue(2)*z);
dobs = dtrue + random('Normal',0,sd,N,1);
% but don't let data become negative
% linearizing transformation, solve by standard least squares
% ln(d) = ln(m1) + m2 * z
mestlin = (G'*G)\(G'*lndobs);
mestlin(1) = exp(mestlin(1));
dprelin = mestlin(1)*exp(mestlin(2)*z);
% Newton's Method iterative solution
% dd/dm2 = m1 z exp( m2 z)
% initial guess is previous solution
Nit=10; % maximum number of iterations
sdmmin = 1e-5; % terminate iteration early when increment dm
% has sqrt(variance(dm))<sdmmin
dd = dobs - (mest(1)*exp(mest(2)*z));
G = [exp(mest(2)*z), mest(1)*z.*exp(mest(2)*z)];
sdm = sqrt((dm'*dm)/M); % sqrt(variance(dm))
break; % terminate iterations early
% least squares prediction
dpre = mest(1)*exp(mest(2)*z);
axis( [zmin, zmax, 0, 1] );
plot( z, dobs, 'ro', 'LineWidth', 3 );
plot( z, dtrue, 'r-', 'LineWidth', 3 );
plot( z, dprelin, 'b-', 'LineWidth', 3 );
plot( z, dpre, 'g-', 'LineWidth', 3 );
axis( [zmin, zmax, -3, 0] );
plot( z, log10(dobs), 'ro', 'LineWidth', 3 );
plot( z, log10(dtrue), 'r-', 'LineWidth', 3 );
plot( z, log10(dprelin), 'b-', 'LineWidth', 3 );
plot( z, log10(dpre), 'g-', 'LineWidth', 3 );
fprintf('Caption (left) Fit to exponentially decating data (circles), showing\n');
Caption (left) Fit to exponentially decating data (circles), showing
fprintf('true data (red), linearized fit (blue), iterative fit (green). (Right)\n');
true data (red), linearized fit (blue), iterative fit (green). (Right)
fprintf('same as left, except plot is semi-logarithmic.\n');
same as left, except plot is semi-logarithmic.
fprintf('True m1: %.3f m2: %.3f\n', mtrue(1), mtrue(2) );
True m1: 0.900 m2: -4.000
fprintf('Newtons m1: %.3f m2: %.3f\n', mest(1), mest(2) );
Newtons m1: 0.909 m2: -4.040
fprintf('Linearizing m1: %.3f m2: %.3f\n', mestlin(1), mestlin(2) );
Linearizing m1: 0.904 m2: -4.041
% E(m) for several hypothetial 1D non-linear problems
% only one model parameter, m1
d1true = sin(5*(m1true-2.5)*z)-((m1true-2.5))*z;
d1obs=d1true+random('Normal',0,sd,N,1);
% tabulate error on the grid
d1pre = sin(5*(m(i)-2.5)*z)-((m(i)-2.5))*z;
% find point of minimum error
[E1min, iE1min] = min(E1);
axis( [mmin, mmax, 0, max(E1)] );
plot( m, E1, 'k-', 'Linewidth', 3 );
d1true = ((abs((m1true-2))-0.5)*z);
d1obs=d1true+random('Normal',0,sd,N,1);
% tabulate error on the grid
d1pre = ((abs((m(i)-2))-0.5)*z);
% find point of minimum error
[E1min, iE1min] = min(E1);
axis( [mmin, mmax, 0, max(E1)] );
plot( m, E1, 'k-', 'Linewidth', 3 );
d1true = sin(5*(m1true+z));
d1obs=d1true+random('Normal',0,sd,N,1);
% tabulate error on the grid
% find point of minumum error
[E1min, iE1min] = min(E1);
axis( [mmin, mmax, 0, max(E1)] );
plot( m, E1, 'k-', 'Linewidth', 3 );
t = abs(m1true-2.0) + abs(m1true-3.0);
d1true = exp( -(t*z/10).^2 );
d1obs=d1true+random('Normal',0,sd,N,1);
% tabulate error on the grid
t = abs(m(i)-2.0) + abs(m(i)-3.0);
d1pre = exp( -(t*z/10).^2 );
% find point of minimum error
[E1min, iE1min] = min(E1);
axis( [mmin, mmax, 0, max(E1)] );
plot( m, E1, 'k-', 'Linewidth', 3 );
fprintf('Caption: Hypothetical error surfaces\n');
Caption: Hypothetical error surfaces
% E(m) for several 2D non-linear problems
% 2D grid of model parameters m1 and m2
Dm1 = (m1max-m1min)/(Mg1-1);
m1 = m1min + Dm1*[0:Mg1-1];
Dm2 = (m2max-m2min)/(Mg2-1);
m2 = m2min + Dm2*[0:Mg2-1];
dtrue = ((m1true-0.2)*za-((m2true-0.3)*zb).^2).*z;
% observed data is true data plus random noise
dobs = dtrue + random('Normal',0,sd,N,1);
% tabulate error on the grid, keeping track of
% minimum error along the way
dpre = ((m1(i)-0.2)*za-((m2(j)-0.3)*zb).^2).*z;
fprintf('Emin %f at m1(%d) m2(%d) %f %f\n', Emin, Emini, Eminj, m1(Emini), m2(Eminj) );
Emin 0.000672 at m1(33) m2(33) 0.320000 0.320000
% plot error surface E(m1,m2)
axis( [m2min, m2max, m1min, m1max] );
imagesc( [m2min, m2max], [m1min, m1max], E );
plot( m2(Eminj), m1(Emini), 'wo', 'LineWidth', 3 );
fprintf('Caption: Hypthetical error surface, (colors)\n');
Caption: Hypthetical error surface, (colors)
fprintf('with minimum (white circle) superimposed.\n');
with minimum (white circle) superimposed.
axis( [zmin, zmax, dmin, dmax] );
plot(z,dobs,'ko','LineWidth',2);
plot(z,dtrue,'k-','LineWidth',2);
plot(z,dpresave,'r-','LineWidth',2);
fprintf('Caption: True data (black line), observed (circles) and predicted (red line)).\n');
Caption: True data (black line), observed (circles) and predicted (red line)).
fprintf('with minimum (white circle) superimposed.\n');
with minimum (white circle) superimposed.
dtrue = sin(12*pi*(m1true-0.5))*z+(m2true*z).^0.5;
% observed data is true data plus random noise
dobs = dtrue + random('Normal',0,sd,N,1);
% Tabulate error E(m1,m2) on the grid, searching
% for the point of minimum error along the way
dpre = sin(12*pi*(m1(i)-0.5))*z+(m2(j)*z).^0.5;
fprintf('Emin %f at m1(%d) m2(%d) %f %f\n', Emin, Emini, Eminj, m1(Emini), m2(Eminj) );
Emin 0.109176 at m1(52) m2(92) 0.510000 0.910000
axis( [m2min, m2max, m1min, m1max] );
imagesc( [m2min, m2max], [m1min, m1max], E );
plot( m2(Eminj), m1(Emini), 'wo', 'LineWidth', 3 );
fprintf('Caption: Hypthetical error surface, (colors)\n');
Caption: Hypthetical error surface, (colors)
fprintf('with minimum (white circle) superimposed.\n');
with minimum (white circle) superimposed.
axis( [zmin, zmax, dmin, dmax] );
plot(z,dobs,'ko','LineWidth',2);
plot(z,dtrue,'k-','LineWidth',2);
plot(z,dpresave,'r-','LineWidth',2);
fprintf('Caption: True data (black line), observed (circles) and predicted (red line)).\n');
Caption: True data (black line), observed (circles) and predicted (red line)).
fprintf('with minimum (white circle) superimposed.\n');
with minimum (white circle) superimposed.
% Grid Search method applied to inverse problem
% d(x)=g(x, m1, m2) with g = sin(w0*m(1)*x) + m(1)*m(2)
% data are in a simple auxillary variable, x
% d(x)=g(x, m1, m2) with g = sin(w0*m(1)*x) + m(1)*m(2);
dtrue = sin(w0*mt(1)*x) + mt(1)*mt(2); % true data
dobs = dtrue + random('Normal',0,sd,N,1); % observed data
axis( [0, xmax, 0, 4 ] );
plot(x,dtrue,'k-','LineWidth',3);
plot(x,dobs,'ko','LineWidth',3);
% tabulate error E on grid.
% Note m1 varies along rows of E and m2 along columns
dpre = sin(w0*m1a(j)*x) + m1a(j)*m2a(k);
E(j,k) = (dobs-dpre)'*(dobs-dpre);
% Example of use of Esurface() function
% It refines the minimum using a quadratic approximation
% and provides an error estimate using the 2nd derivative
% note that the "column" variable is sent and returned
% before the "row" variable in this function
[ m2est, m1est, E0, cov21, status ] = gda_Esurface( m2a, m1a, E, sd^2 );
sigmam1 = sqrt( cov21(2,2) );
sigmam2 = sqrt( cov21(1,1) );
% evaluate prediction and plot it
dpre = sin(w0*m1est*x) + m1est*m2est;
plot(x,dpre,'r-','LineWidth',3);
fprintf('Caption: Exemplary curve fit wia grid search, showing true data (black curve)\n');
Caption: Exemplary curve fit wia grid search, showing true data (black curve)
fprintf('observed data (circles) and predicted data (red curve)\n');
observed data (circles) and predicted data (red curve)
axis( [m2min, m2max, m1min, m1max] );
imagesc( [m2min, m2max], [m1min, m1max], E);
% plot true and estimate model
plot( m2est, m1est, 'wo', 'LineWidth', 3 );
plot( mt(2), mt(1), 'go', 'LineWidth', 3 );
plot( [m2est, m2est]', [m1est-2*sigmam1, m1est+2*sigmam1]', 'r-', 'LineWidth', 2 );
plot( [m2est-2*sigmam2, m2est+2*sigmam2]', [m1est, m1est]', 'r-', 'LineWidth', 2 );
fprintf('Caption: Error surface, with true solution (green circle), estimate solution\n');
Caption: Error surface, with true solution (green circle), estimate solution
fprintf('(white circles) and 95 percent confidence intervals (red bars), superimposed\n');
(white circles) and 95 percent confidence intervals (red bars), superimposed
% Newton's Method solution to exemplary 1D non-linear
% inverse problem, d(z) = sin(k*m*z)*z;
% This version uses a starting guess for the model
% parameter m1 that leads to convergence to the global
% minimum of the error surface (and hence to the correct
% value of the model parameter).
% define 1D grid for model parameter m1
% only one model parameter, m1
dtrue = sin(k*mtrue.*zp).*z;
% observed data is true data plus random noise
dobs=dtrue+random('Normal',0,sd,N,1);
% tabulate error E(m) on the grid
dpre = sin(k*m(i).*zp).*z;
[E1min, iE1min] = min(E1);
% d = sin(k*m(i).*zp).*z;
% dd/dm = k.*zp.*z.*cos(k*m(i).*zp);
% d = d(m0) + (dd/dm)|m0 (m-m0)
% tabulate a quadratic version of the error
% correspinding to a linearized version of
% the inverse problem (linearized around a point m0)
im0 = floor((m0-mmin)/Dm)+1;
dddm = k.*zp.*z.*cos(k*m0.*zp);
dpre = d0 + dddm * (m(i)-m0); % linearized approximation
% find minimum of error surface
[E2min, iE2min] = min(E2);
axis( [mmin, mmax, 0, max(E1)] );
% true error surface, with circle at minimum, and line dropped to axis
plot( m, E1, 'k-', 'Linewidth', 3 );
plot( m1est, E1min, 'ko', 'Linewidth', 3 );
plot( [m1est, m1est], [0, E1min], 'k:', 'Linewidth', 2 );
% parabiolic approximation, with circle at minimum, and line dropped to
plot( m, E2, 'r:', 'Linewidth', 3 );
plot( m2est, E2min, 'ro', 'Linewidth', 3 );
plot( [m2est, m2est], [0, E2min], 'r:', 'Linewidth', 2 );
plot( m0, E2(im0), 'ko', 'Linewidth', 3 );
plot( [m0, m0], [0, E2(im0)], 'k:', 'Linewidth', 2 );
fprintf('Caption: Exemplary error surface E(m) (back curve) with minimum value at m=3 (black circle).');
Caption: Exemplary error surface E(m) (back curve) with minimum value at m=3 (black circle).
fprintf('showing parabola tangegent to curve at m=2.5 (red curve), with minimum at m=3.3 (red circle)\n');
showing parabola tangegent to curve at m=2.5 (red curve), with minimum at m=3.3 (red circle)
% Newton's Method solution to exemplary 1D non-linear
% inverse problem, d(z) = sin(k*m*z)*z
% This version uses a starting guess for the model
% parameter m1 that leads to convergence to a local
% minimum of the error surface (and hence to an incorrect
% value of the model parameter).
% define 1D grid for model parameter m1
% only one model parameter, m1
dtrue = sin(k*mtrue.*zp).*z;
% observed data is true data plus random noise
dobs=dtrue+random('Normal',0,sd,N,1);
% tabulate error E(m) on the grid
dpre = sin(k*m(i).*zp).*z;
[E1min, iE1min] = min(E1);
% d = sin(k*m(i).*zp).*z;
% dd/dm = k.*zp.*z.*cos(k*m(i).*zp);
% d = d(m0) + (dd/dm)|m0 (m-m0)
% tabulate a quadratic version of the error
% correspinding to a linearized version of
% the inverse problem (linearized around a point m0)E2=zeros(Mg,1);
im0 = floor((m0-mmin)/Dm)+1;
dddm = k.*zp.*z.*cos(k*m0.*zp);
dpre = d0 + dddm * (m(i)-m0);
% find minimum of error surface
[E2min, iE2min] = min(E2);
axis( [mmin, mmax, 0, max(E1)] );
% true error surface, with circle at minimum, and line dropped to axis
plot( m, E1, 'k-', 'Linewidth', 3 );
plot( m1est, E1min, 'ko', 'Linewidth', 3 );
plot( [m1est, m1est], [0, E1min], 'k:', 'Linewidth', 2 );
% parabiolic approximation, with circle at minimum, and line dropped to
plot( m, E2, 'r:', 'Linewidth', 3 );
plot( m2est, E2min, 'ro', 'Linewidth', 3 );
plot( [m2est, m2est], [0, E2min], 'r:', 'Linewidth', 2 );
plot( m0, E2(im0), 'ko', 'Linewidth', 3 );
plot( [m0, m0], [0, E2(im0)], 'k:', 'Linewidth', 2 );
fprintf('Caption: Exemplary error surface E(m) (back curve) with minimum value at m=3 (black circle).');
Caption: Exemplary error surface E(m) (back curve) with minimum value at m=3 (black circle).
fprintf('showing parabola tangegent to curve at m=1 (red curve), with minimum at m=3.3 (red circle)\n');
showing parabola tangegent to curve at m=1 (red curve), with minimum at m=3.3 (red circle)
% Newton's method applied to inverse problem
% d(x)=g(x, m1, m2) with g = sin(w0*m(1)*x) + m(1)*m(2)
% d(x)=g(x, m1, m2) with g=sin(w0*m(1)*x) + m(1)*m(2)
dtrue = sin(w0*mt(1)*x) + mt(1)*mt(2); % true data
dobs = dtrue + random('Normal',0,sd,N,1); % observed data
axis( [0, xmax, 0, 4 ] );
plot(x,dtrue,'k-','LineWidth',3);
plot(x,dobs,'ko','LineWidth',3);
% 2D grid, for plotting purposes only
% tabulate error, E, on grid for plotting purposed only
dpre = sin(w0*m1a(j)*x) + m1a(j)*m2a(k);
E(j,k) = (dobs-dpre)'*(dobs-dpre);
% Newton's method, calculate derivatives
% y = sin( w0 m1 x) + m1 m2;
% dy/dm1 = w0 x cos( w0 m1 x) + m2
% initial guess and corresponding error
dg = sin(w0*mg(1)*x) + mg(1)*mg(2);
Eg = (dobs-dg)'*(dobs-dg);
plot( mg(2), mg(1), 'ko', 'LineWidth', 3 );
% save solution and minimum error as a function of iteration number
% iterate to improve initial guess
% predict data at current guess for solution
dg = sin( w0*mg(1)*x) + mg(1)*mg(2);
Eg=dd'*dd; % current error
Ehis(k)=Eg; % save error history
% build linearized data kernel
G(:,1) = w0 * x .* cos( w0 * mg(1) * x ) + mg(2);
G(:,2) = mg(2)*ones(N,1);
% least squares solution for improvement to m
plot( mg(2), mg(1), 'wo', 'LineWidth', 2 );
% estimated solution is from final iteration
% evaluate prediction and plot it
dpre = sin(w0*m1est*x) + m1est*m2est;
plot(x,dpre,'r-','LineWidth',3);
fprintf('Caption: Exemplary curve fit with Newtons methiod, showing observed data (circles),\n');
Caption: Exemplary curve fit with Newtons methiod, showing observed data (circles),
fprintf('true data (black curve) and predicted data (red curve)\n')
true data (black curve) and predicted data (red curve)
axis( [m2min, m2max, m1min, m1max] );
imagesc( [m2min, m2max], [m1min, m1max], E);
% plot true, history, starting and final solution on error surface
plot( m2his, m1his, 'w-', 'LineWidth', 1 );
plot( mt(2), mt(1), 'go', 'LineWidth', 2 );
plot( m2est, m1est, 'ro', 'LineWidth', 2 );
plot( m2his(1), m1his(1), 'wo', 'LineWidth', 2 );
fprintf('Caption: Error surface (colors). with initial guess of solution\n');
Caption: Error surface (colors). with initial guess of solution
fprintf('(white circles). trajectory (white line). estimated solution (red\n');
(white circles). trajectory (white line). estimated solution (red
fprintf('circle) and true solution (green)\n');
circle) and true solution (green)
% plots of the history of E, m1 and m2
plot( [0:Niter-1], Ehis, 'k-', 'LineWidth', 2 );
plot( [0, Niter-1], [mt(1), mt(1)], 'r', 'LineWidth', 2 );
plot( [0:Niter-1], m1his, 'k-', 'LineWidth', 2 );
plot( [0, Niter-1], [mt(2), mt(2)], 'r', 'LineWidth', 2 );
plot( [0:Niter-1], m2his, 'k-', 'LineWidth', 2 );
fprintf('Caption: (top) Error as a function of iteration number. (middle) Model parameterr\n');
Caption: (top) Error as a function of iteration number. (middle) Model parameterr
fprintf('m1 as a function of iteration number (black curve) and true value (red line). (bottom) Model parameter m2\n');
m1 as a function of iteration number (black curve) and true value (red line). (bottom) Model parameter m2
fprintf('as a fuction of iteration number (black curve) and true value (red line)\n');
as a fuction of iteration number (black curve) and true value (red line)
% Plots a simple Normal p.d.f. p(x1,x1) with a parameteric
% curve superimposed and then samples the p.d.f. under the
% curve and makes a second plot of p.d.f. as a function of
% arc-length s along the curve. In this version, the curve
% is very smooth and p(s) is bell-shaped.
Dx1 = (x1max-x1min)/(Nx1-1);
x1 = x1min + Dx1*[0:Nx1-1]';
Dx2 = (x2max-x2min)/(Nx2-1);
x2 =x2min + Dx2*[0:Nx2-1]';
% parameters for a Normal pdf
C1 = diag( [sx1^2, sx2^2]' );
norm1 = (1/(2*pi)) * (1/sqrt(DC1));
% tabulate the Normal pdf on the grid
x =[x1(i), x2(j)]' - bar;
P1(i,j) = norm1*exp( -0.5 * x'*CI1*x );
% axis for parametric curve
x2p = 1+s+sin(2*pi*s/smax)-2*(s/smax).^2;
% pdf along parameteric curve
ipx1 = 1+floor((x1p-x1min)/Dx1);
ipx2 = 1+floor((x2p-x2min)/Dx2);
% insure indices in range
Ps(i) = P1(ipx1(i), ipx2(i));
axis( [x1min, x1max, x2min, x2max] );
imagesc( [x1min, x1max], [x2min, x2max], P1 );
plot( x2bar, x1bar, 'wo', 'LineWidth', 3 );
plot( [x2bar, x2bar], [x1min, x1min+0.1], 'w-', 'LineWidth', 3 );
plot( [x2min, x2min+0.1], [x1bar, x1bar], 'w-', 'LineWidth', 3 );
plot( x2p, x1p, 'w-', 'LineWidth', 3 );
plot( x2smax, x1smax, 'ko', 'LineWidth', 4);
plot( [x2min, x2smax], [x1smax, x1smax], 'w:', 'LineWidth', 2);
plot( [x2smax, x2smax], [x1min, x1smax], 'w:', 'LineWidth', 2);
fprintf('Caption: Exemplary normal pdf (colors) with mean (white circle),\n');
Caption: Exemplary normal pdf (colors) with mean (white circle),
fprintf('curve f(x)=0 (white curve), and maximum likelihood point (black circle), superimposed.')
curve f(x)=0 (white curve), and maximum likelihood point (black circle), superimposed.
% plot of 1D pdf (along curve)
axis( [smin, smax, 0, 0.3] );
plot( s, Ps, 'b-', 'Linewidth', 3 );
plot( [smaxP, smaxP], [0, 0.03], 'k-', 'LineWidth', 3);
plot( smaxP, Pmax, 'bo', 'LineWidth', 3);
% calculate mean of distribution
plot( [smean, smean], [0, 0.02], 'k-', 'LineWidth', 3);
fprintf('Caption: probability alone the curve p(x)=0, with the maximum\n');
Caption: probability alone the curve p(x)=0, with the maximum
fprintf('likelihood point shown (circle and long bar) and mean (short bar).');
likelihood point shown (circle and long bar) and mean (short bar).
% Plots a simple Normal p.d.f. p(x1,x1) with a parameteric
% curve superimposed and then samples the p.d.f. under the
% curve and makes a second plot of p.d.f. as a function of
% arc-length s along the curve. In this version, the curve
% is complicated and p(s) is bimodal.
Dx1 = (x1max-x1min)/(Nx1-1);
x1 = x1min + Dx1*[0:Nx1-1]';
Dx2 = (x2max-x2min)/(Nx2-1);
x2 =x2min + Dx2*[0:Nx2-1]';
% paameters for a Normal pdf p(x1,x2)
C1 = diag( [sx1^2, sx2^2]' );
norm1 = (1/(2*pi)) * (1/sqrt(DC1));
% tabulate the Normal pdf on the grid
x =[x1(i), x2(j)]' - bar;
P1(i,j) = norm1*exp( -0.5 * x'*CI1*x );
% axis for parametric curve
% parameric curve (carefully tuned to be aestetically complciated)
x2p = 1+s+sin(2*pi*s/smax)-(2*(s/smax).^2)+0.3*exp(-0.5*((s-2.3).^2)/(0.1^2))-0.3*exp(-0.5*((s-2.8).^2)/(0.1^2));
% pdf on parameteric curve
ipx1 = 1+floor((x1p-x1min)/Dx1);
ipx2 = 1+floor((x2p-x2min)/Dx2);
% insure indices in range
Ps(i) = P1(ipx1(i), ipx2(i));
% 2D plot of p(x1,x2) with curve superimposed
axis( [x1min, x1max, x2min, x2max] );
imagesc( [x1min, x1max], [x2min, x2max], P1 );
plot( x2bar, x1bar, 'wo', 'LineWidth', 3 );
plot( [x2bar, x2bar], [x1min, x1min+0.1], 'w-', 'LineWidth', 3 );
plot( [x2min, x2min+0.1], [x1bar, x1bar], 'w-', 'LineWidth', 3 );
plot( x2p, x1p, 'w-', 'LineWidth', 3 );
plot( x2smax, x1smax, 'ko', 'LineWidth', 4);
plot( [x2min, x2smax], [x1smax, x1smax], 'w:', 'LineWidth', 2);
plot( [x2smax, x2smax], [x1min, x1smax], 'w:', 'LineWidth', 2);
fprintf('Caption: Exemplary normal pdf (colors) with mean (white circle),\n');
Caption: Exemplary normal pdf (colors) with mean (white circle),
fprintf('curve f(x)=0 (white curve), and maximum likelihood point (black circle), superimposed.')
curve f(x)=0 (white curve), and maximum likelihood point (black circle), superimposed.
axis( [smin, smax, 0, 0.3] );
plot( s, Ps, 'b-', 'Linewidth', 3 );
plot( [smaxP, smaxP], [0, 0.03], 'k-', 'LineWidth', 3);
plot( smaxP, Pmax, 'bo', 'LineWidth', 3);
% calculate mean of distribution
plot( [smean, smean], [0, 0.02], 'k-', 'LineWidth', 3);
fprintf('Caption: probability alonr the curve p(x)=0, with the maximum\n');
Caption: probability alonr the curve p(x)=0, with the maximum
fprintf('likelihood point shown (circle and long bar) and mean (short bar).\n');
likelihood point shown (circle and long bar) and mean (short bar).
% Gradient method applied to inverse problem
% d(x)=g(x, m1, m2) with g = sin(w0*m(1)*x) + m(1)*m(2)
dtrue = sin(w0*mt(1)*x) + mt(1)*mt(2);
dobs = dtrue + random('Normal',0,sd,N,1);
% tabulate E(m1,m2) on grid (for plotting purposes only)
yest = sin(w0*m1a(j)*x) + m1a(j)*m2a(k);
E(j,k) = (dobs-yest)'*(dobs-yest);
% parameters for gradient method
% save history of Error and model parameters
% error and its gradient at the trial solution
ygo = sin( w0*mgo(1)*x) + mgo(1)*mgo(2);
Ego = (ygo-dobs)'*(ygo-dobs);
dydmo(:,1) = w0 * x .* cos( w0 * mgo(1) * x ) + mgo(2);
dydmo(:,2) = mgo(2)*ones(N,1);
dEdmo = 2*dydmo'*(ygo-dobs);
v = -dEdmo / sqrt(dEdmo'*dEdmo);
Nhis=Nhis+1; % counts actual iterations
yg = sin( w0*mg(1)*x) + mg(1)*mg(2);
Eg = (yg-dobs)'*(yg-dobs);
dydm(:,1) = w0 * x .* cos( w0 * mg(1) * x ) + mg(2);
dydm(:,2) = mg(2)*ones(N,1);
dEdm = 2*dydm'*(yg-dobs);
if( (Eg<=(Ego + c1*alpha*v'*dEdmo)) )
Dmg = sqrt( (mg-mgo)'*(mg-mgo) );
break; % terminate iterations when change
% in solution is suffiently small
% estimated solution is last iteration
% truncate to actual lenth
% evaluate prediction and plot it
dpre = sin(w0*m1est*x) + m1est*m2est;
% plot true and observed data
plot(x,dobs,'ko','LineWidth',3);
plot(x,dtrue,'k-','LineWidth',3);
plot(x,dpre,'r-','LineWidth',3);
fprintf('Caption: True data (black curve), observed data (black circles) and predicted data (red curve).\n');
Caption: True data (black curve), observed data (black circles) and predicted data (red curve).
axis( [m2min, m2max, m1min, m1max] );
imagesc( [m2min, m2max], [m1min, m1max], E);
% plot true, history, starting and final solution on error surface
plot( m2his, m1his, 'w-', 'LineWidth', 1 );
plot( mt(2), mt(1), 'go', 'LineWidth', 2 );
plot( m2est, m1est, 'ro', 'LineWidth', 2 );
plot( m2his(1), m1his(1), 'wo', 'LineWidth', 2 )
fprintf('Caption: Error surface E(m1,m2) (colors), with initial guess (white circle)\n');
Caption: Error surface E(m1,m2) (colors), with initial guess (white circle)
fprintf('minimization path (white line), estimated solution (red circle)\n');
minimization path (white line), estimated solution (red circle)
fprintf('and true solution (green circle), superimposed.\n');
and true solution (green circle), superimposed.
% plot history of E, m1, m2
plot( [0:Nhis-1], Ehis, 'k-', 'LineWidth', 3 );
plot( [0:Nhis-1], m1his, 'k-', 'LineWidth', 3 );
plot( [0,Nhis-1], [mt(1), mt(1)], 'r:', 'LineWidth', 2);
plot( [0:Nhis-1], m2his, 'k-', 'LineWidth', 3 );
plot( [0,Nhis-1], [mt(2), mt(2)], 'r:', 'LineWidth',2 );
fprintf('Caption: (top) Error E(i) as a function of iteration number i.\n');
Caption: (top) Error E(i) as a function of iteration number i.
fprintf('(middle) Model parameter m1(i) as a function of iteration number i,\n');
(middle) Model parameter m1(i) as a function of iteration number i,
fprintf('with true solution (red line) for comparison. (bottom) Same as\n');
with true solution (red line) for comparison. (bottom) Same as
fprintf('middel, except for model parameter m2\n');
middel, except for model parameter m2
% plots the distributions of one bit-mutations
% for both normal binary and Gray code representations
% of three exemplary 16-bit integers
global gray1 gray1index pow2;
load('gda_gray1table.mat');
axis( [0, 65535, 0, 1] );
plot( [i1,i1]', [0, 0.2]', 'r-', 'LineWidth', 2 );
plot( [i1,i1]', [0.8, 1]', 'r-', 'LineWidth', 2 );
plot( [i2,i2]', [0.2, 0.8]', 'k-', 'LineWidth', 2 );
axis( [0, 65535, 0, 1] );
plot( [i1,i1]', [0, 0.2]', 'r-', 'LineWidth', 2 );
plot( [i1,i1]', [0.8, 1]', 'r-', 'LineWidth', 2 );
plot( [i2,i2]', [0.2, 0.8]', 'k-', 'LineWidth', 2 );
axis( [0, 65535, 0, 1] );
plot( [i1,i1]', [0, 0.2]', 'r-', 'LineWidth', 2 );
plot( [i1,i1]', [0.8, 1]', 'r-', 'LineWidth', 2 );
plot( [i2,i2]', [0.2, 0.8]', 'k-', 'LineWidth', 2 );
axis( [0, 65535, 0, 1] );
plot( [i1,i1]', [0, 0.2]', 'r-', 'LineWidth', 2 );
plot( [i1,i1]', [0.8, 1]', 'r-', 'LineWidth', 2 );
plot( [i2,i2]', [0.2, 0.8]', 'k-', 'LineWidth', 2 );
axis( [0, 65535, 0, 1] );
plot( [i1,i1]', [0, 0.2]', 'r-', 'LineWidth', 2 );
plot( [i1,i1]', [0.8, 1]', 'r-', 'LineWidth', 2 );
plot( [i2,i2]', [0.2, 0.8]', 'k-', 'LineWidth', 2 );
axis( [0, 65535, 0, 1] );
plot( [i1,i1]', [0, 0.2]', 'r-', 'LineWidth', 2 );
plot( [i1,i1]', [0.8, 1]', 'r-', 'LineWidth', 2 );
plot( [i2,i2]', [0.2, 0.8]', 'k-', 'LineWidth', 2 );
fprintf('Caption: Distribution of integers (black bars) resulting from a bit bit mutation\n');
Caption: Distribution of integers (black bars) resulting from a bit bit mutation
fprintf('of a target inter (red bar). (Left column) Standard coding, (right colummn) Gray coding.\n');
of a target inter (red bar). (Left column) Standard coding, (right colummn) Gray coding.
% Genetic Algorithm applied to inverse problem
% d(x)=g(x, m1, m2) with g = sin(w0*m(1)*x) + m(1)*m(2)
global gray1 gray1index pow2;
load('gray1table.mat'); % load table of Gray codes
dtrue = sin(w0*mt(1)*x) + mt(1)*mt(2);
dobs = dtrue + random('Normal',0,sd,N,1);
axis( [0, xmax, 0, 4 ] );
plot(x,dtrue,'k-','LineWidth',3);
plot(x,dobs,'ko','LineWidth',3);
% this is just for plotting purposes
% the genetic algorith does not require a grid
m1a = m1min+Dm*[0:Lm-1]';
m2a = m2min+Dm*[0:Lm-1]';
% compute error E on the grid
% this is just for plotting purposes
% the genetic algorith does not require a grid
dpre = sin(w0*m1a(j)*x) + m1a(j)*m2a(k);
E(j,k) = (dobs-dpre)'*(dobs-dpre);
K = 100; % number of individuals in the population
m0 = [0.25, 0.30]; % initial guess for m1
mL = [m1min, m2min]'; % solution > mL
mR = [m1max, m2max]'; % solution < mR
dpre = sin(w0*m0(1)*x) + m0(1)*m0(2); % initial prediction
e = dobs-dpre; % individual errors
E0 = e'*e; % total error at start
mind = zeros(K, M); % solution for each individual
Eind = E0*ones(K,1); % error for each individual
F = ones(K,1); % fitness of each individual
genes = char(48*ones(K, 16*M)); % genes for each individual
r = random('Normal',0,0.05,K,1);
mind(:,i) = m0(i)*ones(K,1)+r; % all individuals initialized to initial guess
k = floor(65535.999*(mind(i,j)-mL(j))/(mR(j)-mL(j)));
genes(i,k1:k2) = gda_int2gray(k);
% each individual replicates
if( unidrnd(2,1) == 1 ) % mutate only half of individuals
k = unidrnd(16*M,1); % one random mutation
% conjugate genes; only one conjugation per generation
j1 = unidrnd(K,1); % random individual
j2 = unidrnd(K,1); % another random individual
k = unidrnd(M*16-2,1)+1; % 2<=k<=16M-1
g1(1,1:16*M) = genes(j1,:);
g1(1,k+1:16*M) = genes(j2,k+1:16*M);
g2(1,1:16*M) = genes(j2,:);
g2(1,k+1:16*M) = genes(j1,k+1:16*M);
% update solution and error from genes
k = gda_gray2int(genes(i,k1:k2));
mind(i,j) = (mR(j)-mL(j))*(k/65535.999)+mL(j);
dpre = sin(w0*mind(i,1)*x) + mind(i,1)*mind(i,2);
% survival of the fitness
F = exp(-c*Eind/Emax).*random('uniform',0,1,K,1);
msave(gen,1:M)= mind(k,1:M);
% solution is lowest error individual in last generation
% evaluate prediction and plot it
dpre = sin(w0*m1est*x) + m1est*m2est;
plot(x,dpre,'r-','LineWidth',3);
fprintf('Caption: True data (black curve), observed data (black circles)\n');
Caption: True data (black curve), observed data (black circles)
fprintf('predicted data (reed curve)\n');
predicted data (reed curve)
axis( [m2min, m2max, m1min, m1max] );
imagesc( [m2min, m2max], [m1min, m1max], E);
plot( mindsave(:,2), mindsave(:,1), 'k.', 'LineWidth', 2 );
plot( mind(:,2), mind(:,1), 'w.', 'LineWidth', 2 );
plot( mt(2), mt(1), 'go', 'LineWidth', 3 );
plot( m2est, m1est, 'ro', 'LineWidth', 3 );
fprintf('Caption: Errir surface (colors), with initial population (black dots)\n');
Caption: Errir surface (colors), with initial population (black dots)
fprintf('final population (white dots), mean of final population (red circle) and\n');
final population (white dots), mean of final population (red circle) and
fprintf('true solution (green circle)\n');
true solution (green circle)
% figure 3 is the solution progress
axis( [0, L, 0, 1.1*E0] );
plot( [0, L]', [E0, E0]', 'r-', 'LineWidth', 2);
plot( [1:L]', Esave, 'k-', 'LineWidth', 2);
plot( [0, L]', [mt(1), mt(1)]', 'r-', 'LineWidth', 2);
plot( [1:L]', msave(:,1)', 'k-', 'LineWidth', 2);
plot( [0, L]', [mt(2), mt(2)]', 'r-', 'LineWidth', 2);
plot( [1:L]', msave(:,2)', 'k-', 'LineWidth', 2);
fprintf('Caption: (top) Error as a function of generation number (black curve), with\n');
Caption: (top) Error as a function of generation number (black curve), with
fprintf('inital error (red line). (middle) Model parametre m1 as a function of\n');
inital error (red line). (middle) Model parametre m1 as a function of
fprintf('generation number (black curve), with true value shown form comparison (red line).\n');
generation number (black curve), with true value shown form comparison (red line).
fprintf('(bottom) Same as middle except for model parameter m2.\n');
(bottom) Same as middle except for model parameter m2.
% Genetic algorithm applied to an "approximately
% separable inverse problem" where the M=20 model parameters
% have a natural ordering and the data are localized
% averages of the model parameters.
% This code compares error of two cases, A and B,
% where the probability of mutation and recombination
% differ between the cases. Each case has 5 trials.
global gray1 gray1index pow2;
fprintf('This calculation is pretty slow, so progress shown (ends at B5)\n');
This calculation is pretty slow, so progress shown (ends at B5)
% part 1 --------------------------------------------
% number of recombinations per generation
% true model parameters are linear ramp
% data average of 3 neighboring model parameters
dtrue = (mt+[0;mt(1:M-1)]+[0;0;mt(1:M-2)])/3;
dobs = dtrue + random('Normal',0,sd,N,1);
K = 100; % number of individuals in the population
m0 = ones(M,1); % initial guess for m1
mL = zeros(M,1); % solution > mL
mR = 2*ones(M,1)'; % solution < mR
mind = zeros(K, M); % solution for each individual
Eind = zeros(K,1); % error for each individual
Ftind = zeros(K,1); % fitness of each individual
genes = char(48*ones(K, 16*M)); % genes for each individual
% all individuals initialized to initial guess + random number
r = random('Normal',0,0.025,K,1);
mind(:,i) = m0(i)*ones(K,1)+r;
dpre = (mind(i,:)'+[0;mind(i,1:M-1)']+[0;0;mind(i,1:M-2)'])/3; % predicetd data
Ftind = exp(-c*Eind/Emax).*random('uniform',0,1,K,1); % initial fitness
for i=(1:K) % convert model parameters to genes
k = floor(65535.999*(mind(i,j)-mL(j))/(mR(j)-mL(j)));
genes(i,k1:k2) = gda_int2gray(k);
for gen=(1:L) % loop over generations
% each individual replicates
if( unidrnd(imutate,1) == 1 ) % mutate 1/imutate of individuals
k = unidrnd(16*M,1); % one random mutation
% recominate genes; Nrecom per generation
j1 = unidrnd(K,1); % random individual
j2 = unidrnd(K,1); % another random individual
k = 16*(unidrnd(M-2,1)+1)+1; % always at start of word
g1(1,1:16*M) = genes(j1,:);
g1(1,k:16*M) = genes(j2,k:16*M);
g2(1,1:16*M) = genes(j2,:);
g2(1,k:16*M) = genes(j1,k:16*M);
% update solution and error from genes
k = gda_gray2int(genes(i,k1:k2));
mind(i,j) = (mR(j)-mL(j))*(k/65535.999)+mL(j);
dpre = (mind(i,:)'+[0;mind(i,1:M-1)']+[0;0;mind(i,1:M-2)'])/3; % predicetd data
% survival of the fitness
F = exp(-c*Eind/Emax).*random('uniform',0,1,K,1);
msave(gen,1:M)= mind(k,1:M);
% evaluate prediction and plot it
dpre = (mind(i,:)'+[0;mind(i,1:M-1)']+[0;0;mind(i,1:M-2)'])/3; % predicetd data
plot([1:L]',Esave,'k-','LineWidth',2);
fprintf('Done with A %d\n', itrial);
end
Done with A 1
Done with A 2
Done with A 3
Done with A 4
Done with A 5
% part 2 --------------------------------------------
% true model parameters are linear ramp
% data average of 3 neighboring model parameters
dtrue = (mt+[0;mt(1:M-1)]+[0;0;mt(1:M-2)])/3;
dobs = dtrue + random('Normal',0,sd,N,1);
K = 100; % number of individuals in the population
m0 = ones(M,1); % initial guess for m1
mL = zeros(M,1); % solution > mL
mR = 2*ones(M,1)'; % solution < mR
mind = zeros(K, M); % solution for each individual
Eind = zeros(K,1); % error for each individual
F = zeros(K,1); % fitness of each individual
genes = char(48*ones(K, 16*M)); % genes for each individual
% all individuals initialized to initial guess + random number
r = random('Normal',0,0.025,K,1);
mind(:,i) = m0(i)*ones(K,1)+r;
dpre = (mind(i,:)'+[0;mind(i,1:M-1)']+[0;0;mind(i,1:M-2)'])/3; % predicetd data
F = exp(-c*Eind/Emax).*random('uniform',0,1,K,1); % initial fitness
for i=(1:K) % convert model parameters to genes
k = floor(65535.999*(mind(i,j)-mL(j))/(mR(j)-mL(j)));
genes(i,k1:k2) = gda_int2gray(k);
% each individual replicates
if( unidrnd(imutate,1) == 1 ) % mutate 1/imutate of individuals
k = unidrnd(16*M,1); % one random mutation
% recominate genes; Nrecom per generation
j1 = unidrnd(K,1); % random individual
j2 = unidrnd(K,1); % another random individual
k = 16*(unidrnd(M-2,1)+1)+1; % always at start of word
g1(1,1:16*M) = genes(j1,:);
g1(1,k:16*M) = genes(j2,k:16*M);
g2(1,1:16*M) = genes(j2,:);
g2(1,k:16*M) = genes(j1,k:16*M);
% update solution and error from genes
k = gda_gray2int(genes(i,k1:k2));
mind(i,j) = (mR(j)-mL(j))*(k/65535.999)+mL(j);
dpre = (mind(i,:)'+[0;mind(i,1:M-1)']+[0;0;mind(i,1:M-2)'])/3; % predicetd data
% survival of the fitness
F = exp(-c*Eind/Emax).*random('uniform',0,1,K,1);
msave(gen,1:M)= mind(k,1:M);
fprintf('Done with B %d\n', itrial);
% evaluate prediction and plot it
dpre = (mind(i,:)'+[0;mind(i,1:M-1)']+[0;0;mind(i,1:M-2)'])/3; % predicetd data
plot([1:L]',Esave,'r-','LineWidth',2);
end
Done with B 1
Done with B 2
Done with B 3
Done with B 4
Done with B 5
fprintf('Caption: Error as a function of generation number for five trials\n');
Caption: Error as a function of generation number for five trials
fprintf('that omit conjugation (black curves) and five that include it (red curves)\n');
that omit conjugation (black curves) and five that include it (red curves)
% Bootstrap estimate of confidence interval
% for solution computed via Newton's method
% This function with these derivatives is being solved
% d(x) = sin( w0 m1 x) + m1 m2;
% dy/dm1 = w0 x cos( w0 m1 x) + m2
% data are in an auxillary variable, x
dtrue = sin(w0*mt(1)*x) + mt(1)*mt(2);
dobs = dtrue + random('Normal',0,sd,N,1);
% 2D grid, for plotting purposes only
% compute error, E, on grid for plotting purposed only
dpre = sin(w0*m1a(j)*x) + m1a(j)*m2a(k);
E(j,k) = (dobs-dpre)'*(dobs-dpre);
axis( [m2min, m2max, m1min, m1max] );
imagesc( [m2min, m2max], [m1min, m1max], E);
plot( mt(2), mt(1), 'go', 'LineWidth', 3 );
m1save = zeros(Nresamples,1);
m2save = zeros(Nresamples,1);
% resampling with duplications of data
% (first estimate is without resampling)
rowindex = unidrnd(N,N,1);
xresampled = x( rowindex );
dresampled = dobs( rowindex );
% initial guess and corresponding error
dg = sin(w0*mg(1)*xresampled) + mg(1)*mg(2);
Eg = (dobs-dg)'*(dobs-dg);
% iterate to improve initial guess
dg = sin( w0*mg(1)*xresampled) + mg(1)*mg(2);
G(:,1) = w0 * xresampled .* cos( w0 * mg(1) * xresampled ) + mg(2);
G(:,2) = mg(2)*ones(N,1);
% plot estimated solution
plot( m2est, m1est, 'ro', 'LineWidth', 2 );
% plot resampled solutions
plot( mg(2), mg(1), 'w.', 'LineWidth', 2 );
% plot again so is on top
plot( mt(2), mt(1), 'go', 'LineWidth', 3 );
plot( m2est, m1est, 'ro', 'LineWidth', 2 );
fprintf('Caption: Error surface (colors), with bootstrap solutions (white dots),\n');
Caption: Error surface (colors), with bootstrap solutions (white dots),
fprintf('estimated solution (red circle) and true solution (green circle), superimposes\n');
estimated solution (red circle) and true solution (green circle), superimposes
% histogram2 for m1 and m2
Dm1bins = (m1hmax-m1hmin)/(Nbins-1);
m1bins=m1hmin+Dm1bins*[0:Nbins-1]';
m1hist = hist(m1save,m1bins);
pm1 = m1hist/(Dm1bins*sum(m1hist)); % norm al to pdf
Pm1 = Dm1bins*cumsum(pm1);
m1low=m1bins(find(Pm1>0.025,1));
m1high=m1bins(find(Pm1>0.975,1));
axis( [m1hmin, m1hmax, 0, maxpm1] );
plot( m1bins, pm1, 'k-', 'LineWidth', 3 );
plot( [m1mean, m1mean]', [0 maxpm1/10]', 'r-', 'LineWidth', 3 );
plot( [m1low, m1low]', [0 maxpm1/20]', 'r-', 'LineWidth', 3 );
plot( [m1high, m1high]', [0 maxpm1/20]', 'r-', 'LineWidth', 3 );
fprintf('estimated m1: %f < %f < %f (95 percent confidence)\n', m1low, m1est, m1high );
estimated m1: 1.181039 < 1.206381 < 1.225460 (95 percent confidence)
Dm2bins = (m2hmax-m2hmin)/(Nbins-1);
m2bins=m2hmin+Dm2bins*[0:Nbins-1]';
m2hist = hist(m2save,m2bins);
pm2 = m2hist/(Dm2bins*sum(m2hist)); % norm al to pdf
Pm2 = Dm2bins*cumsum(pm2);
m2low=m2bins(find(Pm2>0.025,1));
m2high=m2bins(find(Pm2>0.975,1));
axis( [m2hmin, m2hmax, 0, maxpm2] );
plot( m2bins, pm2, 'k-', 'LineWidth', 3 );
plot( [m2est, m2est]', [0 maxpm2/10]', 'r-', 'LineWidth', 3 );
plot( [m2low, m2low]', [0 maxpm2/20]', 'r-', 'LineWidth', 3 );
plot( [m2high, m2high]', [0 maxpm2/20]', 'r-', 'LineWidth', 3 );
fprintf('Caption: (top) Empirical pdfp(m1) for model parameter m1. (black curv) with mean (large red bar) and\n');
Caption: (top) Empirical pdfp(m1) for model parameter m1. (black curv) with mean (large red bar) and
fprintf('95 percent confidence intervals (small red bars).\n')
95 percent confidence intervals (small red bars).
fprintf('estimated m2: %f < %f < %f (95 percent confidence)\n', m2low, m2est, m2high );
estimated m2: 1.397780 < 1.525420 < 1.642337 (95 percent confidence)