% hilomotDemo3 Demo 3. Static process with 2 inputs and 2 outputs

% 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 outputs for training
[u1g u2g] = meshgrid(linspace(0,1,25), linspace(0,1,25));
u1 = u1g(:);
u2 = u2g(:);
y1 = (1./(0.1+u1) + (2*u2).^2)/14;
y2 = 0.1./(0.1+(1-u1)/2+(1-u2)/2);
LMN.input = [u1 u2];
LMN.output = [y1, y2];

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

% Train LMN 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([1 2],1)
figure
LMNBest.plotModel([1 2],2)
figure
LMNBest.plotPartition

% Generalization
[u1G u2G] = meshgrid(linspace(0,1,30), linspace(0,1,30));
u1G = u1G(:);
u2G = u2G(:);
y1G = (1./(0.1+u1G) + (2*u2G).^2)/14;
y2G = 0.1./(0.1+(1-u1G)/2+(1-u2G)/2);

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