Ejemplo n.º 1
0
 def selectParents(self):
     parents = []
     contestants = []
     while len(parents) < self.population_size:
         r = range(self.population_size)
         contestants[:] = []
         for i in range(self.tournament_size):
             temp = r.pop(random.randint(0, len(r)-1))
             contestants.append(self.chromosomes[temp])
             
         temp = Chromosome(0)
         best_contestant = max(contestants,key=attrgetter('rate'))
         temp.moves = best_contestant.moves[:]
         temp.rate = best_contestant.rate
         parents.append(temp)
     
     return parents
def handle_elitism(population,user_elitism,next_generation,user_mutation_freq,baseline_rms,steg,audio,message_hex):
	ordered_list = sorted(population, key=lambda x: x.fitness, reverse=True)
	for x in range(0,len(population)):
		print(ordered_list[x].fitness)
	best = list()
	for x in range(0,user_elitism):
		best.append(ordered_list[x])
	N = len(best)	
	next_gen = list()
	for x in range(0,N):
			parent_one = random.randint(0,N-1)
			parent_two = -1
			while parent_two != parent_one:
				parent_two = random.randint(0,N-1)
				print "Parent 1 " + str(parent_one)
				print "Parent 2 " + str(parent_two)
			child_key = best[parent_one].crossover(best[parent_two])
			child = Chromosome(child_key,-2)
			child.mutate(user_mutation_freq)
			child.fitness = steg.measure_individual(audio,message_hex,child,baseline_rms,)
			print "Child " + str(child.fitness)
			next_gen.append(child)
	return next_gen
class Indivisual:
    def __init__(self, init_chrom=None):
        # この個体が持つ染色体
        #染色体の遺伝子数の初期値は個体ごとにランダムとする
        self.chrom = Chromosome()

        # 初期値がある場合は一旦ツリーを削除してコピーする
        if init_chrom is not None:
            self.chrom.delete_subtree(0)
            self.chrom.chrom_dict = init_chrom.chrom_dict
            self.chrom.reset_chrom_info()

        # GAと異なり、染色体側でlenを決める
        self.g_len = self.chrom.g_len
        # 遺伝子型(genotype) 遺伝子長は個体(解きたい問題)により異なる
        self.gtype = self.chrom.get_GType()
        # 表現型(phenotype)
        self.ptype = self.decoder()
        # 適応度
        self.fitness = self.calc_fitness()

    def show_indivisual_info(self):
        """ 個体情報を表示する """
        # 染色体情報
        print(f'{self.gtype} {self.ptype}')
        # 適応度
        print(f'fitness: {self.fitness:.3f}')

    def visualize_indivisual(self):
        """ グラフを描画する """
        g_tree = Digraph(format='png')
        for g_id, gene in self.chrom.chrom_dict.items():
            g_tree.node(f'({g_id}) {gene.g_code}')
            if gene.node_type == Gene.NODE_ARITHMETIC:
                # 演算子ノードの場合
                arg1_code = self.chrom.chrom_dict[gene.arg1_id].g_code
                arg2_code = self.chrom.chrom_dict[gene.arg2_id].g_code
                g_tree.edge(f'({g_id}) {gene.g_code}',
                            f'({gene.arg1_id}) {arg1_code}')
                g_tree.edge(f'({g_id}) {gene.g_code}',
                            f'({gene.arg2_id}) {arg2_code}')

        g_tree.view(tempfile.mktemp('.gv'))
        return

    def show_GType(self):
        """ G typeだけ表示する """
        print(f'{self.gtype}')

    def calc_fitness(self):
        """ 適応度計算 """
        # ツリーで各テストデータの計算を行い、結果の平均誤差を適応度とする
        # = 小さいほど優良個体
        mean_err = 0
        for tc_num, tc in GP.testcase.items():
            # ツリーによる計算結果
            calc_result = self.chrom.calc_gene_tree(g_id=0, **tc)
            # 絶対誤差の平均を加算
            abs_err = np.abs(GP.testcase_answer[tc_num] -
                             calc_result) / GP.testcase.__len__()
            mean_err += abs_err
            # 誤差が一定値超えたら頭打ち
            if mean_err > 1.0e7:
                break

        f_val = mean_err

        return f_val

#%%

    def decoder(self):
        """
        デコーダ Gtype -> Ptpye の変換
        木構造を式の形に変形する?
        """
        ptype_array = []
        """
        for locus in range(self.g_len):
            city = self.gtype[locus]
            ptype_array.append(GA.item[city])
        """

        return ptype_array

#%%

    def crossover(self, partner_chrom: Chromosome):
        """ 
         交叉 他の個体とランダムで遺伝子を交換する        
        """
        # ルートノード以外の任意のノード(遺伝子)を一つ選び、交換する
        # 遺伝子idのリスト(0以外. 0から入れ替えると遺伝子すべてを入れ替えてしまう)
        g_id_list1 = list(self.chrom.chrom_dict.keys())
        g_id_list1.remove(0)
        crosspoint_id1 = np.random.choice(g_id_list1)

        g_id_list2 = list(partner_chrom.chrom_dict.keys())
        g_id_list2.remove(0)
        crosspoint_id2 = np.random.choice(g_id_list2)

        # crosspointで幹(trunk)と部分木(subtree)に分割
        trunk1 = {}  # 幹
        self.chrom.get_gene_subtree(g_id=0, subtree=trunk1)
        subtree1 = {}  # 部分木
        self.chrom.get_gene_subtree(g_id=crosspoint_id1, subtree=subtree1)

        trunk2 = {}
        partner_chrom.get_gene_subtree(g_id=0, subtree=trunk2)
        subtree2 = {}
        partner_chrom.get_gene_subtree(g_id=crosspoint_id2, subtree=subtree2)

        # サブツリーの入れ替え
        self.chrom.graft_gene_tree(x_id=crosspoint_id1,
                                   trunk=trunk1,
                                   subtree=subtree2)
        child1 = Indivisual(self.chrom)

        partner_chrom.graft_gene_tree(x_id=crosspoint_id2,
                                      trunk=trunk2,
                                      subtree=subtree1)
        child2 = Indivisual(partner_chrom)
        """
        print("-----------------")
        self.chrom.show_chrom_g_code(self.chrom.chrom_dict[0], self.chrom.chrom_dict)
        partner_chrom.show_chrom_g_code(partner_chrom.chrom_dict[0], partner_chrom.chrom_dict)
        print("-----------------")
        """

        return child1, child2

