Beispiel #1
0
def G2DListMutatorIntegerRange(genome, **args):
   """ Simple integer range mutator for G2DList

   Accepts the *rangemin* and *rangemax* genome parameters, both optional.

   """
   if args["pmut"] <= 0.0:
      return 0
   height, width = genome.getSize()
   elements = height * width

   mutations = args["pmut"] * elements

   range_min = genome.getParam("rangemin", Consts.CDefRangeMin)
   range_max = genome.getParam("rangemax", Consts.CDefRangeMax)

   if mutations < 1.0:
      mutations = 0
      for i in range(genome.getHeight()):
         for j in range(genome.getWidth()):
            if Util.randomFlipCoin(args["pmut"]):
               random_int = rand_randint(range_min, range_max)
               genome.setItem(i, j, random_int)
               mutations += 1

   else:
      for it in range(int(round(mutations))):
         which_x = rand_randint(0, genome.getWidth() - 1)
         which_y = rand_randint(0, genome.getHeight() - 1)
         random_int = rand_randint(range_min, range_max)
         genome.setItem(which_y, which_x, random_int)

   return int(mutations)
Beispiel #2
0
def G2DListMutatorIntegerRange(genome, **args):
   """ Simple integer range mutator for G2DList

   Accepts the *rangemin* and *rangemax* genome parameters, both optional.

   """
   if args["pmut"] <= 0.0: return 0
   height, width = genome.get_size()
   elements = height * width

   mutations = args["pmut"] * elements

   range_min = genome.get_param("rangemin", CDefRangeMin)
   range_max = genome.get_param("rangemax", CDefRangeMax)

   if mutations < 1.0:
      mutations = 0
      for i in xrange(genome.get_height()):
         for j in xrange(genome.get_width()):
            if utils.random_flip_coin(args["pmut"]):
               random_int = rand_randint(range_min, range_max)
               genome.set_item(i, j, random_int)
               mutations += 1

   else: 
      for it in xrange(int(round(mutations))):
         which_x = rand_randint(0, genome.get_width()-1)
         which_y = rand_randint(0, genome.get_height()-1)
         random_int = rand_randint(range_min, range_max)
         genome.set_item(which_y, which_x, random_int)

   return int(mutations)
Beispiel #3
0
def G1DBinaryStringXTwoPoint(genome, **args):
   """ The 1D Binary String crossover, Two Point

   .. warning:: You can't use this crossover method for binary strings with length of 1.

   """
   sister = None
   brother = None
   gMom = args["mom"]
   gDad = args["dad"]
   
   if len(gMom) == 1:
      Util.raiseException("The Binary String have one element, can't use the Two Point Crossover method !", TypeError)

   cuts = [rand_randint(1, len(gMom)-1), rand_randint(1, len(gMom)-1)]

   if cuts[0] > cuts[1]:
      Util.listSwapElement(cuts, 0, 1)

   if args["count"] >= 1:
      sister = gMom.clone()
      sister.resetStats()
      sister[cuts[0]:cuts[1]] = gDad[cuts[0]:cuts[1]]

   if args["count"] == 2:
      brother = gDad.clone()
      brother.resetStats()
      brother[cuts[0]:cuts[1]] = gMom[cuts[0]:cuts[1]]

   return (sister, brother)
Beispiel #4
0
def G2DBinaryStringMutatorFlip(genome, **args):
    """ A flip mutator for G2DBinaryString
   
   .. versionadded:: 0.6
      The *G2DBinaryStringMutatorFlip* function
   """
    if args["pmut"] <= 0.0: return 0
    height, width = genome.getSize()
    elements = height * width

    mutations = args["pmut"] * elements

    if mutations < 1.0:
        mutations = 0

        for i in xrange(genome.getHeight()):
            for j in xrange(genome.getWidth()):
                if Util.randomFlipCoin(args["pmut"]):
                    if genome[i][j] == 0: genome.setItem(i, j, 1)
                    else: genome.setItem(i, j, 0)
                    mutations += 1
    else:

        for it in xrange(int(round(mutations))):
            which_x = rand_randint(0, genome.getWidth() - 1)
            which_y = rand_randint(0, genome.getHeight() - 1)

            if genome[i][j] == 0: genome.setItem(which_y, which_x, 1)
            else: genome.setItem(which_y, which_x, 0)

    return int(mutations)
Beispiel #5
0
def G1DListMutatorSIM(genome, **args):
   """ The mutator of G1DList, Simple Inversion Mutation

   .. note:: this mutator is :term:`Data Type Independent`

   """
   mutations = 0
   if args["pmut"] <= 0.0:
      return 0

   cuts = [rand_randint(0, len(genome)), rand_randint(0, len(genome))]

   if cuts[0] > cuts[1]:
      Util.listSwapElement(cuts, 0, 1)

   if (cuts[1] - cuts[0]) <= 0:
      cuts[1] = rand_randint(cuts[0], len(genome))

   if Util.randomFlipCoin(args["pmut"]):
      part = genome[cuts[0]:cuts[1]]
      if len(part) == 0:
         return 0
      part.reverse()
      genome[cuts[0]:cuts[1]] = part
      mutations += 1

   return mutations
Beispiel #6
0
def G2DBinaryStringMutatorFlip(genome, **args):
   """ A flip mutator for G2DBinaryString
   
   .. versionadded:: 0.6
      The *G2DBinaryStringMutatorFlip* function
   """
   if args["pmut"] <= 0.0: return 0
   height, width = genome.get_size()
   elements = height * width

   mutations = args["pmut"] * elements

   if mutations < 1.0:
      mutations = 0
      
      for i in xrange(genome.get_height()):
         for j in xrange(genome.get_width()):
            if utils.random_flip_coin(args["pmut"]):
               if genome[i][j] == 0: genome.set_item(i, j, 1)
               else:                 genome.set_item(i, j, 0)
               mutations += 1
   else: 

      for it in xrange(int(round(mutations))):
         which_x = rand_randint(0, genome.get_width()-1)
         which_y = rand_randint(0, genome.get_height()-1)

         if genome[i][j] == 0: genome.set_item(which_y, which_x, 1)
         else:                 genome.set_item(which_y, which_x, 0)

   return int(mutations)
Beispiel #7
0
def G1DBinaryStringXTwoPoint(genome, **args):
    """ The 1D Binary String crossover, Two Point

    .. warning:: You can't use this crossover method for binary strings with length of 1.

    """
    sister = None
    brother = None
    gMom = args["mom"]
    gDad = args["dad"]

    if len(gMom) == 1:
        Util.raiseException(
            "The Binary String have one element, can't use the Two Point Crossover method !",
            TypeError)

    cuts = [rand_randint(1, len(gMom) - 1), rand_randint(1, len(gMom) - 1)]

    if cuts[0] > cuts[1]:
        Util.listSwapElement(cuts, 0, 1)

    if args["count"] >= 1:
        sister = gMom.clone()
        sister.resetStats()
        sister[cuts[0]:cuts[1]] = gDad[cuts[0]:cuts[1]]

    if args["count"] == 2:
        brother = gDad.clone()
        brother.resetStats()
        brother[cuts[0]:cuts[1]] = gMom[cuts[0]:cuts[1]]

    return (sister, brother)
def G1DListMutatorDisplacement(genome: G1DList, **args):
    """ The mutator of G1DList, Swap Mutator

    .. note:: this mutator is :term:`Data Type Independent`

    """
    mutations = 0
    pmut = args["pmut"]
    if pmut <= 0.0:
        return mutations
    if not Util.randomFlipCoin(pmut):
        return mutations

    listSize = len(genome)
    
    
    to_remove = rand_randint(0, listSize - 1)
    while True:
        to_insert = rand_randint(0, listSize - 1)
        if to_remove != to_insert:
            break

    val = genome.genomeList.pop(to_remove)
    genome.genomeList.insert(to_insert, val)
    mutations = mutations + 1

    return mutations
