Ejemplo n.º 1
0
    def __init__(self, data, pop_max=10, evolve_time=100):
        '''
        初始化DNA: 一层hidden(节点数不同); 都为linear
        接收传入的训练数据 data
        初始化 Mutation 类
        '''
        self.population = []
        self.model_stack = {}

        for i in range(self._population_size_setpoint):
            dna_iter = DNA()
            self.population.append(dna_iter)
            dna_iter.calculate_flow()
            self.model_stack[dna_iter.dna_cnt] = Model(dna_iter)

            global DNA_cnt
            DNA_cnt = self._population_size_setpoint

        self.data = data
        self.struct_mutation = StructMutation()

        self._population_size_setpoint = pop_max
        self._evolve_time = evolve_time

        self.fitness_dir = {}
Ejemplo n.º 2
0
    def crossover(self, parents):
        p_index = random.randint(0, 1)
        if p_index:
            a_i = 1
            b_i = 0
        else:
            a_i = 0
            b_i = 1

        parentA = parents[a_i]
        parentB = parents[b_i]

        #randomly select a midpoint
        midpoint = random.randint(0, math.floor(minimum(len(parentA.genome), len(parentB.genome)) * 2/3))

        #create the child
        child = DNA(chromosome_length=self.chromosome_length)
        # if parentA.genome[midpoint].command == Command.DY or parentB.genome[midpoint].command == Command.DY:
        #    midpoint -= 1

        #copy genome
        child.genome += parentA.genome[:midpoint]
        child.genome += parentB.genome[midpoint:]

        # randomly find an index to be replaced by the child
        index = random.randint(0, self.maxPop - 1)
        child.genome_to_gene()  # convert the genome to gene
        self.population[index] = child  # put the child in the population
Ejemplo n.º 3
0
 def crossOver(self, parent1, parent2, middle):
     child = DNA(len(self.target))
     for num in range(0, len(self.target)):
         if num < middle:
             child.genes[num] = parent1[num]
         else:
             child.genes[num] = parent2[num]
     return child
def test_next_letter_DNA():
    assert next(DNA('AGCT')) == 'A'
    assert next(DNA('AGCT')) == 'A'
    checker_DNA = DNA('AGCT')
    assert next(checker_DNA) == 'A'
    assert next(checker_DNA) == 'G'
    assert next(checker_DNA) == 'C'
    assert next(checker_DNA) == 'T'
Ejemplo n.º 5
0
    def __init__(self, target, genes=None, mutation_rate=10):

        self.target = target
        if genes is None:
            self.dna = DNA(size=len(target))
        else:
            self.dna = DNA(genes=genes)
        self.fitness = 0
        self.mutation_rate = mutation_rate
Ejemplo n.º 6
0
def GetPopulation(params):
    population = []
    if 'population' in params:
        count = params['population']
        total = 2*params['moves'] + params['blockedCells'] + 1
        arhitecture =  params['arhitecture']
        arhitecture = [total]  + arhitecture
        arhitecture.append(total + params['moves'])
        population = [DNA.Random(arhitecture) for i in range (count)]
    else:
        files = os.listdir(params['importFrom'])
        for file in files:
           if file.endswith(".json"):
               population.append(DNA.ReadFromJson(file))
    return population
Ejemplo n.º 7
0
    def __init__(self, xDim, yDim, n_rockets, lifespan):
        # init game
        self.gameSize = (xDim, yDim)
        self.lifespan = lifespan
        self.generation = 0

        pygame.init()
        self.font = pygame.font.Font(None, 30)
        self.screen = pygame.display.set_mode(self.gameSize, 0, 32)
        self.screen.fill((0, 0, 0))  # fill black

        # FPS = Frames Per Second
        self.FPSCLOCK = pygame.time.Clock()

        # init target
        self.targetPos = (500, 100)

        # init obstacle(s)
        self.obstacles = []
        self.obstacles.append(Rectangle(500, 700, 25, 300, 0))
        self.obstacles.append(Rectangle(200, 550, 25, 200, 0))
        self.obstacles.append(Rectangle(800, 550, 25, 200, 0))

        # init rockets
        self.n_rockets = n_rockets
        self.success = 0
        self.total_success = 0
        self.rockets = []
        for i in range(n_rockets):
            self.rockets.append(
                Rocket(self.screen, self.gameSize, DNA(lifespan), lifespan,
                       self.targetPos, self.obstacles))

        self.maxFit = 0
Ejemplo n.º 8
0
    def fitness_measure(self):
        dna_len = len(DNA(self.dna_n).cromosome)
        self.max_score = np.power(dna_len + dna_len * (dna_len - 1), 2)
        # print('maxxxxxx:', self.max_score)

        for c, cromosome in enumerate(self.pop):
            self.score[c] = self.fitness(cromosome)
