Esempio n. 1
0
def main():

	random.seed()

	ga = GenAlg( size=popsize,
		elitism      = 0.03,
		crossover    = 0.47,
		pureMutation = 0.50,
		selectionFcn = GenAlgOps.simpleSelectionParentPct,
		crossoverFcn = GenAlgOps.crossover22,
		mutationFcn = GenAlgOps.mutateFew,
		# for pure-mutation of all chromos .. no need to run tournament selection
		# pureMutationSelectionFcn = lambda x: [0,0],
		# pureMutationFcn = GenAlgOps.mutateAll,
		chromoClass  = MyChromo,
		minOrMax     = 'max',
		showBest     = 0,
		# optional params ..
		params       = {
			'mutateNum': 3,    # for mutateFew .. make 2 mutations each time
			'parentPct': 0.50  # for parent-pct .. only top 50% of chromos are eligible as parents
		},
	)

	ga.describe()
	#print( 'random state', random.getstate() )

	#
	# if a data-file exists, we load it
	if( os.path.isfile('ga_mathsq.dat') ):
		pop = IoOps.loadPopulation( ga, 'ga_mathsq.dat' )
		ga.appendToPopulation( pop )
		print( 'Read init data from file ('+str(len(pop))+' chromos)')
	else:
		# otherwise, init the gen-alg library from scratch
		ga.initPopulation()
		print( 'Created random init data' )

	#
	# Run it !!
	# : we'll just do 10 epochs of 10 steps each
	for i in range( outeriter ):
		ga.evolve( inneriter )
		sys.stdout.write( '.' )
		sys.stdout.flush()

	#
	# all done ... output final results
	print( "\nfinal best chromo: " + str(ga.population[0].fitness) )
	ga.population[0].showGrid()
	debuglevel = 100
	ga.population[0].calcFitness()

	#
	# we'll always save the pickle-file, just delete it
	# if you want to start over from scratch
	IoOps.savePopulation( ga, 'ga_mathsq.dat' )
	print('Final data stored to file (rm ga_mathsq.dat to start fresh)')
Esempio n. 2
0
def main():

    ga = GenAlg(
        size=100,
        elitism=0.10,
        crossover=0.60,
        pureMutation=0.30,
        chromoClass=MyChromo,
        #selectionFcn = GenAlgOps.tournamentSelection,
        #crossoverFcn = GenAlgOps.crossover22,
        #mutationFcn  = GenAlgOps.mutateFew,
        #pureMutationSelectionFcn = GenAlgOps.simpleSelection,
        #pureMutationFcn = GenAlgOps.mutateFew,
        #feasibleSolnFcn = GenAlgOps.disallowDupes,
        minOrMax='max',
        showBest=0,
    )
    ga.describe()

    #
    # if a data-file exists, we load it
    if (False and os.path.isfile('ga_hello.dat')):
        pop = IoOps.loadPopulation(ga, 'ga_hello.dat')
        ga.appendToPopulation(pop)
        print('Read init data from file (' + str(len(pop)) + ' chromos)')
    else:
        # otherwise, init the gen-alg library from scratch
        ga.initPopulation()
        print('Created random init data')

    #
    # Run it !!
    # : we'll just do 10 epochs of 10 steps each
    for i in range(10):
        ga.evolve(10)

        # give some running feedback on our progress
        print('iter ' + str(i) + ", best chromo:")
        for i in range(10):
            print(ga.population[i])

    #
    # all done ... output final results
    print("\nfinal best chromos:")
    for i in range(10):
        print(ga.population[i])

    #
    # we'll always save the pickle-file, just delete it
    # if you want to start over from scratch
    IoOps.savePopulation(ga, 'ga_hello.dat')
    print('Final data stored to file (rm ga_hello.dat to start fresh)')
Esempio n. 3
0
def main():
    global debuglevel

    ga = GenAlg(size=250,
                elitismPct=0.10,
                crossoverPct=0.30,
                mutationPct=0.60,
                chromoClass=MyChromo,
                minOrMax='max',
                showBest=0)

    #
    # if a data-file exists, we load it
    if (os.path.isfile('ga_maze.dat')):
        pop = IoOps.loadPopulation(ga, 'ga_maze.dat')
        ga.appendToPopulation(pop)
        print('Read init data from file (' + str(len(pop)) + ' chromos)')
    else:
        # otherwise, init the gen-alg library from scratch
        ga.initPopulation()
        print('Created random init data')

    #
    # Run it !!
    # : we'll just do 10 epochs of 10 steps each
    for i in range(10):
        ga.evolve(100)
        sys.stdout.write('.')
        sys.stdout.flush()

    #
    # all done ... output final results
    print("\nfinal best chromo: " + str(ga.population[0].fitness))
    ga.population[0].showGrid()
    debuglevel = 100
    ga.population[0].calcFitness()

    #
    # we'll always save the pickle-file, just delete it
    # if you want to start over from scratch
    IoOps.savePopulation(ga, 'ga_maze.dat')
    print('Final data stored to file (rm ga_maze.dat to start fresh)')
