def iterate( self ): location = breve.vector() velocity = breve.vector() birdLocation = breve.vector() topDiff = 0 self.updateNeighbors() for self.item in self.birds: self.item.fly( self.birds ) location = ( location + self.item.getLocation() ) location = ( location / self.birds ) topDiff = 0.000000 for self.item in self.birds: if ( topDiff < breve.length( ( location - self.item.getLocation() ) ) ): topDiff = breve.length( ( location - self.item.getLocation() ) ) if self.cameraControl: self.aimCamera( location ) self.zoomCamera( ( ( 0.500000 * topDiff ) + 10 ) ) breve.Control.iterate( self )
def postIterate( self ): location = breve.vector() target = breve.vector() if ( self.selection and self.selection.isA( 'Bird' ) ): target = self.selection.getVelocity() location = self.selection.getLocation() if breve.length( target ): target = ( target / breve.length( target ) ) if ( breve.length( self.visionDirection ) == 0 ): self.visionDirection = target else: self.visionDirection = ( self.visionDirection * 0.800000 ) self.visionDirection = ( self.visionDirection + ( target * 0.200000 ) ) if ( breve.length( self.visionDirection ) != 0.000000 ): self.visionDirection = ( self.visionDirection / breve.length( self.visionDirection ) ) self.vision.look( ( self.visionDirection + location ), ( -self.visionDirection ) ) else: self.vision.look( breve.vector( 0, 0, 0 ), breve.vector( 0, 20, 0 ) )
def closestOther( self ): others = breve.objectList() item = None closestDistance = 0 thisDistance = 0 closestOther = None for item in self.getNeighbors(): if item.isA( 'Bird' ): if ( self.isFriend( item ) == 0 ): others.append( item ) if ( breve.length( others ) < 1 ): closestOther = self else: closestDistance = 1000000 for item in others: thisDistance = breve.length( ( item.getLocation() - self.getLocation() ) ) if ( thisDistance < closestDistance ): closestDistance = thisDistance closestOther = item return closestOther
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 )
def closestFriend( self ): friends = breve.objectList() item = None closestDistance = 0 thisDistance = 0 closestFriend = None for item in self.getNeighbors(): if item.isA( 'Bird' ): if self.isFriend( item ): friends.append( item ) if ( breve.length( friends ) < 1 ): closestFriend = self else: closestDistance = 1000000 for item in friends: thisDistance = breve.length( ( item.getLocation() - self.getLocation() ) ) if ( thisDistance < closestDistance ): closestDistance = thisDistance closestFriend = item return closestFriend
def changeDrivers( self ): newDriver = 0 newOffset = breve.vector() if self.locked: return newOffset = ( breve.randomExpression( breve.vector( 30, 6, 30 ) ) + breve.vector( -15, 1, -15 ) ) if ( breve.length( newOffset ) < 9 ): newOffset = ( ( 9 * newOffset ) / breve.length( newOffset ) ) self.panCameraOffset( newOffset, 30 ) self.seats[ self.currentSeat ].setDistance( breve.length( self.wigglyThing.getLocation() ) ) self.currentSeat = ( self.currentSeat + 1 ) if ( self.currentSeat > 3 ): self.breedNewMonkeys() self.pickDrivers() newDriver = self.seats[ self.currentSeat ].getNumber() if self.wigglyThing: breve.deleteInstances( self.wigglyThing ) self.wigglyThing = breve.createInstances( breve.Creature, 1 ) self.wigglyThing.initWith( self.seats[ self.currentSeat ].getGenome() ) self.wigglyThing.move( breve.vector( 0, 3, 0 ) ) self.watch( self.wigglyThing ) self.schedule( 'changeDrivers', ( self.getTime() + 20.000000 ) ) self.displayCurrentDriver()
def getAngle( self, otherMobile ): tempVector = breve.vector() tempVector = ( otherMobile.getLocation() - self.getLocation() ) if ( ( breve.length( tempVector ) == 0.000000 ) or ( breve.length( self.getVelocity() ) == 0.000000 ) ): return 0.000000 return breve.breveInternalFunctionFinder.angle( self, self.getVelocity(), tempVector )
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 startFitnessTest( self, o ): newOffset = breve.vector() newOffset = ( breve.randomExpression( breve.vector( 40, 2, 40 ) ) + breve.vector( -20, 0.150000, -20 ) ) if ( breve.length( newOffset ) < 20 ): newOffset = ( ( 20 * newOffset ) / breve.length( newOffset ) ) self.controller.panCameraOffset( newOffset, 600 ) self.controller.setupTest( o )
def getAngle( self, otherMobile ): velocity = breve.vector() tempVector = breve.vector() tempVector = ( otherMobile.getLocation() - self.getLocation() ) velocity = self.getVelocity() if ( ( breve.length( tempVector ) < 0.010000 ) or ( breve.length( velocity ) < 0.010000 ) ): return 0 return breve.breveInternalFunctionFinder.angle( self, velocity, tempVector )
def see_plants(self, plants): if not plants: return None closest = None for plant in plants: to_plant = plant.getLocation() - self.getLocation() if closest is None or breve.length(closest) > breve.length(to_plant): closest = to_plant return closest
def mutate(self): """Mutates the directed graph. The mutation adds a random connection, removes a random connection, and mutates the parameters of a random connection and node.""" connections = breve.objectList() nodes = breve.objectList() m = 0 n = 0 connection = None nodes = self.rootNode.getConnectedNodes() n = breve.randomExpression((breve.length(nodes) - 1)) m = breve.randomExpression((breve.length(nodes) - 1)) connection = nodes[n].connect(nodes[m], []) connection.setParameterLength(self._connParamCount) connection.randomizeParameters() m = breve.randomExpression((breve.length(nodes) - 1)) connections = nodes[m].getConnections() if breve.length(connections) > 1: connections.pop(breve.randomExpression((breve.length(connections) - 1))) m = breve.randomExpression((breve.length(nodes) - 1)) connections = nodes[m].getConnections() if breve.length(connections): connections[breve.randomExpression((breve.length(connections) - 1))].mutate() m = breve.randomExpression((breve.length(nodes) - 1)) nodes[m].mutate()
def iterate( self ): if ( breve.length( self.getLocation() ) > self.wanderMag ): self.setAcceleration( ( ( ( 8 * ( -self.topVelocity ) ) * self.getLocation() ) / breve.length( self.getLocation() ) ) ) return else: self.setAcceleration( ( ( 8 * ( ( 2 * breve.randomExpression( self.wanderVec ) ) - self.wanderVec ) ) * self.topVelocity ) ) if ( breve.length( self.getVelocity() ) > self.topVelocity ): self.setVelocity( ( ( self.topVelocity * self.getVelocity() ) / breve.length( self.getVelocity() ) ) )
def hit( self, location, c, agent ): newParticle = None newParticle = breve.createInstances( breve.Stationary, 1 ) newParticle.register( self.sphereShape, location ) newParticle.setColor( ( c + ( breve.randomExpression( breve.vector( 0.200000, 0.200000, 0.200000 ) ) - breve.vector( 0.100000, 0.100000, 0.100000 ) ) ) ) newParticle.setTextureImage( 0 ) if ( breve.length( location ) > self.maxLocation ): self.maxLocation = breve.length( location ) agent.setMaximumDistance( self.maxLocation ) agent.offsetFromCenter( ( self.maxLocation + 2 ) )
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 iterate( self ): velocity = breve.vector() if ( breve.randomExpression( 20 ) == 0 ): self.reset() velocity = self.getVelocity() if breve.length( velocity ): velocity = ( velocity / breve.length( velocity ) ) self.setVelocity( ( self.vel * velocity ) ) self.setAcceleration( ( breve.randomExpression( breve.vector( self.acc, self.acc, 0 ) ) - breve.vector( ( self.acc / 2 ), ( self.acc / 2 ), 0 ) ) )
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 ) ) )
def parse( self, root, n, rootNode, f = 0.000000 ): connections = breve.objectList() nodeParams = breve.objectList() connectionParams = breve.objectList() joint = None childNode = None child = None norm = breve.vector() size = breve.vector() point = breve.vector() ppoint = breve.vector() cpoint = breve.vector() jointRange = 0 connections = root.getConnections() nodeParams = root.getParameters() size = ( ( 3.000000 * breve.vector( breve.length( nodeParams[ 0 ] ), breve.length( nodeParams[ 1 ] ), breve.length( nodeParams[ 2 ] ) ) ) + breve.vector( 0.500000, 0.500000, 0.500000 ) ) if ( ( ( self._linkCount > 20 ) or ( n > 6 ) ) or ( ( n > 1 ) and ( nodeParams[ 9 ] < 0.000000 ) ) ): return 0 for child in connections: childNode = self.createNode( child.getTarget(), ( n + 1 ) ) if childNode: connectionParams = child.getParameters() point = breve.vector( connectionParams[ 0 ], connectionParams[ 1 ], connectionParams[ 2 ] ) if f: point.x = ( point.x * -1 ) point.x = ( point.x * size.x ) point.y = ( point.y * size.y ) point.z = ( point.z * size.z ) cpoint = childNode.getShape().getPointOnShape( point ) ppoint = rootNode.getShape().getPointOnShape( ( -point ) ) norm = breve.vector( connectionParams[ 4 ], connectionParams[ 5 ], connectionParams[ 6 ] ) norm = ( norm / breve.length( norm ) ) if f: norm.x = ( norm.x * -1 ) joint = breve.createInstances( breve.SineJoint, 1 ) joint.link( norm, ppoint, cpoint, childNode, rootNode ) joint.setPhaseshift( ( ( n * 3.140000 ) * connectionParams[ 7 ] ) ) joint.setFrequency( ( 0.100000 + connectionParams[ 8 ] ) ) jointRange = ( 0.500000 + ( 1 * breve.length( connectionParams[ 9 ] ) ) ) joint.setDoubleSpring( jointRange, ( -jointRange ), 1 ) joint.setStrengthLimit( 1000 ) self.parse( child.getTarget(), ( n + 1 ), childNode ) return rootNode
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
def myPoint( self, theVertex, theLocation ): v = self.cross( theVertex, theLocation ) a = breve.breveInternalFunctionFinder.angle( self, theVertex, theLocation ) if ( breve.length( v ) == 0.000000 ): self.rotate( theVertex, 0.100000 ) return self.rotate( v, a )
def iterate( self ): newScale = 0 radius = 0 if self.drifting: if self.controller.getUnitDriftMode(): self.move( self.driftLocation ) self.drifting = 0 else: self.offset( ( 0.060000 * ( self.driftLocation - self.getLocation() ) ) ) if ( breve.length( ( self.driftLocation - self.getLocation() ) ) < 0.001000 ): self.move( self.driftLocation ) self.drifting = 0 self.energy = ( self.energy + 0.001000 ) if ( self.energy > 1 ): self.energy = 1 radius = breve.breveInternalFunctionFinder.sqrt( self, self.energy ) newScale = ( ( radius * 2 ) + 0.000010 ) if ( newScale == self.lastScale ): return newScale = ( newScale / self.lastScale ) self.shape.scale( breve.vector( newScale, newScale, newScale ) ) self.lastScale = ( ( radius * 2 ) + 0.000010 )
def getCurrentIndividual( self ): '''Returns the PushProgram currently being evaluated.''' if ( self.current and ( self.currentIndividual < breve.length( self.current ) ) ): return self.current[ self.currentIndividual ] return 0
def relativeRotate( self, thisAxis, amount ): '''Sets the rotation of this object around vector axis thisAxis by scalar amount (in radians). This is a rotation relative to the current position.''' length = 0 length = breve.length( thisAxis ) breve.breveInternalFunctionFinder.linkRotateRelative( self, self.realWorldPointer, thisAxis, amount )
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 )
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 )
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 pointCamera( self, location, offset = breve.vector( 0.000000, 0.000000, 0.000000 ) ): '''Points the camera at the vector location. The optional argument offset specifies the offset of the camera relative to the location target.''' self.camTarget = location self.setCameraTarget( location ) if ( breve.length( offset ) != 0.000000 ): self.camOffset = offset self.setCameraOffset( offset )
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 ) ) )
def point( self, theVertex, theLocation ): '''An easier way to rotate an object--this function rotates an object such that the local point theVertex, points towards the world direction theLocation. In other words, theLocation is where you want the object to face, and theVertex indicates which side of the object is to be considered the "front".''' v = breve.vector() a = 0 if ( ( breve.length( theVertex ) == 0.000000 ) or ( breve.length( theLocation ) == 0.000000 ) ): return v = breve.breveInternalFunctionFinder.cross( self, theVertex, theLocation ) a = breve.breveInternalFunctionFinder.angle( self, theVertex, theLocation ) if ( breve.length( v ) == 0.000000 ): self.rotate( theVertex, 0.010000 ) return self.rotate( v, a )
def dearchive( self ): y = 0 x = 0 self.setSize( breve.length( self.archiveList ), breve.length( self.archiveList[ 0 ] ) ) y = 0 while ( y < self.yDim ): x = 0 while ( x < self.xDim ): self.setValue( x, y, self.archiveList[ y ][ x ] ) x = ( x + 1 ) y = ( y + 1 ) return breve.Matrix.dearchive( self )
def getCurrentIndividual(self): '''Returns the current GeneticAlgorithmIndividual subclass instance being evaluated. See also METHOD(get-current-individual-index).''' if (breve.length(self.populations[self.currentPopulation]) == 0): self.generatePopulation() if (self.currentIndividual == -1): return 0 return self.populations[self.currentPopulation][self.currentIndividual]
def tournament(self, birds, dim): leng = breve.length(birds) if leng == 0: return None candidate = birds[random.randint(0, leng - 1)] for i in range(dim - 1): candidate2 = birds[random.randint(0, leng - 1)] if candidate2.energy > candidate.energy: candidate = candidate2 return candidate
def getAngle(self, otherMobile): tempVector = breve.vector() if (breve.length(self.getVelocity()) == 0): return 0 tempVector = (otherMobile.getLocation() - self.getLocation()) return breve.breveInternalFunctionFinder.angle(self, self.getVelocity(), tempVector)
def nonSpatialTournamentSelect(self): '''This method performs a tournament selection for reproduction. It is used internally and typically not called by any other object. ''' n = 0 test = 0 best = 0 best = breve.randomExpression( (breve.length(self.populations[self.currentPopulation]) - 1)) n = 0 while (n < (self.tournamentSize - 1)): test = breve.randomExpression( (breve.length(self.populations[self.currentPopulation]) - 1)) if (self.populations[self.currentPopulation][test].getFitness( ) > self.populations[self.currentPopulation][best].getFitness()): best = test n = (n + 1) return self.populations[self.currentPopulation][best]
def iterate(self): location = breve.vector() topDiff = 0 highLoc = breve.vector() self.updateNeighbors() for self.item in self.birds: self.item.fly() location = (location + self.item.getLocation()) if (breve.length(self.item.getLocation()) > breve.length(highLoc)): highLoc = self.item.getLocation() location = (location / breve.length(self.birds)) topDiff = 0.000000 for self.item in self.birds: if (topDiff < breve.length((location - self.item.getLocation()))): topDiff = breve.length((location - self.item.getLocation())) self.aimCamera(location) breve.Control.iterate(self)
def pickRootNode(self, nodes): node = None best = None bestCount = 0 for node in nodes: if (breve.length(node.getConnectedNodes()) > bestCount): best = node bestCount = node.getConnectedNodes() return best
def checkPenetration(self): link = None self.running = 1 if self.body.checkSelfPenetration(): breve.deleteInstances(breve.allInstances("breve.Links")) breve.allInstances("SineJoints").activate() self.startlocation = breve.vector(0, 0, 0) for link in breve.allInstances("Links"): link.setStartLocation() 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)))
def setRotation( self, thisAxis, amount ): '''Sets the rotation of this object around vector axis thisAxis by scalar amount (in radians). This is an "absolute" rotation--the current rotation of the object does not affect how the object will be rotated. For a rotation relative to the current orientation, set METHOD(relative-rotate).''' length = 0 length = breve.length( thisAxis ) if ( length == 0.000000 ): return thisAxis = ( thisAxis / length ) breve.breveInternalFunctionFinder.realSetRotation( self, self.realWorldPointer, thisAxis, amount )
def dearchive(self): n = 0 self.setSize(breve.length(self.vectorList)) n = 0 while (n < self.dim): self.setValue(n, self.vectorList[n]) n = (n + 1) return breve.Object.archive(self)
def rotate( self, thisAxis, amount ): '''Sets the rotation of this multibody around vector axis thisAxis by scalar amount (in radians). This is an "absolute" rotation--the current rotation of the object does not affect how the object will be rotated. <p> This method implicitly changes the rotation and location of all attached link objects.''' length = 0 length = breve.length( thisAxis ) if ( length == 0.000000 ): return thisAxis = ( thisAxis / length ) breve.breveInternalFunctionFinder.multibodySetRotation( self, self.multibodyPointer, thisAxis, amount )
def crossover(self, p1, p2): crossoverPoint = 0 n = 0 tmp = None if breve.randomExpression(1): tmp = p2 p2 = p1 p1 = tmp crossoverPoint = breve.randomExpression( (breve.length(self.genomeData) - 1)) n = 0 while (n < breve.length(self.genomeData)): if (n < crossoverPoint): self.genomeData[n] = p1.getValue(n) else: self.genomeData[n] = p2.getValue(n) n = (n + 1)
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 iterate(self): item = None location = breve.vector() topDiff = 0 self.updateNeighbors() for item in self.birds: item.fly() location = (location + item.getLocation()) location = (location / breve.length(self.birds)) topDiff = 0.000000 for item in self.birds: if (topDiff < breve.length((location - item.getLocation()))): topDiff = breve.length((location - item.getLocation())) self.aimCamera(location) if self.useDizzyCameraControl: self.setCameraRotation(breve.length(location), 0.000000) breve.Control.iterate(self)
def myPoint(self, theVertex, theLocation): v = breve.vector() a = 0 v = self.cross(theVertex, theLocation) a = breve.breveInternalFunctionFinder.angle(self, theVertex, theLocation) if (breve.length(v) == 0.000000): self.rotate(theVertex, 0.100000) return self.rotate(v, a)
def randomizeLocation(self): '''Move the Wanderer to a random location within the wander space.''' randomVector = breve.vector() self.move( (self.wanderMag * ((2 * breve.randomExpression(self.wanderVec)) - self.wanderVec))) randomVector = (breve.randomExpression( (2 * self.wanderVec)) - self.wanderVec) randomVector = (randomVector / breve.length(randomVector)) self.setVelocity((self.topVelocity * randomVector))
def iterate( self ): location = breve.vector() topDiff = 0 self.updateNeighbors() for self.item in self.birds: self.item.fly() location = ( location + self.item.getLocation() ) location = ( location / breve.length( self.birds ) ) topDiff = 0.000000 for self.item in self.birds: if ( topDiff < breve.length( ( location - self.item.getLocation() ) ) ): topDiff = breve.length( ( location - self.item.getLocation() ) ) self.aimCamera( location ) self.zoomCamera( ( ( 0.500000 * topDiff ) + 10 ) ) breve.Control.iterate( self )
def destroy( self ): chem = None if ( breve.length( self.diffusingChemicals ) > 0 ): breve.deleteInstances( self.patches ) for chem in self.diffusingChemicals: breve.deleteInstances( self.chemicalConcentrationMatrix[ chem ] ) breve.deleteInstances( self.tempMatrix ) if self.gridPointer: breve.breveInternalFunctionFinder.patchGridFree( self, self.gridPointer )
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 )
def init(self): n = 0 m = 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(0, 0, 70)) self.U = breve.createInstances(breve.Matrix2D, 1) self.V = breve.createInstances(breve.Matrix2D, 1) self.inflow = breve.createInstances(breve.Matrix2D, 1) self.delta = breve.createInstances(breve.Matrix2D, 1) self.deltareact = breve.createInstances(breve.Matrix2D, 1) self.U.setSize(128, 128) self.V.setSize(128, 128) self.delta.setSize(128, 128) self.deltareact.setSize(128, 128) self.inflow.setSize(128, 128) self.texture = breve.createInstances(breve.MatrixImage, 1) self.texture.initWith(self.U, 1.000000) self.texture.setRed(self.V) self.texture.setBlue(self.U) self.cube = breve.createInstances(breve.Mobile, 1) self.cube.setShape( breve.createInstances(breve.Cube, 1).initWith(breve.vector(400, 400, 1))) self.cube.setTextureImage(self.texture) self.cube.setTextureScale(40) n = 0 while (n < 128): m = 0 while (m < 128): 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.020000 * (breve.randomExpression(1.000000) - 0.500000))), m, n) self.V.setValue( (((1.000000 - self.U.getValue(m, n)) / (1.000000 + (0.040000 / 0.010000))) + (0.020000 * (breve.randomExpression(1.000000) - 0.500000))), m, n) self.inflow.setValue(0.010000, n, m) m = (m + 1) n = (n + 1)
def popState(self): '''"Pops" a state from the state stack and makes it current. This method reenables the most recently "pushed" state (done with METHOD(push-state)).''' state = breve.objectList() if (breve.length(self.states) < 1): return state = self.states.pop() self.currentPoint = state[0] self.currentDirection = state[1] self.currentColor = state[2] self.penDown = state[4] self.setColor(self.currentColor)
def changeDrivers( self ): newDriver = 0 newOffset = breve.vector() if self.locked: return newOffset = ( breve.randomExpression( breve.vector( 30, 6, 30 ) ) + breve.vector( -15, 1, -15 ) ) if ( breve.length( newOffset ) < 14 ): newOffset = ( ( 14 * newOffset ) / breve.length( newOffset ) ) self.panCameraOffset( newOffset, 30 ) self.seats[ self.currentSeat ].setDistance( breve.length( self.walker.getLocation() ) ) self.walker.center() self.currentSeat = ( self.currentSeat + 1 ) if ( self.currentSeat > 3 ): self.breedNewMonkeys() self.pickDrivers() newDriver = self.seats[ self.currentSeat ].getNumber() self.schedule( 'changeDrivers', ( self.getTime() + 20.000000 ) ) self.displayCurrentDriver()
def evaluate(self): fitness = 0 n = 0 fitness = self.computeZeroDurationFitness( self.current[self.currentIndividual]) if (fitness < 0.000000): print '''warning: error value lower than 0 for GP individual''' fitness = 100000000 if (fitness < 0.001000): print ';;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;' print ''';; Solution found at generation %s:''' % ( self.generation), self.current[ self.currentIndividual].getString() self.examine(self.current[self.currentIndividual]) self.controller.endSimulation() if ((not self._bestOfGen) or (fitness < self._bestOfGen.getFitness())): self._bestOfGen = self.current[self.currentIndividual] self._totalSize = (self._totalSize + self.current[self.currentIndividual].getSize()) self._totalErrors = (self._totalErrors + fitness) self.current[self.currentIndividual].setFitness(fitness) self.currentIndividual = (self.currentIndividual + 1) if (self.currentIndividual == self.populationSize): n = 0 while (n < breve.length(self._solutionCountsGeneration)): self._solutionRatesGeneration[n] = ( self._solutionCountsGeneration[n] / self.populationSize) self._solutionRatesTotal[n] = (self._solutionCountsTotal[n] / (self.populationSize * (self.generation + 1))) n = (n + 1) self.report(self._bestOfGen) self.reproduce() self.swapCurrent() self.currentIndividual = 0 self.generation = (self.generation + 1) self._bestOfGen = 0 self._totalSize = 0 self._totalErrors = 0 if (self.generation > self.generationLimit): print ';;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;' print ''';; FAILURE: no solution found after %s generations''' % ( self.generation) self.controller.endSimulation()
def displayFoodSupply( self ): total = 0 displayTotal = 0 feeder = None total = 0.000000 for feeder in self.feeders: total = ( total + feeder.getEnergy() ) total = ( total / breve.length( self.feeders ) ) displayTotal = ( total * 100 ) self.setInterfaceItem( 101, '''%s''' % ( displayTotal ) ) self.foodAccum = ( self.foodAccum + total )
def dearchive( self ): z = 0 y = 0 x = 0 self.setSize( breve.length( self.archiveList ), breve.length( self.archiveList[ 0 ] ), breve.length( self.archiveList[ 0 ][ 0 ] ) ) z = 0 while ( z < self.zDim ): y = 0 while ( y < self.yDim ): x = 0 while ( x < self.xDim ): self.setValue( x, y, z, self.archiveList[ z ][ y ][ x ] ) x = ( x + 1 ) y = ( y + 1 ) z = ( z + 1 ) return breve.Matrix.dearchive( self )
def getFeederUrge(self, feeders): closestFood = breve.vector() thisFood = breve.vector() item = None closestDistance = 0 thisDistance = 0 closestDistance = 10000.000000 for item in feeders: thisFood = (item.getLocation() - self.getLocation()) thisDistance = breve.length(thisFood) if (thisDistance < closestDistance): closestFood = thisFood closestDistance = thisDistance return closestFood
def computeDiversity(self, t): '''Computes the diversity of the current population, as defined by the OBJECT(PushDiversityPool) object. Returns the number of unique "species" which differ by less than t points.''' pool = None n = 0 pool = breve.createInstances(breve.PushDiversityPool, 1) pool.setTolerance(t) n = 0 while (n < breve.length(self.current)): pool.add(self.current[n]) n = (n + 1) n = pool.getSize() breve.deleteInstances(pool) return n
def addLayer(self, count): '''Adds a layer to the output end of the neural network, with count neurons. The first layer added serves as the input layer, and then subsequent layers serve as hidden or output layers. <p> To create a network with one hidden layer, for example, you would first call METHOD(add-layer) for the input layer, then the hidden layer, then the output layer.''' newLayer = None if (count < 1): print '''cannot add neural network layer with %s nodes ''' % (count) return newLayer = breve.breveInternalFunctionFinder.newFFLayer( self, count, self.outputLayer) if (self.layers == 0): self.inputLayer = newLayer self.layers[breve.length(self.layers)] = newLayer self.outputLayer = newLayer
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 )
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)
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 )