Beispiel #1
0
def test_readMemoryByFrame(): #Req 6
    """
    The Pac-Man AI shall read memory from the NES emulator 
    when the game produces a new frame.
    """
    evolver = Evolver.Evolver(api, populationSize=2, mutationRate=0.15, maxGenerations=2, \
        showResults=True, keepBestProportion=0.5, keepRandomProportion=0.0)
    def frameCounter():
        """
        Counts the number of frames and stops after 25,000 frames
        """
        global frameCount
        frameCount += 1
        #If the evolver failed to read memory, the frame counts wont match!
        assert frameCount == evolver.frameCount 
        #Test 25,000 frames of gameplay, making sure the tester's frame counter never falls 
        #out of sync with the evolver.
        if frameCount > 25000: 
            api.removeFrameListener(frameCounter)
            api.removeFrameListener(evolver.playGame)
            api.stop()
    api.addFrameListener(frameCounter)
    api.addFrameListener(evolver.playGame)
    api.addAccessPointListener(evolver.onLifeCountChanged, nintaco.PostWrite, 0x0067)
    api.run()
Beispiel #2
0
def test_geneticAlgorithmParameters(): #Req 2
    """
    The Pac-Man AI shall accept parameters for the
    genetic algorithm's settings when the user enters them.
    """
    evolver = Evolver.Evolver(api=api, populationSize=100, \
        mutationRate=0.15, maxGenerations=2, showResults=False)
    assert evolver.populationSize == 100 and \
        evolver.mutationRate == pytest.approx(0.15) and \
        evolver.maxGenerations == 2 and evolver.showResults == False
Beispiel #3
0
def test_cullPoorNetworks(): #Req 4
    """
    The Pac-Man AI shall cull poor-performing neural networks
    when it evaluates its neural network's performance
    """
    evolver = Evolver.Evolver(api, populationSize=10)
    #We will go through and assign a fake fitness to each network,
    #because we have already determined our fitness checking
    #function works. Then we will have the evolver make a new network
    #and check that the poorest one was in fact removed.
    for network in evolver.population:
        network.fitness = 1000
    evolver.population[0].fitness = 0 #Worst one.
    evolver.population[0]._poorPerformerFlag = True #Set a flag to show that this one is bad.
    evolver.generateNewPopulation(keepBestProportion=0.1, keepRandomProportion=0.0)
    for network in evolver.population:
        assert not hasattr(network, "_poorPerformerFlag")
Beispiel #4
0
def test_getFitness(): #Req 3
    """
    The Pac-Man AI shall evaluate its neural network's
    performance against the fitness function when it dies.
    """
    evolver = Evolver.Evolver(api)
    def testFitness():
        """
        Gets the current fitness
        """
        global fitness
        fitness = evolver.getCurrentFitness()
        api.removeActivateListener(testFitness)
        api.stop()
    
    api.addActivateListener(testFitness)
    api.run()
    assert fitness >= 0 #Pac-man cannot have a negative score.
Beispiel #5
0
def test_sendControllerInput(): #Req 1
    """
    The Pac-Man AI shall begin sending output to the
    NES controller when it is enabled.
    """
    evolver = Evolver.Evolver(api)
    def writeAndRead():
        """
        Checks to make sure the enter button is pressed and
        then released.
        """
        evolver.writeGamepad(Evolver.GAMEPAD_START, True)
        assert api.readGamepad(0, Evolver.GAMEPAD_START)
        evolver.writeGamepad(Evolver.GAMEPAD_START, False)
        assert not api.readGamepad(0, Evolver.GAMEPAD_START)
        api.removeActivateListener(writeAndRead)
        api.stop()
    
    api.addActivateListener(writeAndRead)
    api.run()
