Source

privateer / privateer_pyevolve / PrivateerMutators.py

from __future__ import division
import random
import math
import sys
from bitwise_utils import MANTISSA_BITS, bitcross, clip
from pyevolve import Util
from pyevolve import Consts

def G1DListMutatorRealPseudoBitwiseAuto(genome, **args):
    """ The mutator of G1DList, pseudo-bitwise Mutator. only permute sign and mantissa. Careful about using this to converge to zero, since mutation size decreases as the mutation rate does
    """
    if args["pmut"] <= 0.0: return 0
    mutations = int(random.expovariate(1./args["pmut"])*53. + 0.5)

    for it in range(mutations):
        listSize = len(genome)
        target_i = random.randint(0, listSize-1)
        source = genome[target_i]
        
        if  Util.randomFlipCoin(1/53.):
            #sign flip
            genome[target_i] *= -1
            continue
        #else
        delta_exp_ceiling = math.frexp(source)[1]
        delta_exp = delta_exp_ceiling-random.randint(0,52)
        if delta_exp < sys.float_info.min_exp:
            continue
        delta = 2.**(delta_exp)
        delta *= (2.*random.randint(0, 1)-1)
        print "delta:", delta
        final_value = source + delta
        final_value = min(final_value, genome.getParam("rangemax", Consts.CDefRangeMax))
        final_value = max(final_value, genome.getParam("rangemin", Consts.CDefRangeMin))
        genome[target_i] = final_value
        
    return mutations
    
def G1DListMutatorRealPseudoBitwise(genome, **args):
    """ The mutator of G1DList, pseudo-bitwise Mutator. Gets range from genome
    properties
    """
    if args["pmut"] <= 0.0: return 0
    mutations = int(random.expovariate(1./args["pmut"])*53. + 0.5)

    delta_exp_ceiling = math.frexp(
      genome.getParam("rangemax", Consts.CDefRangeMax)-
      genome.getParam("rangemin", Consts.CDefRangeMax)
    )[1]

    for it in range(mutations):
        listSize = len(genome)
        target_i = random.randint(0, listSize-1)
        source = genome[target_i]
        
        if  Util.randomFlipCoin(1/53.):
            #sign flip
            genome[target_i] *= -1
            continue
        #else
        delta_exp = delta_exp_ceiling-random.randint(0,52)
        if delta_exp < sys.float_info.min_exp:
            continue
        delta = 2.**(delta_exp)
        delta *= (2.*random.randint(0, 1)-1)
        print "delta:", delta
        final_value = source + delta
        final_value = min(final_value, genome.getParam("rangemax", Consts.CDefRangeMax))
        final_value = max(final_value, genome.getParam("rangemin", Consts.CDefRangeMin))
        genome[target_i] = final_value
        
    return mutations