Python Genetic Algorithm
Wildemar Wildenburger
lasses_weil at klapptsowieso.net
Sun Jan 27 18:35:51 EST 2008
Max wrote:
> In GAs, you operate on a Population of solutions. Each Individual from
> the Population is a potential solution to the problem you're
> optimizing, and Individuals have what's called a chromosome - a
> specification of what it contains. For example, common chromosomes are
> bit strings, lists of ints/floats, permutations...etc. I'm stuck on
> how to implement the different chromosomes. I have a Population class,
> which is going to contain a list of Individuals. Each individual will
> be of a certain chromosome. I envision the chromosomes as subclasses
> of an abstract Individual class, perhaps all in the same module. I'm
> just having trouble envisioning how this would be coded at the
> population level. Presumably, when a population is created, a
> parameter to its __init__ would be the chromosome type, but I don't
> know how to take that in Python and use it to specify a certain class.
>
I'm not sure I'm following you here. So a "chromosome" is bit of
functionality, right? So basically it is a function. So my advice would
be to write these functions and store it to the "indivuals"-list like so:
class Population(object):
def __init__(self, *individuals):
self.individuals = list(individuals)
Then you can say:
p = Population(indiv1, indiv2, indiv3)
for individual in p.individual:
individual(whatever_your_problem)
(Don't know if this is the way GA's are supposed to work)
You can also create callable classes (that is, classes that implement
the __call__ method), and use instances of these as the individuals. For
example you can create a Permutation class that returns a permutation
(defined in it's __init__()) when it's __call__ method is called. (Am I
making sense?)
This is just generic advice, maybe this helps and maybe it doesn't at
all. :)
> I'm doing something similar with my crossover methods, by specifying
> them as functions in a module called Crossover, importing that, and
> defining
>
> crossover_function = getattr(Crossover, "%s_crossover" % xover)
>
> Where xover is a parameter defining the type of crossover to be used.
> I'm hoping there's some similar trick to accomplish what I want to do
> with chromosomes - or maybe I'm going about this completely the wrong
> way, trying to get Python to do something it's not made for. Any help/
> feedback would be wonderful.
>
This isn't too bad, but for such things dictionaries are your Go-To
datatype. Just have a dictionary of xover-functions handy and call the
thusly:
crossover_function = Crossover.function[xover]
> Thanks,
> Max Martin
If that helps :)
regards
/W
More information about the Python-list
mailing list