Ejemplo n.º 9
0
    def __init__(self, cap, mutation_rate, target):
        """
        Initializes a new Samples object
        :param cap: The maximum number of elements in the sample population
        :param mutation_rate: A whole number that represents the probability that a member of the population is mutated
        :param target: The target phrase who's length will be the basis of the creation
        of the initial sample population (dna pool)
        """

        if not isinstance(target, str):
            target = str(
                target
            )  # Just convert it to a string. I don't think it's a big deal
        if not isinstance(cap, int):
            raise TypeError("Parameter \"cap\" should be an integer.")
        if not isinstance(mutation_rate, int):
            raise TypeError(
                "The parameter \"mutation_rate\" should be an integer")
        self.__dna_pool = []
        self.__mating_pool = []
        self.__mutation_rate = mutation_rate / 100
        self.__target = target
        self.__max_fitness = 0
        self.__cap = cap  # The maximum number of elements in the dna pool
        self.__generation = 0
        self.__fittest = ""
        self.__average_fitness = 0

        self.__dna_pool = [DNA(len(target)) for x in enumerate(range(cap))]
Ejemplo n.º 10
0
 def __init__(self, land, pos, dna=None):
     Life.__init__(self, land, pos)
     self.livingDays = 0
     self.remainingDays = random.randrange(40) #(10, 20)
     self.dna = dna
     if not self.dna:
         self.dna = DNA()
Ejemplo n.º 11
0
 def __init__(self, num, target, mr):
     self.population = [DNA(len(target), target) for i in range((num))]
     self.target = target
     self.matingPool = []
     self.generations = 0
     self.mutationRate = mr
     self.finished = False
     self.bphrase = ''
Ejemplo n.º 12
0
 def __init__(self, target, mutationRate, popMax):
     self.target = target
     self.mutationRate = mutationRate
     for i in range(popMax):
         self.population.append(DNA(len(target)))
     self.calcFitness()
     self.finished = False
     self.perfectScore = 1
Ejemplo n.º 13
0
    def mutate(self, child):
        string = ""
        for char in child:
            if random.randint(1, 100) <= self.mutation * 100:
                string += DNA.newChar()
            else:
                string += char

        return string
Ejemplo n.º 14
0
def index():
    """
    Handles requests to the home page (index page)

    :return: The rendered index page that will be displayed, with rele
    """
    global SESSION_INFO
    SESSION_INFO = LavaSession(username="******", name="John Doe")
    global dna
    dna = DNA()
    dna.interestedcolo = INITIALIZED
    dna.db = database()
    dna.qb = QuestionBaseInterface()
    dna.currentquestion = dna.qb.matchColo(INITIALIZED)
    SESSION_INFO.question = dna.currentquestion.toQestion()
    #session['sid'] = SESSION_INFO.sid
    print SESSION_INFO.toJson()
    return render_template('index.html', session_info=SESSION_INFO.toJson())
Ejemplo n.º 15
0
 def cross_over(self, p1, p2):
     dna = DNA(self.dna_n).cromosome
     random_point = np.random.randint(0, len(dna))
     c1 = np.concatenate(
         [np.array(p1[:random_point]),
          np.array(p2[random_point:])])
     c2 = np.concatenate(
         [np.array(p2[:random_point]),
          np.array(p1[random_point:])])
     return c1, c2
Ejemplo n.º 16
0
 def __init__(self, mutationRate, crossoverRate, qtd):
     self.mutationRate = mutationRate
     self.crossorverRate = crossoverRate
     self.generation = 0
     self.population = []
     self.qtd = qtd
     for i in range(qtd):
         self.population.append(DNA(4))
         self.population[i].calcFitness()
     self.populationCopy = deepcopy(self.population)
Ejemplo n.º 17
0
 def test(self):
     seq = [[[16, 94], [41, 75], [25, 116], [29, 91], [28, 78], [35, 75]],
            [[22, 53], [32, 116], [43, 106]],
            [[38, 105], [37, 43], [18, 109], [12, 82], [50, 75]],
            [[6, 120], [54, 70], [32, 98], [50, 97], [26, 80]],
            [[13, 105], [30, 112], [31, 100]],
            [[23, 71], [32, 89], [29, 91], [22, 59]],
            [[38, 91], [38, 98], [11, 203], [24, 105], [25, 111], [54, 78],
             [44, 85], [49, 82], [58, 72], [30, 86], [22, 112]]]
     f = Fitness(DNA(seq))
     print(f.fitness)
