Пример #1
0
	def save_data(self):
		# feeders
		f =  open('data/feeder_push.pkl', 'wb')
		for feeder in breve.allInstances( "Feeder" ):
			temp_feeder = Data_Stationary(feeder.pos_x, feeder.pos_y, feeder.energy, feeder.lastScale, feeder.rapid, feeder.VirtualEnergy)
			cPickle.dump(temp_feeder, f)
		f.close()

		# preys
		f =  open('data/prey_push.pkl', 'wb')
		for prey in breve.allInstances( "Prey" ):
			if prey.isAlive:
				temp_accel = prey.getAcceleration()
				temp_prey = Data_mobile(prey.pos_x, prey.pos_y, prey.vel_x, prey.vel_y, temp_accel.x, temp_accel.y, prey.energy, prey.age, prey.isAlive, prey.maxVel, prey.maxAccel, prey.gener, prey.radius, prey.pushCode.getList(), prey.lastScale)
				cPickle.dump(temp_prey, f)
		for prey in self.pollPreys:
			temp_accel = prey.getAcceleration()
			temp_prey = Data_mobile(prey.pos_x, prey.pos_y, prey.vel_x, prey.vel_y, temp_accel.x, temp_accel.y, prey.energy, prey.age, prey.isAlive, prey.maxVel, prey.maxAccel, prey.gener, prey.radius, prey.pushCode.getList(), prey.lastScale)
			cPickle.dump(temp_prey, f)
		f.close()

		# prepadors
		f =  open('data/predator_push.pkl', 'wb')
		for predator in breve.allInstances( "Predator" ):
			if predator.isAlive:
				temp_accel = predator.getAcceleration()
				temp_predator = Data_mobile(predator.pos_x, predator.pos_y, predator.vel_x, predator.vel_y, temp_accel.x, temp_accel.y, predator.energy, predator.age, predator.isAlive, predator.maxVel, predator.maxAccel, predator.gener, predator.radius, predator.pushCode.getList(), predator.lastScale)
				cPickle.dump(temp_predator, f)
		for predator in self.pollPredators:
			temp_accel = predator.getAcceleration()
			temp_predator = Data_mobile(predator.pos_x, predator.pos_y, predator.vel_x, predator.vel_y, temp_accel.x, temp_accel.y, predator.energy, predator.age, predator.isAlive, predator.maxVel, predator.maxAccel, predator.gener, predator.radius, predator.pushCode.getList(), predator.lastScale)
			cPickle.dump(temp_predator, f)
		f.close()
Пример #2
0
	def save_data(self):
		# feeders
		f =  open('data/feeder_ga.pkl', 'wb')
		for feeder in breve.allInstances( "Feeder" ):
			temp_feeder = Data_Stationary(feeder.pos_x, feeder.pos_y, feeder.energy, feeder.lastScale, feeder.rapid, feeder.VirtualEnergy)
			cPickle.dump(temp_feeder, f)
		f.close()

		# preys
		f =  open('data/prey_ga.pkl', 'wb')
		for prey in breve.allInstances( "Prey" ):
			if prey.isAlive:
				temp_accel = prey.getAcceleration()
				temp_prey = Data_mobile(prey.pos_x, prey.pos_y, prey.vel_x, prey.vel_y, temp_accel.x, temp_accel.y, prey.energy, prey.age, prey.isAlive, prey.maxVel, prey.maxAccel, prey.gener, prey.radius, prey.geno, prey.lastScale)
				cPickle.dump(temp_prey, f)
		for prey in self.pollPreys:
			temp_accel = prey.getAcceleration()
			temp_prey = Data_mobile(prey.pos_x, prey.pos_y, prey.vel_x, prey.vel_y, temp_accel.x, temp_accel.y, prey.energy, prey.age, prey.isAlive, prey.maxVel, prey.maxAccel, prey.gener, prey.radius, prey.geno, prey.lastScale)
			cPickle.dump(temp_prey, f)
		f.close()

		# prepadors
		f =  open('data/predator_ga.pkl', 'wb')
		for predator in breve.allInstances( "Predator" ):
			if predator.isAlive:
				temp_accel = predator.getAcceleration()
				temp_predator = Data_mobile(predator.pos_x, predator.pos_y, predator.vel_x, predator.vel_y, temp_accel.x, temp_accel.y, predator.energy, predator.age, predator.isAlive, predator.maxVel, predator.maxAccel, predator.gener, predator.radius, predator.geno, predator.lastScale)
				cPickle.dump(temp_predator, f)
		for predator in self.pollPredators:
			temp_accel = predator.getAcceleration()
			temp_predator = Data_mobile(predator.pos_x, predator.pos_y, predator.vel_x, predator.vel_y, temp_accel.x, temp_accel.y, predator.energy, predator.age, predator.isAlive, predator.maxVel, predator.maxAccel, predator.gener, predator.radius, predator.geno, predator.lastScale)
			cPickle.dump(temp_predator, f)
		f.close()
