Esempio n. 1
0
def pairPop(pop, layerVector):
    """
    This function evaluates each gene within a population and returns
    the genes paired with their corresponding fitnesses
    """
    weights, fitnesses = [], []
    for i in range(len(pop)):
        # Select a set of weights an initialise the Neural Net
        weight = pop[i]
        NN = NeuralNet(layerVector, weight)

        # Reset the fitness on each iteration
        fitness = 0
        # Calculate a fitness for each track selected
        for each in worlds:
            # Create  the world
            world = each
            dt = world.dt

            pod = pods.CarPod(world)
            equip_car(pod)

            if GUI:
                frames_per_sec = int(1 / dt)
                simple_gui = gui.SimpleGui(frames_per_sec=frames_per_sec,
                                           world=world,
                                           pods=[pod])
                # Sum the fitnesses together on each iteration for the
                # different trakcs
                fitness += evaluate(pod, NN, simple_gui)
            else:
                # Sum the fitnesses together on each iteration for the
                # different trakcs
                fitness += evaluate(pod, NN, 0)

        # If in test mode then print the fitness
        if TEST:
            print "Finished with a fitness of: " + repr(fitness)

        # Add the current set of weights and corresponding fitness to
        # lists
        weights.append(weight)
        fitnesses.append(fitness)

    # Return a combined tuple of weights and their fitnesses
    return zip(weights, fitnesses)
Esempio n. 2
0
"""
Showing how to use the gui (nice for debugging)
"""

import math

from pod import pods, world, gui

# world definition file

worldFile = "worlds/carCircuit.world"

# create  the world
world = world.World(worldFile)
pod = pods.CarPod(world)

# I set the frame rate so the animation is real time (you can make it faster/slower if you want)
simple_gui = gui.SimpleGui(frames_per_sec=int(1 / world.dt),
                           world=world,
                           pods=[pod])

pod.control.up = .1

pod.control.left = .4

while True:

    pod.step()

    # YOu can display debug text if you want.
    mess = str(pod.state)
def tester(world_name, punter_names, fout):

    global simple_gui
    global FPS_FACT

    N = len(punter_names)

    ###  START OF PROGRAM
    world_test = world.World(world_name)

    pod_list = []
    zombies = []
    cnt = 0
    default_dir = os.getcwd()

    for name in punter_names:
        pod = pods.CarPod(world_test)
        pod_list.append(pod)
        pod.score = 0.0
        pod.stat = "-"
        pod.name = name
        pod.mess = "Uninitialized"

        try:
            punters_path = 'punters_test/' + name
            os.chdir(punters_path)
            plug = importlib.import_module('punters_test.' + name + '.plugin')

            # call the plugin to equip the car
            # set the current path to the punters directory

            plug.equip_car(pod)
            os.chdir(default_dir)

            pod.controller = plug.controller

            hue = (360.0 * cnt) / N
            col = pygame.Color(0)
            col.hsla = (hue, 100, 50, 0)
            pod.col = (col.r, col.g, col.b)
            cnt += 1
        except:
            print name
            print "Unexpected error:", sys.exc_info()
            #            fout.write(name+" Error "+ str(sys.exc_info()[0]))
            pod.mess = "Unable to run" + str(sys.exc_info()[0])
            pod.score = 0.0
            pod.stat = "E"
            zombies.append(pod)
            os.chdir(default_dir)

    runners = copy.copy(pod_list)

    # remove zombies
    for pod in zombies:
        runners.remove(pod)

    if GUI:
        simple_gui = gui.SimpleGui(frames_per_sec=int(FPS_FACT /
                                                      world_test.dt),
                                   world=world_test,
                                   pods=runners,
                                   back_ground=(5, 5, 5))

    # use a control to activate the car.
    control = pods.Control()

    while runners:

        zombies = []

        for pod in runners:
            try:
                control.left = 0
                control.right = 0
                control.up = 0
                control.down = 0

                pod.controller(pod, control)
                pod.step(control)
                score, kill, mess = evaluate(pod)
                pod.score = score
                pod.mess = mess

            except:

                print name + ": Unexpected error:", sys.exc_info()

                pod.score = 0
                pod.mess = "Error ->" + str(sys.exc_info())
                kill = True
                pod.stat = "e"

            if kill:
                zombies.append(pod)

        # remove crashed
        for pod in zombies:
            runners.remove(pod)

        ranked = sorted(pod_list, key=lambda x: x.score, reverse=True)

        if GUI:
            disp = ""
            pos = [0, 10]
            simple_gui.clear()

            for pod in ranked:
                col = pod.col

                gui_base.draw_string(simple_gui.screen,
                                     pod.stat + ":" + pod.name, pos, col,
                                     FONT_SIZE, 'Courier New')

                pos[1] += FONT_SIZE

            simple_gui.display(clear=False, fps=int(FPS_FACT / world_test.dt))

            if simple_gui.check_for_quit():
                sys.exit(0)

            if simple_gui.get_pressed()[gui.keys.K_p]:
                pause = True

            if simple_gui.get_pressed()[gui.keys.K_EQUALS]:
                FPS_FACT = min(FPS_FACT * 2, 200)
                print FPS_FACT

            if simple_gui.get_pressed()[gui.keys.K_MINUS]:
                FPS_FACT = max(int(FPS_FACT / 2), 1)
                print FPS_FACT

            if simple_gui.get_pressed()[gui.keys.K_s]:
                pause = False

    ranked = sorted(pod_list, key=lambda x: x.score, reverse=True)

    for pod in ranked:
        buff = "%15s %6.3f %s" % (pod.name + ":", pod.score,
                                  ":" + pod.mess + "\n")
        fout.write(buff)

    return pod_list
