コード例 #1
0
def initialize_animats(initial_list, object_list, scale, number, speed, kind):
    for i in range(0, number):
        if (kind == 'prey'):
            animat = Prey(prey_path, scale, speed, RL.QLearn)
            overlap = False
            for j in range(0, len(initial_list)):
                if (doRectsOverlap(animat.get_rect(),
                                   initial_list[j].get_rect())):
                    overlap = True
                    break
            if (overlap):
                i = i - 1
            else:
                object_list.append(animat)
                all_sprites.add(animat)
                initial_list.append(animat)
        else:
            animat = Predator(predator_path, scale, speed, RL.QLearn)
            overlap = False
            for j in range(0, len(initial_list)):
                if (doRectsOverlap(animat.get_rect(),
                                   initial_list[j].get_rect())):
                    overlap = True
                    break
            if (overlap):
                i = i - 1
            else:
                object_list.append(animat)
                all_sprites.add(animat)
                initial_list.append(animat)
コード例 #2
0
def new_predator():
	if (len(predList) < 9):
		x = random.randrange((window_size[0] - 40))
		y = random.randrange((window_size[1] - 40))
		while (y < 380):
			y = random.randrange((window_size[1] - 40))
		predList.append(Predator(pygame.image.load("images/predator.png").convert(), [x, y], window_size))
コード例 #3
0
    def Start_Evaluation(self, pp, pb):
        #run simulator without pausing
        self.sim = pyrosim.Simulator(eval_time=c.evalTime,
                                     play_blind=pb,
                                     play_paused=pp)

        #create instance of the robot class
        #sends a random value between -1 and 1 for each iteration
        self.predator = Predator(self.sim, self.predatorGenome)
        self.prey = Prey(self.sim, self.preyGenome)

        #start the simulator
        self.sim.start()
コード例 #4
0
def initSimulation():
    State['iter'] = 0

    for i in range(INI_FLORA):
        Flora(canvas)

    for i in range(INI_BOIDS):
        Boid(canvas)

    for i in range(INI_PREDS):
        Predator(canvas)

    Boid.setPredatorGrid(Predator.grid)
コード例 #5
0
 def Start_Evaluation(self, env, pp, pb):
     #run simulator without pausing
     self.sim = pyrosim.Simulator(eval_time = c.evalTime, play_blind = pb, play_paused = pp)
     
     env.Send_To( self.sim )
     #create instance of the robot class
     #sends a random value between -1 and 1 for each iteration
     self.robot = Predator(self.sim, self.genome)
     self.collided = self.sim.assign_collision(self.robot, env.source)
     
     
     #start the simulator
     self.sim.start()
コード例 #6
0
def test_sanity_check():
    data = {
        "text": [
            "How far is it from Denver to Aspen?",
            "What county is Modesto, California in?",
            "Who was Galileo?",
            "What is an atom?",
            "When did Hawaii become a state?",
            "How tall is the Sears Building?",
            "George Bush purchased a small interest in which baseball team?",
            "What is Australia's national flower?",
            "Why does the moon turn orange?",
            "What is autism?",
            "What city had a world fair in 1900?",
            "What person's head is on a dime?",
            "What is the average weight of a Yellow Labrador?",
            "Who was the first man to fly across the Pacific Ocean?",
            "When did Idaho become a state?",
            "What is the life expectancy for crickets?",
            "What metal has the highest melting point?",
            "Who developed the vaccination against polio?",
            "What is epilepsy?",
            "What year did the Titanic sink?",
            "Who was the first American to walk in space?",
            "What is a biosphere?",
            "What river in the US is known as the Big Muddy?",
            "What is bipolar disorder?",
            "What is cholesterol?",
            "Who developed the Macintosh computer?",
            "What is caffeine?",
            "What imaginary line is halfway between the North and South Poles?",
            "Where is John Wayne airport?",
            "What hemisphere is the Philippines in?",
            "What is the average speed of the horses at the Kentucky Derby?",
        ],
        "label": [0] * 15 + [1] * 16,
    }
    df_train = df_valid = pd.DataFrame(data)

    device = "cuda" if torch.cuda.is_available() else "cpu"

    print(df_train)
    print(df_valid)

    predator = Predator(df_train, df_valid, device=device)
    predator.train()

    df_aug = predator.augment(augment_ratio=2.0)
    print(df_aug)
    assert df_aug is not None
