function [obj] = estimateFirstLM(obj)
% ESTIMATEFIRSTLM trains a global polynomial model in order to initialize the HiLoMoT algorithm.
%
%
% [obj] = estimateFirstLM(obj)
%
%
% INPUT/OUTPUT
%
%   obj                 object  HiLoMoT object containing all relevant properties and methods
%
%
% HiLoMoT - Nonlinear System Identification Toolbox
% Benjamin Hartmann, 04-April-2012
% Institute of Mechanics & Automatic Control, University of Siegen, Germany
% Copyright (c) 2012 by Prof. Dr.-Ing. Oliver Nelles


% Define some variables
obj.numberOfInputs  = size(obj.input,2);
obj.numberOfOutputs = size(obj.output,2);
zLowerBound         = min(obj.zRegressor);
zUpperBound         = max(obj.zRegressor);
center              = (zLowerBound+zUpperBound)/2;

% Initialize the local model object
obj = obj.addChildren([], [], center);

% Smoothness equal for all local models
obj.localModels.localSmoothness = obj.smoothness;

% update the active model vector and store it in history
obj.leafModels = true; % the first active model

% Calculate validity function values (Here: all equal to 1)
obj.phi = obj.calculatePhi(obj.zRegressor, obj.leafModels);

% Check for sufficient amount of data samples
if obj.pointsPerLMFactor * size(obj.xRegressor,2) - sum(obj.phi) > eps
    obj.idxAllowedLM = false;
    warning('hilomot:estimateFirstModel','the first local model has not enough valid point to estimate its parameters properly.')
else
    obj.idxAllowedLM = true;
end

% Estimate parameters of the first LM
[obj.localModels.parameter, obj.localModels.pseudoInv] = estimateParametersLocal(obj, obj.xRegressor, obj.output, obj.phi, size(obj.xRegressor,2), obj.dataWeighting);

% Calculate model output
obj.outputModel = calculateModelOutput(obj);

% Evaluate loss function values
obj.localModels.localLossFunctionValue = calcLocalLossFunction(obj, obj.unscaledOutput, obj.outputModel, obj.phi, obj.dataWeighting);

end