Ejemplo n.º 18
0
 def mutation(self, cromosome):
     for g, gen in enumerate(cromosome):
         r = np.random.rand()
         if r < self.mut_rate:
             dna = DNA(self.dna_n).cromosome
             random_g = np.random.choice(dna)
             while random_g == gen and list(cromosome).count(random_g) != 1:
                 random_g = np.random.choice(dna)
             else:
                 cromosome[g] = random_g
     return cromosome
    def __init__(self, target, mutationRate, popmax):
        self.target = target
        self.mutationRate = mutationRate
        self.popmax = popmax
        self.generation = 0
        self.matingPool = []
        self.population = []
        self.finished = False
        self.got = ""

        for i in range(popmax):
            self.population.append(DNA(len(target)))
Ejemplo n.º 20
0
    def __init__(self, crossover_rate, mut_rate, max_strategies):
        self.crossover_rate = crossover_rate
        self.mut_rate = mut_rate
        self.max_strategies = max_strategies
        self.population = []
        self.mating_pool = []
        self.generations = 0

        for i in range(0, max_strategies):
            self.population.append(DNA())

        self.calc_fitness()
Ejemplo n.º 21
0
 def __init__(self, target: str, mutationRate: float, populationSize: int):
     self.DNAList = []
     self.matingPool = []
     self.target = target
     self.generations = 0
     self.mutationRate = mutationRate
     self.isFinished = False
     self.perfectScore = 1
     for i in range(populationSize):
         newDNA = DNA(target)
         self.DNAList.append(newDNA)
     self.calcFitnessAllMembers()
Ejemplo n.º 22
0
 def __init__(self, x, y, lifespan, dna):
     self.position = Vector(x, y)
     self.velocity = Vector(0, 0)
     self.acceleration = Vector(0, 0)
     self.image = pygame.image.load('images/rocket.png')
     if dna is not None:
         self.dna = dna
     else:
         self.dna = DNA(lifespan, None)
     self.fitness = 0
     self.completed = False
     self.crashed = False
Ejemplo n.º 23
0
 def initialize(self):
     if not self.train_data:
         self.train_data = process(self.source)
         self.train_data.extract_info()
         self.maxstring = len(self.train_data.genotype[0]) - 1
         self.total = self.train_data.intrusion + self.train_data.normal
     print("---------------")
     print("Initializing Random Population")
     for i in range(0, self.popsize):
         self.population.append(DNA(self.maxstring))
     print("Operation Complete")
     print("---------------")
Ejemplo n.º 24
0
    def __init__(self, target, mut_rate, pop_max):
        self.target = target
        self.mut_rate = mut_rate
        self.pop_max = pop_max
        self.population = []
        self.pop_fitness = []
        self.mating_pool = []
        self.generations = 0

        for i in range(0, pop_max):
            self.population.append(DNA(target.shape))

        self.calc_fitness()
Ejemplo n.º 25
0
    def __init__(self, target, mutationRate, popMax):
        self.target = target
        self.mutationRate = mutationRate
        self.population = []
        #create population
        for i in range(popMax):
            self.population.append(DNA(len(target)))

        self.matingPool = []
        self.finished = False
        self.generations = 0

        self.perfectScore = 1
Ejemplo n.º 26
0
    def __init__(self, target, mut_rate, pop_max):
        self.target = target
        self.mut_rate = mut_rate
        self.pop_max = pop_max
        self.population = []
        self.mating_pool = []
        self.finished = False
        self.generations = 0
        self.perfect_score = 1

        for i in range(0, pop_max):
            self.population.append(DNA(len(target)))

        self.calc_fitness()
Ejemplo n.º 27
0
    def __init__(self, target, mutation_rate, popmax):
        self.target = target
        self.mutation_rate = mutation_rate
        self.popmax = popmax

        self.generations = 0
        self.finished = False
        self.perfect_score = 1

        self.best = ""

        self.population = []
        for i in range(self.popmax):
            self.population.append(DNA(len(self.target)))
Ejemplo n.º 28
0
    def __init__(self, p, m, num):
        self.maxFitness = 0.0
        self.population = []  #   Array to hold the current population
        self.matingPool = [
        ]  #   ArrayList which we will use for our "mating pool"
        self.generations = 0  #   Number of generations
        self.finished = False  #   Are we finished evolving?
        self.target = p  #   Target phrase
        self.mutationRate = m  #   Mutation rate
        self.perfectScore = 1.

        for i in range(num):
            x = DNA(len(self.target))
            self.population.append(x)
Ejemplo n.º 29
0
 def __init__(self, mutation_rate, target, coefs, num):
     self.mutation_rate = 0
     self.population = []
     self.mating_pool = []
     self.coefs = []
     self.target = 0
     self.generations = 0
     self.finished = False
     self.perfect_score = 0
     self.target = target
     self.mutation_rate = mutation_rate
     self.coefs = coefs
     for i in range(num):
         self.population.append(DNA(target))
     self.calc_fitness()
