
% Example where the Rosenbrock function is approximated
close all, clear variables
clc

% Definition of the current path folder
FileName = mfilename('fullpath');
[directory,~,~] = fileparts(FileName);
[dirmain,~,~] = fileparts(fileparts(directory));
addpath(genpath(dirmain)) 
setup

% % Rosenbrock function
% funct = @(x,y) (1-x).^2 + 100*(y-x.^2).^2;
% maxx =  2;      minx = -2;
% maxy =  1;      miny = -1;
% maxz =  3000;	  minz =  0;

% 6-hump camelback function
funct = @(x,y) (4 - 2.1*x.^2 + 1/3.*x.^4).*x.^2 + x.*y + (-4 + 4*y.^2).*y.^2; 
maxx =  2; minx =  0;
maxy =  2; miny =  0;
maxz =  4; minz = -1;

% Auxiliary function for the Ndim Problem
funct2 = @(x) sum(x,2);

range = [10:10:250 270:20:350];
% time.sum1 = zeros(numel(range),1);
% time.sum2 = time.sum1;
% n_var1    = time.sum1;
% n_var2    = time.sum1;
%%
for k = 29:numel(range)
    
%     NNdim = range(k);
%     Xndim = linspace(1,5,NNdim)';   
% 
%     [A{1}, A{2}, A{3}, A{4}, A{5}, A{6}, A{7}, A{8}] = ndgrid(Xndim);   % , A{6}
% 
%     for l = 1:numel(A)
%         A{l} = A{l}(:);
%     end
%     % Definition of the vectors for BSplinebuilder
%     xs2 = cell2mat(A);
%     zs2 = funct2(xs2);
% 
%     % Definition of a Quartic bspline
%     time.in.sum2 = tic;
%     approx.sum2  = BSplineBuilder(xs2, zs2, min(NNdim-1,3)).build();
%     time.sum2(k) = toc(time.in.sum2);
% 
%     % Definition of the number of variables
%     n_var2(k) = numel(zs2);
%     
%     % Printing of the results
%     fprintf('%1.0i model - It took %8.2f s to solve the problem with %6.0i elements. \n',numel(A),time.sum2(k),n_var2(k))

    % Coarse grid for with sample points
    N = range(k);
%     N = sqrt(n_var2(k));
    x = linspace(-2,2,N);
    y = linspace(-1,1,N);
    [X,Y] = meshgrid(x,y);
    Z = funct(X,Y);

    % Definition of the vectors for BSplinebuilder
    xs = [X(:) Y(:)];
    zs = Z(:);

    % Definition of a Quartic bspline
    time.in.Quartic = tic;
    approx.Quartic  = BSplineBuilder(xs, zs, 3).build();
    time.sum1(k)     = toc(time.in.Quartic);

    % Definition of the number of variables
    n_var1(k) = N^2;

    % Printing of the results
    fprintf('2 model - It took %8.2f s to solve the problem with %6.0i elements. \n\n',time.sum1(k),n_var1(k))

end