
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%  Title: StatisCLAS: A Package of Classification Methods   %%%%
%%%%  Author: David Casado de Lucas                            %%%%
%%%%  Version: 29th May 2013                                   %%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% PURPOSE: This function provides the trimmed reference curve of a set of curves...
%          and the positions of those included in the calculation of the previous mean.

% INPUT VARIABLES:
%    curves: Matrix with the functions as rows.
%    alpha: Parameter to determine the trim.

% OUTPUT VARIABLES:
%    trimmedReference: Trimmed reference curve.
%    deepestFpositions: Positions of the included curves (the deepest).

% COMMENTS:
%   (1) This function can be used outside the framework of this paper.
%   (2) This function can be used to identify the deepest elements and to construct
%       other robust quantities, not necessarily the mean. Not to trim
%       twice, the mean is set as reference curve when this function is
%       called pointing at the trimmed mean.
%   (3) This function is based on code of Sara López-Pintado.

function [trimmedReference deepestFpositions] = trimFunction(curves, alpha, numberFDreference, infoFDreference)

if ~exist('numberFDreference','var')
  numberFDreference = 1; % The mean, by default
end
if isequal(numberFDreference,2) % When called with the trimmed mean...
  numberFDreference = 1; % ...the mean is enabled instead, not to trim twice
end
if ~exist('infoFDreference','var')
  infoFDreference = {};
end

sampleSize = size(curves,1);

depthsF = modBandDepth2(curves);  % Computing the generalized band depths

[Msg,isg] = sort(depthsF);  % Ordering the functions

N = sampleSize - ceil(alpha*sampleSize);  % Sample size after the trim

% Taking the deepest functions
deepestFpositions = isg(sampleSize-N+1:sampleSize);
deepestFcurves = curves(deepestFpositions,:);

% Notice that when 'numberFDreference' points at the mean, 'trimmedReference' is the alpha-trimmed mean
trimmedReference = referenceElement(numberFDreference,infoFDreference,deepestFcurves);  % Alpha-trimmed reference curve

end

% PURPOSE: This function calculates the modified band depth of order 2.
% INPUT VARIABLES:
%    functions: Matrix with the functions as rows.
% OUTPUT VARIABLES:
%    depths: Vector with the values of the depth.
% COMMENTS:
%   (1) This function can be used outside the framework of this paper.
function depths = modBandDepth2(functions)
sampleSize = size(functions,1);
cont = zeros(1,sampleSize);
for i=1:(sampleSize-1)
   for j=(i+1):(sampleSize)
       cont = cont + a([i j],functions);         
   end
end
% depths=cont/combinat(n,2); % To avoid computes
depths = cont;
end
function result = a(v,Z)
sampleSize2 = size(Z,1);
inf = (min(Z(v,:)))';
sup = (max(Z(v,:)))';
len = sum((and(Z' <= sup*ones(1,sampleSize2), Z' >= inf*ones(1,sampleSize2))));
result = (len/size(Z,2));
end
