Exemple #1
0
def main():

    ga = GenAlg(chromoSize=len(solution),
                dtype=chromo_type,
                range=chromo_range,
                fitnessFcn=calcFitness,
                crossoverFcn=crossover2,
                size=1024,
                elitism=0.10,
                crossover=0.60,
                pureMutation=0.30,
                minOrMax='max',
                showBest=0)
    ga.describe()

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

    # print( "init data best chromo:" )
    # print( ga.population[range(len(solutionWord))], ga.fitnessVals[0] )
    # print( ga.population[range(len(solutionWord),2*len(solutionWord))], ga.fitnessVals[1] )

    #
    # 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(len(solutionWord))], ga.fitnessVals[0])
        #print( ga.population[range(len(solutionWord),2*len(solutionWord))], ga.fitnessVals[1] )

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

    print('solution -  maxchr=', len(letters))
    print(solution[:])

    #
    # 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)')

    ga.cudaAnalysis()
Exemple #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)')
Exemple #3
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)')
Exemple #4
0
def main():
    global debuglevel

    ga = PsoAlg(size=popsize,
                omega=0.75,
                phi_p=1.50,
                phi_g=1.00,
                learning_rate=1.0,
                chromoClass=MyChromo,
                minOrMax='max',
                showBest=0)

    #
    # if a data-file exists, we load it
    if (os.path.isfile('ga_maze2_pso.dat')):
        pop = IoOps.loadPopulation(ga, 'ga_maze2_pso.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].chromo.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_maze2_pso.dat')
    print('Final data stored to file (rm ga_maze2_pso.dat to start fresh)')
Exemple #5
0
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)')
Exemple #6
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)')
Exemple #7
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 = 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.simpleSelection,
    # 	pureMutationFcn = GenAlgOps.mutateAll,
    # 	#feasibleSolnFcn = GenAlgOps.disallowDupes,
    # 	minOrMax     = 'min',
    # 	showBest     = 0,
    # 	# optional params ..
    # 	params = {
    # 		'mutateNum': ctxobj.get('mutatenum'),
    # 		'parentPct': 0.50,
    # 	}
    # )
    ga = PsoAlg(
        size=ctxobj.get('popsize'),
        omega=0.75,
        phi_p=1.50,
        phi_g=1.00,
        learning_rate=1.0,
        chromoClass=MyChromo,
        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_cpuDAG.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')

    if (verbose > 0):
        ga.describe()
        print('Chromo size: %d :: %d %d' %
              (len(ga.population[0].chromo.data), num_levels, nodes_per_level))
        print('Epoch/Inner iters:', epoch_it, inner_it)
        print('Instruction set:',
              ' '.join(ga.population[0].chromo.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].chromo.cpu.show_prog(show_pc=False, nl='/'))
        print('    ' + ga.population[0].chromo.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].chromo.cpu.show_prog(show_pc=False, nl='/'))
        print('    ' + ga.population[i].chromo.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_cpuDAG.dat')
        print('Final data stored to file (rm ga_cpuDAG.dat to start fresh)')
Exemple #8
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)')