source: framspy/evolalg/structures/hall_of_fame.py @ 1190

Last change on this file since 1190 was 1190, checked in by Maciej Komosinski, 17 months ago

Added the "evolalg" module for evolutionary optimization

File size: 893 bytes
Line 
1class HallOfFame:
2    """A simple function that keeps the specified number of individuals, adding only better ones.
3    The list remains sorted from best to worst."""
4
5    def __init__(self, hofsize):
6        self.hofsize = hofsize
7        self.hof = []
8
9    def __iter__(self):
10        return iter(self.hof)
11
12    def __len__(self):
13        return len(self.hof)
14
15    def add(self, individual):
16        if len(self.hof) < 1:  # empty hof?
17            self.hof.append(individual)  # then add the first individual
18        else:  # we have some individuals in hof?
19            # only add if the new one is better than the first stored in hof
20            if individual.rawfitness > self.hof[0].rawfitness:
21                self.hof.insert(0, individual)  # add as first
22        while len(self.hof) > self.hofsize:  # exceeded desired hof capacity?
23            self.hof.pop()  # delete last (=worst)
Note: See TracBrowser for help on using the repository browser.