1 """General functionality for mutations.
2 """
3
4 import random
5
6
7 from Bio.GA.Organism import Organism
8
10 """Perform mutations, but do not allow decreases in organism fitness.
11
12 This doesn't actually do any mutation work, but just checks that
13 newly create organisms do not have lower fitnesses.
14 """
15 - def __init__(self, actual_mutation, accept_less = 0.0):
16 """Initialize to do safe mutations
17
18 Arguments:
19
20 o actual_mutation - A Mutation class which actually implements
21 mutation. functionality.
22
23 o accept_less - A probability to accept mutations which
24 generate lower fitness. This allows you to accept some
25 crossovers which reduce fitness, but not all of them.
26 """
27 self._mutation = actual_mutation
28 self._accept_less_percent = accept_less
29 self._accept_less_rand = random.Random()
30
32 """Perform safe mutation of the specified organism.
33 """
34 new_org = self._mutation.mutate(org)
35 new_org.recalculate_fitness()
36
37 if org.fitness > new_org.fitness:
38 accept_less_chance = self._accept_less_rand.random()
39 if accept_less_chance <= self._accept_less_percent:
40 return new_org
41 else:
42 return org
43 else:
44 return new_org
45