% pour tester le parrallèle
clear all



% differentiation in 2D.
Nx=50;
L=20;
x=linspace(0,L,Nx)';
dx=x(2)-x(1);
D=zeros(Nx,Nx);
D(1,1:2)=[-1,1];
for ind=2:Nx-1
    D(ind,ind-1:ind+1)=[-1/2,0,1/2];
end
D(end,end-1:end)=[-1,1];
D=D/dx;
DD=D*D;

Ny=30;
y=linspace(-5,5,Ny);
[X,Y]=meshgrid(x,y);

u=exp(-(X-5).^2-Y.^2);

surf(X,Y,u); shading interp

D2=kron(eye(30),D);


ux=D2*u(:);
ux=reshape(ux,size(X));
surf(X,Y,ux); shading interp;

break

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% differentiation
N=400;
L=20;
x=linspace(0,L,N)';
dx=x(2)-x(1);
D=zeros(N,N);
D(1,1:2)=[-1,1];
for ind=2:N-1
    D(ind,ind-1:ind+1)=[-1/2,0,1/2];
end
D(end,end-1:end)=[-1,1];
D=D/dx;
DD=D*D;
% 
% f=cos(x);
% df=-sin(x);
% ddf=-cos(x);
% plot(x,f,'b',x,df,'r',x,D*f,'ko',x,ddf,'m',x,D^2*f,'m+');
% 
% % solving a static diffusion problem
% b=zeros(N,1);
% b(end)=1;
% 
% I=eye(N);
% linsel=[1,N];
% DD(linsel,:)=I(linsel,:);
% 
% tic
% g=DD\b;
% t1=toc



%plot(x,g)



% advection diffusion
mu=0;
%U=0.5;

% building the matrices
I=eye(N);
U=tanh(x-10)/2+1.5; 
A=-diag(U)*D+mu*DD;
E=I;

% impose the boundary conditions
linsel=[1];
A(linsel,:)=I(linsel,:);
E(linsel,:)=0;

dt=0.05;
H=(E-A*dt/2)\(E+A*dt/2);

u=exp(-(2*(x-4)).^2);


plot(x,u)
nt=400;
mem=zeros(N,nt);
for ind=1:nt
    % advance in time
    u=H*u;
    mem(:,ind)=u;
    plot(x,u);
    ylim([-1,1]);
    drawnow
end
tvec=0:dt:(nt-1)*dt;
surf(x,tvec,mem);

shading interp






break
%%%%%%%%%%%%%%%%%%%%%%%%%%
% test the spmd


spmd
labindex
    
a=codistributed.randn(1,10);
a
end






%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%ùù
break
% example of using parfor
n=500;
ncomp=16;
A=randn(n,n,ncomp);
mem=zeros(n,ncomp);
disp('1 worker')
tic
parfor (ind=1:ncomp,1)
    mem(:,ind)=eig(A(:,:,ind));
end
t1=toc


disp('4 workers')
tic
parfor (ind=1:ncomp,4)
    mem(:,ind)=eig(A(:,:,ind));
end
t2=toc








%%%%%%%%%%%%%%%%%%%%%%%%%%%
break
% example of codistribute




spmd
    A = [11:20; 21:30; 31:40];
    D = codistributed(A);
    D
    %getLocalPart(D)
end






%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 
 break
 % test of the parfor speeding
 n=500;
 N=20;
 
 %disp('start pool'); matlabpool(4)
 %disp('close pool'); matlabpool close
 
 
 disp('normal loop')
 mem=zeros(n,N);
 tic
 for ind=1:N
     %disp(ind)
     mem(:,ind)=eig(randn(n,n));
 end
 t1=toc
 
 disp('one worker')
 mem=zeros(n,N);
 tic
 parfor (ind=1:N,1)
     %disp(ind)
     mem(:,ind)=eig(randn(n,n));
 end
 t2=toc
 
 disp('four workers')
 mem=zeros(n,N);
 tic
 parfor ind=1:N
    % disp(ind)  
     mem(:,ind)=eig(randn(n,n));
 end
 t3=toc
 
 

