コード例 #1
0
ファイル: ga_sprinkler.py プロジェクト: jbp4444/PyGenAlg
def analyze(ctx):
    ctxobj = ctx.obj

    ga = GenAlg(
        chromoSize=3 * num_sprayers,
        dtype=np.float32,
        range=dataRanges,
        fitnessFcn=calcFitness,
        crossoverFcn=crossover,
        userDataI=cutout_region,  # user-provided cut-out region
        userDataF=scoring,  # user-provided scoring system
        size=128,
        elitism=ctxobj.get('elitism'),
        crossover=ctxobj.get('crossover'),
        pureMutation=ctxobj.get('puremutation'),
        minOrMax='max',
        showBest=0)

    # otherwise, init the gen-alg library from scratch
    ga.initPopulation()

    ga.describe()

    # Run it !!
    ga.evolve(1)

    ga.cudaAnalysis()
コード例 #2
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)')
コード例 #3
0
ファイル: ga_hello.py プロジェクト: jbp4444/PyGenAlg
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)')
コード例 #4
0
def test1(ctx):
    ctxobj = ctx.obj
    verbose = ctxobj.get('verbose')

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

    # otherwise, init the gen-alg library from scratch
    ga.initPopulation()
    print('Created random init data')

    # simulate a cross-over
    mother = ga.population[0]
    print('mother', str(mother))
    father = ga.population[1]
    print('father', str(father))
    children = ga.crossoverFcn(mother, father, ga.params)
    for child in children:
        print('child', str(child))

    asm_prog = [
        'ROM0', 'XYZ0', 'MPY', 'ROM1', 'XYZ1', 'MPY', 'ADD', 'ROM2', 'ADD'
    ]
    prog = ga.population[2].cpu.compile(asm_prog)
    print('prog', prog)
    prog.extend([1, 1, 1])  # add the 3 rom/coeffs
    # but make these the last N steps of prog, so the output _is_ the prog output
    ga.population[2].data[-len(prog):] = prog
    fit = ga.population[2].calcFitness()
    print('code', ga.population[2].cpu.show_prog(show_pc=False, nl='/'))
    print('code', ga.population[2].cpu.show_prog_as_func())
    print('fitness', fit)
コード例 #5
0
ファイル: ga_cpuDAG.py プロジェクト: jbp4444/PyGenAlg
def test1(ctx):
    ctxobj = ctx.obj
    verbose = ctxobj.get('verbose')

    ga = GenAlg(
        size=4,
        elitism=ctxobj.get('elitism'),
        crossover=ctxobj.get('crossover'),
        pureMutation=ctxobj.get('puremutation'),
        chromoClass=MyChromo,
        #selectionFcn = GenAlgOps.tournamentSelection,
        crossoverFcn=GenAlgOps.crossover12,
        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=GenAlgOps.mutateAll,
        #feasibleSolnFcn = GenAlgOps.disallowDupes,
        minOrMax='min',
        showBest=0,
        # optional params ..
        params={
            'mutateNum': ctxobj.get('mutatenum'),
            'parentPct': 0.50,
        })

    # otherwise, init the gen-alg library from scratch
    ga.initPopulation()
    print('Created random init data')

    mother = ga.population[0]
    mother.fitness = mother.calcFitness()
    print('mother', str(mother))
    #print( '   ', mother.dataRange )
    print('   ', mother.cpu.show_prog_as_func())

    father = ga.population[1]
    father.fitness = father.calcFitness()
    print('father', str(father))
    #print( '   ', father.dataRange )
    print('   ', father.cpu.show_prog_as_func())

    # simulate a cross-over
    children = ga.crossoverFcn(mother, father, ga.params)
    for child in children:
        child.fitness = child.calcFitness()
        print('child', str(child))
コード例 #6
0
ファイル: ga_maze.py プロジェクト: jbp4444/PyGenAlg
def main():
    global debuglevel

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

    #
    # if a data-file exists, we load it
    if (os.path.isfile('ga_maze.dat')):
        ga.loadPopulation('ga_maze.dat')
        print('Read init data from file')
    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
    ga.savePopulation('ga_maze.dat')
    print('Final data stored to file (rm ga_maze.dat to start fresh)')
