% Cartoon movie of increasing microbunching in XFELs
clear; close all;
vid = VideoWriter('microbunching.mp4','MPEG-4');
vid.Quality = 100;
vid.FrameRate = 15;
open(vid);
figure('units','pixels','position',[0 0 1920 1080],'ToolBar','none');
set(0,'defaultfigurecolor',[1 1 1]); % black background = [0 0 0]. Normally white [1 1 1]
set(gcf,'color','white');
set(gca,'linewidth',7);


M = 160; % Number of loops
col = [0.3 0.4 0.7];

for i = 1:M
    newplot;
    hold on
    for j = -9:3:9
        nE = 4*round(4*M*exp(-j^2/100)); % number of electrons/microbunch
        x = randn(nE,1); % positions of electrons along x
        y = randn(nE,1); % positions of electrons along y
        xR = 10/log((i^(i/40)+2)^2); % scale of ellipse in x-direction
        yR = 1.6*exp(-j^2/100); % scale of ellipse in y-direction
        bunch = scatter(x*xR - j,yR*y,14,'filled','MarkerFaceColor',col); % plot electrons in phase space
        alpha = 0.7; % Opaqueness of each individual electron
        set(bunch, 'MarkerEdgeAlpha',0,'MarkerFaceAlpha',alpha);
        axis square % Keep scaling 1:1 for x,y
        axis([-14 14 -7 7]) % axis limits
        axis off
    end
    % Store the frame
    frame = getframe(gcf);
    writeVideo(vid,frame);
    hold off;
end
hold off;
% Output the movie as an mpg file
close(vid);
