%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Flower Constancy algortihm created by Pawel Kopciewicz, February 2018   %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% An example usage of Flower Constancy algorithm for function model       %
% fitting (data from distorted Gauss distribution with C, mi, sigma).                                                                %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [C,mi,sigma] = FC_fit()

N=250;  % Number of algorithm iterations
n=20;   % Number of flowers

P=30;   % Number of points we fit a model to
d=3;    % model parameters

%%Generating data from distorted Gauss:
X=linspace(0,8,P);   
for i=1:P
Y(i)=6*gaussmf(X(i),[1 6])+0.5*(rand-0.5);
end

%%Random initial solution + cost evaluation. Objective function is a
%%variance of data&fit.
POS(:,1:d)=10*rand(n,3);
cost(1:n)=0;
for j=1:n
    for k=1:P
        cost(j)=cost(j)+(Y(k)-POS(j,1)*gaussmf(X(k),[POS(j,3) POS(j,2)]))^2;
    end
end
 
%%Flower Constancy Algorithm
for i=1:N
    for j=1:n
        %%Pollination:
        e=2*rand-1;
        z=round((n-1)*rand+1); q=round((n-1)*rand+1);
        POS2(j,:)=POS(j,:)+e*(POS(q,:)-POS(z,:));
        %% New solution cost evaluation:
            %(Add constraint-handling code here if needed.)
        cost2=0;    
        for k=1:P
          cost2=cost2+(Y(k)-POS2(j,1)*gaussmf(X(k),[POS2(j,3) POS2(j,2)]))^2;
        end
        
        %%If new solution is better, update it
        if cost2<cost(j)
            POS(j,:)=POS2(j,:);
            cost(j)=cost2;
        end
    end
end
%%End solutions cost evaluation
cost(1:n)=0;
for j=1:n
    for k=1:P
      cost(j)=cost(j)+(Y(k)-POS(j,1)*gaussmf(X(k),[POS(j,3) POS(j,2)]))^2;
    end
end
[value,no]=min(cost);
C=POS(no,1);
mi=POS(no,2);
sigma=POS(no,3);

%% Plot obtained fit.
plot(X,Y,'r.');
hold on;
xxx=linspace(0,8,100);
for i=1:100
yyy(i)=C*gaussmf(xxx(i),[sigma mi]);
end
plot(xxx,yyy);