#%%

    def mutation(self):
        """ 突然変異体 ツリーの一部を別のツリーに置き換える """
        mutant_chrom = Chromosome(is_mutant=True)

        mutation_point = np.random.randint(1, self.g_len)
        #mutation_point = 1

        # 突然変異の染色体と交叉する
        trunk = {}  # 幹
        self.chrom.get_gene_subtree(g_id=0, subtree=trunk)
        self.chrom.graft_gene_tree(x_id=mutation_point,
                                   trunk=trunk,
                                   subtree=mutant_chrom.chrom_dict)
        mutant = Indivisual(self.chrom)

        return mutant
Ejemplo n.º 4
0
 def initialization(self, chromosomeParameters):
     for _ in range(0, self.__algorithmParameters["populationSize"]):
         chromosome = Chromosome(chromosomeParameters)
         self.__population.append(chromosome)
Ejemplo n.º 5
0
def crossover(parent1, parent2, pc, crossoverName):
    size_gene = len(parent1.gene)

    boundary = parent1.gene_boundary
    child1 = Chromosome(size_gene, boundary)
    child2 = Chromosome(size_gene, boundary)

    gene_len = len(parent1.gene)
    ub = gene_len - 1
    lb = 0

    if crossoverName == "single":
        cross_indx = random.randint(lb + 1, ub)

        part1 = parent1.gene[0:cross_indx]
        part2 = parent2.gene[cross_indx:gene_len]
        child1.gene = part1 + part2

        part1 = parent1.gene[0:cross_indx]
        part2 = parent2.gene[cross_indx:gene_len]
        child2.gene = part1 + part2

    if crossoverName == "double":
        cross_indx_1 = random.randint(lb + 1, ub)
        cross_indx_2 = random.randint(lb + 1, ub)

        while cross_indx_1 == cross_indx_2:
            cross_indx_2 = random.randint(lb + 1, ub)

        if cross_indx_1 > cross_indx_2:
            temp = cross_indx_1
            cross_indx_1 = cross_indx_2
            cross_indx_2 = temp

        part1 = parent1.gene[0:cross_indx_1]
        part2 = parent2.gene[cross_indx_1:cross_indx_2]
        part3 = parent1.gene[cross_indx_2:gene_len]
        child1.gene = part1 + part2 + part3

        part1 = parent2.gene[0:cross_indx_1]
        part2 = parent1.gene[cross_indx_1:cross_indx_2]
        part3 = parent2.gene[cross_indx_2:gene_len]
        child2.gene = part1 + part2 + part3

    if crossoverName == "continuous":
        for i in range(gene_len):
            beta = random.uniform(0, 1)
            child1.gene[i] = beta * parent1.gene[i] + (1 -
                                                       beta) * parent2.gene[i]
            child2.gene[i] = (1 -
                              beta) * parent1.gene[i] + beta * parent2.gene[i]

    if random.uniform(0, 1) <= pc:
        child1 = child1
    else:
        child1 = parent1

    if random.uniform(0, 1) <= pc:
        child2 = child2
    else:
        child2 = parent2

    return child1, child2
Ejemplo n.º 6
0
import random
from Chromosome import Chromosome

totalPopulation = 30
maxRank = 40
userString = [1,2,3,4,5]
userChromosome = Chromosome(userString)
print len(userChromosome.rankString)
initialPopulation = [];
print "Initializing Population"
for i in range(totalPopulation):
    initialPopulation.append(Chromosome(Chromosome.randomChromosomeString(maxRank,len(userChromosome.rankString))))

print "Initial Population"
Chromosome.printPopulation(initialPopulation)
for i in range(50):

    print "ITERATION ",i
    nextPopulation = []
    initialPopulation = Chromosome.rouletteSelection(initialPopulation,userChromosome)
    print "Undergoing Elitism"

    print "Best Four Chromosomes in Gen",i+1
    for i in range(4):
        index = Chromosome.getFittestChromosome(initialPopulation)
        nextPopulation.append(initialPopulation[index])
        print initialPopulation[index].rankString
        initialPopulation.pop(index)

    print "Undergoing Crossover and Mutation"
Ejemplo n.º 7
0
import unittest
import utils
import math

from Chromosome import Chromosome
from algorithm_implementation.StopConditions import MaxGenerationStopCondition
from algorithm_implementation.StopConditions import StructureStopCondition
from algorithm_implementation.StopConditions import ContentStopCondition
from algorithm_implementation.StopConditions import OptimalStopCondition

chromosome1 = Chromosome(genes=[1, 1, 1])
chromosome2 = Chromosome(genes=[2, 2, 2])
chromosome3 = Chromosome(genes=[3, 3, 3])
chromosome4 = Chromosome(genes=[4, 4, 4])
chromosome5 = Chromosome(genes=[5, 5, 5])
chromosome6 = Chromosome(genes=[6, 6, 6])

