% This program illustrates a simple implementation of a genetic algorithm.
%
% The GA optimizes a Hamiltonian that simulates the occupation 
% of particles on a 1D lattice where each site is coupled (with
% a random strength) to every other site. An "on-site" term is also 
% present for each lattice site. The objective is to find the number
% and location of particles on the lattice to minimize the energy
%
% MCC Summer School 2005
% Gus Hart   Northern Arizona Univesity
% mail: gus.hart "at" nau.edu

clc  % clear the command window
clear all % clear all variables
close all % close windows

load Precomputed_EandH

BFmin = min(energies);  % Save the minimum from the brute-force search
N=length(H(1,:));       % Number of sites in the model
Nperms = 2^N;           % Number of possible permutations of occupation variables

% Parameters for the GA
Npop = 25;         % Number of individuals in the population
max_its = 2000;     % Maximum number of iterations (generations)

Ntrials = 20 ; % Number of trials to average over
Nr = 15;       % Number of different mutation rates to try
r_mut = logspace(-4,-1,Nr)*5;  % range of rates to try (logarithmically spaced)
av_gens = zeros(1,Nr);
av_err = zeros(1,Nr);
for i = 1:Nr
    av_gens(i) = 0;
    dist = zeros(1,Ntrials);
    for j = 1:Ntrials
        [en_hist, its] = ga_minimize(H, Npop, r_mut(i), max_its, BFmin);
        dist(j) = its;    
        av_gens(i) = av_gens(i) + its;
    end
    av_err(i) = std(dist);
    av_gens(i) = av_gens(i)/Ntrials;
    fprintf('Finished r_mut: %6.3g\n',i)
end

% Output the results and make a plot
errorbar(log(r_mut),av_gens,av_err,'.-')
xlabel('Log of mutation rate')
ylabel('Number of generations')