Пример #3
0
	def iterate( self ):
		self.updateNeighbors()

		self.numBirds = 0
		for bird in breve.allInstances( "Bird" ):
			if bird.isAlive:
				bird.fly()
				self.numBirds += 1

		self.numPred = 0
		for predator in breve.allInstances( "Predator" ):
			if predator.isAlive:
				predator.fly()
				self.numPred += 1

		self.totalFoodSupply = 0
		for feeder in breve.allInstances( "Feeder" ):
			if feeder.rapid:
				feeder.rapidGrow()
				self.totalFoodSupply += feeder.VirtualEnergy
			self.totalFoodSupply += feeder.energy
			if feeder.energy <= 0 and not feeder.rapid:
				breve.deleteInstances( feeder )
		self.addRandomFeederIfNecessary(rapid=True)

		for corpse in breve.allInstances( "Corpse" ):
			corpse.changeColor()
			if sum(corpse.getColor()) <= 0:	
				breve.deleteInstances( corpse.shape )
				breve.deleteInstances( corpse )

		self.current_generation += 1
		if self.current_generation % self.breeding_season == 0:
			if breve.length(self.pollBirds) < self.breeding_inc*self.numBirds:
				new_birds = int(math.ceil(self.breeding_inc*self.numBirds)) - breve.length(self.pollBirds)
				breve.createInstances( breve.Bird, new_birds).dropDead(False)

			if breve.length(self.pollPredators) < self.breeding_inc*self.numPred:
				new_preds = int(math.ceil(self.breeding_inc*self.numPred)) - breve.length(self.pollPredators)
				breve.createInstances( breve.Predator, new_preds).dropDead(False)

			for i in range(int(math.ceil(self.breeding_inc*self.numBirds))):
				self.evolutionayAlgorithm(self.pollBirds)
			if self.numPred < self.numBirds*self.max_pop_predadors:
				for i in range(int(min(math.ceil(self.breeding_inc*self.numPred), self.numBirds*self.max_pop_predadors))):
					self.evolutionayAlgorithm(self.pollPredators)


		self.setDisplayText("Birds Alive: "+str(self.numBirds), xLoc = -0.950000, yLoc = -0.650000, messageNumber = 2, theColor = breve.vector( 1, 1, 1 ))
		self.setDisplayText("Predators Alive: "+str(self.numPred), xLoc = -0.950000, yLoc = -0.750000, messageNumber = 3, theColor = breve.vector( 1, 1, 1 ))
		self.setDisplayText("Dead Birds: "+str(self.num_dead_birds), xLoc = -0.950000, yLoc = -0.850000, messageNumber = 0, theColor = breve.vector( 1, 1, 1 ))
		self.setDisplayText("Dead Predators: "+str(self.num_dead_predators), xLoc = -0.950000, yLoc = -0.950000, messageNumber = 1, theColor = breve.vector( 1, 1, 1 ))

		# needed to move the agents with velocity and acceleration
		# also needed to detect collisions
		# print str(self.numBirdsBirth)

		breve.Control.iterate( self )
    def init(self):
        n = 0
        m = 0
        k = 0
        j = 0
        i = 0

        self.setBackgroundColor(breve.vector(1, 1, 1))
        self.setIterationStep(1.000000)
        self.setIntegrationStep(1.000000)
        self.pointCamera(breve.vector(0, 0, 0), breve.vector(30, 6, -30))
        self.U = breve.createInstances(breve.Matrix3D, 1)
        self.V = breve.createInstances(breve.Matrix3D, 1)
        self.inflow = breve.createInstances(breve.Matrix3D, 1)
        self.temp = breve.createInstances(breve.Matrix3D, 1)
        self.tempreact = breve.createInstances(breve.Matrix3D, 1)
        self.U.setSize(32, 32, 32)
        self.V.setSize(32, 32, 32)
        self.temp.setSize(32, 32, 32)
        self.tempreact.setSize(32, 32, 32)
        self.inflow.setSize(32, 32, 32)
        self.grid = breve.createInstances(breve.PatchGrid, 1)
        self.grid.initWith(breve.vector(0.500000, 0.500000, 0.500000), 32, 32,
                           32)
        self.grid.enableSmoothDrawing()
        self.inflow.setAllValues(0.010000)
        i = 0
        while (i < 32):
            n = 0
            while (n < 32):
                m = 0
                while (m < 32):
                    self.U.setValue(
                        ((0.500000 + breve.breveInternalFunctionFinder.sqrt(
                            self,
                            breve.length(
                                (0.250000 -
                                 ((0.010000 * (1.000000 +
                                               (0.040000 / 0.010000))) *
                                  (1.000000 + (0.040000 / 0.010000))))))) +
                         (0.010000 *
                          (breve.randomExpression(1.000000) - 0.500000))), m,
                        n, i)
                    self.V.setValue(
                        (((1.000000 - self.U.getValue(m, n, i)) /
                          (1.000000 + (0.040000 / 0.010000))) +
                         (0.010000 *
                          (breve.randomExpression(1.000000) - 0.500000))), m,
                        n, i)

                    m = (m + 1)

                n = (n + 1)

            i = (i + 1)

        breve.allInstances("Patches").setTransparency(0.900000)
	def iterate( self ):
		self.updateNeighbors()

		self.numBirds = 0
		for bird in breve.allInstances( "Bird" ):
			if bird.isAlive:
				bird.fly()
				self.numBirds += 1

		self.numPred = 0
		for predator in breve.allInstances( "Predator" ):
			if predator.isAlive:
				predator.fly()
				self.numPred += 1

		self.totalFoodSupply = 0
		for feeder in breve.allInstances( "Feeder" ):
			if feeder.rapid:
				feeder.rapidGrow()
				self.totalFoodSupply += feeder.VirtualEnergy
			self.totalFoodSupply += feeder.energy
			if feeder.energy <= 0 and not feeder.rapid:
				breve.deleteInstances( feeder )
		self.addRandomFeederIfNecessary(rapid=True)

		for corpse in breve.allInstances( "Corpse" ):
			corpse.changeColor()
			if sum(corpse.getColor()) <= 0:	
				breve.deleteInstances( corpse.shape )
				breve.deleteInstances( corpse )

		self.current_generation += 1
		if self.current_generation % self.breeding_season == 0:
			if breve.length(self.pollBirds) < self.breeding_inc*self.numBirds:
				new_birds = int(math.ceil(self.breeding_inc*self.numBirds)) - breve.length(self.pollBirds)
				breve.createInstances( breve.Bird, new_birds).dropDead(False)

			if breve.length(self.pollPredators) < self.breeding_inc*self.numPred:
				new_preds = int(math.ceil(self.breeding_inc*self.numPred)) - breve.length(self.pollPredators)
				breve.createInstances( breve.Predator, new_preds).dropDead(False)

			for i in range(int(math.ceil(self.breeding_inc*self.numBirds))/2):
				self.evolutionayAlgorithm(self.pollBirds)
			if self.numPred < self.numBirds*self.max_pop_predadors:
				for i in range(int(min(math.ceil(self.breeding_inc*self.numPred), self.numBirds*self.max_pop_predadors))/2):
					self.evolutionayAlgorithm(self.pollPredators)

		self.setDisplayText("Birds Alive: "+str(self.numBirds), xLoc = -0.950000, yLoc = -0.650000, messageNumber = 2, theColor = breve.vector( 1, 1, 1 ))
		self.setDisplayText("Predators Alive: "+str(self.numPred), xLoc = -0.950000, yLoc = -0.750000, messageNumber = 3, theColor = breve.vector( 1, 1, 1 ))
		self.setDisplayText("Dead Birds: "+str(self.num_dead_birds), xLoc = -0.950000, yLoc = -0.850000, messageNumber = 0, theColor = breve.vector( 1, 1, 1 ))
		self.setDisplayText("Dead Predators: "+str(self.num_dead_predators), xLoc = -0.950000, yLoc = -0.950000, messageNumber = 1, theColor = breve.vector( 1, 1, 1 ))

		# needed to move the agents with velocity and acceleration
		# also needed to detect collisions
		# print str(self.numBirdsBirth)

		breve.Control.iterate( self )
Пример #6
0
	def init( self ):
		floor = None
		i = 0

		self.stability = 1100
		if ( self.getArgumentCount() > 1 ):
			self.runID = self.getArgument( 1 )
			self.shareMode = self.getArgument( 2 )
			print '''running with runID = %s''' % (  self.runID )
			print '''running with shareMode = %s''' % (  self.shareMode )


		self.nextID = 0
		self.births = 0
		breve.createInstances( breve.Birds, 10 )
		breve.allInstances( "Birds" ).initializeRandomly()
		self.feeders = breve.createInstances( breve.Feeders, 20 )
		self.randomBirdsAdded = 10
		floor = breve.createInstances( breve.Stationary, 1 )
		floor.register( breve.createInstances( breve.Cube, 1 ).initWith( breve.vector( 100, 2, 100 ) ), breve.vector( 0, -5, 0 ) )
		floor.catchShadows()
		self.deaths = 0
		self.decisions = 0
		self.foodDeviations = 0
		self.friendFeedings = 0
		self.otherFeedings = 0
		self.reproductiveDiscounts = 0
		self.reproMutations = 0
		self.reproMutationRates = 0.000000
		self.discrepancies = 0.000000
		self.naturalBirths = 0
		self.corpseShape = breve.createInstances( breve.PolygonCone, 1 ).initWith( 5, 0.200000, 0.060000 )
		self.servos = 0
		self.enableLighting()
		self.moveLight( breve.vector( 0, 20, 20 ) )
		self.autoCameraMenu = self.addMenu( '''Automatic Camera Control''', 'setAutoCameraMode' )
		self.manualCameraMenu = self.addMenu( '''Manual Camera Control''', 'setManualCameraMode' )
		self.autoCameraMode = 1
		self.autoCameraMenu.check()
		self.manualCameraMenu.uncheck()
		self.unitDriftMode = 0
		i = 0
		self.setInterfaceItem( 666, '''%s''' % (  i ) )
		self.addMenuSeparator()
		self.drawEveryFrameMenu = self.addMenu( '''Draw Every Frame''', 'setDrawEveryFrame' )
		self.skipFramesIfNecessaryMenu = self.addMenu( '''Skip Frames if Necessary''', 'setSkipFramesIfNecessaryMenu' )
		self.drawEveryFrameMenu.check()
		self.skipFramesIfNecessaryMenu.uncheck()
		#self.setBackgroundTextureImage( breve.createInstances( breve.Image, 1 ).load( 'images/clouds.png' ) )
		self.offsetCamera( breve.vector( 5, 1.500000, 6 ) )
		self.cameraHasBeenAimed = 0
		self.maxZoomDelta = 0.050000
		self.maxAimDelta = 0.050000
		self.enableShadows()
		self.disableText()
	def init( self ):
		floor = None
		i = 0

		self.stability = 1100
		if ( self.getArgumentCount() > 1 ):
			self.runID = self.getArgument( 1 )
			self.shareMode = self.getArgument( 2 )
			print '''running with runID = %s''' % (  self.runID )
			print '''running with shareMode = %s''' % (  self.shareMode )


		self.nextID = 0
		self.births = 0
		breve.createInstances( breve.Birds, 10 )
		breve.allInstances( "Birds" ).initializeRandomly()
		self.feeders = breve.createInstances( breve.Feeders, 20 )
		self.randomBirdsAdded = 10
		floor = breve.createInstances( breve.Stationary, 1 )
		floor.register( breve.createInstances( breve.Cube, 1 ).initWith( breve.vector( 100, 2, 100 ) ), breve.vector( 0, -5, 0 ) )
		floor.catchShadows()
		self.deaths = 0
		self.decisions = 0
		self.foodDeviations = 0
		self.friendFeedings = 0
		self.otherFeedings = 0
		self.reproductiveDiscounts = 0
		self.reproMutations = 0
		self.reproMutationRates = 0.000000
		self.discrepancies = 0.000000
		self.naturalBirths = 0
		self.corpseShape = breve.createInstances( breve.PolygonCone, 1 ).initWith( 5, 0.200000, 0.060000 )
		self.servos = 0
		self.enableLighting()
		self.moveLight( breve.vector( 0, 20, 20 ) )
		self.autoCameraMenu = self.addMenu( '''Automatic Camera Control''', 'setAutoCameraMode' )
		self.manualCameraMenu = self.addMenu( '''Manual Camera Control''', 'setManualCameraMode' )
		self.autoCameraMode = 1
		self.autoCameraMenu.check()
		self.manualCameraMenu.uncheck()
		self.unitDriftMode = 0
		i = 0
		self.setInterfaceItem( 666, '''%s''' % (  i ) )
		self.addMenuSeparator()
		self.drawEveryFrameMenu = self.addMenu( '''Draw Every Frame''', 'setDrawEveryFrame' )
		self.skipFramesIfNecessaryMenu = self.addMenu( '''Skip Frames if Necessary''', 'setSkipFramesIfNecessaryMenu' )
		self.drawEveryFrameMenu.check()
		self.skipFramesIfNecessaryMenu.uncheck()
		self.setBackgroundTextureImage( breve.createInstances( breve.Image, 1 ).load( 'images/clouds.png' ) )
		self.offsetCamera( breve.vector( 5, 1.500000, 6 ) )
		self.cameraHasBeenAimed = 0
		self.maxZoomDelta = 0.050000
		self.maxAimDelta = 0.050000
		self.enableShadows()
		self.disableText()