Esempio n. 4
0
        if GUI:
            if simple_gui.check_for_quit():  # Provide a way out for the user
                break


# world definition file

worldFiles = ["worlds/carCircuit.world", "worlds/pjl_chick.world"]

# use a control object to do thrust steer etc.
control = pods.Control()

# create  the world
worlds = []

for worldFile in worldFiles:
    worlds.append(world.World(worldFile))

# You can now create a pod without a world by passing None
pod = pods.CarPod(None)

if GUI:
    # Note world.DEFAULT_DT is the standard time step
    simple_gui = gui.SimpleGui(frames_per_sec=int(1 / world.DEFAULT_DT),
                               world=None,
                               pods=[pod])

for w in worlds:
    test_world(pod, w)
Esempio n. 5
0
Simple example:
create a car and run it into a wall!
"""

from pod import pods, world
import math

# world (car track) definition file
worldFile = "worlds/carCircuit.world"

# create  the world
myWorld = world.World(worldFile)

#Create a pod
# Note that the world is responsible for setting the initial state of the pod
pod = pods.CarPod(myWorld)

# use a control to activate the car.
control = pods.Control()

while True:

    control.up = .1
    control.left = .1

    # perform a single time step of the car.
    pod.step(control)

    # the state should change (look at the console)
    print pod.state
Esempio n. 6
0
if len(sys.argv) > 2:
    world_name = sys.argv[2]
else:
    world_name = "pjl_chick"

###  START OF PROGRAM
track = world.World("worlds/" + world_name + ".world")

punters_path = "punters/" + name
default_dir = os.getcwd()

try:

    os.chdir(punters_path)
    pod = pods.CarPod(track)
    plug = importlib.import_module('punters.' + name + '.plugin')
    plug.equip_car(pod)
    os.chdir(default_dir)
    pod.controller = plug.controller

except:

    print name
    print "Unexpected error:", sys.exc_info()
    traceback.print_tb(sys.exc_info()[2])
    pod.mess = "Loading Error: " + str(sys.exc_info()[0])
    os.chdir(default_dir)
    sys.exit(0)

os.chdir(default_dir)