Beispiel #9
0
def GTreeMutatorIntegerRange(genome, **args):
   """ The mutator of GTree, Integer Range Mutator

   Accepts the *rangemin* and *rangemax* genome parameters, both optional.

   .. versionadded:: 0.6
      The *GTreeMutatorIntegerRange* function
   """
   if args["pmut"] <= 0.0:
      return 0
   elements = len(genome)
   mutations = args["pmut"] * elements

   range_min = genome.getParam("rangemin", Consts.CDefRangeMin)
   range_max = genome.getParam("rangemax", Consts.CDefRangeMax)

   if mutations < 1.0:
      mutations = 0
      for i in range(len(genome)):
         if Util.randomFlipCoin(args["pmut"]):
            mutations += 1
            rand_node = genome.getRandomNode()
            random_int = rand_randint(range_min, range_max)
            rand_node.setData(random_int)

   else:
      for it in range(int(round(mutations))):
         rand_node = genome.getRandomNode()
         random_int = rand_randint(range_min, range_max)
         rand_node.setData(random_int)

   return int(mutations)
Beispiel #10
0
def G1DListMutatorIntegerRange(genome, **args):
   """ Simple integer range mutator for G1DList

   Accepts the *rangemin* and *rangemax* genome parameters, both optional.

   """
   if args["pmut"] <= 0.0:
      return 0
   listSize = len(genome)
   mutations = args["pmut"] * listSize

   if mutations < 1.0:
      mutations = 0
      for it in xrange(listSize):
         if Util.randomFlipCoin(args["pmut"]):
            genome[it] = rand_randint(genome.getParam("rangemin", Consts.CDefRangeMin),
                                      genome.getParam("rangemax", Consts.CDefRangeMax))
            mutations += 1

   else:
      for it in xrange(int(round(mutations))):
         which_gene = rand_randint(0, listSize - 1)
         genome[which_gene] = rand_randint(genome.getParam("rangemin", Consts.CDefRangeMin),
                                           genome.getParam("rangemax", Consts.CDefRangeMax))

   return int(mutations)
Beispiel #11
0
def G1DListMutatorSIM(genome, **args):
   """ The mutator of G1DList, Simple Inversion Mutation

   .. note:: this mutator is :term:`Data Type Independent`

   """
   mutations = 0
   if args["pmut"] <= 0.0:
      return 0

   cuts = [rand_randint(0, len(genome)), rand_randint(0, len(genome))]

   if cuts[0] > cuts[1]:
      Util.listSwapElement(cuts, 0, 1)

   if (cuts[1] - cuts[0]) <= 0:
      cuts[1] = rand_randint(cuts[0], len(genome))

   if Util.randomFlipCoin(args["pmut"]):
      part = genome[cuts[0]:cuts[1]]
      if len(part) == 0:
         return 0
      part.reverse()
      genome[cuts[0]:cuts[1]] = part
      mutations += 1

   return mutations
Beispiel #12
0
def GTreeMutatorIntegerRange(genome, **args):
   """ The mutator of GTree, Integer Range Mutator

   Accepts the *rangemin* and *rangemax* genome parameters, both optional.

   .. versionadded:: 0.6
      The *GTreeMutatorIntegerRange* function
   """
   if args["pmut"] <= 0.0:
      return 0
   elements = len(genome)
   mutations = args["pmut"] * elements

   range_min = genome.getParam("rangemin", Consts.CDefRangeMin)
   range_max = genome.getParam("rangemax", Consts.CDefRangeMax)

   if mutations < 1.0:
      mutations = 0
      for i in xrange(len(genome)):
         if Util.randomFlipCoin(args["pmut"]):
            mutations += 1
            rand_node = genome.getRandomNode()
            random_int = rand_randint(range_min, range_max)
            rand_node.setData(random_int)

   else:
      for it in xrange(int(round(mutations))):
         rand_node = genome.getRandomNode()
         random_int = rand_randint(range_min, range_max)
         rand_node.setData(random_int)

   return int(mutations)
Beispiel #13
0
def G1DListCrossoverTwoPoint(genome, **args):
   """ The G1DList crossover, Two Point

   .. warning:: You can't use this crossover method for lists with just one or two elements.

   """
   sister = None
   brother = None
   gMom = args["mom"]
   gDad = args["dad"]
   
   if len(gMom) < 3:
      Util.raiseException("The 1D List has less than 3 elements, can't use the Two Point Crossover method !", TypeError)

   cuts = [0, 0]
   # Keep generating random cuts until they are in different places
   while cuts[0] == cuts[1]:
       cuts = [rand_randint(1, len(gMom)-1), rand_randint(1, len(gMom)-1)]

   if cuts[0] > cuts[1]:
      Util.listSwapElement(cuts, 0, 1)

   if args["count"] >= 1:
      sister = gMom.clone()
      sister.resetStats()
      sister[cuts[0]:cuts[1]] = gDad[cuts[0]:cuts[1]]

   if args["count"] == 2:
      brother = gDad.clone()
      brother.resetStats()
      brother[cuts[0]:cuts[1]] = gMom[cuts[0]:cuts[1]]

   return (sister, brother)
Beispiel #14
0
def G1DListCrossoverOX(genome, **args):
    """ The OX Crossover for G1DList  (order crossover) """
    sister = None
    brother = None
    gMom = args["mom"]
    gDad = args["dad"]
    listSize = len(gMom)

    c1, c2 = [rand_randint(1, len(gMom) - 1), rand_randint(1, len(gMom) - 1)]

    while c1 == c2:
        c2 = rand_randint(1, len(gMom) - 1)

    if c1 > c2:
        h = c1
        c1 = c2
        c2 = h

    if args["count"] >= 1:
        sister = gMom.clone()
        sister.resetStats()
        P1 = [c for c in gMom[c2:] + gMom[:c2] if c not in gDad[c1:c2]]
        sister.genomeList = P1[listSize - c2:] + gDad[c1:c2] + P1[:listSize - c2]

    if args["count"] == 2:
        brother = gDad.clone()
        brother.resetStats()
        P2 = [c for c in gDad[c2:] + gDad[:c2] if c not in gMom[c1:c2]]
        brother.genomeList = P2[listSize - c2:] + gMom[c1:c2] + P2[:listSize - c2]

    assert listSize == len(sister)
    assert listSize == len(brother)

    return (sister, brother)
Beispiel #15
0
def G1DListCrossoverOX(genome, **args):
   """ The OX Crossover for G1DList  (order crossover) """
   sister = None
   brother = None
   gMom = args["mom"]
   gDad = args["dad"]
   listSize = len(gMom)

   c1, c2 = [rand_randint(1, len(gMom)-1), rand_randint(1, len(gMom)-1)]

   while c1 == c2:
      c2 = rand_randint(1, len(gMom)-1)

   if c1 > c2:
      h = c1
      c1 = c2
      c2 = h

   if args["count"] >= 1:
      sister = gMom.clone()
      sister.resetStats()
      P1 = [ c for c in gMom[c2:] + gMom[:c2] if c not in gDad[c1:c2] ]
      sister.genomeList = P1[listSize - c2:] + gDad[c1:c2] + P1[:listSize-c2]
    
   if args["count"] == 2:
      brother = gDad.clone()
      brother.resetStats()
      P2 = [ c for c in gDad[c2:] + gDad[:c2] if c not in gMom[c1:c2] ]
      brother.genomeList = P2[listSize - c2:] + gMom[c1:c2] + P2[:listSize-c2]

   assert listSize == len(sister)
   assert listSize == len(brother)

   return (sister, brother)
