Ejemplo n.º 1
0
    def search():
        
        #start with N random genetic codes
        codes = [ GeneticCode() for _ in range( 0 , N ) ]
        
        for gen in range( 0 , T+1 ):
            
            sumFitness = sum( [ x.get_fitness() for x in codes ] )
            
            #pick K pairs of states and cross them.
            for childNum in range( 0 , K ):
                
                #select first parent proportional to fitness    
                key1 = uniform( 0 , sumFitness )
                currSum = 0
                for code in codes:
                    currSum += code.get_fitness()
                    if ( currSum > key1 ):
                        parent1 = code
                        break
                
                #select second parent proportional to fitness    
                key2 = uniform( 0 , sumFitness )
                currSum = 0
                for code in codes:
                    currSum += code.get_fitness()
                    if ( currSum > key2 ):
                        parent2 = code
                        break
                    
                child = GeneticCode.cross( parent1 , parent2 )
                child.mutate()
                codes.append( child )
                
                #save the image every 1000 children
                if ( (K * gen + childNum) % 1000 == 0 ):
                    bestCode = max( codes , key = lambda p : p.get_fitness() )
                    print "Processing generation " + str( gen ) + "; best fitness = " + str( bestCode.get_fitness() )
                    Search.save_code_as_image( bestCode , gen )
                    
            #keep N best states
            codes.sort( Search.fitness_comparator )
            codes = codes[ 0:N ]
            
            #repeat T times 

        #save the last image
        #print "Processing generation " + str( T-1 )
        #Search.save_code_as_image( codes[ 0 ] , T-1 )
        return codes