
% Perform Beck's sequential function specification method (SFS) with a temporary assumption of linear form for the unknown function
%   -dimensionless data must be supplied
%   -geometry is the insulated finite plate
%   -uses function fdX22B10T0.m
% dt is the dimensionless time step in the data
%  x is a scalar dimensionless measurement location
%  r is a scalar number of future times for the estimation
%  Y is the vector of measurements beginning at time=dt
% function [qhat,Tsur] = SFS_Linear( dt, x, r, Y )
function [qhat,Tsur] = SFS_Linear( dt, x, r, Y )
A = 15;  % for evaluation of fdX22B10T0
if( nargin == 0 )
   dt = 1;
   x = 0.5;
   r = 3;
   Y = (1:1:10)';
end

N = size(Y,1);   % the total number of observations
if( N == 1 )
   error('Y must be a column vector');
end
time = [dt:dt:N*dt]';          
phi = fdX22B10T0( x, time, A ); % get the sensitivity values
phisum = cumsum(phi(1:r));            % sum of phi(1:i)
oldqmultiplier = [0; phisum(1:end-1)];          % sum of phi(1:i-1)
% Compute Denominator 
denom = sum(phisum.^2);
K = phisum/denom;

qhat = zeros(N-r, 1);
% do the first one separately
qhat(1) = Y(1:r)' * K; %%% avoid  issues with zero index in loop below
for M = 2 : N-r
   % create a vector for estimated temperature at each step 
   estimator = 0;
    for i = 1:r
        T_hat_qM0 = 0;
        for k = 1:M-1
            T_hat_qM0 = T_hat_qM0 + qhat(k) * (phi(M + i - k) - phi(M + i - k - 1));
        end
        % compute the influence of all the previous q's
        That = T_hat_qM0 - qhat(M - 1) * oldqmultiplier(i);
        estimator = estimator + (Y(M + i - 1) - That) * K(i);
    end
     % now use the Beck's SFS Linear formula to compute the next qhat
    qhat(M) = estimator;
end
%
% now we know all the q components.  
% Compute the surface temperature via Beck's Eq. 3.15

phi0 = fdX22B10T0(0, time, A);  % get the sensitivity values @ x=0
dphi0 = diff([0;phi0]);
Tsur = zeros(N-r, 1);
for M = 1 : N-r
   Tsur(M) = 0;
   for n = 1:M
      Tsur(M) = Tsur(M) + qhat(n)*dphi0(M-n+1);
   end
end

end