Beispiel #16
0
def G1DListCrossoverTwoPoint(genome, **args):
    """ The G1DList crossover, Two Point

   .. warning:: You can't use this crossover method for lists with just one element.

   """
    sister = None
    brother = None
    gMom = args["mom"]
    gDad = args["dad"]

    if len(gMom) == 1:
        utils.raise_exception("The 1D List have one element, can't use the Two Point Crossover method !", TypeError)

    cuts = [rand_randint(1, len(gMom) - 1), rand_randint(1, len(gMom) - 1)]

    if cuts[0] > cuts[1]:
        utils.list_swap_element(cuts, 0, 1)

    if args["count"] >= 1:
        sister = gMom.clone()
        sister.reset_stats()
        sister[cuts[0] : cuts[1]] = gDad[cuts[0] : cuts[1]]

    if args["count"] == 2:
        brother = gDad.clone()
        brother.reset_stats()
        brother[cuts[0] : cuts[1]] = gMom[cuts[0] : cuts[1]]

    return (sister, brother)
Beispiel #17
0
def G1DListMutatorIntegerRange(genome, **args):
   """ Simple integer range mutator for G1DList

   Accepts the *rangemin* and *rangemax* genome parameters, both optional.

   """
   if args["pmut"] <= 0.0:
      return 0
   listSize = len(genome)
   mutations = args["pmut"] * listSize

   if mutations < 1.0:
      mutations = 0
      for it in range(listSize):
         if Util.randomFlipCoin(args["pmut"]):
            genome[it] = rand_randint(genome.getParam("rangemin", Consts.CDefRangeMin),
                                      genome.getParam("rangemax", Consts.CDefRangeMax))
            mutations += 1

   else:
      for it in range(int(round(mutations))):
         which_gene = rand_randint(0, listSize - 1)
         genome[which_gene] = rand_randint(genome.getParam("rangemin", Consts.CDefRangeMin),
                                           genome.getParam("rangemax", Consts.CDefRangeMax))

   return int(mutations)
Beispiel #18
0
def G2DListMutatorRealGaussian(genome, **args):
    """ A gaussian mutator for G2DList of Real

    Accepts the *rangemin* and *rangemax* genome parameters, both optional. Also
    accepts the parameter *gauss_mu* and the *gauss_sigma* which respectively
    represents the mean and the std. dev. of the random distribution.

    """
    from . import Consts

    if args["pmut"] <= 0.0:
        return 0
    height, width = genome.getSize()
    elements = height * width

    mutations = args["pmut"] * elements

    mu = genome.getParam("gauss_mu")
    sigma = genome.getParam("gauss_sigma")

    if mu is None:
        mu = Consts.CDefG2DListMutRealMU

    if sigma is None:
        sigma = Consts.CDefG2DListMutRealSIGMA

    if mutations < 1.0:
        mutations = 0

        for i in range(genome.getHeight()):
            for j in range(genome.getWidth()):
                if Util.randomFlipCoin(args["pmut"]):
                    final_value = genome[i][j] + rand_gauss(mu, sigma)

                    final_value = min(
                        final_value,
                        genome.getParam("rangemax", Consts.CDefRangeMax))
                    final_value = max(
                        final_value,
                        genome.getParam("rangemin", Consts.CDefRangeMin))

                    genome.setItem(i, j, final_value)
                    mutations += 1
    else:

        for it in range(int(round(mutations))):
            which_x = rand_randint(0, genome.getWidth() - 1)
            which_y = rand_randint(0, genome.getHeight() - 1)

            final_value = genome[which_y][which_x] + rand_gauss(mu, sigma)

            final_value = min(final_value,
                              genome.getParam("rangemax", Consts.CDefRangeMax))
            final_value = max(final_value,
                              genome.getParam("rangemin", Consts.CDefRangeMin))

            genome.setItem(which_y, which_x, final_value)

    return int(mutations)
Beispiel #19
0
def G2DListMutatorIntegerGaussianGradient(genome, **args):
    """ A gaussian mutator for G2DList of Integers

    Accepts the *rangemin* and *rangemax* genome parameters, both optional.

    This routine generates a gaussian value with mu=1.0 and std=0.0333 and then
    the gene is multiplied by this value. This will cause the gene to drift
    no matter how large it is.

    """
    from . import Consts

    if args["pmut"] <= 0.0:
        return 0
    height, width = genome.getSize()
    elements = height * width

    mutations = args["pmut"] * elements

    mu = Consts.CDefGaussianGradientMU
    sigma = Consts.CDefGaussianGradientSIGMA

    if mutations < 1.0:
        mutations = 0

        for i in range(genome.getHeight()):
            for j in range(genome.getWidth()):
                if Util.randomFlipCoin(args["pmut"]):
                    final_value = int(genome[i][j] *
                                      abs(rand_gauss(mu, sigma)))

                    final_value = min(
                        final_value,
                        genome.getParam("rangemax", Consts.CDefRangeMax))
                    final_value = max(
                        final_value,
                        genome.getParam("rangemin", Consts.CDefRangeMin))

                    genome.setItem(i, j, final_value)
                    mutations += 1
    else:

        for it in range(int(round(mutations))):
            which_x = rand_randint(0, genome.getWidth() - 1)
            which_y = rand_randint(0, genome.getHeight() - 1)

            final_value = int(genome[which_y][which_x] *
                              abs(rand_gauss(mu, sigma)))

            final_value = min(final_value,
                              genome.getParam("rangemax", Consts.CDefRangeMax))
            final_value = max(final_value,
                              genome.getParam("rangemin", Consts.CDefRangeMin))

            genome.setItem(which_y, which_x, final_value)

    return int(mutations)
Beispiel #20
0
def population_init(genome, **args):
    # genome will have 1 <= i <= MAX rules within the rule set
    MAX_NUMBER_OF_RULES = genome.getParam("initrules")
    genomeExamples = genome.getExamplesRef()

    number_of_rules_to_add = rand_randint(1, MAX_NUMBER_OF_RULES)
    for i in range(0, number_of_rules_to_add):
        genome.addRuleAsString(genomeExamples[rand_randint(
            0,
            len(genomeExamples) - 1)])
Beispiel #21
0
def G2DListMutatorRealGaussian(genome, **args):
    """ A gaussian mutator for G2DList of Real

    Accepts the *rangemin* and *rangemax* genome parameters, both optional. Also
    accepts the parameter *gauss_mu* and the *gauss_sigma* which respectively
    represents the mean and the std. dev. of the random distribution.

    """
    if args["pmut"] <= 0.0:
        return 0
    height, width = genome.getSize()
    elements = height * width

    mutations = args["pmut"] * elements

    mu = genome.getParam("gauss_mu")
    sigma = genome.getParam("gauss_sigma")

    if mu is None:
        mu = Consts.CDefG2DListMutRealMU

    if sigma is None:
        sigma = Consts.CDefG2DListMutRealSIGMA

    if mutations < 1.0:
        mutations = 0

        for i in xrange(genome.getHeight()):
            for j in xrange(genome.getWidth()):
                if Util.randomFlipCoin(args["pmut"]):
                    final_value = genome[i][j] + rand_gauss(mu, sigma)

                    final_value = min(final_value, genome.getParam(
                        "rangemax", Consts.CDefRangeMax))
                    final_value = max(final_value, genome.getParam(
                        "rangemin", Consts.CDefRangeMin))

                    genome.setItem(i, j, final_value)
                    mutations += 1
    else:

        for it in xrange(int(round(mutations))):
            which_x = rand_randint(0, genome.getWidth() - 1)
            which_y = rand_randint(0, genome.getHeight() - 1)

            final_value = genome[which_y][which_x] + rand_gauss(mu, sigma)

            final_value = min(final_value, genome.getParam(
                "rangemax", Consts.CDefRangeMax))
            final_value = max(final_value, genome.getParam(
                "rangemin", Consts.CDefRangeMin))

            genome.setItem(which_y, which_x, final_value)

    return int(mutations)
