function objectiveValue = genericObjectiveFunction(x, heMatrix, dec, ...
    par, grassStruct, sampleProjectionData)
% objective function for optimal approximation
% 
% THIS IS NO USER FUNCTION

% The elk-library: convex geometry applied to crystallization modeling.
%   Copyright (C) 2013 Alexander Reinhold
%
% This program is free software: you can redistribute it and/or modify it 
%   under the terms of the GNU General Public License as published by the 
%   Free Software Foundation, either version 3 of the License, or (at your 
%   option) any later version.
%
% This program is distributed in the hope that it will be useful, but 
%   WITHOUT ANY WARRANTY; without even the implied warranty of 
%   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU 
%   General Public License for more details.
%
% You should have received a copy of the GNU General Public License along 
%   with this program.  If not, see <http://www.gnu.org/licenses/>.

% projection matrix
projectionMatrix = computeProjectionFromGrass(x, grassStruct);
% define penalty function
% penaltyValue = @(validRatio)((validRatio < par.penaltyRatioLimit)*...
%     (par.penaltyRatioLimit - validRatio)*par.penaltySlope);

%% projection
if strcmpi(par.projectionType, 'true')
    heMatrixProjected = projectionMatrix * heMatrix;
else
    %! DEV: this is temporarily not supported:
    error('elk:approximation:internalError', 'DEV: not supported');
    heMatrixProjected = estimateHeMatrix(heMatrix, projectionMatrix, ...
        sampleProjectionData);
    %/
end

%% evaluate error
if strcmpi(par.errorType, 'PCA')
    % objective
    objectiveValue = sum((heMatrix(:) - heMatrixProjected(:)).^2);
else
    % measure matrix (enforce validity)
    measureMatrix = computeMeasureDec(dec, 'hC', ...
        heMatrixProjected, par.measureList, [], [], 1);  
    
    % get ratio of columns that contribute to errors
%     ratio = sum(fadeOutScaling) / length(fadeOutScaling);
    
    % error vector
    errorVector = computeMatrixError(par.measureValueMatrix, ...
        measureMatrix, par.errorType, par.errorGroupVector);
    
    % apply weights and penalty
%     objectiveValue = par.measureWeightVector(:)'*errorVector + penaltyValue(ratio);
    objectiveValue = par.measureWeightVector(:)'*errorVector;
    
end