コード例 #7
0
ファイル: test_roulette.py プロジェクト: jbp4444/PyGenAlg
def main():

    sims = [('max', MyChromoPos), ('min', MyChromoPos), ('max', MyChromoNeg),
            ('min', MyChromoNeg)]

    for s in sims:
        print(s)
        ga = GenAlg(
            size=10,
            elitism=0.10,
            crossover=0.60,
            pureMutation=0.30,
            parentsPct=0.80,
            chromoClass=s[1],
            #selectionFcn = GenAlgOps.tournamentSelection,
            #crossoverFcn = GenAlgOps.crossover22,
            #mutationFcn  = GenAlgOps.mutateFew,
            #pureMutationSelectionFcn = GenAlgOps.simpleSelection,
            #pureMutationFcn = GenAlgOps.mutateFew,
            #feasibleSolnFcn = GenAlgOps.disallowDupes,
            minOrMax=s[0],
            showBest=0,
        )

        ga.initPopulation()
        for i in range(10):
            if (s[1] == MyChromoNeg):
                ga.population[i].data[0] = -i - 1
            else:
                ga.population[i].data[0] = i + 1
        ga.calcFitness()
        ga.sortPopulation()
        printGaPopulation(ga)

        counts = [0 for i in range(10)]

        for i in range(10000):
            idx1, idx2 = GenAlgOps.rouletteWheelSelection(ga)
            counts[idx1] = counts[idx1] + 1
            counts[idx2] = counts[idx2] + 1
        print('     roulette counts = ' + str(counts))

        counts = [0 for i in range(10)]

        for i in range(10000):
            idx1, idx2 = GenAlgOps.rankSelection(ga)
            counts[idx1] = counts[idx1] + 1
            counts[idx2] = counts[idx2] + 1
        print('     rank counts = ' + str(counts))
コード例 #8
0
ファイル: ga_coins.py プロジェクト: jbp4444/PyGenAlg
def main():

    ga = GenAlg(chromoSize=4,
                dtype=np.int32,
                range=(0, 10),
                fitnessFcn=calcFitness,
                crossoverFcn=crossover2,
                size=1024,
                elitism=0.10,
                crossover=0.60,
                pureMutation=0.30,
                minOrMax='max',
                showBest=0)

    #
    # if a data-file exists, we load it
    if (os.path.isfile('ga_coins.dat')):
        pop = IoOps.loadPopulation(ga, 'ga_coins.dat')
        ga.loadPopulation(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:")
        print(ga.population[range(4)], ga.fitnessVals[0])

    #
    # all done ... output final results
    print("\nfinal best chromos:")
    print(ga.population[range(4)], ga.fitnessVals[0])
    print(ga.population[range(4, 8)], ga.fitnessVals[1])

    #
    # we'll always save the pickle-file, just delete it
    # if you want to start over from scratch
    IoOps.savePopulation(ga, 'ga_coins.dat')
    print('Final data stored to file (rm ga_coins.dat to start fresh)')
コード例 #9
0
ファイル: test_gamgr.py プロジェクト: jbp4444/PyGenAlg
def main():

    ga = GenAlg(
        size=10,
        elitism=0.10,
        crossover=0.60,
        pureMutation=0.30,
        parentsPct=0.80,
        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.initPopulation()
    ga.calcFitness()

    child = MyChromo()
    child.data[0] = ga.population[4].data[0]
    child.fitness = ga.population[4].fitness
    feas = GenAlgOps.disallowDupes(ga, child)
    print('unsorted population; data present; feas=', feas)
    child.data[0] = ga.population[4].data[0] + 9
    child.fitness = ga.population[4].fitness + 9
    feas = GenAlgOps.disallowDupes(ga, child)
    print('unsorted population; data not present; feas=', feas)

    ga.sortPopulation()
    child.data[0] = ga.population[4].data[0]
    child.fitness = ga.population[4].fitness
    feas = GenAlgOps.disallowDupes(ga, child)
    print('sorted population; data at pos=4; feas=', feas)
    child.data[0] = ga.population[4].data[0] + 9
    child.fitness = ga.population[4].fitness + 9
    feas = GenAlgOps.disallowDupes(ga, child)
    print('sorted population; data not present; feas=', feas)
コード例 #10
0
    def run(self):
        tid = self.tid
        num_pes = self.num_pes
        parMgr = self.parMgr
        # TODO: maybe this is an MPI_INIT kind of functionality?
        # : e.g. store this worker-tid into parMgr; init per-worker values
        parMgr.tid = tid

        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=100,
                    elitismPct=0.10,
                    crossoverPct=0.30,
                    mutationPct=0.50,
                    migrationPct=0.10,
                    migrationFcn=self.migrationFcn,
                    chromoClass=MyChromo,
                    minOrMax='max',
                    showBest=0)
        ga.initPopulation()
        #ga.loadPopulation( 'ga_data.dat' )

        #
        # Run it !!
        # : we'll just do 10 epochs of 10 steps each
        for i in range(10):
            print('pop_sz=' + str(len(ga.population)))
            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 = parMgr.collect(ga.population[:10])
        bestVals = [x for y in rtn for x in y]
        bestVals.sort()

        #
        # all done ... output final results
        print("\nfinal best chromos:")
        for i in range(10):
            print(bestVals[i])
コード例 #11
0
ファイル: ga_sprinkler.py プロジェクト: jbp4444/PyGenAlg
def sweep(ctx, sweep_iters, append, outfile):
    ctxobj = ctx.obj
    verbose = ctxobj.get('verbose')
    epoch_it = ctxobj.get('epoch_it')
    inner_it = ctxobj.get('inner_it')

    ga = GenAlg(
        chromoSize=3 * num_sprayers,
        dtype=np.float32,
        range=dataRanges,
        fitnessFcn=calcFitness,
        crossoverFcn=crossover,
        userDataI=cutout_region,  # user-provided cut-out region
        userDataF=scoring,  # user-provided scoring system
        size=ctxobj.get('popsize'),
        elitism=ctxobj.get('elitism'),
        crossover=ctxobj.get('crossover'),
        pureMutation=ctxobj.get('puremutation'),
        parentPct=ctxobj.get('parent_pct'),
        minOrMax='max',
        showBest=0)

    if (append):
        fp_out = open(append, 'a')
    elif (outfile):
        fp_out = open(outfile, 'w')
    else:
        fp_out = sys.stdout

    if (verbose > 0):
        print('Epoch/Inner iters:', epoch_it, inner_it)
        print('Sweep iters:', sweep_iters)

    for m in range(sweep_iters):
        ga.initPopulation()

        with click.progressbar(range(epoch_it)) as bar:
            for i in bar:
                ga.evolve(inner_it)

        fp_out.write('%d, %d, %d, %f\n' %
                     (ga.population_sz, epoch_it, inner_it, ga.fitnessVals[0]))

    fp_out.close()
コード例 #12
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,
    )

    # 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(100):
        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(3):
        print(ga.population[i])