Пример #8
0
    def getCurrentCritterFitness(self):
        t = breve.vector()
        link = None

        for link in breve.allInstances("Links"):
            t = (t + link.getLocation())

        if breve.length(breve.allInstances("Links")):
            t = (t / breve.length(breve.allInstances("Links")))

        return breve.length((t - self.startlocation))
Пример #9
0
	def getCurrentCritterFitness( self ):
		t = breve.vector()
		link = None

		for link in breve.allInstances( "Links" ):
			t = ( t + link.getLocation() )


		if breve.length( breve.allInstances( "Links" ) ):
			t = ( t / breve.length( breve.allInstances( "Links" ) ) )

		return breve.length( ( t - self.startlocation ) )
	def init( self ):
		fields = breve.objectList()
		average = breve.vector()
		atomString = ''

		self.setBackgroundColor( breve.vector( 0.600000, 0.600000, 0.600000 ) )
		self.enableLighting()
		self.hShape = breve.createInstances( breve.Sphere, 1 ).initWith( 0.200000 )
		self.file = breve.createInstances( breve.File, 1 )
		if ( self.getArgumentCount() > 1 ):
			self.file.openForReading( self.getArgument( 1 ) )

		else:
			self.file.openForReading( 'DNA.pdb' )


		while ( breve.length( fields = self.file.readLineAsWhitespaceDelimitedList() ) != 0 ):
			if ( fields[ 0 ] == 'ATOM' ):
				if ( breve.length( fields ) == 10 ):
					atomString = fields[ 9 ]
					self.location = breve.vector( fields[ 5 ], fields[ 6 ], fields[ 7 ] )

				else:
					atomString = fields[ 11 ]
					self.location = breve.vector( fields[ 6 ], fields[ 7 ], fields[ 8 ] )


				average = ( average + self.location )
				self.atom = breve.createInstances( breve.Mobile, 1 )
				self.atom.move( self.location )
				if ( atomString == 'C' ):
					self.atom.setColor( breve.vector( 0, 0, 0 ) )

				if ( atomString == 'O' ):
					self.atom.setColor( breve.vector( 0, 0, 1 ) )

				if ( atomString == 'N' ):
					self.atom.setColor( breve.vector( 0, 1, 0 ) )

				if ( atomString == 'P' ):
					self.atom.setColor( breve.vector( 1, 0, 0 ) )

				if ( atomString == 'H' ):
					self.atom.setShape( self.hShape )





		average = ( average / breve.length( breve.allInstances( "Mobiles" ) ) )
		print breve.length( breve.allInstances( "Mobiles" ) ), ''' atoms'''
		self.pointCamera( average, ( average + breve.vector( 30, 0, 30 ) ) )
Пример #11
0
	def unwatch(self, obj): # return whether the object was the target or not
		if obj == self.watchObject:
			targets = breve.allInstances(MaleVehicle) + breve.allInstances(FemaleVehicle) + breve.allInstances(Egg)
			targets.remove(obj)
			try:
				self.watch(sample(targets, 1)[0])
			except ValueError:
				self.watch(None)
				self.pause()

			return True

		return False
Пример #12
0
	def reset( self ):
		breve.allInstances( "Mobiles" ).setVelocity( breve.vector( 0, 0, 0 ) )
		self.vehicle.rotate( breve.vector( 1, 0, 0 ), 0 )
		self.blocks[ 0 ].move( breve.vector( 65, 0.600000, -1.650000 ) )
		self.blocks[ 1 ].move( breve.vector( 65, 0.600000, -0.550000 ) )
		self.blocks[ 2 ].move( breve.vector( 65, 0.600000, 0.550000 ) )
		self.blocks[ 3 ].move( breve.vector( 65, 0.600000, 1.650000 ) )
		self.blocks[ 4 ].move( breve.vector( 65, 1.610000, -1.100000 ) )
		self.blocks[ 5 ].move( breve.vector( 65, 1.610000, 0 ) )
		self.blocks[ 6 ].move( breve.vector( 65, 1.610000, 1.100000 ) )
		self.blocks[ 7 ].move( breve.vector( 65, 2.620000, -0.550000 ) )
		self.blocks[ 8 ].move( breve.vector( 65, 2.620000, 0.550000 ) )
		self.blocks[ 9 ].move( breve.vector( 65, 3.630000, 0 ) )
		self.blocks.setRotationMatrix( breve.matrix(  1, 0, 0, 0, 1, 0, 0, 0, 1 ) )
		self.vehicle.move( breve.vector( 0, 0.800000, 0 ) )
Пример #13
0
    def getCurrentCritterFitness(self):
        link = None
        mindist = 0

        if (breve.length(breve.allInstances("Links")) == 0):
            return 0.000000

        mindist = 10000
        for link in breve.allInstances("Links"):
            if (breve.length(
                (link.getLocation() - link._startLocation)) < mindist):
                mindist = breve.length(
                    (link.getLocation() - link._startLocation))

        return mindist
Пример #14
0
	def getCurrentCritterFitness( self ):
		link = None
		mindist = 0

		if ( breve.length( breve.allInstances( "Links" ) ) == 0 ):
			return 0.000000

		mindist = 10000
		for link in breve.allInstances( "Links" ):
			if ( breve.length( ( link.getLocation() - link._startLocation ) ) < mindist ):
				mindist = breve.length( ( link.getLocation() - link._startLocation ) )



		return mindist
Пример #15
0
    def iterate(self):
        self.updateNeighbors()

        for bird in breve.allInstances("Bird"):
            if bird.isAlive:
                bird.fly()

        for predator in breve.allInstances("Predator"):
            if predator.isAlive:
                predator.fly()

        self.totalFoodSupply = 0
        for feeder in breve.allInstances("Feeder"):
            if feeder.rapid:
                feeder.rapidGrow()
                self.totalFoodSupply += feeder.VirtualEnergy
            self.totalFoodSupply += feeder.energy
            if feeder.energy <= 0 and not feeder.rapid:
                breve.deleteInstances(feeder)
        self.addRandomFeederIfNecessary(rapid=True)

        for corpse in breve.allInstances("Corpse"):
            corpse.changeColor()
            if sum(corpse.getColor()) <= 0:
                breve.deleteInstances(corpse.shape)
                breve.deleteInstances(corpse)

        for i in range(breve.length(self.pollBirds)):
            self.evolutionayAlgorithm(self.pollBirds)
        for i in range(breve.length(self.pollPredators)):
            self.evolutionayAlgorithm(self.pollPredators)

        self.setDisplayText("Dead Birds: " + str(self.num_dead_birds),
                            xLoc=-0.950000,
                            yLoc=-0.850000,
                            messageNumber=0,
                            theColor=breve.vector(1, 1, 1))
        self.setDisplayText("Dead Predators: " + str(self.num_dead_predators),
                            xLoc=-0.950000,
                            yLoc=-0.950000,
                            messageNumber=1,
                            theColor=breve.vector(1, 1, 1))

        # needed to move the agents with velocity and acceleration
        # also needed to detect collisions
        # print str(self.numBirdsBirth)

        breve.Control.iterate(self)