fits_population = [(1, chromosome1), (2, chromosome2), (3, chromosome3),
                   (4, chromosome4), (5, chromosome5), (5, chromosome5),
                   (1, chromosome1), (3, chromosome3), (4, chromosome4),
                   (2, chromosome2)]


class StopConditionsTest(unittest.TestCase):
    def test_max_generation(self):
        stop_condition = MaxGenerationStopCondition()
        self.assertFalse(stop_condition.check_stop(10, 11))
        self.assertTrue(stop_condition.check_stop(11, 10))

    def test_structure(self):
        stop_condition = StructureStopCondition()
 def initializePopulation(self):
     for i in range(self.__populationSize):
         c = Chromosome(self.__nrCities)
         c.__setattr__("fitness", self.evaluate(c))
         self.__population.append(c)
Ejemplo n.º 9
0
 def initialisation(self):
     for _ in range(0, self.__popSize):
         c = Chromosome(self.__n)
         self.__population.append(c)
Ejemplo n.º 10
0
 def initPop(self):
     for i in range(0, self.__dimension):
         self.__population.append(Chromosome())
Ejemplo n.º 11
0
 def initialization(self):
     for _ in range(0, self.__populationSize):
         c = Chromosome(self.__params)
         self.__population.append(c)
     self.evaluation(self.__population)
Ejemplo n.º 12
0
	def __init__(self,popSize):
		self.chromosomes=[None]*popSize
		for i in range(popSize):
			self.chromosomes[i]=Chromosome()
def main():	
	selection = "rank"
	fname = "ocarina.wav"
	print "The file to encode is : \t" + fname 
	#get_from_user("enter a filename: ")
	steg = stegolib()
	config = steg.load_key("setup.conf")
	user_config =read_config(config)
	user_selection = user_config[0]
	user_pressure = user_config[1]
	user_mutation_freq = user_config[2]
	user_elitism = user_config[3]



	get_from_user("\nPress enter to continue.")
	

	
	af = steg.open_audio_file(fname)
	parameters = steg.get_audio_information(af)
	#message = "abc"
	#message = "It was the best of times, it was the worst of times, it was the age of wisdom, it was the age of foolishness, it was the epoch of belief, it was the epoch of incredulity, it was the season of Light, it was the season of Darkness, it was the spring of hope, it was the winter of despair, we had everything before us, we had nothing before us, we were all going direct to Heaven, we were all going direct the other way – in short, the period was so far like the present period, that some of its noisiest authorities insisted on its being received, for good or for evil, in the superlative degree of comparison only. "
	message = "It was the best of times, it was the worst of times, it was the age of wisdom, it was the age of foolishness, it was the epoch of belief, it was the epoch of incredulity, it was the season of Light, it was the season of Darkness, it was the spring of hope, it was the winter of despair, we had everything before us, we had nothing before us, we were all going direct to Heaven, we were all going direct the other way – in short, the period was so far like the present period, that some of its noisiest authorities insisted on its being received, for good or for evil, in the superlative degree of comparison only."
	print "Encoding message :\n" + message
	print "\n"
	message = message + message + message + message + message
	message_hex = binascii.hexlify(message)
	#The GA maintains a population of n chromosomes (solutions) with associated fitness values. Parents are selected to mate, on the basis of their fitness, producing offspring via a reproductive plan. Consequently highly fit solutions are given more opportunities to 
	audio = steg.as_hex(af)
	baseline_rms = steg.compute_rms_power(audio,"RMS power before added noise : ")
	num_individuals = 20
	print "Step 1) The first step of a genetic algorithm is to initialize a random population. The initial randomness creates genetic variation which is the basis for our search heuristic. \nWe measure the fitness function of each member of our population and use that as a metric for selecting the best individuals whose genes move to the next generation "
	
	get_from_user("Press enter to initialize a population")
	print "Initializing random population of " + str(num_individuals) + " individuals... \n"
	population = steg.init_population(audio,20,message_hex)
	population_fitness = steg.measure_population(audio,message_hex,population,baseline_rms)
	best_values = list()
	best_genes = list()
	strongest_chromosomes = list()
	print_pop_fitness(population,best_values,best_genes,"individual")
	#ScatterPlot.plot(best_values)
	get_from_user("\nPress enter to continue")
	#best = handle_elitism(population,user_elitism)

	#print "\n BEST"
	#for x in range (0,len(best)):
	#	print str(best[x].fitness)
	

	###################################
	
	#get_parents()
	#survive = parents[0]
	#survive2 = parents[1]
	#print "parent one fitness: " + str(survive.fitness)
	#print "parent two fitness: " + str(survive2.fitness)	
	#exit()
	###################################
	
	##################################

	next_generation = list()
	print "Step 2 : Initialize new generation"
	print "The most fit individuals are selected using the RouletteWheel model to produce children. The fittest individuals cross genes in hopes that after multiple iterations future generations will \nbegin to converge towards an optimal or near optimal value."
	get_from_user("\nPress enter to continue")
	
	num_generations = 20
	for y in range(0,num_generations):
		print "ENTERING GENERATION : " + str(y)
		next_generation = handle_elitism(population,user_elitism,next_generation,user_mutation_freq,baseline_rms,steg,audio,message_hex)
		print "len " + str(len(next_generation))
		for x in range(0,len(next_generation)):
			print(next_generation[x].fitness)
		
		for x in range(0,len(population) - user_elitism):
			if x is 0 and y is 0:
				print "Spinning RouletteWheel..."
			parents = get_parents(population,user_selection,user_pressure)
			survive = parents[0]
			survive2 = parents[1]
			if x is 0 and y is 0:
				print "\nParents selected:"
				print "Parent one fitness: " + str(survive.fitness)
				print "Parent two fitness: " + str(survive2.fitness)	
				print "\nThe selected individuals are going to crossover genes to create a child chromosome that will hopefully adopt the best of both parents and move on to the next generation. The selection algorithm is called single split point selection "
			child_key = survive.crossover(survive2)
			child = Chromosome(child_key,-2)
			child.mutate(user_mutation_freq)

			#exit()
			child.fitness = steg.measure_individual(audio,message_hex,child,baseline_rms,)	
			if x is 0 and y is 0:
				print "the child fitness is : " + str(child.fitness) + ", and it is moving on to the next generation. \n" 
				get_from_user("Press enter to run this for all members of the population.")
			next_generation.append(child)
		print_pop_fitness(next_generation,best_values,best_genes,"child")
		if y is 0:
			#print "X is:  " + str(x)
			print "\n\nWe just finished one generation. We kept the best value from our initial population and the best value from our first\n round of genetic combination."
			print ("Best values so far: " + str(best_values))
			get_from_user("Press Enter to repeat for " + str(num_generations) + " generations")
		population = list(next_generation)
		del next_generation[:]
		#if y is 4 or y is 9 or y is 14:
		#	ScatterPlot.plot(best_values)

	
	print"\n\nFinished " + str(num_generations) +  "." + "Here is a list of the highest fitness values from each generation:"
	print "BEST VALUES " + str(best_values)

	ordered = result_tuples(best_values)
	print_analysis(ordered)
	ScatterPlot.plot(best_values)

	#exit()
	#print population_fitness
	
	

	sorted_genes = sorted(best_genes, key=lambda x: x.fitness, reverse=True)
	edited_info = steg.encode(audio,message_hex,sorted_genes[0].key)							
	edited_audio = edited_info[0]
	key = edited_info[1]
	edited_rms = steg.compute_rms_power(edited_audio,"rms power after adding noise")		# computes the rms power of the edited file
	noise_fname = steg.get_noise_fname(fname)											
	steg.write_wave_file(noise_fname,edited_audio,parameters)	# writes a copy of the edited file to disk
	snr = steg.compute_fitness_function(baseline_rms,edited_rms)


	print ("The signal to noise ratio is: " , snr)
	print "The noise file has been saved as " + noise_fname 
	saved_keyname = get_from_user("Audio hidden in " + fname  + "\nEnter name for your stego key:")
	steg.save_key(key,saved_keyname)
	keyname = get_from_user("Enter a .key to decode the text from the audio file: ")
	key = steg.load_key(keyname)
	steg.decode_message(edited_audio,key)