コード例 #7
0
ファイル: game.py プロジェクト: BackupTheBerlios/pysma-svn
def main(WIDTH=21, HEIGHT=10, PREDATORS=8):
    mygame = Kernel()

    myscheduler = DummyScheduler()
    mygame.addAgent(myscheduler, "Scheduler")

    mymesh = Mesh(WIDTH, HEIGHT)
    mygame.addAgent(mymesh, "Mesh")

    anAgent = Prey()
    mygame.addAgent(anAgent, "Prey")
    mymesh.addAgent(mygame.getAgentId(anAgent))

    for i in range(PREDATORS):
        anAgent = Predator()
        mygame.addAgent(anAgent, "Predator%s" % i)
        mymesh.addAgent(mygame.getAgentId(anAgent))

    while (Kernel.instance != None):
        time.sleep(3)
コード例 #8
0
 def __init__(self, number, seed=1337, predator=False):
     random.seed(seed)
     self.birds = []
     self.predPresent = False
     if predator:
         self.predPresent = True
         self.predator = Predator()
     else:
         self.predator = None
     for n in range(0,number):
         self.birds.append(Bird())
     # Initialize plot
     self.fig = plt.figure()
     self.ax = self.fig.add_subplot(111)
     plt.ion()
     plt.show()
     plt.xlim(0, 1)
     plt.ylim(0, 1)
     self.ax.get_xaxis().set_visible(False)
     self.ax.get_yaxis().set_visible(False)
コード例 #9
0
    def make_agents(self):
        '''
        Create self.population agents, with random positions and starting headings.
        '''
        for i in range(50):
            x = random.random() * self.space.x_max
            y = random.random() * self.space.y_max
            center_x = self.space.x_max / 2
            center_y = self.space.y_max / 2
            pos = np.array((x, y))
            center = np.array((center_x, center_y))
            velocity = np.random.random(2) * 2 - 1
            velocity = np.zeros(2) + self.space.get_distance(pos, center)
            velocity[0] *= self.target[0]
            velocity[1] *= self.target[1]
            boid = Boid(i, self, pos, self.speed, velocity, self.vision,
                        self.separation, self.collision_separation, "boid.png",
                        10, **self.factors)
            self.space.place_agent(boid, pos)
            self.schedule.add(boid)

        for i in range(4):
            x = random.random() * self.space.x_max
            y = random.random() * self.space.y_max
            pos = np.array((x, y))
            obstacle = Obstacle(i + self.population, self, pos, 30)
            obstacle2 = Obstacle(i + self.population + 5, self, pos, 4)
            self.space.place_agent(obstacle, pos)
            self.space.place_agent(obstacle2, pos)
            self.schedule.add(obstacle)
            self.schedule.add(obstacle2)
        if self.predators:
            x = random.random() * self.space.x_max
            y = random.random() * self.space.y_max
            pos = np.array((x, y))
            velocity = np.random.random(2) * 2 - 1
            predator = Predator(2003, self, pos, self.speed + 0.1, velocity,
                                self.vision + 5, 12, self.collision_separation,
                                "predator.png")
            self.space.place_agent(predator, pos)
            self.schedule.add(predator)
コード例 #10
0
ファイル: main.py プロジェクト: chuwilliamson/PYstar
def main():
    '''main execution func'''
    game = SteeringBehavioursGame("SteeringBehaviours")

    for _ in range(1):
        pos = Vector2(randrange(0, 800), randrange(0, 800))
        vel = Vector2(randrange(0, 800), randrange(0, 800)).normalized
        agent0 = Prey("max", pos, vel)
        pos = Vector2(randrange(0, 800), randrange(0, 800))
        vel = Vector2(randrange(0, 800), randrange(0, 800)).normalized
        agent1 = Prey("donray", pos, vel)
        pos = Vector2(randrange(0, 800), randrange(0, 800))
        vel = Vector2(randrange(0, 800), randrange(0, 800))
        agent2 = Predator("trent", pos, vel, [agent0, agent1])

        agent0.set_target(agent2)
        agent1.set_target(agent2)

        game.addtobatch(agent0)
        game.addtobatch(agent1)
        game.addtobatch(agent2)
    game.run()