Esempio n. 4
0
def run(ctx):
    ctxobj = ctx.obj
    verbose = ctxobj.get('verbose')
    epoch_it = ctxobj.get('epoch_it')
    inner_it = ctxobj.get('inner_it')

    ga = GenAlg(
        size=ctxobj.get('popsize'),
        elitism=ctxobj.get('elitism'),
        crossover=ctxobj.get('crossover'),
        pureMutation=ctxobj.get('puremutation'),
        chromoClass=MyChromo,
        #selectionFcn = GenAlgOps.tournamentSelection,
        crossoverFcn=MyCrossover212,
        mutationFcn=GenAlgOps.mutateNone,
        # for pure-mutation of all chromos .. no need to run tournament selection
        #pureMutationSelectionFcn = lambda x: [0,0],
        #pureMutationFcn = GenAlgOps.mutateAll,
        pureMutationSelectionFcn=GenAlgOps.simpleSelectionParentPct,
        pureMutationFcn=MyMutate,
        feasibleSolnFcn=GenAlgOps.disallowDupes,
        minOrMax='min',
        showBest=0,
        # optional params ..
        params={
            'mutateNum': ctxobj.get('mutatenum'),
            'parentPct': 0.50,
        })

    #
    # if a data-file exists, we load it
    if (ctxobj.get('load_in')):
        pop = IoOps.loadPopulation(ga, 'ga_cpu.dat')
        ga.appendToPopulation(pop)
        print('Read init data from file (' + str(len(pop)) + ' chromos)')
    else:
        # otherwise, init the gen-alg library from scratch
        ga.initPopulation()
        print('Created random init data')

        # add some 'good' candidate solns ... ROM0*XYZ0, ROM1*XYZ1, etc.
        cpu = ga.population[0].cpu
        prog = cpu.compile(['ROM0', 'XYZ0', 'MPY', 'ROM1', 'XYZ1', 'MPY'])
        for i in range(0, prog_size - 6):
            ga.population[i].data[-len(prog):] = prog

    if (verbose > 0):
        ga.describe()
        print('Chromo size: %d :: %d %d' %
              (len(ga.population[0].data), prog_size, rom_size))
        print('Epoch/Inner iters:', epoch_it, inner_it)
        print('Instruction set:',
              ' '.join(ga.population[0].cpu.PARSEops.keys()))

    #
    # Run it !!
    # : we'll just do 10 epochs of 10 steps each
    for i in range(epoch_it):
        print('it=', i, time.time())
        ga.evolve(inner_it)

        # give some running feedback on our progress
        txt = ''
        for j in range(10):
            txt = txt + ' %d' % (ga.population[j].fitness)
        print('iter ' + str(i) + ", best fitnesses:" + txt)
        print('    ' + ga.population[0].cpu.show_prog(show_pc=False, nl='/') +
              ' :: ' + ga.population[0].cpu.dump_rommemory())
        print('    ' + ga.population[0].cpu.show_prog_as_func())

    #
    # all done ... output final results
    print("\nfinal best chromos:")
    for i in range(5):
        #print( ga.population[i] )
        print('  fit=%d' % (ga.population[i].fitness))
        print('    ' + ga.population[i].cpu.show_prog(show_pc=False, nl='/') +
              ' :: ' + ga.population[i].cpu.dump_rommemory())
        print('    ' + ga.population[i].cpu.show_prog_as_func())

    #
    # we'll always save the pickle-file, just delete it
    # if you want to start over from scratch
    if (ctxobj.get('save_out')):
        IoOps.savePopulation(ga, 'ga_cpu.dat')
        print('Final data stored to file (rm ga_cpu.dat to start fresh)')