Ejemplo n.º 14
0
import random
from Chromosome import Chromosome

totalPopulation = 30
maxRank = 40
userString = [1,2,3,4,5]
userChromosome = Chromosome(userString)
print len(userChromosome.rankString)
initialPopulation = [];
print "Initializing Population"
for i in range(totalPopulation):
    initialPopulation.append(Chromosome(Chromosome.randomChromosomeString(maxRank,len(userChromosome.rankString))))

print "Initial Population"
Chromosome.printPopulation(initialPopulation)
for i in range(50):

    print "ITERATION ",i
    nextPopulation = []
    initialPopulation = Chromosome.rouletteSelection(initialPopulation,userChromosome)
    print "Undergoing Elitism"

    print "Best Four Chromosomes in Gen",i+1
    for i in range(4):
        index = Chromosome.getFittestChromosome(initialPopulation)
        nextPopulation.append(initialPopulation[index])
        print initialPopulation[index].rankString
        initialPopulation.pop(index)

    print "Undergoing Crossover and Mutation"
            for locus in range(self.chrom.n_codon):
                orig_g = self.chrom.get_gene(locus)
            
                is_mutation = np.random.randint(self.ge.MUTATION_RATE)                
                if is_mutation == 0:
                    mutant_flg = True
                else:
                    mutant_chrom.set_gene(locus, orig_g)

        mutant = Indivisual(mutant_chrom)        
        return mutant
        
        