コード例 #11
0
def main():
    numberOfRuns = 3
    maximumLengthOfRun = 30000

    initialNumberOfPreys = 400
    initialNumberOfPredators = 10
    initialNumberOfClusters = 30
    gridSize = 512
    clusterSpawnRate = 0.02  # The probability of generating a new cluster for each generation
    clusterDistributionParameter = 40  # A higher value will tend to create the clusters more evenly spread.
    # In the limit that the parameter is 1 the clusters will spawn completely random.
    clusterSizeParameter = 30  # The amount of plants per cluster (SHOULD THIS BE THE UPPER LIMIT OR MEAN?!?!?!?!?!)
    clusterStandardDeviation = 9  # The standard deviation used to generate the plants which make up the cluster.

    # Initializes "graphics"
    plt.ioff()
    plt.show()
    plt.axis([-1, gridSize, -1, gridSize])
    preyPlotHandle = plt.plot([], [], '.', markersize=3,
                              color=(0.2, 0.3, 0.8))[0]
    predatorsPlotHandle = plt.plot([], [],
                                   '.',
                                   markersize=5,
                                   color=(0.9, 0.1, 0.1))[0]
    plantPlotHandle = plt.plot([], [],
                               '.',
                               markersize=2,
                               color=(0.3, 0.9, 0.1))[0]
    clusterPlotHandle = plt.plot([], [],
                                 'o',
                                 markersize=10,
                                 color=(0.3, 0.5, 0.7),
                                 alpha=0.5)[0]

    file = open("run_data", "w")
    file.write("Initial number of preys = %i \n" % initialNumberOfPreys)
    file.write("Initial number of predators = %i \n" %
               initialNumberOfPredators)
    file.write("Initial number of plant clusters = %i \n" %
               initialNumberOfClusters)
    file.write("Grid size = %i \n" % gridSize)
    file.write("cluster spawn rate = %f \n" % clusterSpawnRate)
    file.write("cluster distribution parameter = %i \n" %
               clusterDistributionParameter)
    file.write("cluster size parameter = %i \n" % clusterSizeParameter)
    file.write("cluster standard deviation %f \n" % clusterStandardDeviation)

    for iRun in range(0, numberOfRuns, 1):
        file.write(
            "\n========================================================== \n")
        clusterObjects, plantObjects = plant_module.InitializePlants(
            initialNumberOfClusters, gridSize, clusterDistributionParameter,
            clusterSizeParameter, clusterStandardDeviation)
        clusterObjects[0].setClusterCheckRadius(
            clusterStandardDeviation *
            math.sqrt(-2 * math.log(0.001 * clusterStandardDeviation *
                                    math.sqrt(2 * math.pi))) + 40)

        preys = [
            Prey(gridSize, visibilityRadius=27, reproductionRate=0.1)
            for i in range(initialNumberOfPreys)
        ]
        predators = [
            Predator(gridSize, visibilityRadius=22, reproductionRate=0.2)
            for j in range(initialNumberOfPredators)
        ]
        for prey in preys:
            prey.update_pointers(preys, predators, plantObjects,
                                 clusterObjects)
        for predator in predators:
            predator.update_pointers(preys, predators)

        number_of_preys = []
        number_of_predators = []
        number_of_plants = []
        number_of_preys.append(np.size(preys))
        number_of_predators.append(10 * np.size(predators))
        number_of_plants.append(np.size(plantObjects))
        i = 0
        while preys and predators and i < maximumLengthOfRun:
            i += 1
            clusterObjects, plantObjects = plant_module.PlantGrowth(
                clusterObjects, plantObjects, gridSize, clusterSpawnRate,
                clusterDistributionParameter, clusterSizeParameter,
                clusterStandardDeviation)

            if np.size(clusterObjects) == 1:
                plantObjects[0].UpdatePointers(
                    plantObjects, clusterObjects
                )  # Needed when new plants grow when before there
                for prey in preys:  # were no plants. Without this code the preys
                    prey.update_pointers(
                        preys, predators, plantObjects,
                        clusterObjects)  # seem to lose track of the plants

            for prey in preys:
                prey()
            for predator in predators:
                predator()
            plt.title("Prey = {}, Predators = {}, Iteration = {}".format(
                np.size(preys), np.size(predators), i))

            #if i%100 == 0:
            #    print("i = %i\n# of preys = %i\n# of plants = %i\n# of predators = %i" %(i,np.size(preys),np.size(plantObjects),np.size(predators)))
            #if i%1 == 0:
            #    plt.axis([-1, gridSize, -1, gridSize])
            #    plot(preys, predators, plantObjects, clusterObjects, preyPlotHandle, plantPlotHandle, clusterPlotHandle,
            #         predatorsPlotHandle)
            #    plt.savefig('pictures/pic{:04}.png'.format(i), format='png')
            number_of_preys.append(np.size(preys))
            number_of_predators.append(10 * np.size(predators))
            number_of_plants.append(np.size(plantObjects))

        plt.figure(2 + iRun)
        tmpList = [
            max(number_of_plants),
            max(number_of_preys),
            max(number_of_predators)
        ]
        plt.axis([0, i, 0, max(tmpList)])
        plt.plot(range(0, i + 1), number_of_plants, 'g')
        plt.plot(range(0, i + 1), number_of_preys, 'b')
        plt.plot(range(0, i + 1), number_of_predators, 'r')
        plt.title("iRun = %i" % iRun)
        plt.savefig('pictures/aBlood{:04}.png'.format(iRun), format='png')
        #plt.show()

        # Save to text file here
        file.write("Iterations passed = %i\n" % i)
        file.write("number of preys = %i\n" % np.size(preys))
        file.write("number of predators = %i\n" % np.size(predators))
        file.write("number of plant clusters = %i\n" % np.size(clusterObjects))
        file.write("number of plants = %i\n" % np.size(plantObjects))

        print("Run number %i complete\n" % (iRun + 1))
        print(
            "i = %i\n# of preys = %i\n# of plants = %i\n# of predators = %i" %
            (i, np.size(preys), np.size(plantObjects), np.size(predators)))

        # Awful way of deleting all the plants/clusters between runs
        i = 1
        while i > 0:
            for plant in plantObjects:
                plant.PlantGetsEaten()
            i = np.size(plantObjects)

    file.close()
    print("All runs are done")
