% hilomotDemo2 Demo 2. Static process with 2 inputs and 1 output

% 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


% Initialize new hilomot object as local model network (LMN)
LMN = hilomot;

% Set inputs and output for training
[u1g u2g] = meshgrid(linspace(0,1,25), linspace(0,1,25));
u1 = u1g(:);
u2 = u2g(:);
y = 0.1./(0.1+(1-u1)/2+(1-u2)/2);
LMN.input = [u1 u2];
LMN.output = y;

% Set minimum training error as termination criterion
LMN.minError = 0.05;

% Train hilomot object
LMN = LMN.train;

% Find best performance/complexity trade-off
[~, idxBest] = min(LMN.history.penaltyLossFunction);
LMNBest = LMN;
LMNBest.leafModels = LMN.history.leafModelIter{idxBest};

% Visualization
figure
LMNBest.plotModel
figure
LMNBest.plotPartition

% Generalization
[u1G u2G] = meshgrid(linspace(0,1,30), linspace(0,1,30));
u1G = u1G(:);
u2G = u2G(:);
yG = 0.1./(0.1+(1-u1G)/2+(1-u2G)/2);

% Calculate model output and global loss function
yGModel = calculateModelOutput(LMNBest, [u1G u2G], yG);
JG = calcGlobalLossFunction(LMNBest ,yG, yGModel);