Esempio n. 5
0
    def run(self):
        print('TID start')
        sys.stdout.flush()

        tid = self.tid
        num_pes = self.num_pes
        commMgr = self.commMgr
        # TODO: maybe this is an MPI_INIT kind of functionality?

        print('TID' + str(tid) + ' started (out of ' + str(num_pes) + ')')
        sys.stdout.flush()

        # TODO: calculate the splitting across the PEs

        # otherwise, init the gen-alg library from scratch
        ga = GenAlg(size=1000,
                    elitism=0.10,
                    crossover=0.50,
                    pureMutation=0.35,
                    migration=0.05,
                    migrationSendFcn=self.migrationSendFcn,
                    migrationRecvFcn=self.migrationRecvFcn,
                    parents=0.80,
                    chromoClass=MyChromo,
                    minOrMax='max',
                    showBest=0)

        #
        # if a pickle-file exists, we load it
        if (os.path.isfile('ga_sprinkler.dat')):
            # in a parallel sim, we need to load different chunks of the data-file
            # into each TID .. so we need to manage this through the commMgr
            # pop = IoOps.loadPopulation( ga, 'ga_sprinkler.dat' )
            pop = commMgr.loadPopulation(ga, 'ga_sprinkler.dat')
            ga.appendToPopulation(pop)
            print('Read init data from file (' + str(len(pop)) + ' chromos)')
        else:
            # otherwise, init the gen-alg library from scratch
            ga.initPopulation()
            print('Created random init data')

        #
        # Run it !!
        # : we'll just do 10 epochs of 10 steps each
        for i in range(10):
            ga.evolve(10)

            # give some running feedback on our progress
            print('iter ' + str(i) + ", best chromo:")
            for i in range(1):
                print(ga.population[i])

        # at this point, each PE's population is sorted
        rtn = commMgr.collect(ga.population[:10])
        # rtn is a list of lists ... flatten it
        bestVals = [x for y in rtn for x in y]
        bestVals = ga.sortPopulationList(bestVals)

        #
        # all done ... output final results
        if (tid == 0):
            print("\nfinal best chromos:")
            for i in range(1):
                print(bestVals[i])
            bestVals[0].drawImage()

        commMgr.savePopulation(ga, 'ga_sprinkler.dat')
Esempio n. 6
0
def main():

    ga = GenAlg(
        size=100,
        elitism=0.10,
        crossover=0.60,
        pureMutation=0.30,
        chromoClass=MyChromo,
        #selectionFcn = GenAlgOps.tournamentSelection,
        #crossoverFcn = GenAlgOps.crossover22,
        #mutationFcn  = GenAlgOps.mutateFew,
        #pureMutationSelectionFcn = GenAlgOps.simpleSelection,
        #pureMutationFcn = GenAlgOps.mutateFew,
        #feasibleSolnFcn = GenAlgOps.disallowDupes,
        minOrMax='min',
        showBest=0,
    )

    #
    # if a pickle-file exists, we load it
    if (os.path.isfile('ga_voting2.dat')):
        pop = IoOps.loadPopulation(ga, 'ga_voting2.dat')
        ga.appendToPopulation(pop)
        print('Read init data from file (' + str(len(pop)) + ' chromos)')
        if (len(pop) < ga.population_sz):
            # we need to fill this out with random data
            pop = IoOps.randomPopulation(ga, ga.population_sz - len(pop))
            ga.appendToPopulation(pop)
            print('  appended ' + str(len(pop)) + ' random chromos')
    else:
        # otherwise, init the gen-alg library from scratch
        ga.initPopulation()
        print('Created random init data')

    #
    # Run it !!
    # : we'll just do 10 epochs of 10 steps each
    for i in range(10):
        ga.evolve(10)

        # give some running feedback on our progress
        print(str(i) + " best chromo:")
        for i in range(1):
            print(ga.population[i])

    #
    # all done ... output final results
    print("\nfinal best chromos:")
    for i in range(1):
        pop = ga.population[i]
        # print( ga.population[i] )
        pop_ct = pop.population_per_district()
        for j in range(len(pop_ct)):
            ct = pop_ct[j]
            x = pop.data[2 * j]
            y = pop.data[2 * j + 1]
            print('  %10.4f %10.4f : %10d' % (x, y, ct))
    ga.population[0].drawImage()

    ga.population[0].drawImage(showCurrent=True)
    #
    # we'll always save the pickle-file, just delete it
    # if you want to start over from scratch
    IoOps.savePopulation(ga, 'ga_voting2.dat')
    print('Final data stored to file (rm ga_voting2.dat to start fresh)')