Beispiel #22
0
def G2DListMutatorRealGaussianGradient(genome, **args):
    """ A gaussian gradient mutator for G2DList of Real

    Accepts the *rangemin* and *rangemax* genome parameters, both optional.

    The difference is that this multiplies the gene by gauss(1.0, 0.0333), allowing
    for a smooth gradient drift about the value.

    """
    from . import Consts

    if args["pmut"] <= 0.0:
        return 0
    height, width = genome.getSize()
    elements = height * width

    mutations = args["pmut"] * elements

    mu = Consts.CDefGaussianGradientMU
    sigma = Consts.CDefGaussianGradientSIGMA

    if mutations < 1.0:
        mutations = 0

        for i in range(genome.getHeight()):
            for j in range(genome.getWidth()):
                if Util.randomFlipCoin(args["pmut"]):
                    final_value = genome[i][j] * abs(rand_gauss(mu, sigma))

                    final_value = min(
                        final_value,
                        genome.getParam("rangemax", Consts.CDefRangeMax))
                    final_value = max(
                        final_value,
                        genome.getParam("rangemin", Consts.CDefRangeMin))

                    genome.setItem(i, j, final_value)
                    mutations += 1
    else:

        for it in range(int(round(mutations))):
            which_x = rand_randint(0, genome.getWidth() - 1)
            which_y = rand_randint(0, genome.getHeight() - 1)

            final_value = genome[which_y][which_x] * abs(rand_gauss(mu, sigma))

            final_value = min(final_value,
                              genome.getParam("rangemax", Consts.CDefRangeMax))
            final_value = max(final_value,
                              genome.getParam("rangemin", Consts.CDefRangeMin))

            genome.setItem(which_y, which_x, final_value)

    return int(mutations)
Beispiel #23
0
def G2DListMutatorIntegerGaussianGradient(genome, **args):
    """ A gaussian mutator for G2DList of Integers

    Accepts the *rangemin* and *rangemax* genome parameters, both optional.

    This routine generates a gaussian value with mu=1.0 and std=0.0333 and then
    the gene is multiplied by this value. This will cause the gene to drift
    no matter how large it is.

    """
    if args["pmut"] <= 0.0:
        return 0
    height, width = genome.getSize()
    elements = height * width

    mutations = args["pmut"] * elements

    mu = Consts.CDefGaussianGradientMU
    sigma = Consts.CDefGaussianGradientSIGMA

    if mutations < 1.0:
        mutations = 0

        for i in xrange(genome.getHeight()):
            for j in xrange(genome.getWidth()):
                if Util.randomFlipCoin(args["pmut"]):
                    final_value = int(
                        genome[i][j] * abs(rand_gauss(mu, sigma)))

                    final_value = min(final_value, genome.getParam(
                        "rangemax", Consts.CDefRangeMax))
                    final_value = max(final_value, genome.getParam(
                        "rangemin", Consts.CDefRangeMin))

                    genome.setItem(i, j, final_value)
                    mutations += 1
    else:

        for it in xrange(int(round(mutations))):
            which_x = rand_randint(0, genome.getWidth() - 1)
            which_y = rand_randint(0, genome.getHeight() - 1)

            final_value = int(genome[which_y][which_x]
                              * abs(rand_gauss(mu, sigma)))

            final_value = min(final_value, genome.getParam(
                "rangemax", Consts.CDefRangeMax))
            final_value = max(final_value, genome.getParam(
                "rangemin", Consts.CDefRangeMin))

            genome.setItem(which_y, which_x, final_value)

    return int(mutations)
Beispiel #24
0
def crossover_gabil(genome, **args):
#def crossover_gabil(gDad, gMom):
	sister = None
	brother = None
	gMom = args["mom"]
	gDad = args["dad"]
	
	
	if (len(gMom) < len(gDad)):
		gMom , gDad = gDad, gMom
	
	splitMom = [ rand_randint( 1 , len(gMom) + 1) , rand_randint(1, len(gMom) + 1)]
	
	if (splitMom [1] < splitMom[0] ):
		splitMom[0],splitMom[1] = splitMom[1],splitMom[0] 

	s1 = gMom[0:splitMom[0]]
	s2 = gMom[splitMom[0]:splitMom[1]]
	s3 = gMom[splitMom[1]:len(gMom)]
	
	
	nRulesD = len(gDad) / RULE_SIZE;
	splitDad = [ rand_randint( 1 , nRulesD + 1) , rand_randint(1, nRulesD + 1)]
	
	if (splitDad[0] > splitDad[1] ):
		splitDad[0], splitDad[1] = splitDad[1], splitDad[0]
	
	positionDad = splitMom[0] % RULE_SIZE
	positionDad1 = splitMom[1] % RULE_SIZE
	
	n1 = splitDad[0] + positionDad
	n2 = splitDad[1] + positionDad1

	if (n2 < n1):
		n1,n2 = n2,n1

	d1 = gDad[0:n1]
	d2 = gDad[n1:n2]
	d3 = gDad[n2:len(gDad)]
	
	sister = gMom.clone()
	sister.resetStats()
	sister.genomeString = s1 + d2 + s3
	sister.stringLength = len(s1 + d2 + s3)
	
	brother = gDad.clone()
	brother.resetStats()
	brother.genomeString = d1 + s2 + d3
	brother.stringLength = len(d1 + s2 + d3)
	
	return (sister, brother)
Beispiel #25
0
def G2DListMutatorRealGaussianGradient(genome, **args):
    """ A gaussian gradient mutator for G2DList of Real

    Accepts the *rangemin* and *rangemax* genome parameters, both optional.

    The difference is that this multiplies the gene by gauss(1.0, 0.0333), allowing
    for a smooth gradient drift about the value.

    """
    if args["pmut"] <= 0.0:
        return 0
    height, width = genome.getSize()
    elements = height * width

    mutations = args["pmut"] * elements

    mu = Consts.CDefGaussianGradientMU
    sigma = Consts.CDefGaussianGradientSIGMA

    if mutations < 1.0:
        mutations = 0

        for i in xrange(genome.getHeight()):
            for j in xrange(genome.getWidth()):
                if Util.randomFlipCoin(args["pmut"]):
                    final_value = genome[i][j] * abs(rand_gauss(mu, sigma))

                    final_value = min(final_value, genome.getParam(
                        "rangemax", Consts.CDefRangeMax))
                    final_value = max(final_value, genome.getParam(
                        "rangemin", Consts.CDefRangeMin))

                    genome.setItem(i, j, final_value)
                    mutations += 1
    else:

        for it in xrange(int(round(mutations))):
            which_x = rand_randint(0, genome.getWidth() - 1)
            which_y = rand_randint(0, genome.getHeight() - 1)

            final_value = genome[which_y][which_x] * abs(rand_gauss(mu, sigma))

            final_value = min(final_value, genome.getParam(
                "rangemax", Consts.CDefRangeMax))
            final_value = max(final_value, genome.getParam(
                "rangemin", Consts.CDefRangeMin))

            genome.setItem(which_y, which_x, final_value)

    return int(mutations)
Beispiel #26
0
def G1DBinaryStringMutatorFlip(genome, **args):
   """ The classical flip mutator for binary strings """
   if args["pmut"] <= 0.0:
      return 0
   stringLength = len(genome)
   mutations = args["pmut"] * (stringLength)

   if mutations < 1.0:
      mutations = 0
      for it in xrange(stringLength):
         if Util.randomFlipCoin(args["pmut"]):
            if genome[it] == 0:
               genome[it] = 1
            else:
               genome[it] = 0
            mutations += 1

   else:
      for it in xrange(int(round(mutations))):
         which = rand_randint(0, stringLength - 1)
         if genome[which] == 0:
            genome[which] = 1
         else:
            genome[which] = 0

   return int(mutations)
