source: liacs/nc/low-correlation/sa.m@ 37

Last change on this file since 37 was 32, checked in by Rick van der Zwet, 15 years ago

SA - fitness calculations

File size: 2.3 KB
RevLine 
[32]1% Simulated Annealing low-autocorrelation program
[28]2% BSDLicence
3% Rick van der Zwet - 0433373 - <hvdzwet@liacs.nl>
4
[30]5% Brute-force result of length 20
6% best_20 = [-1,1,1,-1,-1,-1,1,1,-1,1,-1,-1,-1,1,-1,1,1,1,1,1];
7% autocorrelation(best_20);
8
[32]9function number = randint(low,high)
10 number = round(rand() * (high - low)) + low;
11endfunction
12
13function new = mutation(old)
14 loc = randint(1,length(old));
15 old(loc) = old(loc) * -1;
16 new = old;
17endfunction
18
19function s = initseq(n)
20 % Generate a random column s={-1,1}^n
21 s = rand(n,1);
22 s = round(s);
23 s = s - (s == 0);
24endfunction
25
26function [fitness,value] = sa(length, temperature, stopLimit)
[31]27 best_fitness = 0;
[32]28 s = initseq(length);
29 stopCounter = 0;
30
31 while (stopCounter < stopLimit)
32 % Generate new mutation
33 newseq = mutation(s);
34
35 % Better is always accept
36 fitness = autocorrelation(newseq);
[31]37 if (fitness > best_fitness)
38 best_value = s;
39 best_fitness = fitness;
[32]40 s = newseq;
41 fitness
42 disp(rot90(newseq,-1));
43 stopCounter = 0;
44 else
45 % Make the next 'move' less atractive
46 temperature =- 1;
47
48 stopCounter += 1;
49 % Accept on an certain probability
50 if (temperature < 0)
51 break;
52 else
53 if(randint(0,temperature) > temperature / 4)
54 s = newseq;
55 endif
56 endif
[31]57 endif
[32]58 endwhile
59 value = best_value;
[31]60 fitness = best_fitness;
61endfunction
[30]62
[32]63%% Basic variables
64iterations = [1:10:1000];
[31]65repetitions = 20;
66length = 20;
[32]67temperature = 1000;
[28]68
[31]69
70% Plot the stuff
71fitnesses = [];
72for iteration = iterations
73 fitness = [];
74 for rep = 1:repetitions
75 printf('Iter:%i, Rep:%i\n',iteration,rep);
[32]76 [new_fitness, value] = sa(length,iteration,temperature);
[31]77 fitness = [fitness, new_fitness];
78
[28]79 % Little hack to display output nicely
[31]80 % disp(rot90(value,-1));
81 endfor
82
83 fitnesses = [fitnesses,mean(fitness)];
84endfor
[28]85
[31]86plot(iterations,fitnesses);
[32]87title(sprintf('Simulated Annealing on Low-Corretation set - repetitions %i',repetitions));
[31]88ylabel('fitness');
89xlabel('iterations');
90grid on;
91legend(sprintf('Length %i',length));
[32]92print("sa-fitness.eps","-depsc2");
[31]93
Note: See TracBrowser for help on using the repository browser.