% Movie of generating nonlaminar beam and its phase-space ellipse as a
% function of position along beam

clear; close all;
vid = VideoWriter('electronEllipseEmittance.mp4','MPEG-4');
vid.Quality = 100;
vid.FrameRate = 30;
open(vid);

figure('units','pixels','position',[0 0 1920 1080],'ToolBar','none');
%set(0,'defaultfigurecolor',[1 1 1]); % White
set(gca,'linewidth',7);


M = 5000; % Number of emitting electrons
col = [0.3 0.4 0.7];

x = randn(M,1); % Gaussian random distribution used for position
y = randn(M,1); % Gaussian random distribution used for angle
R = 1; % ratio of normalized x and x' determines b/a of ellipse

for i = -1:0.01:1 % Number of loops (frames)
    newplot;
    subplot(1, 9, [7, 8, 9]);  % Last two slots of six for this plot. Used 6 and not 3 to make the gap between
    % this subplot and the other smaller
    
    hold off;
    xnow = x+(y*i); % Move along beam direction from beginning of converging beam at -1
    % to focus at 0, and on to spreading beam up to +1
    scatter(xnow/R,R*y,10,'filled','MarkerFaceColor',col); % plot electrons in phase space
    axis square % Keep scaling 1:1 for x,y
    axis([-4.4 4.4 -5 5]) % axis limits
    axis off
    
    
    subplot(1, 9, [1, 2, 3, 4, 5, 6]) % Occupies the first four of six horizontal plot positions
    newplot;
    hold off;
    axis square % Keep scaling 1:1 for x,y
    axis off
    xchord = [0*x-1 1+(0*x)]; % From zero to 1.0 in x-direction
    ychord = [(x-y)/R R*(x+y)]; % From position of electron on x-axis to the end of the emitted ray
    % determined by the angle generator in y
    cc = jet(100);
    for j = 1:2:M % Plot the rays in the x-plane
        hold on
        colIndex = 50+round(y(j)*100/(max(y) - min(y))); % maximize range of jet palette
        if (colIndex>100)
            colIndex = 100;
        end
        if (colIndex<1)
            colIndex = 1;
        end
        ebeam = plot(xchord(j,:), ychord(j,:), 'color',cc(colIndex,:), 'Linewidth', 1.4);
        ebeam.Color(4) = 0.5; % Semitransparent line
    end
    p1 = plot([i i], [-5.6 5.6], 'color', 'red', 'Linewidth', 8); % Moving vertical line along beam path
    p1.Color(4) = 0.25; % Semitransparent line
    p2 = plot([i+0.005 i+0.005], [-5.6 5.6], 'color', 'red', 'Linewidth', 8); % Moving vertical line along beam path
    p2.Color(4) = 0.25; % Semitransparent line
    
    hold off;
    axis([-1 1 -10 10])
    hold off;
    % Store the frame
    frame = getframe(gcf);
    writeVideo(vid,frame);
end
hold off;
% Output the movie as an mpg file
close(vid);