Пример #16
0
    def send(self, message):
        qtest = 0
        agents = breve.objectList()
        i = None
        col = 0

        col = breve.randomExpression(100)
        self.updatePos()
        self.draw.clear()
        agents = breve.allInstances("basicAgent")
        self.draw.setColor(breve.vector(1, 0, 0))
        self.draw.drawLine(self.getLocation(),
                           (self.getLocation() +
                            (self.getRotation() * breve.vector(0, 0, 27))))
        for i in agents:
            if (i != self.owner):
                qtest = (
                    233 *
                    breve.breveInternalFunctionFinder.calculateQualityToObject(
                        self, self.realWorldPointer_owner, self.getLocation(),
                        self.getRotation(), i.getRealWorldPointer(),
                        self.sensorType))
                self.draw.setColor(breve.vector(0, 0, 0))
                if (qtest > self.communicationThreshold):
                    i.receiveMessage2(message, self.getOwner())
Пример #17
0
    def iterate(self):
        i = None
        lights = 0
        angle = 0
        strength = 0
        total = 0
        transDir = breve.vector()
        toLight = breve.vector()

        transDir = (self.getRotation() * self.direction)
        for i in breve.allInstances("BraitenbergLights"):
            toLight = (i.getLocation() - self.getLocation())
            angle = breve.breveInternalFunctionFinder.angle(
                self, toLight, transDir)
            if (angle < self.sensorAngle):
                strength = breve.length((self.getLocation() - i.getLocation()))
                strength = (1.000000 / (strength * strength))
                if (self.activationMethod and self.activationObject):
                    strength = self.activationObject.callMethod(
                        self.activationMethod, [strength])

                if (strength > 10):
                    strength = 10

                total = (total + strength)
                lights = (lights + 1)

        if (lights != 0):
            total = (total / lights)

        total = ((50 * total) * self.bias)
        self.wheels.activate(total)
Пример #18
0
	def selectParent( self, specie):
		birds = breve.objectList()
		for item in breve.allInstances( specie ):
			if item.isAlive:
				birds.append( item )
		parent = self.tournament(birds, 5)
		return parent
Пример #19
0
	def iterate( self ):
		i = None
		lights = 0
		angle = 0
		strength = 0
		total = 0
		transDir = breve.vector()
		toLight = breve.vector()

		transDir = ( self.getRotation() * self.direction )
		for i in breve.allInstances( "BraitenbergLights" ):
			toLight = ( i.getLocation() - self.getLocation() )
			angle = breve.breveInternalFunctionFinder.angle( self, toLight, transDir )
			if ( angle < self.sensorAngle ):
				strength = breve.length( ( self.getLocation() - i.getLocation() ) )
				strength = ( 1.000000 / ( strength * strength ) )
				if ( self.activationMethod and self.activationObject ):
					strength = self.activationObject.callMethod( self.activationMethod, [ strength ] )


				if ( strength > 10 ):
					strength = 10

				total = ( total + strength )
				lights = ( lights + 1 )




		if ( lights != 0 ):
			total = ( total / lights )

		total = ( ( 50 * total ) * self.bias )
		self.wheels.activate( total )
Пример #20
0
 def selectParent(self, specie):
     birds = breve.objectList()
     for item in breve.allInstances(specie):
         if item.isAlive:
             birds.append(item)
     parent = self.tournament(birds, 5)
     return parent
Пример #21
0
	def iterate( self ):
		'''Calculates the signal strength according to the closest source that it finds within the it's range.'''
		i = None
		objects = 0
		angle = 0
		strength = 0
		total = 0
		transDir = breve.vector()
		dist = breve.vector()

		minDist=None
		
		transDir = ( self.getRotation() * self.direction )
		'''Only detects blocks.'''
		for i in breve.allInstances( "BraitenbergBlocks" ):
			dist = ( i.getLocation() - self.getLocation() )
			angle = breve.breveInternalFunctionFinder.angle( self, dist, transDir )
			'''It's inside the angle and it's closer than any other block analyzed so far.'''
			if angle < self.sensorAngle :
				t = breve.length(self.getLocation() - i.getLocation())
				
				'''Updates the min distance.'''
				if minDist == None or t < minDist:
					minDist = t
					
				strength = breve.length( ( self.getLocation() - i.getLocation() ) )
				strength = ( 1.000000 / ( strength * strength ) )

				total = strength

		total = ( ( 50 * total ) * self.bias )
		self.wheels.activate( total )
Пример #22
0
	def iterate( self ):
		i = None
		lights = 0
		angle = 0
		strength = 0
		total = 0
		transDir = breve.vector()
		toLight = breve.vector()

		transDir = ( self.getRotation() * self.direction )
		'''It's by the sensorType string that we distinguish between a sound, olfaction or light sensor. '''
		for i in breve.allInstances( self.sensorType ):
			toLight = ( i.getLocation() - self.getLocation() )
			angle = breve.breveInternalFunctionFinder.angle( self, toLight, transDir )
			if ( angle < self.sensorAngle ):
				strength = breve.length( ( self.getLocation() - i.getLocation() ) )
				strength = ( 1.000000 / ( strength * strength ) )
				if ( self.activationObject ):
					strength = self.activationObject.activate(strength)

				if ( strength > 10 ):
					strength = 10

				total = ( total + strength )
				lights = ( lights + 1 )

		if ( lights != 0 ):
			total = ( total / lights )

		total = ( ( 50 * total ) * self.bias )
		self.wheels.activate( total )
Пример #23
0
    def send(self, message):
        qtest = 0
        agents = breve.objectList()
        i = None
        col = 0

        col = breve.randomExpression(100)
        self.updatePos()
        self.draw.clear()
        agents = breve.allInstances("basicAgent")
        self.draw.setColor(breve.vector(1, 0, 0))
        self.draw.drawLine(self.getLocation(), (self.getLocation() + (self.getRotation() * breve.vector(0, 0, 27))))
        for i in agents:
            if i != self.owner:
                qtest = 233 * breve.breveInternalFunctionFinder.calculateQualityToObject(
                    self,
                    self.realWorldPointer_owner,
                    self.getLocation(),
                    self.getRotation(),
                    i.getRealWorldPointer(),
                    self.sensorType,
                )
                self.draw.setColor(breve.vector(0, 0, 0))
                if qtest > self.communicationThreshold:
                    i.receiveMessage2(message, self.getOwner())
Пример #24
0
	def addRandomBirdsIfNecessary( self ):
		numBirds = 0

		numBirds = breve.length( breve.allInstances( "Birds" ) )
		if ( numBirds < 10 ):
			breve.createInstances( breve.Bird, 1 ).initializeRandomly()
			self.randomBirdsAdded = ( self.randomBirdsAdded + 1 )
			self.addRandomBirdsIfNecessary()
	def addRandomBirdsIfNecessary( self ):
		numBirds = 0

		numBirds = breve.length( breve.allInstances( "Birds" ) )
		if ( numBirds < 10 ):
			breve.createInstances( breve.Bird, 1 ).initializeRandomly()
			self.randomBirdsAdded = ( self.randomBirdsAdded + 1 )
			self.addRandomBirdsIfNecessary()
Пример #26
0
	def selectNearParent( self, parent1, specie):
		# neighbour = parent1.getNeighbors()
		birds = breve.objectList()
		neighbour = breve.allInstances( specie )

		for item in neighbour:
			if item.isA( specie ) and item.isAlive:
				birds.append( item )
		parent2 = self.tournament(birds, 5)
		return parent2
Пример #27
0
	def iterate( self ):
		t = breve.vector()
		dist = 0
		link = None

		for link in breve.allInstances( "Links" ):
			t = ( t + link.getLocation() )


		if breve.length( breve.allInstances( "Links" ) ):
			t = ( t / breve.length( breve.allInstances( "Links" ) ) )

		self.pointCamera( t )
		dist = self.getCurrentCritterFitness()
		if self.running:
			self.setDisplayText( '''Distance traveled: %s''' % (  dist ), -0.950000, -0.950000 )

		self.pivotCamera( 0.000000, 0.000200 )
		breve.PhysicalControl.iterate( self )
Пример #28
0
    def iterate(self):
        t = breve.vector()
        dist = 0
        link = None

        for link in breve.allInstances("Links"):
            t = (t + link.getLocation())

        if breve.length(breve.allInstances("Links")):
            t = (t / breve.length(breve.allInstances("Links")))

        self.pointCamera(t)
        dist = self.getCurrentCritterFitness()
        if self.running:
            self.setDisplayText('''Distance traveled: %s''' % (dist),
                                -0.950000, -0.950000)

        self.pivotCamera(0.000000, 0.000200)
        breve.PhysicalControl.iterate(self)
