%% This file is to estimate the needed parameters for the variance decomposition
% Intermediate function for regularisiations on the
% covariance matrix
%
%Inputs
%   Y: A 3D matrix of dimensions Na x Ta x R.
%   F: scalar for number of hyperparameters
%   Regularization: A structure containing two fields A and Sigma.
%   deltas: A delta hyperparameters in a vector of length Na.
%   realCof: structure with true parameters.
%   target: String for FEVD target.
%   H: A scalar value for the horizon of the FEVD.
%%Outputs
%   regCurve,
%   olsCurves,
%   tpfpReg,
%   tpfpOLS,
%   Areg
%
%Functionality
%   The function computes multiple metrics curves for accuracy, bias and
%   viarance of the regularization and OLS regression. 
%   The computation is done in parallel using a parfor loop.
%
% Author: Ruben Hipp, 2021
function [regCurve, olsCurves, tpfpReg, tpfpOLS,Areg] = estimationBias(Y,F,Regularization,deltas,real,target,H)

[~,~,R]=size(Y);
RegA1=Regularization.A;
RegSigma1=Regularization.Sigma;

%%
parfor r = 1:R
    
    Xa = Y(:,2:end,r);
    Za = Y(:,1:end-1,r);
    if size(F,3)>1
        Fa = F(:,:,r);
    else
        Fa = F;
    end
    
    [regCurves(:,r), olsCurves(:,r), resultingEstimators(:,:,r), tpfpReg(:,:,r), tpfpOLS(:,:,r), Areg(:,:,r)] = parforloopBias(Xa,Za,RegA1,RegSigma1,Fa,deltas,real,target,H);
    disp(r)
end

regCurve = [mean(regCurves,2)' mean(var(squeeze(resultingEstimators(:,1,:)),[],2))];
olsCurves = [mean(olsCurves,2)' 0 mean(var(squeeze(resultingEstimators(:,2,:)),[],2))];

tpfpReg = mean(tpfpReg,3);
tpfpOLS = mean(tpfpOLS,3);

end