Beispiel #27
0
def G1DListMutatorAllele(genome, **args):
   """ The mutator of G1DList, Allele Mutator

   To use this mutator, you must specify the *allele* genome parameter with the
   :class:`GAllele.GAlleles` instance.

   """
   if args["pmut"] <= 0.0:
      return 0
   listSize = len(genome) - 1
   mutations = args["pmut"] * (listSize + 1)

   allele = genome.getParam("allele", None)
   if allele is None:
      Util.raiseException("to use the G1DListMutatorAllele, you must specify the 'allele' parameter", TypeError)

   if mutations < 1.0:
      mutations = 0
      for it in xrange(listSize + 1):
         if Util.randomFlipCoin(args["pmut"]):
            new_val = allele[it].getRandomAllele()
            genome[it] = new_val
            mutations += 1
   else:
      for it in xrange(int(round(mutations))):
         which_gene = rand_randint(0, listSize)
         new_val = allele[which_gene].getRandomAllele()
         genome[which_gene] = new_val

   return int(mutations)
Beispiel #28
0
def G1DListMutatorIntegerBinary(genome, **args):
   """ The mutator of G1DList, the binary mutator

   This mutator will random change the 0 and 1 elements of the 1D List.

   """
   if args["pmut"] <= 0.0:
      return 0
   listSize = len(genome)
   mutations = args["pmut"] * (listSize)

   if mutations < 1.0:
      mutations = 0
      for it in xrange(listSize):
         if Util.randomFlipCoin(args["pmut"]):
            if genome[it] == 0:
               genome[it] = 1
            elif genome[it] == 1:
               genome[it] = 0

            mutations += 1
   else:
      for it in xrange(int(round(mutations))):
         which_gene = rand_randint(0, listSize - 1)
         if genome[which_gene] == 0:
            genome[which_gene] = 1
         elif genome[which_gene] == 1:
            genome[which_gene] = 0

   return int(mutations)
Beispiel #29
0
def G1DBinaryStringXSinglePoint(genome, **args):
    """ The crossover of 1D Binary String, Single Point

    .. warning:: You can't use this crossover method for binary strings with length of 1.

    """
    sister = None
    brother = None
    gMom = args["mom"]
    gDad = args["dad"]

    if len(gMom) == 1:
        Util.raiseException(
            "The Binary String have one element, can't use the Single Point Crossover method !",
            TypeError)

    cut = rand_randint(1, len(gMom) - 1)

    if args["count"] >= 1:
        sister = gMom.clone()
        sister.resetStats()
        sister[cut:] = gDad[cut:]

    if args["count"] == 2:
        brother = gDad.clone()
        brother.resetStats()
        brother[cut:] = gMom[cut:]

    return (sister, brother)
Beispiel #30
0
def G1DBinaryStringMutatorFlip_GABIL(genome, **args):
	if args["pmut"] <= 0.0:
		return 0
	stringLength = len(genome)
	
	mutations = args["pmut"] * (stringLength)
	
	if mutations < 1.0:
		mutations = 0
		for it in xrange(stringLength):
			if Util.randomFlipCoin(args["pmut"]):
				if genome.genomeString[it] == '0': 
					genome.genomeString[it] = '1'
				else: 
					genome.genomeString[it] = '0'
				mutations += 1.0
	else:
		for it in xrange(int(round(mutations))):
			which = rand_randint(0, stringLength - 1)
			if genome.genomeString[which] == '0':
				genome.genomeString[which] = '1'
			else:
				genome.genomeString[which] = '0'
	
	return int(mutations)
Beispiel #31
0
def G1DListMutatorRealRange(genome, **args):
   """ Simple real range mutator for G1DList

   Accepts the *rangemin* and *rangemax* genome parameters, both optional.

   """
   if args["pmut"] <= 0.0: return 0
   listSize = len(genome)
   mutations = args["pmut"] * (listSize)

   if mutations < 1.0:
      mutations = 0
      for it in xrange(listSize):
         if utils.random_flip_coin(args["pmut"]):
            genome[it] = rand_uniform(genome.get_param("rangemin", CDefRangeMin),
                         genome.get_param("rangemax", CDefRangeMax))
            mutations += 1
   
   else: 
      for it in xrange(int(round(mutations))):
         which_gene = rand_randint(0, listSize-1)
         genome[which_gene] = rand_uniform(genome.get_param("rangemin", CDefRangeMin),
                              genome.get_param("rangemax", CDefRangeMax))

   return int(mutations)
Beispiel #32
0
 def __init__(self, host, port, group_name):
    super(WANMigration, self).__init__()
    self.setMyself(host, port)
    self.setGroupName(group_name)
    self.topologyGraph = None
    self.serverThread = Network.UDPThreadServer(host, port)
    self.clientThread = Network.UDPThreadUnicastClient(self.myself[0], rand_randint(30000, 65534))
Beispiel #33
0
def G1DListCrossoverSinglePoint(genome, **args):
    """ The crossover of G1DList, Single Point

   .. warning:: You can't use this crossover method for lists with just one element.

   """
    sister = None
    brother = None
    gMom = args["mom"]
    gDad = args["dad"]

    if len(gMom) == 1:
        utils.raise_exception("The 1D List have one element, can't use the Single Point Crossover method !", TypeError)

    cut = rand_randint(1, len(gMom) - 1)

    if args["count"] >= 1:
        sister = gMom.clone()
        sister.reset_stats()
        sister[cut:] = gDad[cut:]

    if args["count"] == 2:
        brother = gDad.clone()
        brother.reset_stats()
        brother[cut:] = gMom[cut:]

    return (sister, brother)
Beispiel #34
0
def G2DBinaryStringXSingleHPoint(genome, **args):
   """ The crossover of G2DBinaryString, Single Horizontal Point
   
   .. versionadded:: 0.6
      The *G2DBinaryStringXSingleHPoint* function
  
   """
   sister = None
   brother = None
   gMom = args["mom"]
   gDad = args["dad"]

   cut = rand_randint(1, gMom.getHeight()-1)

   if args["count"] >= 1:
      sister = gMom.clone()
      sister.resetStats()
      for i in xrange(cut, sister.getHeight()):
         sister[i][:] = gDad[i][:]

   if args["count"] == 2:
      brother = gDad.clone()
      brother.resetStats()
      for i in xrange(brother.getHeight()):
         brother[i][:] = gMom[i][:]

   return (sister, brother)
Beispiel #35
0
def G2DBinaryStringXSingleHPoint(genome, **args):
    """ The crossover of G2DBinaryString, Single Horizontal Point

    .. versionadded:: 0.6
       The *G2DBinaryStringXSingleHPoint* function

    """
    sister = None
    brother = None
    gMom = args["mom"]
    gDad = args["dad"]

    cut = rand_randint(1, gMom.getHeight() - 1)

    if args["count"] >= 1:
        sister = gMom.clone()
        sister.resetStats()
        for i in range(cut, sister.getHeight()):
            sister[i][:] = gDad[i][:]

    if args["count"] == 2:
        brother = gDad.clone()
        brother.resetStats()
        for i in range(brother.getHeight()):
            brother[i][:] = gMom[i][:]

    return (sister, brother)
Beispiel #36
0
def G1DListMutatorAllele(genome, **args):
   """ The mutator of G1DList, Allele Mutator

   To use this mutator, you must specify the *allele* genome parameter with the
   :class:`GAllele.GAlleles` instance.

   """
   if args["pmut"] <= 0.0:
      return 0
   listSize = len(genome)
   mutations = args["pmut"] * listSize

   allele = genome.getParam("allele", None)
   if allele is None:
      Util.raiseException("to use the G1DListMutatorAllele, you must specify the 'allele' parameter", TypeError)

   if mutations < 1.0:
      mutations = 0
      for it in range(listSize):
         if Util.randomFlipCoin(args["pmut"]):
            new_val = allele[it].getRandomAllele()
            genome[it] = new_val
            mutations += 1
   else:
      for it in range(int(round(mutations))):
         which_gene = rand_randint(0, listSize - 1)
         new_val = allele[which_gene].getRandomAllele()
         genome[which_gene] = new_val

   return int(mutations)