Пример #29
0
	def iterate( self ):
		item = None
		swarmCenter = breve.vector()
		numBirds = 0

		numBirds = breve.length( breve.allInstances( "Birds" ) )
		self.iteration = ( self.iteration + 1 )
		if ( self.iteration > 6000 ):
			raise Exception( '''%s iterations complete''' % (  self.iteration ) )


		self.updateNeighbors()
		swarmCenter = breve.vector( 0, 0, 0 )
		for item in breve.allInstances( "Birds" ):
			if item:
				item.fly()

			if item:
				swarmCenter = ( swarmCenter + item.getLocation() )



		swarmCenter = ( swarmCenter / numBirds )
		if self.autoCameraMode:
			self.adjustCamera( swarmCenter )

		for item in breve.allInstances( "Birds" ):
			item.adjustSize()

		for item in breve.allInstances( "Birds" ):
			if ( ( item.getEnergy() == 0 ) or ( item.getAge() > 150 ) ):
				item.dropDead()


		self.addRandomBirdsIfNecessary()
		self.feeders.maybeTeleport()
		self.controller.displayFoodSupply()
		self.controller.displayPopulation()
		self.controller.displayIteration()
		if ( ( self.iteration % 100 ) == 0 ):
			self.report()

		breve.Control.iterate( self )
Пример #30
0
    def selectNearParent(self, parent1, specie):
        #neighbour = parent1.getNeighbors()
        birds = breve.objectList()
        neighbour = breve.allInstances(specie)

        for item in neighbour:
            if item.isA(specie) and item.isAlive:
                birds.append(item)
        parent2 = self.tournament(birds, 5)
        return parent2
	def iterate( self ):
		item = None
		swarmCenter = breve.vector()
		numBirds = 0

		numBirds = breve.length( breve.allInstances( "Birds" ) )
		self.iteration = ( self.iteration + 1 )
		if ( self.iteration > 6000 ):
			raise Exception( '''%s iterations complete''' % (  self.iteration ) )


		self.updateNeighbors()
		swarmCenter = breve.vector( 0, 0, 0 )
		for item in breve.allInstances( "Birds" ):
			if item:
				item.fly()

			if item:
				swarmCenter = ( swarmCenter + item.getLocation() )



		swarmCenter = ( swarmCenter / numBirds )
		if self.autoCameraMode:
			self.adjustCamera( swarmCenter )

		for item in breve.allInstances( "Birds" ):
			item.adjustSize()

		for item in breve.allInstances( "Birds" ):
			if ( ( item.getEnergy() == 0 ) or ( item.getAge() > 150 ) ):
				item.dropDead()


		self.addRandomBirdsIfNecessary()
		self.feeders.maybeTeleport()
		self.controller.displayFoodSupply()
		self.controller.displayPopulation()
		self.controller.displayIteration()
		if ( ( self.iteration % 100 ) == 0 ):
			self.report()

		breve.Control.iterate( self )
Пример #32
0
	def init( self ):
		n = 0
		m = 0
		k = 0
		j = 0
		i = 0

		self.setBackgroundColor( breve.vector( 1, 1, 1 ) )
		self.setIterationStep( 1.000000 )
		self.setIntegrationStep( 1.000000 )
		self.pointCamera( breve.vector( 0, 0, 0 ), breve.vector( 30, 6, -30 ) )
		self.U = breve.createInstances( breve.Matrix3D, 1 )
		self.V = breve.createInstances( breve.Matrix3D, 1 )
		self.inflow = breve.createInstances( breve.Matrix3D, 1 )
		self.temp = breve.createInstances( breve.Matrix3D, 1 )
		self.tempreact = breve.createInstances( breve.Matrix3D, 1 )
		self.U.setSize( 32, 32, 32 )
		self.V.setSize( 32, 32, 32 )
		self.temp.setSize( 32, 32, 32 )
		self.tempreact.setSize( 32, 32, 32 )
		self.inflow.setSize( 32, 32, 32 )
		self.grid = breve.createInstances( breve.PatchGrid, 1 )
		self.grid.initWith( breve.vector( 0.500000, 0.500000, 0.500000 ), 32, 32, 32 )
		self.grid.enableSmoothDrawing()
		self.inflow.setAllValues( 0.010000 )
		i = 0
		while ( i < 32 ):
			n = 0
			while ( n < 32 ):
				m = 0
				while ( m < 32 ):
					self.U.setValue( ( ( 0.500000 + breve.breveInternalFunctionFinder.sqrt( self, breve.length( ( 0.250000 - ( ( 0.010000 * ( 1.000000 + ( 0.040000 / 0.010000 ) ) ) * ( 1.000000 + ( 0.040000 / 0.010000 ) ) ) ) ) ) ) + ( 0.010000 * ( breve.randomExpression( 1.000000 ) - 0.500000 ) ) ), m, n, i )
					self.V.setValue( ( ( ( 1.000000 - self.U.getValue( m, n, i ) ) / ( 1.000000 + ( 0.040000 / 0.010000 ) ) ) + ( 0.010000 * ( breve.randomExpression( 1.000000 ) - 0.500000 ) ) ), m, n, i )

					m = ( m + 1 )

				n = ( n + 1 )

			i = ( i + 1 )

		breve.allInstances( "Patches" ).setTransparency( 0.900000 )
Пример #33
0
	def setupTest( self, i ):
		l = None
		low = breve.vector()
		lowest = 0

		for l in breve.allInstances( "Links" ):
			breve.deleteInstances( l.getShape() )

		breve.deleteInstances( breve.allInstances( "Links" ) )
		breve.deleteInstances( breve.allInstances( "Joints" ) )
		if self.body:
			breve.deleteInstances( self.body )

		self.body = breve.createInstances( breve.MultiBody, 1 )
		self.body.setRoot( self.parser.parseTopLevel( i.getGenome().getRoot() ) )
		self.body.disableSelfCollisions()
		self.addDependency( self.body )
		self.schedule( 'checkPenetration', ( self.getTime() + 8.000000 ) )
		self.setDisplayText( '''Preparing to test %s...''' % (  i ), -0.950000, -0.950000 )
		self.updateText()
		self.running = 0
Пример #34
0
	def iterate( self ):
		self.updateNeighbors()

		for bird in breve.allInstances( "Bird" ):
			if bird.isAlive:
				bird.fly()

		for predator in breve.allInstances( "Predator" ):
			if predator.isAlive:
				predator.fly()

		self.totalFoodSupply = 0
		for feeder in breve.allInstances( "Feeder" ):
			if feeder.rapid:
				feeder.rapidGrow()
				self.totalFoodSupply += feeder.VirtualEnergy
			self.totalFoodSupply += feeder.energy
			if feeder.energy <= 0 and not feeder.rapid:
				breve.deleteInstances( feeder )
		self.addRandomFeederIfNecessary(rapid=True)

		for corpse in breve.allInstances( "Corpse" ):
			corpse.changeColor()
			if sum(corpse.getColor()) <= 0:	
				breve.deleteInstances( corpse.shape )
				breve.deleteInstances( corpse )

		for i in range(breve.length(self.pollBirds)):
			self.evolutionayAlgorithm(self.pollBirds)
		for i in range(breve.length(self.pollPredators)):
			self.evolutionayAlgorithm(self.pollPredators)

		self.setDisplayText("Dead Birds: "+str(self.num_dead_birds), xLoc = -0.950000, yLoc = -0.850000, messageNumber = 0, theColor = breve.vector( 1, 1, 1 ))
		self.setDisplayText("Dead Predators: "+str(self.num_dead_predators), xLoc = -0.950000, yLoc = -0.950000, messageNumber = 1, theColor = breve.vector( 1, 1, 1 ))

		# needed to move the agents with velocity and acceleration
		# also needed to detect collisions
		# print str(self.numBirdsBirth)

		breve.Control.iterate( self )
