File: Uniform.py

package info (click to toggle)
python-biopython 1.68%2Bdfsg-3~bpo8%2B1
  • links: PTS, VCS
  • area: main
  • in suites: jessie-backports
  • size: 46,856 kB
  • sloc: python: 160,306; xml: 93,216; ansic: 9,118; sql: 1,208; makefile: 155; sh: 63
file content (57 lines) | stat: -rw-r--r-- 1,925 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# This code is part of the Biopython distribution and governed by its
# license.  Please see the LICENSE file that should have been included
# as part of this package.
#

"""Perform uniform crossovers between the genomes of two organisms.


    | genome 1 --       A B C D E F G
    |                   .   . .   .
    | genome 2 --       a b c d e f g
    |
    | After crossover:
    |
    | new genome 1 --  a B c d E f G
    | new genome 2 --  A b C D e F g

Uniform Crossover is a standard crossover technique for
rapid mutation-behavior.
"""
# standard modules
import random


class UniformCrossover(object):
    """Perform single point crossover between genomes at some defined rates.

    This performs a single crossover between two genomes at some
    defined frequency. The location of the crossover is chosen randomly
    if the crossover meets the probability to occur.
    """
    def __init__(self, crossover_prob=.1, uniform_prob=0.7):
        """Initialize to do uniform crossover at the specified probability and frequency.
        """
        self._crossover_prob = crossover_prob
        self._uniform_prob = uniform_prob
        return

    def do_crossover(self, org_1, org_2):
        """Potentially do a crossover between the two organisms.
        """
        new_org_1 = org_1.copy()
        new_org_2 = org_2.copy()

        # determine if we have a crossover
        crossover_chance = random.random()
        if crossover_chance <= self._crossover_prob:
            minlen = min(len(new_org_1.genome), len(new_org_2.genome))
            for i in range(minlen):
                uniform_chance = random.random()
                if uniform_chance <= self._uniform_prob:
                    # cycle element
                    temp = new_org_1.genome[i]
                    new_org_1.genome[i] = new_org_2.genome[i]
                    new_org_2.genome[i] = temp

        return new_org_1, new_org_2