#%%
if __name__ == '__main__':
    ch = Chromosome(n_codon=4)
    idv = Indivisual(ch)
    idv.show_chrom_info()

    """
    ch2 = Chromosome(n_codon=8)
    idv2 = Indivisual(ch2)
    idv2.show_chrom_info()
    """
    
    print('-----')
    
    """
    print(idv.ptype)
    print(idv.fitness)
    #a = idv.calc_grammatical_formula(x=1)
class Indivisual:
    
    def __init__(self, init_chrom=None):
        self.ge = GESetting()
        
        if init_chrom is None:
            self.chrom = Chromosome(n_codon=np.random.randint(self.ge.MIN_CODON_LEN, self.ge.MAX_CODON_LEN))
        else:
            self.chrom = copy.deepcopy(init_chrom)
            
        self.gtype = self.Gtype_array()
        self.ptype = self.Ptype_mapping()
        self.isvalid = True
        self.fitness = self.calc_fitness()
        self.formula = ''.join(self.ptype)

#%%
    def Gtype_array(self):
        """ 8ビットコドン(バイナリコード)をひとつの配列に展開 """
        gtype_arr = []
        for codon in self.chrom.g_array:
            gtype_arr.extend(codon.g_code)

        return gtype_arr
   
    
    def Ptype_mapping(self):
        """ プロダクションルールに則り表現型を得る """
        ptype_arr = [] # 終端記号を格納していく
        
        gramm_list = copy.deepcopy(self.ge.start_grammer)
        wrapping_num = 0       
        locus = 0
        while len(gramm_list) > 0:
            if wrapping_num > self.ge.max_wrapping: # ラッピングが一定数超えたら終了
                self.isvalid = False # 無効個体
                break 
            
            # 現在のgrammリストの先頭からgrammをポップ
            gramm = gramm_list.pop(0)
            if gramm in self.ge.terminal: 
                # 終端記号なら
                ptype_arr.append(gramm)
                
            else:
                codon = self.chrom.d_array[locus]                        
                prod = self.ge.prod_rule[gramm]
                rule = codon % len(prod)
                new_gramm = copy.deepcopy(prod[rule])
                if isinstance(new_gramm, str):
                    gramm_list.insert(0, new_gramm)
                    
                else:
                    new_gramm.extend(gramm_list)
                    gramm_list = new_gramm
            
                # コドンの遺伝子座更新
                locus += 1
                if locus > self.chrom.n_codon-1:
                    locus = 0
                    wrapping_num += 1
                    
                    # ラッピング発生時はルールを変更して収束させる
                    if wrapping_num == self.ge.rule_change_wrapping:
                        prod = self.ge.prod_rule['<expr>']
                        self.ge.prod_rule['<expr>'] = prod[2]

        return ptype_arr
    
    
    def calc_fitness(self):
        """ 適応度計算 """
        if self.isvalid == False:
            # 無効個体は負数
            return -1

        else:        
            total_err = 0
            for tc_idx, tc in self.ge.testcase.items():
                # 個体のBNFによる計算結果
                idv_ans = self.calc_grammatical_formula(x=tc['x'])  
                # 正解データ
                train_ans = self.ge.testcase_answer[tc_idx]
                
                # 絶対誤差の平均を加算
                mean_err = np.abs(train_ans - idv_ans) / self.ge.testcase.__len__()
                total_err += mean_err
                # 誤差が一定値超えたら頭打ち
                if total_err > 1.0e7:
                    break
            
            # 誤差平均の逆数 誤差10000分の1以下は正解として打ち切り
            eps = 0.0001 # 1.0e-7
            f_val = 1 / total_err if total_err > eps else 10000

            return f_val

        
    def calc_grammatical_formula(self, x):
        """ この個体の式を計算する """
        ptype_str = ''.join(self.ptype)
        ans = eval(ptype_str)
        return ans
        
                        
    def show_chrom_info(self):
        """ 個体の染色体情報 """
        self.chrom.show_chrom_code()
        
        
#%%
    def crossover(self, partner_chrom: Chromosome):
        """ 
         交叉 他の個体のG-typeとランダムで遺伝子を交換する        
        """        
        child1_chrom = copy.deepcopy(self.chrom)        
        child2_chrom = copy.deepcopy(partner_chrom)

        # 一様交叉
        """
        イメージ (a~hはコドン)        
        ch1 = [a, b, c,  ,  ]
        ch2 = [d, e, f, g, h]
        ↓
        ch1 = [a, e, c, g,  ]
        ch2 = [d, b, f,  , h]       
        """        
        if child1_chrom.n_codon > child2_chrom.n_codon:
            for i in range(child1_chrom.n_codon - child2_chrom.n_codon):
                child2_chrom.append_gene(None)
        elif child2_chrom.n_codon > child1_chrom.n_codon:
            for i in range(child2_chrom.n_codon - child1_chrom.n_codon):
                child1_chrom.append_gene(None)
        
        # コドンを交叉で入れ替える 長さが違う場合はNoneと入れ替える(無を取得)
        for locus in range(child1_chrom.n_codon):
            p1_g = child1_chrom.get_gene(locus)
            p2_g = child2_chrom.get_gene(locus)             
            is_cross = np.random.randint(2)
            if is_cross == 1:
                child1_chrom.set_gene(locus, p2_g)
                child2_chrom.set_gene(locus, p1_g)
            else:
                child1_chrom.set_gene(locus, p1_g)
                child2_chrom.set_gene(locus, p2_g)
 
        child1_chrom.compress_none()
        child2_chrom.compress_none()
        
        child1 = Indivisual(child1_chrom)
        child2 = Indivisual(child2_chrom)        
        
        return child1, child2
    

#%%
    def mutation(self):
        """ 突然変異体を生成する """
        
        # 少なくともひとつの遺伝子座の遺伝子を一定確率でランダムに置き換える
        mutant_flg = False
        while mutant_flg is False:            
            mutant_chrom = Chromosome(self.chrom.n_codon)            
            for locus in range(self.chrom.n_codon):
                orig_g = self.chrom.get_gene(locus)
            
                is_mutation = np.random.randint(self.ge.MUTATION_RATE)                
                if is_mutation == 0:
                    mutant_flg = True
                else:
                    mutant_chrom.set_gene(locus, orig_g)

        mutant = Indivisual(mutant_chrom)        
        return mutant
Ejemplo n.º 17
0
    def __init__(self):
        #Encryption of plain text
        message=input("Enter the message to be hidden within the given image: ");
        messageUtf=message.encode('utf-8')
        key = Fernet.generate_key()
        print("The key generated for this encryption is: ",key)
        print()
        time.sleep(1)
        cipher_suite = Fernet(key)
        cipher_text = cipher_suite.encrypt(messageUtf)
        plain_text = cipher_suite.decrypt(cipher_text)
        data=cipher_text.decode('utf-8')
        data=data+'~'
        cipher=[]
        for i in data:
            cipher.append(ord(i))
        qwerty=cipher[:]

        #Extract pixel
        img=Image.open('rsz_abc.png')
        arr=array(img)
        row=len(arr)
        column=len(arr[0])
        testing=row
        testing1=column

        print('Initializing the initial population ')
        time.sleep(1)
        chromosomes= [None]*(row*column)
        index=0

        #Initialise chromosomes with pixel values
        for x in range(column):
            for y in range(row): 
                chromosomes[index]=Chromosome(index,arr[x][y][0],arr[x][y][1],arr[x][y][2],-1,x,y,-1)
                index+=1

        print("Starting the genetic algorithm...")
        time.sleep(1)
        geneticAlgoritm = GA(cipher,len(chromosomes))
        for i in range(len(cipher)):
            geneticAlgoritm.initializePopulation(chromosomes)
            pop = geneticAlgoritm.evolvePopulation()
            chroms = pop.getAllChromosome()
            for j in range(len(chroms)):
                chromosomes[j]=chroms[j]
        print("Genetic algorithm has completed execution..")
        time.sleep(1)


        print("Started building the new image")
        time.sleep(1.5)
        if len(cipher)>(row*column):    
            print('The image will not be able to accomodate the data')
            print("Try with some other image")
        else:
            print('The image will be able to accomodate the data')
            time.sleep(1.5)
            i=0
            j=0
            k=0
            a=arr[:]
            count=0
            for i in range(row):
                for j in range(column):
                    for k in range(len(chromosomes)):
                        if chromosomes[k].getX()==i and chromosomes[k].getY()==j:
                            a[i][j][0]=chromosomes[k].getGene(0)
                            a[i][j][1]=chromosomes[k].getGene(1)
                            a[i][j][2]=chromosomes[k].getGene(2)
            print('We have now completed building the new image...')
            time.sleep(1)
            final_img=Image.fromarray(a)
            final_img.save('final.png')
            print('The image has been saved as final.png in the same folder as this program.')
            print()
            print()
            time.sleep(1.5)

            # This is the is visual cryptography part of the algorithm
            print('Visual cryptography algorithm has started to run')
            time.sleep(1.5)
            objVisual=visual_cryptography("final.png")
            keyVisual=objVisual.encrypt()
            print()
            
            # Now we are generating the pixel index table
            print("Generating the pixel index table....")
            time.sleep(1.5)
            pitTable=[]
            for i in range(len(cipher)):
                pitTable.append(Pit())
            pitTableIndex = 0

            for i in range(len(cipher)):
                for j in range(len(chromosomes)):
                    if chromosomes[j].getSolutionId()==i:
                        test=chromosomes[j].getAllGenes()                
                        minDxs = getMinDx(chromosomes[j].getAllGenes(),cipher[i])
                        pitTable[pitTableIndex] = Pit(chromosomes[j].getX(),chromosomes[j].getY(),minDxs)
                        pitTableIndex+=1 
            for i in range(len(pitTable)):
                f = open("pit1.csv",'a')
                f.write(pitTable[i].toString()+"\n")
            f.close()
            print('The Pixel Index Table file has been generated.') 
        print('The key for decryption of the visual cryptography is: ',keyVisual)
        time.sleep(1.5)
        print('The key for decryption of message is: ',key.decode('utf-8'))
        time.sleep(1.5)

        pass1='The key for decryption of the visual cryptography is:'+keyVisual
        pass2='The key for decryption of message is:'+key.decode('utf-8')
        file=open('Passwords','w')
        file.write(pass1)
        file.write('\n')
        file.write(pass2)
        print('The keys for decryption are stored in Passwords file in the same folder as this code.')
Ejemplo n.º 18
0
 def initialisation(self):
     for _ in range(0, self.__param['popSize']):
         c = Chromosome(self.__problParam)
         self.__population.append(c)
Ejemplo n.º 19
0
		similarityAfter += simiPopAfter

	similarityBefore /= popPoolSize
	similarityAfter /= popPoolSize

	return similarityAfter < similarityBefore 

def getSimularityOfScenarioVsPrevPop(scenario, prePopPool):
	
	similarity = 0
	for i in prePopPool:
		popSimilarity = 0
		for j in i:
			simi = tools.getSimilaritybetweenScenarios(j.scenario, scenario.scenario)
			popSimilarity += simi
		popSimilarity /= len(i)
		similarity += popSimilarity
	similarity /= len(prePopPool)

	return similarity	

if __name__ == '__main__':
    prevPopPool = getAllCheckpoints('GaCheckpoints')
    npcSize = len(prevPopPool[0][0].scenario)
    chromosome1 = Chromosome([[0, 34], [0, 3]], npcSize, len(prevPopPool[0][0].scenario[0]))
    chromosome1.rand_init()
    chromosome2 = Chromosome([[0, 34], [0, 3]], npcSize, len(prevPopPool[0][0].scenario[0]))
    chromosome2.rand_init()
    checkIfRemutataion('GaCheckpoints', chromosome1, chromosome2)

Ejemplo n.º 20
0
    def run_genetic_algorithm(self,
                              number_of_iterations=1000,
                              mutation_probability=0.7,
                              crossover_probability=0.7):

        # Run for a fixed number of iterations
        for it in tqdm(range(number_of_iterations)):

            # Tournament selection
            k = self.population_size
            j = (int)(self.population_size * 0.6)
            for _ in range(self.population_size - k):
                del self.population[-np.random.randint(0, len(self.population)
                                                       )]
            for _ in range(k - j):
                worst_chromosome_score = self.population[0].score
                worst_chromosome_index = 0
                for i in range(1, len(self.population)):
                    if self.population[i].score > worst_chromosome_score:
                        worst_chromosome_score = self.population[i].score
                        worst_chromosome_index = i
                del self.population[-worst_chromosome_index]

            for _ in range(self.population_size - len(self.population)):
                self.population.append(
                    Chromosome(number_of_cities=self.n_cities,
                               number_of_traveling_salesman=self.n_salesman,
                               adj=self.adj))

            # Mutate globally
            for index in range(len(self.population)):
                if np.random.random(1)[0] < mutation_probability:
                    chromosome = copy.deepcopy(self.population[index])
                    chromosome.mutate_global()
                    if chromosome.score < self.population[index].score:
                        self.population[index] = chromosome

            # Mutate locally
            for index in range(len(self.population)):
                if np.random.random(1)[0] < mutation_probability:
                    chromosome = copy.deepcopy(self.population[index])
                    chromosome.mutate_local()
                    if chromosome.score < self.population[index].score:
                        self.population[index] = chromosome

            # Crossover
            for index1 in range(len(self.population)):
                if np.random.random(1)[0] < crossover_probability:
                    index2 = np.random.randint(0, len(self.population))
                    if index1 == index2:
                        index2 = np.random.randint(0, len(self.population))
                    child1 = copy.deepcopy(self.population[index1])
                    child2 = copy.deepcopy(self.population[index2])
                    child1.crossover(self.population[index2])
                    child2.crossover(self.population[index1])
                    if child1.score < self.population[index1].score:
                        self.population[index1] = child1
                    if child2.score < self.population[index2].score:
                        self.population[index2] = child2

            # Log the progress statistics in the history
            self.get_best_result(verbose=0)
Ejemplo n.º 21
0
 def initialize(self):
     problParam = {"noNodes": self.__nodesNo, "graph": self.__graph}
     for i in range(0, self.__populationSize):
         c = Chromosome(problParam)
         self.__population.append(c)
Ejemplo n.º 22
0
 def InitPop(self):
     for i in range(self._popSize):
         new_chrm = Chromosome(copy.deepcopy(
             self._genomes))  #created random genes values in chromosome
         self._chromosomes.append(new_chrm)
Ejemplo n.º 23
0
def main():
    selection = "rank"
    fname = "ocarina.wav"
    print "The file to encode is : \t" + fname
    #get_from_user("enter a filename: ")
    steg = stegolib()
    config = steg.load_key("setup.conf")
    user_config = read_config(config)
    user_selection = user_config[0]
    user_pressure = user_config[1]
    user_mutation_freq = user_config[2]
    user_elitism = user_config[3]

    get_from_user("\nPress enter to continue.")

    af = steg.open_audio_file(fname)
    parameters = steg.get_audio_information(af)
    #message = "abc"
    #message = "It was the best of times, it was the worst of times, it was the age of wisdom, it was the age of foolishness, it was the epoch of belief, it was the epoch of incredulity, it was the season of Light, it was the season of Darkness, it was the spring of hope, it was the winter of despair, we had everything before us, we had nothing before us, we were all going direct to Heaven, we were all going direct the other way – in short, the period was so far like the present period, that some of its noisiest authorities insisted on its being received, for good or for evil, in the superlative degree of comparison only. "
    message = "It was the best of times, it was the worst of times, it was the age of wisdom, it was the age of foolishness, it was the epoch of belief, it was the epoch of incredulity, it was the season of Light, it was the season of Darkness, it was the spring of hope, it was the winter of despair, we had everything before us, we had nothing before us, we were all going direct to Heaven, we were all going direct the other way – in short, the period was so far like the present period, that some of its noisiest authorities insisted on its being received, for good or for evil, in the superlative degree of comparison only."
    print "Encoding message :\n" + message
    print "\n"
    message = message + message + message + message + message
    message_hex = binascii.hexlify(message)
    #The GA maintains a population of n chromosomes (solutions) with associated fitness values. Parents are selected to mate, on the basis of their fitness, producing offspring via a reproductive plan. Consequently highly fit solutions are given more opportunities to
    audio = steg.as_hex(af)
    baseline_rms = steg.compute_rms_power(audio,
                                          "RMS power before added noise : ")
    num_individuals = 20
    print "Step 1) The first step of a genetic algorithm is to initialize a random population. The initial randomness creates genetic variation which is the basis for our search heuristic. \nWe measure the fitness function of each member of our population and use that as a metric for selecting the best individuals whose genes move to the next generation "

    get_from_user("Press enter to initialize a population")
    print "Initializing random population of " + str(
        num_individuals) + " individuals... \n"
    population = steg.init_population(audio, 20, message_hex)
    population_fitness = steg.measure_population(audio, message_hex,
                                                 population, baseline_rms)
    best_values = list()
    best_genes = list()
    strongest_chromosomes = list()
    print_pop_fitness(population, best_values, best_genes, "individual")
    #ScatterPlot.plot(best_values)
    get_from_user("\nPress enter to continue")
    #best = handle_elitism(population,user_elitism)

    #print "\n BEST"
    #for x in range (0,len(best)):
    #	print str(best[x].fitness)

    ###################################

    #get_parents()
    #survive = parents[0]
    #survive2 = parents[1]
    #print "parent one fitness: " + str(survive.fitness)
    #print "parent two fitness: " + str(survive2.fitness)
    #exit()
    ###################################

    ##################################

    next_generation = list()
    print "Step 2 : Initialize new generation"
    print "The most fit individuals are selected using the RouletteWheel model to produce children. The fittest individuals cross genes in hopes that after multiple iterations future generations will \nbegin to converge towards an optimal or near optimal value."
    get_from_user("\nPress enter to continue")

    num_generations = 20
    for y in range(0, num_generations):
        print "ENTERING GENERATION : " + str(y)
        next_generation = handle_elitism(population, user_elitism,
                                         next_generation, user_mutation_freq,
                                         baseline_rms, steg, audio,
                                         message_hex)
        print "len " + str(len(next_generation))
        for x in range(0, len(next_generation)):
            print(next_generation[x].fitness)

        for x in range(0, len(population) - user_elitism):
            if x is 0 and y is 0:
                print "Spinning RouletteWheel..."
            parents = get_parents(population, user_selection, user_pressure)
            survive = parents[0]
            survive2 = parents[1]
            if x is 0 and y is 0:
                print "\nParents selected:"
                print "Parent one fitness: " + str(survive.fitness)
                print "Parent two fitness: " + str(survive2.fitness)
                print "\nThe selected individuals are going to crossover genes to create a child chromosome that will hopefully adopt the best of both parents and move on to the next generation. The selection algorithm is called single split point selection "
            child_key = survive.crossover(survive2)
            child = Chromosome(child_key, -2)
            child.mutate(user_mutation_freq)

            #exit()
            child.fitness = steg.measure_individual(
                audio,
                message_hex,
                child,
                baseline_rms,
            )
            if x is 0 and y is 0:
                print "the child fitness is : " + str(
                    child.fitness
                ) + ", and it is moving on to the next generation. \n"
                get_from_user(
                    "Press enter to run this for all members of the population."
                )
            next_generation.append(child)
        print_pop_fitness(next_generation, best_values, best_genes, "child")
        if y is 0:
            #print "X is:  " + str(x)
            print "\n\nWe just finished one generation. We kept the best value from our initial population and the best value from our first\n round of genetic combination."
            print("Best values so far: " + str(best_values))
            get_from_user("Press Enter to repeat for " + str(num_generations) +
                          " generations")
        population = list(next_generation)
        del next_generation[:]
        #if y is 4 or y is 9 or y is 14:
        #	ScatterPlot.plot(best_values)

    print "\n\nFinished " + str(
        num_generations
    ) + "." + "Here is a list of the highest fitness values from each generation:"
    print "BEST VALUES " + str(best_values)

    ordered = result_tuples(best_values)
    print_analysis(ordered)
    ScatterPlot.plot(best_values)

    #exit()
    #print population_fitness

    sorted_genes = sorted(best_genes, key=lambda x: x.fitness, reverse=True)
    edited_info = steg.encode(audio, message_hex, sorted_genes[0].key)
    edited_audio = edited_info[0]
    key = edited_info[1]
    edited_rms = steg.compute_rms_power(
        edited_audio, "rms power after adding noise"
    )  # computes the rms power of the edited file
    noise_fname = steg.get_noise_fname(fname)
    steg.write_wave_file(
        noise_fname, edited_audio,
        parameters)  # writes a copy of the edited file to disk
    snr = steg.compute_fitness_function(baseline_rms, edited_rms)

    print("The signal to noise ratio is: ", snr)
    print "The noise file has been saved as " + noise_fname
    saved_keyname = get_from_user("Audio hidden in " + fname +
                                  "\nEnter name for your stego key:")
    steg.save_key(key, saved_keyname)
    keyname = get_from_user(
        "Enter a .key to decode the text from the audio file: ")
    key = steg.load_key(keyname)
    steg.decode_message(edited_audio, key)
def make_random_int_chromosome(fit_function, length):

    return Chromosome(make_random_int_list(length), fit_function, int_mutation)
Ejemplo n.º 25
0
    def do_mating(self, recomb):

        for i in range(self.mOffspringPerGeneration):
            chromA = self.population[0]
            chromB = self.population[1]
            #crossovertyp ist hier egal
            newChromo1 = ChromosomeDEAP(self.mMaxLength, 2)
            newChromo2 = ChromosomeDEAP(self.mMaxLength, 2)
            self.population.append(newChromo1)
            newIndex1 = len(self.population) - 1
            self.population.append(newChromo2)
            newIndex2 = len(self.population) - 1

            sys.stdout.write("Parent1 mit Fitness ")
            sys.stdout.write(str(Chromosome.get_fitness(chromA)) + " : ")
            Chromosome.toStr(chromA) + "\n"
            sys.stdout.write("Parent2 mit Fitness ")
            sys.stdout.write(str(Chromosome.get_fitness(chromB)) + " : ")
            Chromosome.toStr(chromB) + "\n"

            #TODO NQueen.(gewünschte rekombination), bei bad-recombination NDEAP.bad_recombination
            Operations.partially_mapped_crossover(self, chromA, chromB,
                                                  newIndex1, newIndex2)

            newChromo1 = self.population[newIndex1]
            # Konsole:
            sys.stdout.write("Kind1 mit Fitness ")
            sys.stdout.write(str(Chromosome.get_fitness(newChromo1)) + " : ")
            Chromosome.toStr(newChromo1) + "\n"

            newChromo2 = self.population[newIndex2]
            # Konsole:
            sys.stdout.write("Kind2 mit Fitness ")
            sys.stdout.write(str(Chromosome.get_fitness(newChromo2)) + " : ")
            Chromosome.toStr(newChromo2) + "\n"

            self.childCount += 2
            sys.stdout.write(
                str(len(self.population)) + " Länge der Population\n")

            SingleRekomb.set_conflict_array(self,
                                            Chromosome.get_fitness(chromA),
                                            Chromosome.get_fitness(chromB),
                                            Chromosome.get_fitness(newChromo1),
                                            Chromosome.get_fitness(newChromo2))

            # plot für jeden einzelnen Druchgang
            #self.show_conflicts(chromA, chromB, newChromo1, newChromo2)

        return