Пример #35
0
	def init( self ):
		rampShape = None
		ramp = None

		rampShape = breve.createInstances( breve.Cube, 1 ).initWith( breve.vector( 10, 0.100000, 15 ) )
		self.enableFastPhysics()
		self.setFastPhysicsIterations( 15 )
		ramp = breve.createInstances( breve.Stationary, 1 )
		ramp.register( rampShape, breve.vector( 50, 1.400000, 0 ), breve.matrix(  0.965960, -0.258690, 0.000000, 0.258690, 0.965960, 0.000000, 0.000000, 0.000000, 1.000000 ) )
		self.vehicle = breve.createInstances( breve.BraitenbergHeavyVehicle, 1 )
		self.wheels.append( self.vehicle.addWheel( breve.vector( 1.500000, 0, -1.500000 ) ) )
		self.wheels.append( self.vehicle.addWheel( breve.vector( 1.500000, 0, 1.500000 ) ) )
		self.wheels.append( self.vehicle.addWheel( breve.vector( -1.500000, 0, -1.500000 ) ) )
		self.wheels.append( self.vehicle.addWheel( breve.vector( -1.500000, 0, 1.500000 ) ) )
		self.wheels.setNaturalVelocity( 20.000000 )
		breve.allInstances( "Stationaries" ).setMu( 40.000000 )
		breve.allInstances( "BraitenbergWheels" ).setMu( 40.000000 )
		self.watch( self.vehicle )
		self.setCameraOffset( breve.vector( -11.000000, 4.500000, 5.500000 ) )
		self.panCameraOffset( breve.vector( 20, 10, 9 ), 80 )
		self.blocks = breve.createInstances( breve.Bricks, 10 )
		self.reset()
Пример #36
0
    def setupTest(self, i):
        l = None
        low = breve.vector()
        lowest = 0

        for l in breve.allInstances("Links"):
            breve.deleteInstances(l.getShape())

        breve.deleteInstances(breve.allInstances("Links"))
        breve.deleteInstances(breve.allInstances("Joints"))
        if self.body:
            breve.deleteInstances(self.body)

        self.body = breve.createInstances(breve.MultiBody, 1)
        self.body.setRoot(self.parser.parseTopLevel(i.getGenome().getRoot()))
        self.body.disableSelfCollisions()
        self.addDependency(self.body)
        self.schedule('checkPenetration', (self.getTime() + 8.000000))
        self.setDisplayText('''Preparing to test %s...''' % (i), -0.950000,
                            -0.950000)
        self.updateText()
        self.running = 0
Пример #37
0
	def init( self ):
		self.enableFastPhysics()
		self.setFastPhysicsIterations( 15 )
		self.vehicle = breve.createInstances( breve.BraitenbergHeavyVehicle, 1 )
		self.body = self.vehicle.getRoot()
		self.body.setNeighborhoodSize( 10.000000 )
		self.wheels.append( self.leftFrontWheel = self.vehicle.addWheel( breve.vector( 1.500000, 0, -1.500000 ) ) )
		self.wheels.append( self.rightFrontWheel = self.vehicle.addWheel( breve.vector( 1.500000, 0, 1.500000 ) ) )
		self.wheels.append( self.leftRearWheel = self.vehicle.addWheel( breve.vector( -1.500000, 0, -1.500000 ) ) )
		self.wheels.append( self.rightRearWheel = self.vehicle.addWheel( breve.vector( -1.500000, 0, 1.500000 ) ) )
		self.leftFrontWheel.setNeighborhoodSize( 3.000000 )
		self.rightFrontWheel.setNeighborhoodSize( 3.000000 )
		self.leftRearWheel.setNeighborhoodSize( 3.000000 )
		self.rightRearWheel.setNeighborhoodSize( 3.000000 )
		self.leftSpeed = 0.000000
		self.rightSpeed = 0.000000
		self.wheels.setNaturalVelocity( 0.000000 )
		breve.allInstances( "Stationaries" ).setMu( 40.000000 )
		breve.allInstances( "BraitenbergWheels" ).setMu( 40.000000 )
		self.watch( self.vehicle )
		self.setCameraOffset( breve.vector( -11.000000, 10.000000, 0 ) )
		self.reset()
		self.video = breve.createInstances( breve.Image, 1 )
Пример #38
0
	def __init__(self):
		breve.BraitenbergControl.__init__(self)
		
		f = open('map', 'r')
		lines = f.readlines()
		for i in xrange(len(lines)):
			for j in xrange(len(lines[i])):
				if lines[i][j] == '*':
					breve.createInstances(SphereStationary, 1, 1.0).move(breve.vector(i*D, 1.0, j*D))
				if lines[i][j] == 'E':
					breve.createInstances(Egg, 1).move(breve.vector(i*D, -1.0, j*D))
		f.close()
		
		self.watch(breve.allInstances(Egg)[0])

		self.jazzMusic = breve.createInstances(breve.Sound, 1)
		self.jazzMusic.load("sounds/sax.wav")
Пример #39
0
	def iterate( self ):
		i = None
		strength = 0
		transDir = breve.vector()
		toBall = breve.vector()

		transDir = ( self.getRotation() * self.direction )
		for i in breve.allInstances( "BraitenbergBalls" ):
			toBall = ( i.getLocation() - self.getLocation() )
			angle = breve.breveInternalFunctionFinder.angle( self, toBall, transDir )
			if ( angle < self.sensorAngle ):
				strengthX = -1 * toBall[0]
				strengthY = toBall[2]
				strength = 12 * strengthX / strengthY
			else:
				strength = 0
		self.wheels.activate(strength)
Пример #40
0
	def iterate(self):
		total = 0

		for i in breve.allInstances("SmellSource"):
			if i.getType() != self.type:
				continue

			toSmell = i.getLocation() - self.getLocation()

			distance = toSmell.length()/self.bias

			 # smell intensity is inversely proportional to d**2
			strength = i.getIntensity()/(1.0 + (distance*distance))
			total += strength
	
		total = min(total, 1.0)
		self.activators.activate(total, self)
Пример #41
0
	def iterate( self ):
		i = None
		lights = 0
		angle = 0
		strength = 0
		total = 0
		transDir = breve.vector()
		toBlock = breve.vector()
		transDir = ( self.getRotation() * self.direction )
		
		least = ()
		item = None
		flag = False
		
		for i in breve.allInstances( "BraitenbergBlocks" ):
			toBlock = ( i.getLocation() - self.getLocation() )
			angle = breve.breveInternalFunctionFinder.angle( self, toBlock, transDir )
			if ( angle < self.sensorAngle ):
				strength = breve.length( ( self.getLocation() - i.getLocation() ) ) 
				if(strength < least):
					flag = True
					least = strength
					item = i
				#lights = ( lights + 1 )
				
		if flag:
			strength = (1.000000/(least * least) ) * 1/item.reflection
			#if ( self.activationMethod and self.activationObject ):
			#	strength = self.activationObject.callMethod( self.activationMethod, [ strength ] )
			self.counter=self.counter+1
			
			strength = self.activationMethod(strength)
			
			if ( strength > self.upperBound ):
				strength = self.upperBound
			elif strength < self.lowerBound:
				strength = self.lowerBound
			#total = ( total + least )

		#if ( lights != 0 ):
			#total = ( total / lights )
		total = strength
		total = ( ( 50 * total ) * self.bias )		
		
		self.wheels.activate( total )
Пример #42
0
	def iterate( self ):
		i = None
		objects = 0
		angle = 0
		strength = 0
		total = 0
		transDir = breve.vector()
		toObject = breve.vector()

		transDir = ( self.getRotation() * self.direction )
		for i in breve.allInstances( self.type ):
			toObject = ( i.getLocation() - self.getLocation() )
			
			angle = breve.breveInternalFunctionFinder.angle( self, toObject, transDir )
			if ( angle < self.sensorAngle ):
				strength = breve.length( ( self.getLocation() - i.getLocation() ) ) 

				if self.activationType == "linear" and strength > 15:
					continue
				
				strength = ( 1.000000 / ( strength * strength ) ) * i.intensity
				strength = self.activationMethod(strength)

				if strength > self.upperBound:
					strength = self.upperBound
				elif strength < self.lowerBound:
					strength = self.lowerBound
				
					
				total = ( total + strength )
				objects += 1


		if ( objects != 0 ):
			total = ( total / objects )
		
		total = ( ( 50 * total ) * self.bias )
		if self.leftSensor == 1:
			if breve.length(self.getLocation() - self.position) < 0.001:
				total = 30
			
		self.position = self.getLocation()
		
		self.wheels.activate( total )
Пример #43
0
    def createFeeder(self, num, rapid):
        # Simple Sequential Inhibition
        dist = 0
        x = 0
        y = 0
        while dist < self.feederMinDistance:
            dist = 99999
            x = random.uniform(self.minX, self.maxX)
            y = random.uniform(self.minY, self.maxY)

            feeders = breve.allInstances("Feeder")
            if breve.length(feeders) == 0:
                break
            for feeder in feeders:
                norm = ((x - feeder.pos_x)**2 + (y - feeder.pos_y)**2)**0.5
                if norm < dist:
                    dist = norm
        temp_feed = breve.createInstances(breve.Feeder, 1)
        temp_feed.initializeRandomly(x, y, rapid)
