%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%         5. practice         %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Nonlinear dynamics systems  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%         2019.11.13.         %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Spiderweb diagram of Logistic mapping %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%Parameters:
figure;
%mu=3.83; %3 periods, end of chaos in this parameter window
start=0.2;
iterations=200; %2000;%

%Questions: 
%1.: Catch some parameter duplications! (identify the mu value)
%2.: When (at which mu values) does chaos appear first?
%3.: When (at which mu values) does chaos disappear?
%Set iteratin number, mu value and for loop stepsize to catch these phenomena!

for mu=0.1:0.05:4 %default
%for mu=3:0.01:4 %smaller stepsize, you can se period duplications: 2->4->8 periods,
%for mu=3.828:0.001:3.86 %the chaos temporarely disappears, than starts again with the duplication of 3 periods: 3->6->12
line=linspace(0,1,iterations);
curve=mu*line.*(1-line); % f(x)=mu*x(1-x)

subplot(2,2,1);
%draw the x=y line and the function
plot(line,curve, line,line);
hold on;

%do the iterations
Population=zeros(iterations,1);
Population(1)=start;

for i=1:(iterations-1)
    Population(i+1)=mu*Population(i)*(1-Population(i));
end

% spiderweb diagram:
%{
%from the beginning:
    plot([Population(1),Population(2)],[Population(2),Population(2)],'red');
    plot([Population(1),Population(1)],[0,Population(2)],'red');
for i=2:(iterations-1)
    %}
for i=100:(iterations-1) %only the end: after stabilisation
    plot([Population(i),Population(i+1)],[Population(i+1),Population(i+1)],'red');
    plot([Population(i),Population(i)],[Population(i),Population(i+1)],'red');
end
title(['mu=', num2str(mu)]);
xlabel('x(n)');
ylabel('x(n+1)=mu*x(n)*(1-x(n))');
hold off;

%population size
subplot(2,2,2);
plot(Population);
ylim([0,1]);
xlabel('iteration');
ylabel('population');

%histogram of the distribution of the population sizes
subplot(2,2,3);
curve2=1./(pi*sqrt(line-line.^2));
plot(line, curve2,'g');
hold on;
histsteps=0:0.01:1;
norm_hist=100*hist(Population, histsteps)/iterations;
bar(histsteps, norm_hist, 'b');
xlim([-0.1,1.1]);
ylim([0,100]);
xlabel('population');
ylabel('% of steps');
title('distribution of the population sizes');
legend('1/(pi*sqrt(x-x^2))')
hold off;

subplot(2,2,4);
hold on
plot(mu, Population(0.5*iterations:iterations), 'b.', 'MarkerSize', 1);
title('Bifurcation diagram');
xlim([0,4]);
ylim([0,1]);
xlabel('mu');
ylabel('population');


waitforbuttonpress;
pause(0.1);
end