close all; clear; clc;

%% Make up some data
rng('shuffle'); seed = round(10000*rand); fprintf('seed = %d\n',seed);
%rng(seed); rng(5650);

m = @(x,a,b) a + b*(tan(x*pi/2)); % Nonlinear model
x = linspace(-0.9,0.9,20);
y = m(x,1,3) + randn(size(x)); % Data (model + gaussian noise)

%% Various norms
loss{1} = @(a,b) mean( (y-m(x,a,b)).^2 );
loss{2} = @(a,b) max( abs(y-m(x,a,b)) );
loss{3} = @(a,b) median( (y-m(x,a,b)).^2 );
loss{4} = @(a,b) std( (y-m(x,a,b)).^2 );
loss{5} = @(a,b) iqr( (y-m(x,a,b)).^2 );
loss{6} = @(a,b) max( abs( fft(y-m(x,a,b)) ) );
names = {'L2-norm','L-\infty norm','*Median* 2-norm',...
        'std','iqr','max abs fft'};
nL = numel(loss);
    
%% Hypersurfaces for the loss functions
as = linspace(-2,3,1e2); bs = linspace(2,4,1e2);
for ai = 1:numel(as)
    for bi = 1:numel(bs)
        for nLi = 1:nL
            L{nLi}(ai,bi) = real(loss{nLi}(as(ai),bs(bi)));
        end
    end
end
for nLi = 1:nL
    L{nLi} = L{nLi}';
    pf{nLi} = fminsearch(@(p) loss{nLi}(p(1),p(2)),[0 0]);
end

%% Plot
figure(1); clf;
colormap(viridis);
for nLi = 1:nL
    s = subplot(2,3,nLi); hold on;
    contourf(as,bs,log(abs(L{nLi})));
    axis square;
    s.XTickLabel = ''; s.YTickLabel = '';
    plot(1,3,'ro');
    plot(pf{nLi}(1),pf{nLi}(2),'go');
    title(names{nLi});
end