% This code produces Figure 5 and Figure S6 in Shaw et al (2023) Ecol Lett
% Pushed to the edge: Spatial Sorting can slow down invasions.
% This calculates the speed with and without sorting for the analytical model, described in detail in the appendix.

% model written by Frithjof Lutscher

clear

% defining parameters and variables

p(1) = 0.6;  % dispersal probability of type 1
p(2) = 0.7;  % dispersal probability of type 2
v = 0.25;    % variance of the Laplace kernel
b = sqrt(v/2); % parameter in the Laplace kernel
[mu,a] = meshgrid(0.01:0.01:0.9, 0.01:0.01:0.1);

% the analytical formula for the speed c without sorting
% according to formula (S10)
cwo = b*log( 0.25*sum(p)*(1-mu)./a);

% The following is the second panel in Figure S6
figure(2)
contour(mu,a,cwo,[0.4  0.6 0.8 1 ],'ShowText','on')
xlabel('mortality','Fontsize',20)
ylabel('Allee threshold','Fontsize',20)
title('speed (without)','Fontsize',20)


% Calculation of the speed according to Lemma 4, equation (S20)

EE = 1-8/p(2)*a./(1-mu);
EE = EE.*(EE>0);
EE = 0.5*(1-sqrt(EE));


% the following is the first panel in Figure S6

figure(1)
contour(mu,a,-b*log(EE),[0.4  0.6 0.8 1 ],'ShowText','on')
xlabel('mortality','Fontsize',20)
ylabel('Allee threshold','Fontsize',20)
title('speed (with)','Fontsize',20)

% The following is Figure 5 in the main text and the third panel in Figure S6

figure(3)
contour(mu,a,-b*log(EE)-cwo,[-0.02 -0.01 0 0.01 0.02], 'ShowText','on')
axis([0 0.4 0 0.04])
xlabel('mortality','Fontsize',20)
ylabel('Allee threshold','Fontsize',20)
title('difference','Fontsize',20)