Beispiel #37
0
 def __init__(self, host, port, group_name):
     super(WANMigration, self).__init__()
     self.setMyself(host, port)
     self.setGroupName(group_name)
     self.topologyGraph = None
     self.serverThread = Network.UDPThreadServer(host, port)
     self.clientThread = Network.UDPThreadUnicastClient(self.myself[0], rand_randint(30000, 65534))
Beispiel #38
0
def G1DBinaryStringMutatorFlip(genome, **args):
    """ The classical flip mutator for binary strings """
    if args["pmut"] <= 0.0:
        return 0
    stringLength = len(genome)
    mutations = args["pmut"] * (stringLength)

    if mutations < 1.0:
        mutations = 0
        for it in range(stringLength):
            if Util.randomFlipCoin(args["pmut"]):
                if genome[it] == 0:
                    genome[it] = 1
                else:
                    genome[it] = 0
                mutations += 1

    else:
        for it in range(int(round(mutations))):
            which = rand_randint(0, stringLength - 1)
            if genome[which] == 0:
                genome[which] = 1
            else:
                genome[which] = 0

    return int(mutations)
Beispiel #39
0
def G1DBinaryStringXSinglePoint(genome, **args):
   """ The crossover of 1D Binary String, Single Point

   .. warning:: You can't use this crossover method for binary strings with length of 1.

   """
   sister = None
   brother = None
   gMom = args["mom"]
   gDad = args["dad"]

   if len(gMom) == 1:
      Util.raiseException("The Binary String have one element, can't use the Single Point Crossover method !", TypeError)

   cut = rand_randint(1, len(gMom)-1)

   if args["count"] >= 1:
      sister = gMom.clone()
      sister.resetStats()
      sister[cut:] = gDad[cut:]

   if args["count"] == 2:
      brother = gDad.clone()
      brother.resetStats()
      brother[cut:] = gMom[cut:]

   return (sister, brother)
Beispiel #40
0
def G1DListMutatorIntegerBinary(genome, **args):
   """ The mutator of G1DList, the binary mutator

   This mutator will random change the 0 and 1 elements of the 1D List.

   """
   if args["pmut"] <= 0.0:
      return 0
   listSize = len(genome)
   mutations = args["pmut"] * (listSize)

   if mutations < 1.0:
      mutations = 0
      for it in range(listSize):
         if Util.randomFlipCoin(args["pmut"]):
            if genome[it] == 0:
               genome[it] = 1
            elif genome[it] == 1:
               genome[it] = 0

            mutations += 1
   else:
      for it in range(int(round(mutations))):
         which_gene = rand_randint(0, listSize - 1)
         if genome[which_gene] == 0:
            genome[which_gene] = 1
         elif genome[which_gene] == 1:
            genome[which_gene] = 0

   return int(mutations)
Beispiel #41
0
def G1DBinaryStringSetXTwoPoint(genome, **args):
    """The 1D Binary String Set crossover, Two Point"""

    sister = None
    brother = None

    gMom = args["mom"]
    gDad = args["dad"]

    # the mother will always have the smallest bitstring
    if len(args["mom"]) > len(args["dad"]):
        gMom = args["dad"]  #change roles
        gDad = args["mom"]

    if len(gMom) == 1:
        Util.raiseException(
            "The Binary String have one element, can't use the Two Point Crossover method !",
            TypeError)

    #Generating random crossover points over the mother parent
    cutsMom = [rand_randint(1, len(gMom) - 1), rand_randint(1, len(gMom) - 1)]
    if cutsMom[0] > cutsMom[1]:
        Util.listSwapElement(cutsMom, 0, 1)

    # Computing the distance from the cuts to the nearest rule to the left
    cutsMomDistance = [
        gMom.distanceFromCutToClosestRuleByLeft(cutsMom[0]),
        gMom.distanceFromCutToClosestRuleByLeft(cutsMom[1])
    ]
    # Computing factible crossover points for the dad parent
    factibleDadCuts = gDad.getCutPointsFromDistances(cutsMomDistance[0],
                                                     cutsMomDistance[1])
    #picking one random cut pair for the parent from the factible cuts
    cutsDad = factibleDadCuts[rand_randint(0, len(factibleDadCuts) - 1)]

    # genome crossover
    if args["count"] >= 1:
        sister = gMom.clone()
        sister.resetStats()
        sister.substitute(cutsMom[0], cutsMom[1], gDad[cutsDad[0]:cutsDad[1]])

    if args["count"] == 2:
        brother = gDad.clone()
        brother.resetStats()
        brother.substitute(cutsDad[0], cutsDad[1], gMom[cutsMom[0]:cutsMom[1]])

    return (sister, brother)
Beispiel #42
0
def G1DListMutatorSwap(genome, **args):
   """ The mutator of G1DList, Swap Mutator """
   if args["pmut"] <= 0.0: return 0
   listSize = len(genome) - 1
   mutations = args["pmut"] * (listSize+1)

   if mutations < 1.0:
      mutations = 0
      for it in xrange(listSize+1):
         if Util.randomFlipCoin(args["pmut"]):
            Util.listSwapElement(genome, it, rand_randint(0, listSize))
            mutations+=1
   else:
      for it in xrange(int(round(mutations))):
         Util.listSwapElement(genome, rand_randint(0, listSize), rand_randint(0, listSize))

   return mutations
Beispiel #43
0
def G1DListInitializatorInteger(genome, **args):
    
   """ Integer initialization function of G1DList

   This initializator accepts the *rangemin* and *rangemax* genome parameters.

   """
   r=genome.getParam("range_list", None)
   
   if r is None:
      
      range_min = genome.getParam("rangemin", 0)
      range_max = genome.getParam("rangemax", 100)

      genome.genomeList = [rand_randint(range_min, range_max) for i in xrange(genome.getListSize())]
   else:

      genome.genomeList = [rand_randint(0, r[i]) for i in xrange(genome.getListSize())]
Beispiel #44
0
def separate_dataset(examples):
    training_dataset = []
    test_dataset = []

    #filtering examples where the last bit - the classification bit - is 1
    positives = [example for example in examples if example[-1] == '1']

    #filtering examples where the last bit- the classification bit- is 0
    negatives = [example for example in examples if example[-1] == '0']

    training_dataset_ratio = 0.7
    test_dataset_ratio = 1 - training_dataset_ratio

    training_positives = int(
        math.floor(training_dataset_ratio * len(positives)))
    training_negatives = int(
        math.floor(training_dataset_ratio * len(negatives)))
    test_positives = len(positives) - training_positives
    test_negatives = len(negatives) - training_negatives

    for npositive in xrange(0, training_positives):
        training_positive = positives.pop(rand_randint(0, len(positives) - 1))
        training_dataset.append(training_positive)

    for nnegativee in xrange(0, training_negatives):
        training_negative = negatives.pop(rand_randint(0, len(negatives) - 1))
        training_dataset.append(training_negative)

    for npositive in xrange(0, test_positives):
        test_positive = positives.pop(rand_randint(0, len(positives) - 1))
        test_dataset.append(test_positive)

    for nnegativee in xrange(0, test_negatives):
        test_negative = negatives.pop(rand_randint(0, len(negatives) - 1))
        test_dataset.append(test_negative)

    #checks that all positives and negatives were distributed within the two datasets
    assert (
        (positives == []) and (negatives == [])
    ), 'Error while separating dataset: positives or negatives were not well distributed'

    shuffle(training_dataset)
    shuffle(test_dataset)
    return training_dataset, test_dataset
