%% Problems:   spmdOptim1D.m
%    
% 
%% (1) Max and min-points
%
% Find max and min-values and locations by decomposing domain
%  into labs and working in parallel with all labs available.

%%  First example: 
clear
close all
format compact
%% Define  function f 
%
f=@(x) x.*sin(x);
fplot(f,[-pi 10*pi])
grid on
%% Find local min and max on I=[A,B] 
%  Decompose I into subintervals of length L=(B-A)/nlabs 
%
% Let:
A=-pi;B=10*pi;
nlabs=4;
% nlabs=2; % My laptop
%% Open pool:
p=parpool
%% Alternative way to get value to numlabs by default:
% nlabs=p.NumWorkers  % Triton default: 20
L=(B-A)/nlabs 
%%  spmd-block, remember Numer. integr. example
%   
spmd 
    a=A+(labindex-1)*L;
    b=A+labindex*L;
    fprintf('Subinterval: [%-4g, %-4g]\n',a,b)  
end
%
%% Composite to ordinary variables (workers -> client)
AA=[a{:}];BB=[b{:}];
hold on
plot(AA,0,'xk',BB,0,'or')
%%  Find min and max on each lab.
n=1000;
disp([num2str(n*nlabs) ' calculations, each lab doing ' ... 
    num2str(n) ' simultaneously' ])
spmd
    x=linspace(a,b,n);
    y=f(x);
    % [ymax,maxI]=max(y); % Max on each lab and index of the 1'st
    % [ymin,minI]=min(y); % Min on each lab and its index of the 1'st 
    ymax=max(y); % Max values on each lab
    ymin=min(y); % Min values on each lab
    maxI=ymax==y; % Logical indexvector of (all) max-values on each subint
    minI=ymin==y; % Logical indexvector of (all) min-values in each subint
    xmax=x(maxI); % x-values of max's
    xmin=x(minI); % x-values of min's
end  
%% Global max and min points
% gmaxx=[xmax{1} xmax{2}]
% gmaxy=[ymax{1} ymax{2}]
% gminx=[xmin{1} xmin{2}]
% gminy=[ymin{1} ymin{2}]
%% Composite to ordinary variables (results from workers to client):
Xmax=[xmax{:}];
Ymax=[ymax{:}]; 
Xmin=[xmin{:}]; 
Ymin=[ymin{:}]; 
%% Check lab-borders
sum(Xmax==A)
sum(Xmin==A)
% 
plot(Xmin,Ymin,'*r',Xmax,Ymax,'*k')
%% Increase accuracy!  
% We see that two local minima and one max were skipped, so the
% discretizetion was not quite dense enough.
% 1) Take more labs (Triton)
% 2) Or take a more dense set of points(avoid recomputing old values.)
% 
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Additional exercise: Try fminsearc, fminbnd.
% Sometime...






