예제 #1
0
def GenerateOffspring(parents):
    offspring = []
    while (len(offspring) != len(parents)):
        parentA, parentB = Selection.Selection(parents)
        childA, childB = Crossover.Crossover(parentA, parentB)
        childA = Mutation.Mutation(childA)
        childB = Mutation.Mutation(childB)
        offspring.append(childA)
        offspring.append(childB)
    return offspring
예제 #2
0
 def ga_stuff(self):
     population = Initialization.initialize(population_size, lower_bound, upper_bound, self.degree + 1)
     best_forever = population[0].copy()
     for current_generation in range(generations):
         self.sort_population(population)
         best_of_generation = population[0].copy()
         best_forever = best_of_generation.copy() if self.mse(best_of_generation) < self.mse(
             best_forever) else best_forever
         Crossover.cross(population_size // 2, population, self.x, self.y)
         Mutation.mutate(population, current_generation, generations, depending_factor)
     return best_forever
예제 #3
0
 def __init__(self, params):
     self.epochs = params['epochs']
     self.Crossover = Crossover(params['crossover_type'],
                                params['crossover_prob'])
     self.Population = Population(booth_function, params['population_size'],
                                  2, -10, 10,
                                  params['population_precision'])
     self.Mutation = Mutation(params['mutation_type'],
                              params['mutation_prob'])
     self.Inversion = Inversion(params['inversion_type'],
                                params['inversion_prob'])
     self.Selection = Selection(params['selection_type'],
                                params['selection_prob'])
     self.EliteStrategy = EliteStrategy(params['elite_prob'])
def create_new_genome(input_size, output_size, fully_connected=False):
    nodes_genes = {}
    for i in range(0, input_size):
        nodes_genes[i] = NodeGene(input_nodes=None,
                                  output_nodes=[],
                                  neuron_type='i')
    for j in range(input_size, input_size + output_size):
        nodes_genes[j] = NodeGene(input_nodes=[],
                                  output_nodes=[],
                                  neuron_type='o')

    cpt = input_size + output_size
    connection_genes = dict()
    if fully_connected:
        for i in range(0, input_size):
            for j in range(input_size, input_size + output_size):
                connection_genes[i,
                                 j] = ConnectionGene(cpt,
                                                     Mutation.get_new_weight(),
                                                     False)
                nodes_genes[i].output_nodes.append(j)
                nodes_genes[j].input_nodes.append(i)
                cpt += 1

    return Genome(input_size=input_size,
                  output_size=output_size,
                  nodes_genes=nodes_genes,
                  connection_genes=connection_genes,
                  generation=0,
                  parents_species_id=[])
예제 #5
0
파일: Base.py 프로젝트: shambo001/peat
    def update(self, evt=None):
        """Draw all elements"""
        sequence = self.P.DNAseq
        #print sequence
        self.width=self.winfo_width()
        start = self.xstart
        end = self.width-20
        self.scale = (end-start)/float(len(sequence))
        c = self.canvas
        c.delete(ALL)
        import Mutation
        AAseqs3,AAseqs1 = Mutation.translate(sequence)
        #print AAseqs1
        i=1

        for seq in AAseqs1:
            row = 40+i*30
            c.create_text(start-60,row,
                          font=self.font,text='Frame '+str(i),
                          fill='black',anchor='w',tag=('label'))

            c.create_line(start,row,end,row,width=2,
                          fill='darkgreen',tag=('line'))
            pos=1
            for letter in seq:
                if letter=='*':
                    x = self.getAAPosition(pos)
                    print pos,x, self.scale, len(sequence)
                    c.create_line(x,row,x,row-10,fill='red',width=2)
                    c.create_text(x,row-20,text='%d' %(pos),
                                    font='Arial 7',anchor='n')
                pos+=1
            i+=1
        return
예제 #6
0
파일: Base.py 프로젝트: shambo001/peat
    def showAA3Seq(self, sequence=None):
        """Show 3 letter code amino acid sequence"""
        if sequence == None:
            return
        c = self.canvas
        seqfont = self.getCurrentFont()

        y = (self.baserow+self.orfoffset)*self.yscale
        frame = 0
        AAseqs3,AAseqs1 = Mutation.translate(sequence)
        aaseq = AAseqs3[frame]
        #print aaseq
        for i in range(len(aaseq)):
            pos = self.getAAPosition(i)#,frame+1)
            c.create_text(pos,y,
                            font=seqfont,text=aaseq[i],
                            fill='black',tag=('aasequence'))
        for i in range(len(aaseq)):
            if i%5!=0:
                continue
            pos = self.getAAPosition(i)
            c.create_text(pos,y+45,
                            font='Courier 11',text=i,
                            fill='black',tag=('aasequence'))
            c.create_line(pos,y+35,pos,y+20,fill='red',width=2)
        return
예제 #7
0
    def showAA3Seq(self, sequence=None):
        """Show 3 letter code amino acid sequence"""
        if sequence == None:
            return
        c = self.canvas
        seqfont = self.getCurrentFont()

        y = (self.baserow + self.orfoffset) * self.yscale
        frame = 0
        AAseqs3, AAseqs1 = Mutation.translate(sequence)
        aaseq = AAseqs3[frame]
        #print aaseq
        for i in range(len(aaseq)):
            pos = self.getAAPosition(i)  #,frame+1)
            c.create_text(pos,
                          y,
                          font=seqfont,
                          text=aaseq[i],
                          fill='black',
                          tag=('aasequence'))
        for i in range(len(aaseq)):
            if i % 5 != 0:
                continue
            pos = self.getAAPosition(i)
            c.create_text(pos,
                          y + 45,
                          font='Courier 11',
                          text=i,
                          fill='black',
                          tag=('aasequence'))
            c.create_line(pos, y + 35, pos, y + 20, fill='red', width=2)
        return
예제 #8
0
    def run(self):
        """

        :return:
        """
        offspring = []
        i = 0
        while len(offspring
                  ) < self.mating_pool_size:  # 2 parents  ->  2 individuals
            p1 = self.parents[i]
            p2 = self.parents[i + 1]

            # crossover ################################################################################################
            # print("crossover...")
            if random.random() < self.xover_rate:
                # off1, off2 = Crossover.COWGC(p1, p2, city_map)
                off1 = Crossover.order_crossover(p1, p2, city_map)
                off2 = Crossover.order_crossover(p1, p2, city_map)
            else:
                off1 = copy.copy(p1)
                off2 = copy.copy(p2)
            # print("crossover end")

            # mutation #################################################################################################
            # print("Mutation...")
            if random.random() < self.mut_rate:
                off1 = Mutation.WGWWGM(p1, city_map)
                # off1 = Mutation.IRGIBNNM_mutation(p1, city_map)
                # off1 = Mutation.inversion_mutation(p1, city_map)
            if random.random() < self.mut_rate:
                off2 = Mutation.WGWWGM(p2, city_map)
                # off2 = Mutation.IRGIBNNM_mutation(p2, city_map)
                # off2 = Mutation.inversion_mutation(p2, city_map)
            # print("Mutation end")

            offspring.append(off1)
            offspring.append(off2)
            # print(len(offsprings))

            i += 2
        q.put(offspring)
        print('end')
예제 #9
0
파일: mascotte.py 프로젝트: xtmgah/mascote
def main():
    Support.log(msg="# Parsing and checking the input arguments\n", level="STEP")
    args = Argparser.parse_mascotte_arguments()
    logArgs(args)
    if args['rndseed'] != None:
        random.seed(args['rndseed'])

    Support.log(msg="# Setting up for simulating human diploid genome\n", level="STEP")
    human = Genomics.HumanGenome(reference=args['reference'], snplist=args['snplist'], snpratio=args['snpratio'], HEHOratio=args['HEHOratio'], ignorelist=args['ignore'])
    maternalhuman = os.path.join(args['xdir'], 'human.maternal.fa')
    paternalhuman = os.path.join(args['xdir'], 'human.paternal.fa')
    Support.log(msg="# Simulating human diploid genome\n", level="STEP")
    human.buildGenome(maternalout=maternalhuman, paternalout=paternalhuman)
    Support.log('Chromosomes: {}\n'.format(', '.join(human.chromosomes)), level='INFO')
    Support.log('Number of simulated SNPs: {}\n'.format(human.numsnps), level='INFO')
    Support.log('Number of heterozygous SNPs: {}\n'.format(human.hetsnps), level='INFO')
    Support.log('Maternal chromosome of human genome written in {}\n'.format(maternalhuman), level='INFO')
    Support.log('Maternal chromosome of human genome written in {}\n'.format(paternalhuman), level='INFO')

    Support.log(msg="# Simulating tumor clones and their evolution through specified CNAs\n", level="STEP")
    tumor = Mutation.simulateEvolution(numclones=args['numclones'], humanGenome=human, binsize=args['binsize'], mutations=args['mutations'])
    Support.log('Simulated tumor clones: {}\n'.format(', '.join([clone.label for clone in tumor.clones])), level='INFO')
    Support.log('Founder tumor clone: {}\n'.format(tumor.root.label), level='INFO')
    with open(os.path.join(args['xdir'], 'tumor.dot'), 'w') as o: o.write("{}\n".format(tumor.draw()))
    Support.log('The resulting tumor evolution of clones and related CNAs have been drawn in {} as dot format\n'.format(os.path.join(args['xdir'], 'tumor.dot')), level='INFO')
    Support.log('Genome length of the various tumor clones:\n\t{}\n'.format('\n\t'.join(['{}: {}'.format(clone.label, clone.genomeLength()) for clone in tumor.clones])), level='INFO')
    Support.log('Computing and segmenting the copy-number profiles jointly for all tumor clones\n', level='INFO')
    segments = segmentation(evolution=tumor)
    Support.log('Total number of resulting segments= {}\n'.format(sum(len(segments[chro]) for chro in tumor.human.chromosomes)), level='INFO')
    segout = os.path.join(args['xdir'], 'copynumbers.csv')
    with open(segout, 'w') as o:
        o.write('\t'.join(['#CHR', 'START', 'END'] + [clone.label for clone in tumor.clones]) + '\n')
        o.write('\n'.join(['\t'.join(map(str, [chro, seg[0], seg[1]]+['{}|{}'.format(segments[chro][seg][clone.idx]['m'], segments[chro][seg][clone.idx]['p']) for clone in tumor.clones])) for chro in tumor.human.chromosomes for seg in sorted(segments[chro], key=(lambda x : x[0]))]))
        o.write('\n')
    Support.log('The allele-specific copy number profiles for every tumor clone has been written in {}\n'.format(segout), level='INFO')
    Support.log('Writing the FASTA-format genomes of tumor clones\n', level='INFO')
    if args['jobs'] == 1:
        for clone in tumor.clones:
            maternalout = os.path.join(args['xdir'], '{}.maternal.fa'.format(clone.label))
            paternalout = os.path.join(args['xdir'], '{}.paternal.fa'.format(clone.label))
            clone.buildGenome(maternalout, paternalout)
    else:
        builder = Builder.CloneGenomeBuilder(tumor, args['xdir'])
        builder.parallelbuild(args['jobs'])
    Support.log('Tumor-clone genomes wrote in:\n{}\n'.format('\n'.join(['\t{}: maternal > {} and paternal > {}'.format(clone.label, os.path.join(args['xdir'], '{}.maternal.fa'.format(clone.label)), os.path.join(args['xdir'], '{}.paternal.fa'.format(clone.label))) for clone in tumor.clones])), level='INFO')
    Support.log('KTHXBY!\n', level='STEP')
예제 #10
0
    def update(self, evt=None):
        """Draw all elements"""
        sequence = self.P.DNAseq
        #print sequence
        self.width = self.winfo_width()
        start = self.xstart
        end = self.width - 20
        self.scale = (end - start) / float(len(sequence))
        c = self.canvas
        c.delete(ALL)
        import Mutation
        AAseqs3, AAseqs1 = Mutation.translate(sequence)
        #print AAseqs1
        i = 1

        for seq in AAseqs1:
            row = 40 + i * 30
            c.create_text(start - 60,
                          row,
                          font=self.font,
                          text='Frame ' + str(i),
                          fill='black',
                          anchor='w',
                          tag=('label'))

            c.create_line(start,
                          row,
                          end,
                          row,
                          width=2,
                          fill='darkgreen',
                          tag=('line'))
            pos = 1
            for letter in seq:
                if letter == '*':
                    x = self.getAAPosition(pos)
                    print pos, x, self.scale, len(sequence)
                    c.create_line(x, row, x, row - 10, fill='red', width=2)
                    c.create_text(x,
                                  row - 20,
                                  text='%d' % (pos),
                                  font='Arial 7',
                                  anchor='n')
                pos += 1
            i += 1
        return
예제 #11
0
def loop_over_mutations(db):
    #    pdb=db['#Pdb'].str.slice(start=0, stop=4, step=1)
    i = 0
    m = Mutation.MutationMethods()
    while i < len(db):
        db.loc[db.index[i],
               'ITSM'] = m.getSMScore([db['Mutation(s)_cleaned'].iloc[i]],
                                      'ITSM')
        db.loc[db.index[i],
               'Blosum'] = m.getSMScore([db['Mutation(s)_cleaned'].iloc[i]],
                                        'Blosum')
        db.loc[db.index[i],
               'Proline'] = m.HasProline([db['Mutation(s)_cleaned'].iloc[i]])
        db.loc[db.index[i],
               'Glycine'] = m.HasGlycine([db['Mutation(s)_cleaned'].iloc[i]])
        #dummy placeholder command
        #       print (str(db.index[i])+"_"+pdb.iloc[i]+"_"+db['Mutation(s)_cleaned'].iloc[i])
        i += 1
예제 #12
0
    def run(self, gp, lp, gdir, mutype, cnt):
        gname = os.path.splitext(os.path.basename(gp))[0]
        i = 1
        while i <= cnt:
            cfg = Mutation.mutate_cfg(gp, lp, mutype)
            tp = tempfile.mktemp()
            tf = open(tp, "w")
            tf.write(self.header)
            tf.write("%s\n" % str(cfg))
            tf.close()
            
            if ValidGrammar.valid(tp, lp):
                if not self.check_duplicate_cfg(gdir, tp, lp):
                    _gp = '%s/%s_%s.acc' % (gdir, gname, i)
                    r = subprocess.call(["cp", tp, _gp])
                    if r != 0:
                        Utils.error("Copy failed.\n", r)

                    i += 1
                    sys.stderr.write('.')

                if os.path.exists(tp):
                    os.remove(tp)
예제 #13
0
def create(old_population):

    # for x in range(len(old_population)):
    #     print(old_population[x])

    new_population = [[-1 for x in range(9)] for y in range(20)]
    matrix_aux = [[-1 for x in range(9)] for y in range(2)]

    new_population[0] = old_population[0].copy()

    for x in range(5):
        y = x * 2
        matrix_aux[0] = old_population[y].copy()
        matrix_aux[1] = old_population[y + 1].copy()
        matrix_aux = CrossOver.do(matrix_aux).copy()
        new_population[y + 1] = matrix_aux[0].copy()
        new_population[y + 2] = matrix_aux[1].copy()

    for x in range(9):
        y = x + 11
        new_population[y] = Mutation.do(old_population[y]).copy()

    return new_population
예제 #14
0
def compileMutations(data, type):
    mutationList = MutationList()
    for drug in data['viewer']['mutationsAnalysis']['drugResistance'][0][
            'drugScores']:
        for mutations in drug['partialScores']:
            try:
                x = mutations['mutations'][1]['text']
                muts = []
                for mutation in mutations['mutations']:
                    muts.append(mutation['text'])
                temp = mutations['mutations'][0]['text']
                mutationList.add_multimutant(
                    MultipleMutant(muts, mutations['score']))

            except:
                temp = mutations['mutations'][0]['text']
                if temp not in mutationList.get_names():
                    newMutation = Mutation(temp, type, mutations['score'])
                    mutationList.add_mutation(newMutation)
                else:
                    mutationList.add_score(temp, mutations['score'])
    mutationList.fill_blanks()
    mutationList.get_averages()
    return mutationList
예제 #15
0
        '''
		for x in range (0,10):
			Mutation.Mutate(PerfectPSNP)
			graph.graphPSNP(PerfectPSNP,'mutated'+'['+str(x)+']','mutated')
			#completeName = os.path.join(save_path, name_of_file+".txt")  
			#out = open(completeName, 'w')
			#out.write(' '.join(PerfectPSNP))
		'''
        save_path = os.getcwd() + '\mutated_txt'
        access_rights = 0o755
        try:
            os.mkdir(save_path, access_rights)
        except OSError:
            print("Creation of the directory %s failed" % save_path)
        else:
            print("Successfully created the directory %s " % save_path)

        for x in range(0, 10):
            Mutation.Mutate(PerfectPSNP)
            graph.graphPSNP(PerfectPSNP, 'mutated' + '[' + str(x) + ']',
                            'mutated_graph')
            completePath = os.path.join(
                save_path, 'mutated' + '[' + str(x) + ']' + ".txt")
            out = open(completePath, 'w')
            str_PSNP = [str(i) for i in PerfectPSNP]
            out.write(' '.join(str_PSNP))

        break
    except FileNotFoundError:
        print("Enter a valid filename...")
예제 #16
0
파일: Main.py 프로젝트: Wolff-H/COMP-3-201
            p2 = parents[i + 1]

            # crossover ################################################################################################
            #print("crossover...")
            if random.random() < xover_rate:
                #off1, off2 = Crossover.COWGC(p1, p2, city_map)
                off1, off2 = Crossover.order_crossover(p1, p2, city_map)
            else:
                off1 = copy.copy(p1)
                off2 = copy.copy(p2)
            #print("crossover end")

            # mutation #################################################################################################
            #print("Mutation...")
            if random.random() < mut_rate:
                off1 = Mutation.WGWWGM(p1, city_map)
                #off1 = Mutation.WGWRGM(p1, city_map)
                #off1 = Mutation.IRGIBNNM_mutation(p1, city_map)
                #off1 = Mutation.inversion_mutation(p1, city_map)
            if random.random() < mut_rate:
                off2 = Mutation.WGWWGM(p2, city_map)
                #off2 = Mutation.WGWRGM(p2, city_map)
                #off2 = Mutation.IRGIBNNM_mutation(p2, city_map)
                #off2 = Mutation.inversion_mutation(p2, city_map)
            #print("Mutation end")

            offsprings.append(off1)
            offsprings.append(off2)
            #print(len(offsprings))

            i += 2
예제 #17
0
			ruleCount+=1
			ruleStartList.append(rulestart)
			rulestart = rulestart + 6
			#loopCount+=1
	return (ruleStartList)




while True:
	try:
		fileName = input("Enter PSNP filename to modify: ")
		fileName = fileName+'.txt'
		File = open(fileName, "r+")
		PerfectPSNP = [int(string) for string in File.readline().replace('\n','').split(' ')]
		Mutation.PrintPSNP(PerfectPSNP)
		break
	except FileNotFoundError:
		print("Enter a valid filename...")


neurons = int(PerfectPSNP[0])
rules = int(PerfectPSNP[1])
rulestart = 2+((neurons-1)*neurons)
#print ("Neurons: {}".format(neurons))
#print ("Rules: {}".format(rules))
#print ("Rule Start: {}".format(rulestart))
loopCount = 1
ruleList = []

finRule = []
        if (soup.findAll('a').__len__() == 2):
            #m.EvTypeID = ev.getEvidenceDetailsfromSoup(soup.select('a')[0].text+" "+soup.select('a')[1].text,)
            m.EvUrl1 = soup.select('a')[0].get('href')
            m.EvUrl2 = soup.select('a')[0].get('href')
            m.EvTypeID = ev.getEvidenceDetailsfromSoup(
                soup.select('a')[0].text + " " + soup.select('a')[1].text,
                m.EvUrl1, m.EvUrl2)
        else:
            m.EvTypeID = ev.getEvidenceDetailsfromSoup(soup.text,
                                                       soup.a['href'])
            m.EvUrl1 = soup.a['href']
            m.EvUrl2 = ""

        #This is where Mutation Extra Details will be extracted
        m.MtypeID = mut.getMutationTypeIDDetailsfromSoup(m.EvUrl1)
        # print m.SeqId.encode("utf8")
        try:
            m.MSub = vr.getREF(directory, m.Pos,
                               m.SeqId.replace(u'\u2011', ""))
            m.MObj = vr.getALT(directory, m.Pos, m.SeqId)
        except ValueError:
            m.MSub = 0
            m.MObj = 0
        #print evidence
        # print str(m.GeneType)
        #Evidence URL

        #print soup.findAll('a')[]

        #otp+=str(m.EvTypeID)+u","+str(+m.EvUrl1)+u","+str(m.EvUrl2)+u","+m.SeqId+u","+str(m.Pos)+u","+str(m.MtypeID)+u","+str(m.MObj)+u","+str(m.MSub)+u","+str(m.Mutation)+u","+str(m.Coverage)+u","+str(m.AnnotationTypeID)+u","+str(m.AnnotationCodon1)+u","+str(m.AnnotationCodon2)+","+str(m.AnnotationCodonPosition)+u","+str(m.AnnotationBracket1)+","+str(m.AnnotationBracket2)+","+str(m.Annotation)+","+str(m.GeneParameter1)+","+str(m.GeneParameter2)+","+str(m.Gene)+","+str(m.Description)+",\n"
예제 #19
0
    #         # print("COMBINED IS")
    #         # print(combined)
    #         if (combined == target):
    #             print("Its Done!")
    #             sys.exit()

    f = Fitness.Fitness(population)
    fitness = f.getFitness()

    s = Selection.Selection(fitness)
    firstChoice, secondChoice, maximum = s.selectFromPop()

    c = Crossover.Crossover(population, firstChoice, secondChoice)
    population = c.crossover()

    m = Mutation.Mutation(population, 10)
    population = m.mutate()

    if (catch == 1):

        print(
            "--------------------------------------------------------------------"
        )
        print("Program is finished!")
        print(
            "--------------------------------------------------------------------"
        )
        print("Final fitness: ")
        print(fitness)
        print(
            "--------------------------------------------------------------------"
예제 #20
0
파일: Main.py 프로젝트: Wolff-H/COMP-3-201
def main():

    western29 = "Cities/TSP_WesternSahara_29.txt"
    uruguay734 = "Cities/TSP_Uruguay_734.txt"
    canada4663 = "Cities/TSP_Canada_4663.txt"

    popsize = 2000
    mating_pool_size = 300
    tournament_size = 3
    mut_rate = 0.2
    xover_rate = 0.9
    gen_limit = 100

    advanced_Canada = {
        "description": {
            "instance_name": "none",
            "algorithm": "none",
            "city_all": 4663,
            "generation_all": gen_limit
        },
        "evolutions": [
            # nothing yet
        ]
    }

    advanced_Uruguay = {
        "description": {
            "instance_name": "none",
            "algorithm": "none",
            "city_all": 734,
            "generation_all": gen_limit
        },
        "evolutions": [
            # nothing yet
        ]
    }

    advanced_WesternSahara = {
        "description": {
            "instance_name": "none",
            "algorithm": "none",
            "city_all": 29,
            "evolution_all": 10,
            "generation_all": gen_limit,
            "generation_size": mating_pool_size
        },
        "evolutions": [
            # nothing yet
        ]
    }

    print(json.dumps(advanced_WesternSahara))

    for evo in range(10):  # Experiment

        # construct a trial #
        trial = [[{"time_cost": 0}]]

        print("trial", evo + 1)

        # t = time.time()
        print("Preparing for the information...")
        c = CityMap.CityMap(western29)
        city_map = c.city_map
        print("preparation end.")

        gen = 0
        print("Initialize population...")
        init = Initialization.Population(popsize, city_map)
        init.evalPopulation()
        print("Initialization end.")

        # Evolution ########################################################################################################
        while gen < gen_limit:

            # parent selection ---------------------------------------------------------------------------------------------
            #print("parent selection...")
            parents = Selection.tournament_selection(init.population[1:],
                                                     mating_pool_size,
                                                     tournament_size)
            #print("parent selection end.")

            offsprings = []
            i = 0
            while len(offsprings
                      ) < mating_pool_size:  # 2 parents  ->  2 individuals
                p1 = parents[i]
                p2 = parents[i + 1]

                # crossover ------------------------------------------------------------------------------------------------
                #print("crossover...")
                if random.random() < xover_rate:
                    #off1, off2 = Crossover.COWGC(p1, p2, city_map)
                    off1 = Crossover.order_crossover(p1, p2, city_map)
                    off2 = Crossover.order_crossover(p1, p2, city_map)
                else:
                    off1 = copy.copy(p1)
                    off2 = copy.copy(p2)
                #print("crossover end")

                # mutation -------------------------------------------------------------------------------------------------
                #print("Mutation...")
                if random.random() < mut_rate:
                    off1 = Mutation.WGWWGM(p1, city_map)
                    #off1 = Mutation.IRGIBNNM_mutation(p1, city_map)
                    #off1 = Mutation.inversion_mutation(p1, city_map)
                if random.random() < mut_rate:
                    off2 = Mutation.WGWWGM(p2, city_map)
                    #off2 = Mutation.IRGIBNNM_mutation(p2, city_map)
                    #off2 = Mutation.inversion_mutation(p2, city_map)
                #print("Mutation end")

                offsprings.append(off1)
                offsprings.append(off2)
                #print(len(offsprings))

                i += 2

            # survial selection --------------------------------------------------------------------------------------------
            #print("survival selection")
            init.population[1:] = Selection.mu_plus_lambda(
                init.population[1:], offsprings)
            #print("survival selection end")

            init.evalPopulation()

            print("generation:", gen, " Average length:", init.AverageLength,
                  " Longest length: ", init.worstTour.length,
                  " shortest length:", init.bestTour.length)

            # construct a generation #
            generation = {
                "best-individual-sequence":
                init.bestTour.tour,
                "best-individual-distance":
                init.bestTour.length,
                "worst-individual-sequence":
                init.worstTour.tour,
                "worst-individual-distance":
                init.worstTour.length,
                "average-distance":
                init.AverageLength,
                "individual-distances":
                [round(distance.length) for distance in init.population
                 ]  # distance.length for distance in init.population
            }

            trial.append(generation)

            gen += 1

        advanced_WesternSahara["evolutions"].append(trial)

        print("time cost:", time.time())

    # here processing generating json file #############################################################################

    output_file = open("advanced_WesternSahara.js", "w")

    output_file.write("let advanced_WesternSahara = ")
    output_file.write(json.dumps(advanced_WesternSahara))

    output_file.close()
예제 #21
0
                                                      mutation=mutation,
                                                      sizeOfPopulation=10,
                                                      genPopulation=populationGen,
                                                      numberChromosome=NN, epoche=100,
                                                      data=data)
    ans = bga.fit()
    print(ans)"""

    data = GenMtrx_NN()  # инициализация условий задачи (считывание матрицы расстояний)
    NN = len(data)  # считываем количество городов
    fitness = Fitness.Fitness('fitness_population_NN')
    crossover = Crossover.Crossover('crossover_NN')
    # Можно выбрать: inbreeding_NN,
    #                 outbreeding_NN
    #                 panmixia_NN
    #                 tournament_selection_NN
    #                 roulette_selection_NN
    selection = Selection.Selection('inbreeding_NN')
    mutation = Mutation.Mutation('insertion_deleting_mutation_NN')
    populationGen = Population.Population('elite_selection')
    bga = BasicGeneticAlgorithm.BasicGeneticAlgorithm(generator=genPopulation_NN,
                                                      fitness=fitness,
                                                      crossover=crossover,
                                                      selection=selection,
                                                      mutation=mutation,
                                                      sizeOfPopulation=100,
                                                      genPopulation=populationGen,
                                                      numberChromosome=100, epoche=100,
                                                      data=data)
    ans = bga.fit()
    print(ans)
예제 #22
0
    print('----------------------------------')
    caminhos = []

    for item in demanda:
        caminhos.append(dijkstra_distances[item[0]][item[1]])

    todas_possibilidades = itertools.product(*caminhos)

    fitness_cromossomos = []

    for cromossomo in todas_possibilidades:
        fitness_cromossomos.append((fitness.calc_fitness(g, cromossomo), cromossomo))

    result = roulletweel_selection.roullet_wheel(fitness_cromossomos)
    print('ESCOLHA')
    print(result)
    print('MUTAÇÃO')
    chromosome = Mutation.mutation(g, result[1])
    print('----------------------------------')
    print("POPULAR DEMANDA")
    demand_generator.populate_demand(g, chromosome, [d[2] for d in demanda])
    paths = []
    for edge in g.edges:
        print(edge[0], edge[1], g[edge[0]][edge[1]]['LinkSpeedUsed'])
        paths.append([edge[0], edge[1], g[edge[0]][edge[1]]['LinkSpeedUsed']])
    print('----------------------------------')


import os
os.environ['PYTHONINSPECT'] = 'True'
예제 #23
0
def main():

    western29 = "Cities/TSP_WesternSahara_29.txt"
    uruguay734 = "Cities/TSP_Uruguay_734.txt"
    canada4663 = "Cities/TSP_Canada_4663.txt"

    popsize = 1000
    mating_pool_size = 800
    tournament_size = 3
    mut_rate = 0.2
    xover_rate = 0.9
    gen_limit = 100

    # choose the instance you are using ################################################################################
    instance_name = "WesternSahara"
    evolution_all = 10

    source = None
    city_all = 0

    if instance_name == "WesternSahara":
        city_all = 29
        source = western29
    if instance_name == "Uruguay":
        city_all = 734
        source = uruguay734
    if instance_name == "Canada":
        city_all = 4663
        source = canada4663

    experiment = {
        "description": {
            "instance_name": instance_name,
            "algorithm": "advanced",
            "city_all": city_all,
            "evolution_all": evolution_all,
            "generation_all": gen_limit,
            "generation_size": popsize
        },
        "evolutions": [
            # nothing yet
        ]
    }

    print(json.dumps(experiment))

    for evo in range(evolution_all):  # Experiment

        # construct a trial #
        trial = [{"time_cost": 0}]

        print("trial", evo + 1)

        start_time = time.time()

        print("Preparing for the information...")
        c = CityMap.CityMap(source)
        city_map = c.city_map
        print("preparation end.")

        gen = 0
        print("Initialize population...")
        init = Initialization.Population(popsize, city_map)
        init.evalPopulation()
        print("Initialization end.")

        # Evolution ########################################################################################################
        while gen < gen_limit:

            # parent selection ---------------------------------------------------------------------------------------------
            #print("parent selection...")
            parents = Selection.tournament_selection(init.population[1:],
                                                     mating_pool_size,
                                                     tournament_size)
            #print("parent selection end.")

            offsprings = []
            i = 0
            while len(offsprings
                      ) < mating_pool_size:  # 2 parents  ->  2 individuals
                p1 = parents[i]
                p2 = parents[i + 1]

                # crossover ------------------------------------------------------------------------------------------------
                #print("crossover...")
                if random.random() < xover_rate:
                    #off1, off2 = Crossover.COWGC(p1, p2, city_map)
                    off1, off2 = Crossover.order_crossover(p1, p2, city_map)
                else:
                    off1 = copy.copy(p1)
                    off2 = copy.copy(p2)
                #print("crossover end")

                # mutation ------------------------------------------------------------------------------------------------
                #print("Mutation...")
                if random.random() < mut_rate:
                    off1 = Mutation.WGWWGM(p1, city_map)
                    #off1 = Mutation.WGWRGM(p1, city_map)
                    #off1 = Mutation.IRGIBNNM_mutation(p1, city_map)
                    #off1 = Mutation.inversion_mutation(p1, city_map)
                if random.random() < mut_rate:
                    off2 = Mutation.WGWWGM(p2, city_map)
                    #off2 = Mutation.WGWRGM(p2, city_map)
                    #off2 = Mutation.IRGIBNNM_mutation(p2, city_map)
                    #off2 = Mutation.inversion_mutation(p2, city_map)
                #print("Mutation end")

                offsprings.append(off1)
                offsprings.append(off2)
                #print(len(offsprings))

                i += 2

            # survial selection --------------------------------------------------------------------------------------------
            #print("survival selection")
            init.population[1:] = Selection.mu_plus_lambda(
                init.population[1:], offsprings)
            #print("survival selection end")

            init.evalPopulation()

            print("generation:", gen, " Average length:", init.AverageLength,
                  " Longest length: ", init.worstTour.length,
                  " shortest length:", init.bestTour.length)

            # construct a generation #
            generation = {
                "best-individual-sequence":
                init.bestTour.tour,
                "best-individual-distance":
                init.bestTour.length,
                "worst-individual-sequence":
                init.worstTour.tour,
                "worst-individual-distance":
                init.worstTour.length,
                "average-distance":
                init.AverageLength,
                "individual-distances":
                [round(distance.length) for distance in init.population
                 ]  # distance.length for distance in init.population
            }

            trial.append(generation)

            gen += 1

            trial[0]["time_cost"] = time.time() - start_time

        experiment["evolutions"].append(trial)

    # here processing generating json file #############################################################################

    output_file = None
    variable_declaration = "none"

    if instance_name == "WesternSahara":
        output_file = open("advanced_WesternSahara.js", "w")
        variable_declaration = "let advanced_WesternSahara = "
    if instance_name == "Uruguay":
        output_file = open("advanced_Uruguay.js", "w")
        variable_declaration = "let advanced_Uruguay = "
    if instance_name == "Canada":
        output_file = open("advanced_Canada.js", "w")
        variable_declaration = "let advanced_Canada = "

    output_file.write(variable_declaration)
    output_file.write(json.dumps(experiment))

    output_file.close()
예제 #24
0
파일: Main.py 프로젝트: Wolff-H/COMP-3-201
def main():

    western29 = "Cities/TSP_WesternSahara_29.txt"
    uruguay734 = "Cities/TSP_Uruguay_734.txt"
    canada4663 = "Cities/TSP_Canada_4663.txt"

    popsize = 10000
    mating_pool_size = 8000
    tournament_size = 3
    mut_rate = 0.2
    xover_rate = 0.9
    gen_limit = 10000

    print("Preparing for the information...")
    c = CityMap.CityMap(uruguay734)
    city_map = c.city_map
    print("preparation end.")

    gen = 0
    print("Initialize population...")
    init = Initialization.Population(popsize, city_map)
    init.evalPopulation()
    print("Initialization end.")

    #EA algorithm
    while gen < gen_limit:

        #parent selection
        #print("parent selection...")
        parents = Selection.tournament_selection(init.population[1:],
                                                 mating_pool_size,
                                                 tournament_size)
        #parents = Selection.random_selection(init.population[1:], mating_pool_size)
        #parents = Selection.MPS(init.population[1:], mating_pool_size)

        offsprings = []
        i = 0
        while len(
                offsprings) < mating_pool_size:  # 2 parents  ->  2 individuals
            p1 = parents[i]
            p2 = parents[i + 1]

            # crossover ################################################################################################
            #print("crossover...")
            if random.random() < xover_rate:
                #off1, off2 = Crossover.COWGC(p1, p2, city_map)
                off1, off2 = Crossover.order_crossover(p1, p2, city_map)
            else:
                off1 = copy.copy(p1)
                off2 = copy.copy(p2)
            #print("crossover end")

            # mutation #################################################################################################
            #print("Mutation...")
            if random.random() < mut_rate:
                off1 = Mutation.WGWWGM(p1, city_map)
                #off1 = Mutation.WGWRGM(p1, city_map)
                #off1 = Mutation.IRGIBNNM_mutation(p1, city_map)
                #off1 = Mutation.inversion_mutation(p1, city_map)
            if random.random() < mut_rate:
                off2 = Mutation.WGWWGM(p2, city_map)
                #off2 = Mutation.WGWRGM(p2, city_map)
                #off2 = Mutation.IRGIBNNM_mutation(p2, city_map)
                #off2 = Mutation.inversion_mutation(p2, city_map)
            #print("Mutation end")

            offsprings.append(off1)
            offsprings.append(off2)
            #print(len(offsprings))

            i += 2

        # survial selection ############################################################################################
        #print("survival selection")
        init.population = Selection.mu_plus_lambda(init.population, offsprings)

        init.evalPopulation()

        print("generation:", gen, " Average length:", init.AverageLength,
              " Longest length: ", init.worstTour.length, " shortest length:",
              init.bestTour.length)

        gen += 1
예제 #25
0
class Algorithm:
    def __init__(self, params):
        self.epochs = params['epochs']
        self.Crossover = Crossover(params['crossover_type'],
                                   params['crossover_prob'])
        self.Population = Population(booth_function, params['population_size'],
                                     2, -10, 10,
                                     params['population_precision'])
        self.Mutation = Mutation(params['mutation_type'],
                                 params['mutation_prob'])
        self.Inversion = Inversion(params['inversion_type'],
                                   params['inversion_prob'])
        self.Selection = Selection(params['selection_type'],
                                   params['selection_prob'])
        self.EliteStrategy = EliteStrategy(params['elite_prob'])

    def fill_selected_population(self, selected):
        new_pop = []
        pop_size = self.Population.population_size

        for _ in range(pop_size):
            new_pop.append(random.choice(selected))

        return np.array(new_pop)

    def run(self):
        best_value = []
        avg_value = []
        std_avg_value = []
        best_individual = []

        pop = self.Population.generate_population()
        time_start = time.time()
        for i in range(self.epochs):
            # print(i)
            # dla kazdej epoki
            # ocen populacje (evaluate)
            fitness = self.Population.evaluate_population(pop)

            # zapisz wartosci do wygenerowania wykresow
            best_value.append(fitness.min())
            avg_value.append(fitness.mean())
            std_avg_value.append(fitness.std())
            index_best = fitness.argsort()[0]
            best_individual.append(
                self.Population.decode_population(pop)[index_best])

            # zapisz % najlepszych (strategia elitarna)
            elite = self.EliteStrategy.elite(pop, fitness)
            # wybierz gatunki do crossowania (selection)
            selected, not_selected = self.Selection.select(pop, fitness)
            # krzyzowanie gatunków (cross)
            if self.Selection.decision != 'roulette_wheel':
                selected = self.fill_selected_population(selected)
            pop = self.Crossover.cross(selected)
            # mutacja i/lub inversja
            pop = self.Mutation.mutate(pop)
            pop = self.Inversion.inverse(pop)
            # jezeli strategia elitarna jest uzywana
            if elite.shape[0] != 0:
                #  polacz najlepszy % z populacja
                pop = np.concatenate(
                    (pop[:-elite.shape[0]], elite))  # , axis=0

        time_execution = time.time() - time_start
        # print(f"Algorytm zajął {time_execution:.3f} sekund")

        Plot.draw_save_plot(
            best_value, 'Numer epoki', 'Wartość funkcji',
            'Wykres wartości funkcji dla najlepszych osobników',
            'best_individual')
        Plot.draw_save_plot(avg_value, 'Numer epoki', 'Wartość funkcji',
                            'Wykres średniej wartości funkcji dla populacji',
                            'avg_pop')
        Plot.draw_save_plot(std_avg_value, 'Numer epoki',
                            'Wartość odchylenia standardowego',
                            'Wykres odchylenia standardowego dla populacji',
                            'avg_std_pop')
        Files.numpy_to_csv(best_individual, 'best_individual.csv')

        return time_execution, best_value[-1]
예제 #26
0
파일: Main.py 프로젝트: Wolff-H/COMP-3-201
def main():

    western29 = "Cities/TSP_WesternSahara_29.txt"
    uruguay734 = "Cities/TSP_Uruguay_734.txt"
    canada4663 = "Cities/TSP_Canada_4663.txt"

    popsize = 500
    mating_pool_size = 100
    tournament_size = 3
    mut_rate = 0.2
    xover_rate = 0.9
    gen_limit = 15

    print("Preparing information...")
    c = CityMap.CityMap(western29 )
    city_map = c.city_map
    print("preparation end.")

    gen = 0
    init = Initialization.Population(popsize, city_map)
    population = init.population

    #EA algorithm
    while gen < gen_limit:

        #parent selection
        #print("parent selection...")
        parents = Selection.tournament_selection(population, mating_pool_size, tournament_size)
        #print("parent selection end.")

        offsprings = []
        i = 0
        while len(offsprings) < mating_pool_size:
            p1 = parents[i][0]
            p2 = parents[i + 1][0]

            #crossover
            #print("crossover...")
            if random.random() < xover_rate:
                off1, off2 = Crossover.COWGC(p1, p2, city_map)
            else:
                off1 = copy.copy(p1)
                off2 = copy.copy(p2)
            #print("crossover end")

            #mutation
            #print("Mutation...")
            if random.random() < mut_rate:
                off1 = Mutation.WGWWGM(p1, city_map)
            if random.random() < mut_rate:
                off2 = Mutation.WGWWGM(p2, city_map)
            #print("Mutation end")

            offsprings.append([off1, off1.fitness])
            offsprings.append([off2, off2.fitness])

            i += 2

        #survial selection
        #print("survival selection")
        population = Selection.mu_plus_lambda(population, offsprings)
        #print("survival selection end")

        best_fitness = population[0][1]
        best_tour = population[0][0].tour
        tour_length = population[0][0].length
        for i in population:
            if i[0].length < tour_length:
                best_fitness = i[1]
                best_tour = i[0].tour
                tour_length = i[0].length
        print("generation: ", gen, " best fitness: ", best_fitness, " length: ", tour_length)

        gen += 1