コード例 #13
0
ファイル: ga_sprinkler_par.py プロジェクト: jbp4444/PyGenAlg
    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')
コード例 #14
0
ファイル: ga_sprinkler.py プロジェクト: jbp4444/PyGenAlg
def thresh(ctx, sweep_iters, threshold, append, outfile):
    ctxobj = ctx.obj
    verbose = ctxobj.get('verbose')
    epoch_it = ctxobj.get('epoch_it')
    inner_it = ctxobj.get('inner_it')

    if (append):
        fp_out = open(append, 'a')
    elif (outfile):
        fp_out = open(outfile, 'w')
    else:
        fp_out = sys.stdout

    maxspray = 0.0
    for i in range(num_sprayers):
        maxspray = maxspray + 3.1415 * dataRanges[3 * i + 2][1] * dataRanges[
            3 * i + 2][1]
    maxfield = 100 * 100 - cutout_region[0] * cutout_region[1]
    mx = max(scoring)

    if (threshold < 1):
        threshold = threshold * mx * maxspray

    # find all the pairs of vals to test
    test_list = []
    for m in range(sweep_iters):
        for pp in range(1, 11):
            for ps in [1024, 2048, 4096, 8192, 16384, 32768]:
                test_list.append((ps, pp / 10, m))

    if (verbose > 0):
        print('Epoch/Inner iters:', epoch_it, inner_it)
        print('Sweep iters:', sweep_iters)
        print('Threshold: %.2f' % (threshold))
        print('Max spray: %.2f  ( %d )' % (mx * maxspray, mx * maxfield))
        print('Total num tests:', len(test_list))

    # run the tests w/ progress bar
    with click.progressbar(test_list) as bar:
        for params in bar:
            # print( 'params', params )

            ga = GenAlg(
                chromoSize=3 * num_sprayers,
                dtype=np.float32,
                range=dataRanges,
                fitnessFcn=calcFitness,
                crossoverFcn=crossover,
                userDataI=cutout_region,  # user-provided cut-out region
                userDataF=scoring,  # user-provided scoring system
                size=params[0],
                elitism=ctxobj.get('elitism'),
                crossover=ctxobj.get('crossover'),
                pureMutation=ctxobj.get('puremutation'),
                parentPct=params[1],
                minOrMax='max',
                showBest=0)

            ga.initPopulation()

            totalits = 0
            flag = 0
            for e in range(epoch_it):
                ga.evolve(inner_it)
                totalits = totalits + inner_it

                if (ga.fitnessVals[0] >= threshold):
                    flag = 1
                    break

            fp_out.write(
                '%d, %d, %d, %d, %.2f, %d, %d, %.2f\n' %
                (ga.population_sz, ga.elitism, ga.crossover, ga.pureMutation,
                 ga.parent_pct, flag, totalits, ga.fitnessVals[0]))
            fp_out.flush()

    fp_out.close()