Ejemplo n.º 30
0
    def __init__(self, target, mRate, numPoblacion):
        self.muestreo = 30
        self.arrBest = []
        self.best_fitness = 0
        self.population = []
        self.matingPool = []
        self.finished = False
        self.generations = 0

        self.target = target
        self.mRate = mRate
        self.best = None

        for x in range (numPoblacion):
            self.population.append(DNA(len(self.target)))
Ejemplo n.º 31
0
    def populate(self):
        for i in range(self.maxPop):
            # pe -> DNA object
            pe = DNA(chromosome_length=self.chromosome_length)
            # generating genes and genomes
            pe.generate_genes()
            pe.generate_genome()

            # add pe to population
            self.population.append(pe)
    def __init__(self, dna=None, lifetime=200, position=None, velocity=None, color=None):
        self.dna = dna or DNA(genes_len=lifetime)
        self.lifetime = lifetime
        self.step = 0
        self.color = color

        self.position = position or Vector2()
        self.velocity = velocity or Vector2()
        self.acceleration = Vector2()
        self.reached = False
        self.stuck = False

        self.original_image = create_body(color)
        self.image = self.original_image
        self.body = self.original_image.get_rect(center=self.position)
        self.body.size = (10, 10)
Ejemplo n.º 33
0
from flask import Flask, render_template, request, json, session
from LavaSession import LavaSession
from DNA import DNA
from datamodel import database
from QuestionBaseInterface import QuestionBaseInterface
from Question import Question
app = Flask(__name__)
app.secret_key = '5656798291'


############################ Session Init Info ############################


SESSION_INFO = LavaSession(username="******", name="John Doe")
dna = DNA()
INITIALIZED = [
      "Agriculture",
      "Food and Beverage",
      "Services",
      "Products",
      "Healthcare",
      "Open Entry"
    ]
dna.interestedcolo = INITIALIZED
dna.db = database()
dna.qb = QuestionBaseInterface()
dna.currentquestion = dna.qb.matchColo(INITIALIZED)
SESSION_INFO.question = dna.currentquestion.toQestion()


Ejemplo n.º 34
0
class Animal(Life):
    """
    an animal is a life which has DNA to instruct it do things
    """
    ARBITARY_LONG_DIST = [-1000, 1000]
    
    def __init__(self, land, pos, dna=None):
        Life.__init__(self, land, pos)
        self.livingDays = 0
        self.remainingDays = random.randrange(40) #(10, 20)
        self.dna = dna
        if not self.dna:
            self.dna = DNA()
    
    def updateStatus(self):
        """
        update the animal's status

        shuffle positions with equal distance
        so that it won't favour paticular ones
        """
        status = self.status = [None] * STATUS_MAX_LEN
        for poses in REL_POSES:
            random.shuffle(poses) # shuffle
            for pos in poses:
                globalPos = self.land.transformPos((pos[X]+self.pos[X], pos[Y]+self.pos[Y]))
                if not self.land.pos.has_key(globalPos):
                    continue
                lives = self.land.pos[globalPos]
                if lives[self.__class__.FOOD_CLASS] and status[0] == None:
                    status[0:2] = pos
                if lives[self.__class__.OTHER_CLASS] and status[2] == None:
                    status[2:4] = pos
                if len(lives[self.__class__.SELF_CLASS]) > 1 and status[4] == None:
                    status[4:6] = pos
                if status[0] != None and status[2] != None and status[4] != None:
                    # hope will save a bit of checking when it's very crowded
                    return
    
    def proposeMove(self):
        """
        propose to move to a new location
        """
        for i in range(STATUS_MAX_LEN):
            if self.status[i] == None:
                self.status[i] = random.choice(self.__class__.ARBITARY_LONG_DIST)
        dX, dY = self.dna.eval(self.status)
        x, y = self.pos
        return (x+dX, y+dY)
        
            
    def eat(self):
        """
        try to eat if there's any food
        """
        foodDict = self.land.pos[self.pos][self.FOOD_CLASS]
        if not foodDict:
            return
        life = random.choice(foodDict.keys()) #random choice
        self.remainingDays += life.remainingDays
        self.land.kill(life)

    def mate(self):
        """
        try to mate with the same species
        """
        mates = self.land.pos[self.pos][self.__class__.SELF_CLASS].keys()
        mates.remove(self)
        if mates:
            self._crossover(random.choice(mates)) #random choice


    def _crossover(self, life):
        if not self.remainingDays and not life.remainingDays:
            return
        newDNA = self.dna.crossover(life.dna)
        if not newDNA:
            return
        if self.remainingDays:
            r1 = random.randrange(self.remainingDays)
            self.remainingDays -= r1
        else:
            r1 = 0
        if life.remainingDays:
            r2 = random.randrange(life.remainingDays)
            life.remainingDays -= r2
        else:
            r2 = 0
        newLife = self.__class__(self.land, self.pos[:], newDNA)
        newLife.remainingDays = r1 + r2
        self.land.register(newLife)