Пример #44
0
	def createFeeder(self, num, rapid ):
		# Simple Sequential Inhibition
		dist = 0
		x = 0
		y = 0
		while dist < self.feederMinDistance:
			dist = 99999
			x = random.uniform(self.minX, self.maxX)
			y = random.uniform(self.minY, self.maxY)

			feeders = breve.allInstances( "Feeder" )
			if breve.length(feeders) == 0:
				break
			for feeder in feeders:
				norm = ((x-feeder.pos_x)**2 + (y-feeder.pos_y)**2)**0.5
				if norm < dist:
					dist = norm
		temp_feed = breve.createInstances( breve.Feeder, 1)
		temp_feed.initializeRandomly(x,y,rapid)
Пример #45
0
	def adjustCamera( self, location ):
		topDiff = 0
		item = None

		topDiff = 0.000000
		for item in breve.allInstances( "Birds" ):
			if ( topDiff < breve.length( ( location - item.getLocation() ) ) ):
				topDiff = breve.length( ( location - item.getLocation() ) )



		self.provisionalNewZoom = ( ( 0.500000 * topDiff ) + 10 )
		if ( self.cameraHasBeenAimed == 0 ):
			self.aimCamera( location )
			self.zoomCamera( self.provisionalNewZoom )
			self.prevCameraAim = location
			self.prevCameraZoom = self.provisionalNewZoom
			self.cameraHasBeenAimed = 1

		else:
			if ( breve.length( ( self.prevCameraAim - location ) ) < self.maxAimDelta ):
				self.aimCamera( location )
				self.prevCameraAim = location

			else:
				self.aimCamera( ( ( ( ( location - self.prevCameraAim ) / breve.length( ( location - self.prevCameraAim ) ) ) * self.maxAimDelta ) + self.prevCameraAim ) )
				self.prevCameraAim = ( ( ( ( location - self.prevCameraAim ) / breve.length( ( location - self.prevCameraAim ) ) ) * self.maxAimDelta ) + self.prevCameraAim )


			if ( breve.breveInternalFunctionFinder.abs( self, ( self.prevCameraZoom - self.provisionalNewZoom ) ) < self.maxZoomDelta ):
				self.zoomCamera( self.provisionalNewZoom )
				self.prevCameraZoom = self.provisionalNewZoom

			else:
				if ( ( self.prevCameraZoom - self.provisionalNewZoom ) < 0 ):
					self.zoomCamera( ( self.prevCameraZoom + self.maxZoomDelta ) )
					self.prevCameraZoom = ( self.prevCameraZoom + self.maxZoomDelta )

				else:
					self.zoomCamera( ( self.prevCameraZoom - self.maxZoomDelta ) )
					self.prevCameraZoom = ( self.prevCameraZoom - self.maxZoomDelta )
	def adjustCamera( self, location ):
		topDiff = 0
		item = None

		topDiff = 0.000000
		for item in breve.allInstances( "Birds" ):
			if ( topDiff < breve.length( ( location - item.getLocation() ) ) ):
				topDiff = breve.length( ( location - item.getLocation() ) )



		self.provisionalNewZoom = ( ( 0.500000 * topDiff ) + 10 )
		if ( self.cameraHasBeenAimed == 0 ):
			self.aimCamera( location )
			self.zoomCamera( self.provisionalNewZoom )
			self.prevCameraAim = location
			self.prevCameraZoom = self.provisionalNewZoom
			self.cameraHasBeenAimed = 1

		else:
			if ( breve.length( ( self.prevCameraAim - location ) ) < self.maxAimDelta ):
				self.aimCamera( location )
				self.prevCameraAim = location

			else:
				self.aimCamera( ( ( ( ( location - self.prevCameraAim ) / breve.length( ( location - self.prevCameraAim ) ) ) * self.maxAimDelta ) + self.prevCameraAim ) )
				self.prevCameraAim = ( ( ( ( location - self.prevCameraAim ) / breve.length( ( location - self.prevCameraAim ) ) ) * self.maxAimDelta ) + self.prevCameraAim )


			if ( breve.breveInternalFunctionFinder.abs( self, ( self.prevCameraZoom - self.provisionalNewZoom ) ) < self.maxZoomDelta ):
				self.zoomCamera( self.provisionalNewZoom )
				self.prevCameraZoom = self.provisionalNewZoom

			else:
				if ( ( self.prevCameraZoom - self.provisionalNewZoom ) < 0 ):
					self.zoomCamera( ( self.prevCameraZoom + self.maxZoomDelta ) )
					self.prevCameraZoom = ( self.prevCameraZoom + self.maxZoomDelta )

				else:
					self.zoomCamera( ( self.prevCameraZoom - self.maxZoomDelta ) )
					self.prevCameraZoom = ( self.prevCameraZoom - self.maxZoomDelta )
Пример #47
0
	def iterate(self):
		total = 0

		transDir = self.getRotation() * self.direction
		for c in self.sources:
			for i in breve.allInstances(c):
				if i.getColor() != self.color:
					continue

				toLight = i.getLocation() - self.getLocation()
				angle = breve.breveInternalFunctionFinder.angle( self, toLight, transDir )

				if ( angle < self.sensorAngle ):
					distance = toLight.length()/self.bias

					 # light intensity is inversely proportional to d**2 (area of sphere surface with radius d)
					strength = i.getIntensity()/(1.0 + (distance*distance))*math.cos((math.pi/self.sensorAngle)/2*angle)
					total += strength
	
		total = min(total, 1.0)
		self.activators.activate(total, self)
	def spawn( self ):
		child = None
		tempCode = None
		numBirds = 0
		mutRate = 0

		numBirds = breve.allInstances( "Birds" )
		if ( self.energy > ( 2 * 0.150000 ) ):
			self.controller.incrementNaturalBirths()
			if ( numBirds < 0 ):
				self.adjustEnergy( ( 0 - ( 0.150000 - ( ( ( 0 - numBirds ) * 0.150000 ) / ( 0 - 10 ) ) ) ) )
				self.controller.incrementReproductiveDiscounts()

			else:
				self.adjustEnergy( ( 0 - 0.150000 ) )

			child = breve.createInstances( breve.Bird, 1 )
			child.setEnergy( 0.150000 )
			child.setHue( self.getHue() )
			child.setColor( self.controller.getRgbColor( breve.vector( ( child.getHue() * 360 ), 1, 1 ) ) )
			child.move( ( self.getLocation() + ( breve.randomExpression( breve.vector( ( 1.000000 * 2 ), ( 1.000000 * 2 ), ( 1.000000 * 2 ) ) ) - breve.vector( 1.000000, 1.000000, 1.000000 ) ) ) )
			child.setVelocity( breve.vector( 0, 0, 0 ) )
			child.point( breve.vector( 0, 1, 0 ), breve.randomExpression( breve.vector( 1, 1, 1 ) ) )
			tempCode = breve.createInstances( breve.PushProgram, 1 )
			self.pushInterpreter.copyCodeStackTop( tempCode )
			mutRate = self.pushInterpreter.getIntegerStackTop()
			self.pushInterpreter.popIntegerStack()
			if ( mutRate < 0 ):
				mutRate = ( -mutRate )

			self.controller.incrementReproMutationRates( mutRate )
			if ( breve.randomExpression( mutRate ) == 0 ):
				tempCode.mutate( self.pushInterpreter, 15 )
				self.controller.incrementReproMutations()


			child.getPushCode().parse( tempCode.getString() )
			breve.deleteInstances( tempCode )
Пример #49
0
    def iterate(self):
        if self.current_generation < 5000:
            if not self.movie:
                self.movie = breve.createInstances(breve.Movie, 1)
                self.movie.record('BOID_simple.mpeg')

            self.updateNeighbors()

            birds = breve.allInstances("Bird")

            for bird in birds:
                bird.fly()

            self.current_generation += 1

            # needed to move the agents with velocity and acceleration
            # also needed to detect collisions
            breve.Control.iterate(self)

        elif self.movie:
            self.movie.close()
            breve.deleteInstances(self.movie)
            self.movie = None
Пример #50
0
    def checkPenetration(self):
        link = None

        self.running = 1
        if self.body.checkSelfPenetration():
            breve.deleteInstances(breve.allInstances("Links"))

        breve.allInstances("SineJoints").activate()
        self.startlocation = breve.vector(0, 0, 0)
        for link in breve.allInstances("Links"):
            self.startlocation = (self.startlocation + link.getLocation())

        if breve.length(breve.allInstances("Links")):
            self.startlocation = (self.startlocation /
                                  breve.length(breve.allInstances("Links")))

        self.flag.move(
            (self.startlocation - breve.vector(0,
                                               (self.startlocation.y - 2), 0)))