コード例 #15
0
    def run(self):
        tid = self.tid
        num_pes = self.num_pes
        parMgr = self.parMgr
        # TODO: maybe this is an MPI_INIT kind of functionality?
        # : e.g. store this worker-tid into parMgr; init per-worker values
        parMgr.tid = tid

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

        # TODO: calculate the splitting across the PEs

        ga = GenAlg(
            size=250,
            elitismPct=0.10,
            crossoverPct=0.30,
            mutationPct=0.50,
            migrationPct=0.10,
            #selectionFcn = GenAlgOps.tournamentSelection,
            #crossoverFcn = GenAlgOps.crossover22,
            #mutationFcn  = GenAlgOps.mutateFew,
            #pureMutationSelectionFcn = GenAlgOps.simpleSelection,
            #pureMutationFcn = GenAlgOps.mutateFew,
            #feasibleSolnFcn = GenAlgOps.disallowDupes,
            migrationSendFcn=self.migrationSend,
            migrationRecvFcn=self.migrationRecv,
            chromoClass=MyChromo,
            minOrMax='min',
            showBest=0)

        # 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
        t0 = time.time()
        for i in range(15):
            ga.evolve(10)

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

        t1 = time.time()
        print('TID' + str(tid) + ' time = ' + str(t1 - t0) + ' sec')

        # at this point, each PE's population is sorted
        rtn = parMgr.collect(ga.population[:10])
        bestVals = [x for y in rtn for x in y]
        bestVals.sort()

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

            bestVals[0].drawImage()
コード例 #16
0
ファイル: ga_sprinkler.py プロジェクト: jbp4444/PyGenAlg
def run(ctx, save_out, load_in):
    ctxobj = ctx.obj
    verbose = ctxobj.get('verbose')
    epoch_it = ctxobj.get('epoch_it')
    inner_it = ctxobj.get('inner_it')

    ga = GenAlg(
        chromoSize=3 * num_sprayers,
        dtype=np.float32,
        range=dataRanges,
        fitnessFcn=calcFitness,
        crossoverFcn=crossover,
        userDataI=cutout_region,  # user-provided cut-out region
        userDataF=scoring,  # user-provided scoring system
        size=ctxobj.get('popsize'),
        elitism=ctxobj.get('elitism'),
        crossover=ctxobj.get('crossover'),
        pureMutation=ctxobj.get('puremutation'),
        parentPct=ctxobj.get('parent_pct'),
        minOrMax='max',
        showBest=0)

    #
    # if a pickle-file exists, we load it
    if (load_in):
        pop = IoOps.loadPopulation(ga, 'ga_sprinkler.dat')
        ga.loadPopulation(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')

    if (verbose > 0):
        ga.describe()
        print('Epoch/Inner iters:', epoch_it, inner_it)

        maxspray = 0.0
        for i in range(num_sprayers):
            maxspray = maxspray + 3.1415 * dataRanges[
                3 * i + 2][1] * dataRanges[3 * i + 2][1]
        maxfield = 100 * 100 - cutout_region[0] * cutout_region[1]
        mx = max(scoring)
        print('Max spray: %.2f  ( %d )' % (mx * maxspray, mx * maxfield))

    #
    # Run it !!
    # : we'll just do 10 epochs of 10 steps each
    with click.progressbar(range(epoch_it)) as bar:
        for i in bar:
            ga.evolve(inner_it)

    #
    # all done ... output final results
    print("\nfinal best chromos:")
    print(ga.population[range(3 * num_sprayers)], ga.fitnessVals[0])

    drawImage(ga.population[range(3 * num_sprayers)])

    #
    # we'll always save the pickle-file, just delete it
    # if you want to start over from scratch
    if (save_out):
        IoOps.savePopulation(ga, 'ga_sprinkler.dat')
        print('Final data stored to file (rm ga_sprinkler.dat to start fresh)')
コード例 #17
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)')
コード例 #18
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)')