Beispiel #45
0
def G2DListMutatorAllele(genome, **args):
    """ The mutator of G2DList, Allele Mutator

    To use this mutator, you must specify the *allele* genome parameter with the
    :class:`GAllele.GAlleles` instance.

    .. warning:: the :class:`GAllele.GAlleles` instance must have the homogeneous flag enabled

    """
    if args["pmut"] <= 0.0:
        return 0
    listSize = genome.getHeight() * genome.getWidth() - 1
    mutations = args["pmut"] * (listSize + 1)

    allele = genome.getParam("allele", None)
    if allele is None:
        Util.raiseException(
            "to use the G2DListMutatorAllele, you must specify the 'allele' parameter",
            TypeError)

    if not allele.homogeneous:
        Util.raiseException(
            "to use the G2DListMutatorAllele, the 'allele' must be homogeneous"
        )

    if mutations < 1.0:
        mutations = 0

        for i in range(genome.getHeight()):
            for j in range(genome.getWidth()):
                if Util.randomFlipCoin(args["pmut"]):
                    new_val = allele[0].getRandomAllele()
                    genome.setItem(i, j, new_val)
                    mutations += 1
    else:
        for it in range(int(round(mutations))):
            which_x = rand_randint(0, genome.getHeight() - 1)
            which_y = rand_randint(0, genome.getWidth() - 1)

            new_val = allele[0].getRandomAllele()
            genome.setItem(which_x, which_y, new_val)

    return int(mutations)
Beispiel #46
0
def G1DListInitializatorInteger(genome, **args):
    """ Integer initialization function of G1DList

    This initializator accepts the *rangemin* and *rangemax* genome parameters.

    """
    range_min = genome.getParam("rangemin", 0)
    range_max = genome.getParam("rangemax", 100)

    genome.genomeList = [rand_randint(range_min, range_max) for i in xrange(genome.getListSize())]
Beispiel #47
0
def G1DListInitializatorInteger(genome, **args):
   """ Integer initialization function of G1DList

   This initializator accepts the *rangemin* and *rangemax* genome parameters.

   """
   range_min = genome.get_param("rangemin", 0)
   range_max = genome.get_param("rangemax", 100)

   genome.genomeList = [rand_randint(range_min, range_max) for i in xrange(genome.get_list_size())]
Beispiel #48
0
def G1DListMutatorRealGaussianGradient(genome, **args):
    """ The mutator of G1DList, Gaussian Gradient Mutator

    Accepts the *rangemin* and *rangemax* genome parameters, both optional. The
    random distribution is set with mu=1.0 and std=0.0333

    The difference between this routine and the normal Gaussian Real is that the
    other function generates a gaussian value and adds it to the value. If the
    mu is 0, and the std is 1, a typical value could be 1.8 or -0.5. These small
    values are fine if your range is 0-10, but if your range is much larger, like
    0-100,000, a relative gradient makes sense.

    This routine generates a gaussian value with mu=1.0 and std=0.0333 and then
    the gene is multiplied by this value. This will cause the gene to drift
    no matter how large it is.

    """
    from . import Consts

    if args["pmut"] <= 0.0:
        return 0
    listSize = len(genome)
    mutations = args["pmut"] * (listSize)

    mu = Consts.CDefGaussianGradientMU
    sigma = Consts.CDefGaussianGradientSIGMA

    if mutations < 1.0:
        mutations = 0
        for it in range(listSize):
            if Util.randomFlipCoin(args["pmut"]):
                final_value = genome[it] * abs(rand_gauss(mu, sigma))

                final_value = min(
                    final_value,
                    genome.getParam("rangemax", Consts.CDefRangeMax))
                final_value = max(
                    final_value,
                    genome.getParam("rangemin", Consts.CDefRangeMin))

                genome[it] = final_value
                mutations += 1
    else:
        for it in range(int(round(mutations))):
            which_gene = rand_randint(0, listSize - 1)
            final_value = genome[which_gene] * abs(rand_gauss(mu, sigma))

            final_value = min(final_value,
                              genome.getParam("rangemax", Consts.CDefRangeMax))
            final_value = max(final_value,
                              genome.getParam("rangemin", Consts.CDefRangeMin))

            genome[which_gene] = final_value

    return int(mutations)
Beispiel #49
0
def G1DBinaryStringSetXTwoPoint(genome, **args):
   """The 1D Binary String Set crossover, Two Point"""

   sister = None
   brother = None

   gMom = args["mom"]
   gDad = args["dad"]

   # the mother will always have the smallest bitstring
   if len(args["mom"]) > len(args["dad"]): 
   		gMom = args["dad"] #change roles
   		gDad = args["mom"] 
   
   if len(gMom) == 1:
      Util.raiseException("The Binary String have one element, can't use the Two Point Crossover method !", TypeError)

   #Generating random crossover points over the mother parent
   cutsMom = [rand_randint(1, len(gMom)-1), rand_randint(1, len(gMom)-1)]
   if cutsMom[0] > cutsMom[1]:
      Util.listSwapElement(cutsMom, 0, 1)

   # Computing the distance from the cuts to the nearest rule to the left
   cutsMomDistance = [gMom.distanceFromCutToClosestRuleByLeft(cutsMom[0]),
   						gMom.distanceFromCutToClosestRuleByLeft(cutsMom[1])]
   # Computing factible crossover points for the dad parent
   factibleDadCuts = gDad.getCutPointsFromDistances(cutsMomDistance[0],cutsMomDistance[1])
   #picking one random cut pair for the parent from the factible cuts
   cutsDad = factibleDadCuts[rand_randint(0,len(factibleDadCuts)-1)]

   # genome crossover
   if args["count"] >= 1:
      sister = gMom.clone()
      sister.resetStats()
      sister.substitute(cutsMom[0],cutsMom[1],gDad[cutsDad[0]:cutsDad[1]])

   if args["count"] == 2:
      brother = gDad.clone()
      brother.resetStats()
      brother.substitute(cutsDad[0],cutsDad[1], gMom[cutsMom[0]:cutsMom[1]])

   return (sister, brother)
Beispiel #50
0
def G1DBinaryStringMutatorSwap(genome, **args):
   """ The 1D Binary String Swap Mutator """

   if args["pmut"] <= 0.0: return 0
   stringLength = len(genome)
   #mutations = args["pmut"] * (stringLength)
   mutations = 0.5 * (stringLength)
   if mutations < 1.0:
      mutations = 0
      for it in xrange(stringLength):
         if Util.randomFlipCoin(args["pmut"]):
            Util.listSwapElement(genome, it, rand_randint(0, stringLength-1))
            mutations+=1

   else:
      for it in xrange(int(round(mutations))):
         Util.listSwapElement(genome, rand_randint(0, stringLength-1),
                                      rand_randint(0, stringLength-1))

   return int(mutations)
Beispiel #51
0
 def __init__(self, ruleLength=5, numRules=0):
     """ The initializator of G1DList representation """
     if numRules == 0:
         numRules = rand_randint(1, MAX_RULES)
     super(G1DVariableBinaryString, self).__init__(ruleLength * numRules)
     self.genomeList = []
     self.stringLength = ruleLength * numRules
     self.ruleLength = ruleLength
     self.initializator.set(Consts.CDefG1DVariableBinaryStringInit)
     self.mutator.set(Consts.CDefG1DVariableBinaryStringMutator)
     self.crossover.set(Consts.CDefG1DVariableBinaryStringCrossover)
 def __init__(self, ruleLength=5, numRules=0):
    """ The initializator of G1DList representation """
    if numRules == 0:
       numRules = rand_randint(1,MAX_RULES)
    super(G1DVariableBinaryString, self).__init__(ruleLength*numRules)
    self.genomeList = []
    self.stringLength = ruleLength*numRules
    self.ruleLength = ruleLength
    self.initializator.set(Consts.CDefG1DVariableBinaryStringInit)
    self.mutator.set(Consts.CDefG1DVariableBinaryStringMutator)
    self.crossover.set(Consts.CDefG1DVariableBinaryStringCrossover)