Пример #51
0
    def iterate(self):
        self.updateNeighbors()

        # moviment of Prey
        self.numPreys = 0
        for prey in breve.allInstances("Prey"):
            if prey.isAlive:
                prey.fly()
                self.numPreys += 1

        # moviment of Predator
        self.numPredators = 0
        for predator in breve.allInstances("Predator"):
            if predator.isAlive:
                predator.fly()
                self.numPredators += 1

        # management of the energy from feeders
        self.totalFoodSupply = 0
        for feeder in breve.allInstances("Feeder"):
            if feeder.rapid:
                feeder.rapidGrow()
                self.totalFoodSupply += feeder.VirtualEnergy
            self.totalFoodSupply += feeder.energy
            if feeder.energy <= 0 and not feeder.rapid:
                breve.deleteInstances(feeder)
        self.addRandomFeederIfNecessary(rapid=True)

        # vanish corpse
        for corpse in breve.allInstances("Corpse"):
            corpse.changeColor()
            if sum(corpse.getColor()) <= 0:
                breve.deleteInstances(corpse.shape)
                breve.deleteInstances(corpse)
            print corpse.getColor()

        self.current_generation += 1
        # breeding
        if self.current_generation % self.breeding_season == 0:
            # preys
            tam_prey = int(math.ceil((self.breeding_inc * self.numPreys) / 2))
            if breve.length(self.pollPreys) < tam_prey * 2:
                new_prey = tam_prey - breve.length(self.pollPreys)
                breve.createInstances(breve.Prey, new_prey).dropDead(False)
            for i in range(tam_prey):
                self.evolutionayAlgorithm(self.pollPreys)

            # predators
            predator_max = self.numPreys * self.max_pop_predadors
            predator_breed = self.breeding_inc * self.numPredators
            tam_predator = int(math.ceil(
                min(predator_max, predator_breed) / 2))
            if breve.length(self.pollPredators) < tam_predator * 2:
                new_preds = tam_predator - breve.length(self.pollPredators)
                breve.createInstances(breve.Predator,
                                      new_preds).dropDead(False)
            for i in range(tam_predator):
                self.evolutionayAlgorithm(self.pollPredators)
        # immigrants
        else:
            if self.numPreys < 0.2 * self.initialNumPreys:
                self.revive(self.pollPreys,
                            math.floor(0.15 * self.initialNumPreys))
                self.createPreys(math.floor(0.05 * self.initialNumPreys))
            if self.numPredators < 0.2 * self.initialNumPredators:
                self.revive(self.pollPredators,
                            math.floor(0.15 * self.initialNumPredators))
                self.createPredators(
                    math.floor(0.05 * self.initialNumPredators))

        # checkpoint
        if self.isToSave and self.current_generation % (self.breeding_season *
                                                        25) == 0:
            self.save_data()

        self.setDisplayText("Generation: " + str(
            (int)(math.ceil(self.current_generation / self.breeding_season))),
                            xLoc=-0.950000,
                            yLoc=-0.550000,
                            messageNumber=5,
                            theColor=breve.vector(1, 1, 1))
        self.setDisplayText("Preys Alive: " + str(self.numPreys),
                            xLoc=-0.950000,
                            yLoc=-0.650000,
                            messageNumber=4,
                            theColor=breve.vector(1, 1, 1))
        self.setDisplayText("Predators Alive: " + str(self.numPredators),
                            xLoc=-0.950000,
                            yLoc=-0.750000,
                            messageNumber=3,
                            theColor=breve.vector(1, 1, 1))
        self.setDisplayText("Dead Preys: " + str(self.numDeadPreys),
                            xLoc=-0.950000,
                            yLoc=-0.850000,
                            messageNumber=2,
                            theColor=breve.vector(1, 1, 1))
        self.setDisplayText("Dead Predators: " + str(self.numDeadPredators),
                            xLoc=-0.950000,
                            yLoc=-0.950000,
                            messageNumber=1,
                            theColor=breve.vector(1, 1, 1))

        # needed to move the agents with velocity and acceleration
        # also needed to detect collisions
        # print str(self.numBirdsBirth)
        breve.Control.iterate(self)
	def dumpPrograms( self ):
		b = None

		for b in breve.allInstances( "Birds" ):
			b.getPushCode().dump()
	def report( self ):
		item2 = None
		item = None
		avgFood = 0
		devFood = 0
		numOthers = 0
		hueDiversity = 0
		sizeDiversity = 0
		avProgSize = 0
		numBirds = 0
		oCount = 0
		fCount = 0
		i = 0

		numBirds = breve.length( breve.allInstances( "Birds" ) )
		avgFood = ( self.foodAccum / 100 )
		if ( self.decisions == 0 ):
			devFood = 0.000000

		else:
			devFood = ( self.foodDeviations / self.decisions )


		hueDiversity = 0.000000
		for item in breve.allInstances( "Birds" ):
			numOthers = 0
			for item2 in breve.allInstances( "Birds" ):
				if item.isOther( item2 ):
					numOthers = ( numOthers + 1 )


			hueDiversity = ( hueDiversity + ( numOthers / ( numBirds - 1 ) ) )


		hueDiversity = ( hueDiversity / numBirds )
		sizeDiversity = 0.000000
		for item in breve.allInstances( "Birds" ):
			fCount = ( fCount + item.askIfFriendFeeder() )
			oCount = ( oCount + item.askIfOtherFeeder() )
			if item:
				numOthers = 0
				for item2 in breve.allInstances( "Birds" ):
					if item2:
						if ( ( item.getPushCode().getSize() == item2.getPushCode().getSize() ) == 0 ):
							numOthers = ( numOthers + 1 )



				sizeDiversity = ( sizeDiversity + ( numOthers / ( numBirds - 1 ) ) )




		sizeDiversity = ( sizeDiversity / numBirds )
		avProgSize = 0.000000
		for item in breve.allInstances( "Birds" ):
			if item:
				avProgSize = ( avProgSize + item.getPushCode().getSize() )


		avProgSize = ( avProgSize / numBirds )
		if ( self.naturalBirths > 0 ):
			self.discrepancies = ( self.discrepancies / self.naturalBirths )
			self.reproMutationRates = ( self.reproMutationRates / self.naturalBirths )
			self.reproMutationRates = ( 1 / ( self.reproMutationRates + 1 ) )


		print '''iteration: %s, population size: %s, hue diversity: %s, size diversity: %s, average program size: %s''' % (  self.iteration, numBirds, hueDiversity, sizeDiversity, avProgSize )
		print '''  [ epoch: b: %s, d: %s, spnt: %s, rmut: %s, rate: %s, diversification: %s, food: %s, fdev: %s, feed/f: %s, /o: %s, discounts: %s, servos: %s, fCount: %s, oCount: %s ]''' % (  self.births, self.deaths, self.randomBirdsAdded, self.reproMutations, self.reproMutationRates, self.discrepancies, avgFood, devFood, self.friendFeedings, self.otherFeedings, self.reproductiveDiscounts, self.servos, fCount, oCount )
		print ''' '''
		i = ( self.iteration / 100 )
		self.setInterfaceItem( 699, '''%s''' % (  i ) )
		self.setInterfaceItem( 700, '''%s''' % (  self.births ) )
		self.setInterfaceItem( 698, '''%s''' % (  self.randomBirdsAdded ) )
		self.setInterfaceItem( 701, '''%s''' % (  self.deaths ) )
		self.setInterfaceItem( 702, '''%s''' % (  self.reproMutations ) )
		self.setInterfaceItem( 703, '''%s''' % (  self.reproMutationRates ) )
		self.setInterfaceItem( 704, '''%s''' % (  self.discrepancies ) )
		self.setInterfaceItem( 705, '''%s''' % (  self.friendFeedings ) )
		self.setInterfaceItem( 706, '''%s''' % (  self.otherFeedings ) )
		self.setInterfaceItem( 707, '''%s''' % (  self.servos ) )
		self.births = 0
		self.deaths = 0
		self.foodAccum = 0
		self.foodDeviations = 0
		self.decisions = 0
		self.friendFeedings = 0
		self.otherFeedings = 0
		self.friendExploits = 0
		self.otherExploits = 0
		self.randomBirdsAdded = 0
		self.reproductiveDiscounts = 0
		self.reproMutations = 0
		self.reproMutationRates = 0.000000
		self.discrepancies = 0.000000
		self.naturalBirths = 0
		self.servos = 0