コード例 #12
0
 def add_predator(self):
     pred = Predator(self.get_random_position(), self.predator_radius,
                     self.get_random_velocity())
     self.predators.append(pred)
     return pred
コード例 #13
0
def main():
    numberOfRuns = 3
    maximumLengthOfRun = 5000

    initialNumberOfPreys = 400
    initialNumberOfPredators = 10
    initialNumberOfClusters = 5
    gridSize = 300
    clusterSpawnRate = 0.005  # The probability of generating a new cluster for each generation
    clusterDistributionParameter = 20  # A higher value will tend to create the clusters more evenly spread.
    # In the limit that the parameter is 1 the clusters will spawn completely random.
    clusterSizeParameter = 100  # The amount of plants per cluster (SHOULD THIS BE THE UPPER LIMIT OR MEAN?!?!?!?!?!)
    clusterStandardDeviation = 12  # The standard deviation used to generate the plants which make up the cluster.

    file = open("run_data", "w")
    file.write("Initial number of preys = %i \n" % initialNumberOfPreys)
    file.write("Initial number of predators = %i \n" %
               initialNumberOfPredators)
    file.write("Initial number of plant clusters = %i \n" %
               initialNumberOfClusters)

    for iRun in range(0, numberOfRuns, 1):
        file.write(
            "\n========================================================== \n")

        clusterObjects, plantObjects = plant_module.InitializePlants(
            initialNumberOfClusters, gridSize, clusterDistributionParameter,
            clusterSizeParameter, clusterStandardDeviation)
        clusterObjects[0].setClusterCheckRadius(
            clusterStandardDeviation *
            math.sqrt(-2 * math.log(0.001 * clusterStandardDeviation *
                                    math.sqrt(2 * math.pi))) + 40)

        preys = [Prey(gridSize) for i in range(initialNumberOfPreys)]
        predators = [
            Predator(gridSize) for j in range(initialNumberOfPredators)
        ]
        for prey in preys:
            prey.update_pointers(preys, predators, plantObjects,
                                 clusterObjects)
        for predator in predators:
            predator.update_pointers(preys, predators)
        i = 0
        while preys and predators and i < maximumLengthOfRun:
            i += 1
            clusterObjects, plantObjects = plant_module.PlantGrowth(
                clusterObjects, plantObjects, gridSize, clusterSpawnRate,
                clusterDistributionParameter, clusterSizeParameter,
                clusterStandardDeviation)
            if np.size(clusterObjects) == 1:
                plantObjects[0].UpdatePointers(
                    plantObjects, clusterObjects
                )  # Needed when new plants grow when before there
                for prey in preys:  # were no plants. Without this code the preys
                    prey.update_pointers(
                        preys, predators, plantObjects,
                        clusterObjects)  # seem to lose track of the plants

            for prey in preys:
                prey()
            for predator in predators:
                predator()

        # Save to text file here
        file.write("Iterations passed = %i\n" % i)
        file.write("number of preys = %i\n" % np.size(preys))
        file.write("number of predators = %i\n" % np.size(predators))
        file.write("number of plant clusters = %i\n" % np.size(clusterObjects))
        file.write("number of plants = %i\n" % np.size(plantObjects))

        # Awful way of deleting all the plants/clusters between runs
        i = 1
        while i > 0:
            for plant in plantObjects:
                plant.PlantGetsEaten()
            i = np.size(plantObjects)

    file.close()