Beispiel #53
0
def G2DListMutatorAllele(genome, **args):
    """ The mutator of G2DList, Allele Mutator

    To use this mutator, you must specify the *allele* genome parameter with the
    :class:`GAllele.GAlleles` instance.

    .. warning:: the :class:`GAllele.GAlleles` instance must have the homogeneous flag enabled

    """
    if args["pmut"] <= 0.0:
        return 0
    listSize = genome.getHeight() * genome.getWidth() - 1
    mutations = args["pmut"] * (listSize + 1)

    allele = genome.getParam("allele", None)
    if allele is None:
        Util.raiseException(
            "to use the G2DListMutatorAllele, you must specify the 'allele' parameter", TypeError)

    if not allele.homogeneous:
        Util.raiseException(
            "to use the G2DListMutatorAllele, the 'allele' must be homogeneous")

    if mutations < 1.0:
        mutations = 0

        for i in xrange(genome.getHeight()):
            for j in xrange(genome.getWidth()):
                if Util.randomFlipCoin(args["pmut"]):
                    new_val = allele[0].getRandomAllele()
                    genome.setItem(i, j, new_val)
                    mutations += 1
    else:
        for it in xrange(int(round(mutations))):
            which_x = rand_randint(0, genome.getHeight() - 1)
            which_y = rand_randint(0, genome.getWidth() - 1)

            new_val = allele[0].getRandomAllele()
            genome.setItem(which_x, which_y, new_val)

    return int(mutations)
Beispiel #54
0
def G1DBinaryStringMutatorSwap(genome, **args):
    """ The 1D Binary String Swap Mutator """

    if args["pmut"] <= 0.0:
        return 0
    stringLength = len(genome)
    mutations = args["pmut"] * (stringLength)

    if mutations < 1.0:
        mutations = 0
        for it in range(stringLength):
            if Util.randomFlipCoin(args["pmut"]):
                Util.listSwapElement(genome, it, rand_randint(0, stringLength - 1))
                mutations += 1

    else:
        for it in range(int(round(mutations))):
            Util.listSwapElement(genome, rand_randint(0, stringLength - 1),
                                 rand_randint(0, stringLength - 1))

    return int(mutations)
Beispiel #55
0
def P1DListInitializatorInteger(vector, **args):
    """ Integer initialization function of Particle1D

   This initializator accepts the *rangemin* and *rangemax* particle parameters.

   """
    vector.clearList()

    for i in xrange(vector.listSize):
        randomInteger = rand_randint(vector.getParam("rangemin", 0),
                                     vector.getParam("rangemax", 100))
        vector.append(randomInteger)
Beispiel #56
0
def G1DListMutatorSwap(genome, **args):
   """ The mutator of G1DList, Swap Mutator
   
   .. note:: this mutator is :term:`Data Type Independent`

   """
   if args["pmut"] <= 0.0: return 0
   listSize = len(genome) - 1
   mutations = args["pmut"] * (listSize+1)

   if mutations < 1.0:
      mutations = 0
      for it in xrange(listSize+1):
         if utils.random_flip_coin(args["pmut"]):
            utils.list_swap_element(genome, it, rand_randint(0, listSize))
            mutations+=1
   else:
      for it in xrange(int(round(mutations))):
         utils.list_swap_element(genome, rand_randint(0, listSize), rand_randint(0, listSize))

   return int(mutations)
Beispiel #57
0
def G2DBinaryStringMutatorSwap(genome, **args):
    """ The mutator of G2DBinaryString, Swap Mutator

    .. versionadded:: 0.6
       The *G2DBinaryStringMutatorSwap* function
    """

    if args["pmut"] <= 0.0:
        return 0
    height, width = genome.getSize()
    elements = height * width

    mutations = args["pmut"] * elements

    if mutations < 1.0:
        mutations = 0
        for i in range(height):
            for j in range(width):
                if Util.randomFlipCoin(args["pmut"]):
                    index_b = (rand_randint(0, height - 1), rand_randint(0, width - 1))
                    Util.list2DSwapElement(genome.genomeString, (i, j), index_b)
                    mutations += 1
    else:
        for it in range(int(round(mutations))):
            index_a = (rand_randint(0, height - 1), rand_randint(0, width - 1))
            index_b = (rand_randint(0, height - 1), rand_randint(0, width - 1))
            Util.list2DSwapElement(genome.genomeString, index_a, index_b)

    return int(mutations)
Beispiel #58
0
def G2DListMutatorSwap(genome, **args):
   """ The mutator of G1DList, Swap Mutator

   .. note:: this mutator is :term:`Data Type Independent`

   """

   if args["pmut"] <= 0.0:
      return 0
   height, width = genome.getSize()
   elements = height * width

   mutations = args["pmut"] * elements

   if mutations < 1.0:
      mutations = 0
      for i in range(height):
         for j in range(width):
            if Util.randomFlipCoin(args["pmut"]):
               index_b = (rand_randint(0, height - 1), rand_randint(0, width - 1))
               Util.list2DSwapElement(genome.genomeList, (i, j), index_b)
               mutations += 1
   else:
      for it in range(int(round(mutations))):
         index_a = (rand_randint(0, height - 1), rand_randint(0, width - 1))
         index_b = (rand_randint(0, height - 1), rand_randint(0, width - 1))
         Util.list2DSwapElement(genome.genomeList, index_a, index_b)

   return int(mutations)
Beispiel #59
0
def G1DListMutatorRealGaussian(genome, **args):
    """ The mutator of G1DList, Gaussian Mutator

    Accepts the *rangemin* and *rangemax* genome parameters, both optional. Also
    accepts the parameter *gauss_mu* and the *gauss_sigma* which respectively
    represents the mean and the std. dev. of the random distribution.

    """
    from . import Consts

    if args["pmut"] <= 0.0:
        return 0
    listSize = len(genome)
    mutations = args["pmut"] * (listSize)

    mu = genome.getParam("gauss_mu")
    sigma = genome.getParam("gauss_sigma")

    if mu is None:
        mu = Consts.CDefG1DListMutRealMU

    if sigma is None:
        sigma = Consts.CDefG1DListMutRealSIGMA

    if mutations < 1.0:
        mutations = 0
        for it in range(listSize):
            if Util.randomFlipCoin(args["pmut"]):
                final_value = genome[it] + rand_gauss(mu, sigma)

                final_value = min(
                    final_value,
                    genome.getParam("rangemax", Consts.CDefRangeMax))
                final_value = max(
                    final_value,
                    genome.getParam("rangemin", Consts.CDefRangeMin))

                genome[it] = final_value
                mutations += 1
    else:
        for it in range(int(round(mutations))):
            which_gene = rand_randint(0, listSize - 1)
            final_value = genome[which_gene] + rand_gauss(mu, sigma)

            final_value = min(final_value,
                              genome.getParam("rangemax", Consts.CDefRangeMax))
            final_value = max(final_value,
                              genome.getParam("rangemin", Consts.CDefRangeMin))

            genome[which_gene] = final_value

    return int(mutations)
def G2DListInitializatorInteger(genome, **args):
    """ Integer initialization function of G2DList

    This initializator accepts the *rangemin* and *rangemax* genome parameters.

    """
    genome.clearList()

    for i in xrange(genome.getHeight()):
        for j in xrange(genome.getWidth()):
            randomInteger = rand_randint(genome.getParam("rangemin", 0),
                                         genome.getParam("rangemax", 100))
            genome.setItem(i, j, randomInteger)