def runsim(config_file=None): entity_results = [] captured_results = [] p = {} # get the paramters for the simulation if config_file is None: p = default_params() else: p = config_params(config_file) for trial in range(p['n_trials']): # Set up the environment env = Environment(p['env_size'], p['env_size'], p['n_patches']) entities = random.randint(p['min_entities_per_patch'], p['max_entities_per_patch']) for patch in env.children: patch.create_entities(entities) pred = Predator() pred.xpos = env.length / 2.0 pred.y_pos = env.width / 2.0 pred.parent = env for i in range(p['max_moves']): pred.move() entity = pred.detect() pred.capture(entity) entity_results.append(entities) captured_results.append(len(pred.captured)) return entity_results, captured_results
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
class Flock(object): ''' Class for groups of birds and a possible predator ''' 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) def update(self): ''' Updates position of all birds and the predator according to rules of behavior ''' # Move flock for n in range(0, len(self.birds)): self.birds[n].update(self.birds, self.predator) # Move predator if self.predPresent: self.predator.update(self.birds) def drawPlot(self, m): ''' Updates plot ''' for n in range(0, len(self.birds)): self.ax.quiver(self.birds[n].x, self.birds[n].y, self.birds[n].vx, self.birds[n].vy) if self.predator: self.ax.quiver(self.predator.x, self.predator.y, self.predator.vx, self.predator.vy, color='red') plt.savefig("png/"+str(m).zfill(4)+".png") # Write to file plt.draw() self.ax.clear()
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))
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)
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)
def testPredator(): window = GraphWin("CS81 Final Project",1000,1000) window.setBackground("blue") preyList = [] p1 = Prey(0,15,15,0,window) p2 = Prey(1,200,350,0,window) p3 = Prey(2,220,350,0,window) p4 = Prey(3,210,350,0,window) p5 = Prey(4,300,400,0,window) p6 = Prey(5,310,405,0,window) p7 = Prey(6,650,30,0,window) p8 = Prey(7,170,320,0,window) preyList.append(p1) preyList.append(p2) preyList.append(p3) preyList.append(p4) preyList.append(p5) preyList.append(p6) preyList.append(p7) preyList.append(p8) shark = Predator(650,650,0,window) while True: for p in preyList: p.setNeighborNumber(preyList) inputs = p.calculateInputs(preyList,shark) if inputs == "DEAD": preyList.remove(p) p.move(1,.5) shark.move(preyList) if window.checkMouse(): sys.exit() return
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)
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()
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()
def main(predator_breed_time=6, predator_starve_time=3, initial_predators=10, prey_breed_time=3, initial_prey=50, size=10, ticks=10): '''Initialization of the simulation''' # Initialize class variables Predator.set_breed_time(predator_breed_time) Predator.set_starve_time(predator_starve_time) Prey.set_breed_time(prey_breed_time) seed = int(input("Enter seed for randomness: ")) random.seed(seed) isle = Island(size) put_animals_at_random(isle, Prey, initial_prey) put_animals_at_random(isle, Predator, initial_predators) print(isle) # The simulation is carried out 'ticks' times for _ in range(ticks): for x in range(size): for y in range(size): animal = isle.animal(x, y) if isinstance(animal, Animal): if isinstance(animal, Predator): # a predator can eat animal.eat() animal.breed() if isinstance(animal, Prey): animal.breed(2) animal.move() animal.clock_tick() isle.clear_all_moved_flags() print(isle)
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)
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)
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()
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")
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()
def eval_individual(chromo,logFP=None): brain = nn.create_phenotype(chromo) sumTime = 0 sumPeople = 0 sumDist = 0 for trial in range(3): window = GraphWin("CS81 Final Project",1000,1000) window.setBackground("blue") preyList = [] time = 0 people = 0 distance = 0 p1 = Prey(0,(random()*800) + 100,(random()*800) + 100,choice([-1,1])*2*pi*random(),window) p2 = Prey(1,(random()*800) + 100,(random()*800) + 100,choice([-1,1])*2*pi*random(),window) p3 = Prey(2,(random()*800) + 100,(random()*800) + 100,choice([-1,1])*2*pi*random(),window) p4 = Prey(3,(random()*800) + 100,(random()*800) + 100,choice([-1,1])*2*pi*random(),window) p5 = Prey(4,(random()*800) + 100,(random()*800) + 100,choice([-1,1])*2*pi*random(),window) p6 = Prey(5,(random()*800) + 100,(random()*800) + 100,choice([-1,1])*2*pi*random(),window) p7 = Prey(6,(random()*800) + 100,(random()*800) + 100,choice([-1,1])*2*pi*random(),window) p8 = Prey(7,(random()*800) + 100,(random()*800) + 100,choice([-1,1])*2*pi*random(),window) p9 = Prey(8,(random()*800) + 100,(random()*800) + 100,choice([-1,1])*2*pi*random(),window) p10 = Prey(9,(random()*800) + 100,(random()*800) + 100,choice([-1,1])*2*pi*random(),window) p11 = Prey(10,(random()*800) + 100,(random()*800) + 100,choice([-1,1])*2*pi*random(),window) p12 = Prey(11,(random()*800) + 100,(random()*800) + 100,choice([-1,1])*2*pi*random(),window) p13 = Prey(12,(random()*800) + 100,(random()*800) + 100,choice([-1,1])*2*pi*random(),window) p14 = Prey(13,(random()*800) + 100,(random()*800) + 100,choice([-1,1])*2*pi*random(),window) p15 = Prey(14,(random()*800) + 100,(random()*800) + 100,choice([-1,1])*2*pi*random(),window) p16 = Prey(15,(random()*800) + 100,(random()*800) + 100,choice([-1,1])*2*pi*random(),window) p17 = Prey(16,(random()*800) + 100,(random()*800) + 100,choice([-1,1])*2*pi*random(),window) p18 = Prey(17,(random()*800) + 100,(random()*800) + 100,choice([-1,1])*2*pi*random(),window) p19 = Prey(18,(random()*800) + 100,(random()*800) + 100,choice([-1,1])*2*pi*random(),window) p20 = Prey(19,(random()*800) + 100,(random()*800) + 100,choice([-1,1])*2*pi*random(),window) preyList.append(p1) preyList.append(p2) preyList.append(p3) preyList.append(p4) preyList.append(p5) preyList.append(p6) preyList.append(p7) preyList.append(p8) preyList.append(p9) preyList.append(p10) preyList.append(p11) preyList.append(p12) preyList.append(p13) preyList.append(p14) preyList.append(p15) preyList.append(p16) preyList.append(p17) preyList.append(p18) preyList.append(p19) preyList.append(p20) shark = Predator(1000,1000,5*pi/4,window) while (len(preyList) > 3) and time < 15000: time += 1 for p in preyList: if time %50 == 0: distance += p.getTraveled() p.setPastX(p.getX()) p.setPastY(p.getY()) brain.flush() inputs = p.calculateInputs(preyList,shark) if inputs == "DEAD": preyList.remove(p) else: outputs = brain.pactivate(inputs) p.move(outputs[0],outputs[1]) if time == 4500: print "Shark attack!" if time > 4500: shark.move(preyList) window.close() people = len(preyList) time -= 4500 time /= float(10500) people /= float(20) distance /= float(75000) sumTime += time sumPeople += people sumDist += distance return .4*(sumTime/3) + .4*(sumPeople/3) + .2*(sumDist/3)
def add_predator(self): pred = Predator(self.get_random_position(), self.predator_radius, self.get_random_velocity()) self.predators.append(pred) return pred