Beispiel #6
0
def main():
    """The main routine."""

    with evolver.Evolver() as E:

        n = 1000
        init_bo = 0
        params = np.empty([3, n])

        for i in range(n):
            print '-----------------\nTime Around ' + str(i)

            bo = init_bo + 0.05 * i
            define_values(bo)
            E.open_file('dropSinusoidal.fe')

            for j in range(1):
                #E.refine(1)
                vals = E.evolve(1)

            E.run_command('car_app')
            E.run_command('car')
            E.run_command('')
            E.run_command('dump')
            E.run_command('')
            E.close_file()

            params[0, i] = bo
            params[1, i] = find_values('dropSinusoidal.fe.dmp',
                                       'contact_angle_right')[0]
            params[2, i] = find_values('dropSinusoidal.fe.dmp',
                                       'contact_angle_right_app')[0]

        print 'To Plot'
        plt.plot(params[0, :], params[1, :], label="Contact Angle")
        plt.plot(params[0, :], params[2, :], label="Apparent Contact Angle")
        plt.ylabel('Contact Angle')
        plt.xlabel('Bond Number (Bo)')
        plt.legend()
        plt.show()
Beispiel #7
0
def test_constantOutput(): #Req 5
    """
    The Pac-Man AI shall display results to the user constantly.
    """
    evolver = Evolver.Evolver(api)
    assert evolver.printGenerationResults(60)
Beispiel #8
0
    drawer = ImageDraw.Draw(painting, 'RGBA')
    drawer.rectangle([0, 0, w, h], (255, 255, 255, 255))
    for f in dude:
        drawer.ellipse([f[0], f[1], f[0] + f[2], f[1] + f[3]],
                       (int(f[4]), int(f[5]), int(f[6]), opacity))
    # calculate error
    err = 0
    for i in range(img.size[0]):
        for j in range(img.size[1]):
            r, g, b = img.getpixel((i, j))
            rp, gp, bp = painting.getpixel((i, j))
            err = err + math.sqrt((r - rp)**2 + (g - gp)**2 + (b - bp)**2)
    return err


def makepic(dude):
    drawer = ImageDraw.Draw(painting, 'RGBA')
    drawer.rectangle([0, 0, w, h], (255, 255, 255))
    for f in dude:
        drawer.ellipse([f[0], f[1], f[0] + f[2], f[1] + f[3]],
                       (int(f[4]), int(f[5]), int(f[6]), opacity))
    painting.show()
    filename = "my_drawing.jpg"
    painting.save(filename)


ev = evolver.Evolver(population, parents, mrate, controls, figures)
for i in range(10000):
    ev.evolve(fitfunc)
    makepic(ev.fittest[-1])
Beispiel #9
0
import ising1d
import nqs
import sampler
import evolver
import observables

nsteps = 400

### INITIALIZATION
wf = nqs.NqsLocal(10, 2, 1)  # Set up a translation-invariant neural network
wf.load_parameters(
    '../Outputs/10_Ising05_2loc_200.npz')  # Load this pre-trained ANNQS

## TIME EVOLVE
h = ising1d.Ising1d(10, 1.0)
evo = evolver.Evolver(h)
wf = evo.evolve(wf,
                .01,
                nsteps + 1,
                symmetry="local",
                file='../Outputs/10SpinEvolve/evolution_2loc_',
                print_freq=25,
                out_freq=1,
                batch_size=1000)

### INITIALIZATION
wf = nqs.NqsLocal(10, 1, 1)  # Set up a translation-invariant neural network
wf.load_parameters(
    '../Outputs/10_Ising05_1loc_200.npz')  # Load this pre-trained ANNQS

## TIME EVOLVE
Beispiel #10
0
import nintaco
import evolver as Evolver

populationSize = input("Enter the population size: ")
mutationRate = input("Enter the mutation rate (0-1): ")
maxGenerations = input("How many generations should be ran before \
urning the AI off (0 for infinite): ")
showResults = str(
    raw_input("Show results report after the AI is toggled off (y/n): "))
showResults = showResults == "y" or showResults == "Y"

nintaco.initRemoteAPI("localhost", 9999)
api = nintaco.getAPI()
evolver = Evolver.Evolver(api, populationSize=populationSize, \
    mutationRate = mutationRate, maxGenerations=maxGenerations, showResults=showResults)
api.addFrameListener(evolver.playGame)
api.addAccessPointListener(evolver.onLifeCountChanged, nintaco.PostWrite,
                           0x0067)
api.run()
Beispiel #11
0
def main():
    """The main method."""

    with evolver.Evolver() as E:
        print E.run_command('foo := 3')
        print E.run_command('print foo')