close all; clear; clc; format short

%%
f = @(x,y) log(1 + (x.*sign(real(x))).^(2 + sin(x+y))) + y.^2/20;

tol = 1e-4;

rng(42);

% Plot
cm = lines;
cm2 = [cm(1,:); cm(6,:)];
figure(1); clf;
a = axes; hold on;
x = -1:.1:10; y = -10:.1:1;
[xx,yy] = meshgrid(x,y); ff = f(xx,yy);
imagesc(x,y,ff);
a.XDir = 'normal'; a.YDir = 'normal';
grid on; box on; axis tight square;
xlim([-1 10]); ylim([-10 1]);
colormap(viridis);

p = [8.3,-8.9]; % Starting point p0
%[x,y] = ginput(1); p = x+1i*(y);

fp = f(p(1),p(2));
pold = p;
plot(p(1),p(2),'yo','MarkerSize',10);
plot(0,0,'yp','MarkerSize',10);
tic
lazy = 0;
step_size = 1;
L = []; h = [];
for j = 1:1000 % Limit number of iterations to 1e3
    dp = step_size.*randn(1,2);
    pn = p + dp; fn = f(pn(1),pn(2));
    plot([pold(1) pn(1)],[pold(2) pn(2)],'-','Color',cm(6,:));
    if fn < fp
        p = pn; fp = fn; lazy = 0;
        h(end+1) = plot([pold(1) p(1)],[pold(2) p(2)],'.-','Color',cm(2,:));
        drawnow;
    elseif lazy >= 10 % Standing in one place for too long
        lazy = 0; step_size = step_size/2;
    else
        lazy = lazy + 1;
    end
    L(j) = lazy;
    pold = p;
    if step_size < tol; break; end
end
uistack(h,'top');
pf = p;
toc

%% Print info
fprintf(' iter = %d\n',j);
fprintf('Minimum at:\n');
fprintf('   pf = (% .2e,% .2e)\n',pf);
fprintf(' fval = %.2e\n',f(pf(1),pf(2)));
fprintf('Actual minimum at:\n');
fprintf('   pf = (% .2e,% .2e)\n',[0,0]);
fprintf(' fval = %.2e\n',0);
