Exemple #1
0
	def DNAfill(self, Nucleotides):
		" fills the DNA with given Nucleotides "
		self.__dna = Nucleotides[:] # important: make a ground copy
		if len(Nucleotides) > 0 and len(Nucleotides) != self.nb_nucleotides:
			Tools.error('DNA: initialization','Provided genome length does not match gene map')
		if len(Nucleotides) > 0 and not set(Nucleotides) <= set([0,1]):
			Tools.error('DNA: initialization','Provided genome is not binary')
Exemple #2
0
	def nextNode(self, node, visited):
		""" Finds next node from the node in argument """
		
		if len(visited) > self.size: # the length of the trip before the last step cannot be greater than the number of nodes
			ET.error('nextNode', 'Unexpected behavior')
			return None
			
		elif len(visited) == self.size: # the trip ends so we go to the first node
			return visited[0]
			
		else:
			attractions = []
			
			for n in self.nodes:
				if n not in visited:
					if Gbl.Parameter('PheromoneInfluence') > 0:
						pheromoneInfluence = self.pheromones.getValue(node, n) ** Gbl.Parameter('PheromoneInfluence')
					else:
						pheromoneInfluence = 1
					
					if Gbl.Parameter('DistanceInfluence') > 0:
						distanceInfluence = self.distances.getValue(node, n) ** Gbl.Parameter('DistanceInfluence')
					else:
						distanceInfluence = 1
					
					attractions.append((pheromoneInfluence / distanceInfluence, n))
					
			return max(attractions)[1]
Exemple #3
0
	def __init__(self, Size=100, nbNodes=0):
		#self.TestMessages = []	# Messages used to test the efficiency of the network
		margin = 5 if Size > 20 else 0
		self.nodes = []
		self.currentLength = 0
		
		if Gbl.Parameter('RandomNetwork') and nbNodes > 1:
			self.nodes = [Node('N%d' % i, (random.randint(margin, Size-margin), random.randint(margin, Size-margin))) for i in range(nbNodes)]
		else:	
			# loading network from file
			#	file format:
			#		Name1	x1	y1
			#		Name2	x2	y2
			#		...
			
			try:
				for Line in open(Gbl.Parameter('NetworkFileName'), 'r', 1):	# read one line at a time
					NodeDef = Line.split()
					self.nodes.append(Node(NodeDef[0], tuple(map(int, NodeDef[1:]))))
			except IOError:	ET.error('Unable to find Network description', Gbl.Parameter('NetworkFileName'))
			
			
		self.size = len(self.nodes)
		
		for n in self.nodes:
			print "%s %d %d" % (n.name, n.getX(), n.getY())

		self.distances = Distances(self.nodes)
		self.pheromones = Pheromones(self.nodes)
Exemple #4
0
    def __init__(self, Size=100, NbNodes=0, NetworkFileName=None):
        self.TestMessages = [
        ]  # Messages used to test the efficiency of the network
        margin = 5 if Size > 20 else 0
        self.NodeNames = {}
        self.Nodes = []
        self.Links = []
        if Gbl.Parameter('RandomNetwork') and NbNodes > 1:
            self.Nodes = [
                Node('N%d' % i, (random.randint(margin, Size - margin),
                                 random.randint(margin, Size - margin)))
                for i in range(NbNodes)
            ]
            if NbNodes > 1:
                for n in self.Nodes:
                    OtherNodes = self.Nodes[:]
                    OtherNodes.remove(n)  # does not need to be efficient
                    if OtherNodes:
                        self.Links.append((n, random.choice(OtherNodes)))
                        self.Links.append((n, random.choice(OtherNodes)))
            self.Links = list(set(self.Links))  # to remove duplicates
            self.NodeNames = dict([(n.Name, n) for n in self.Nodes])
        else:  # loading network from file
            #	file format:
            #		Name1	x1	y1
            #		Name2	x2	y2
            #		...
            #		Link	NameA	NameB	C	(C = capacity)
            #		...
            #	('Link' = keyword)
            LinkDefinitions = []
            try:
                for Line in open(Gbl.Parameter('NetworkFileName'), 'r',
                                 1):  # read one line at a time
                    Link = re.match('(?i)link\s+(.*)', Line)
                    if Link is not None:
                        LinkDefinitions.append(Link.group(1).split())
                    elif Line:
                        NodeDef = Line.split()
                        self.Nodes.append(
                            Node(NodeDef[0], tuple(map(int, NodeDef[1:]))))
                        self.NodeNames[NodeDef[0]] = self.Nodes[-1]
            except IOError:
                ET.error('Unable to find Network description',
                         Gbl.Parameter('NetworkFileName'))
            for L in LinkDefinitions:
                self.Links.append((
                    self.NodeNames[L[0]],
                    self.NodeNames[L[1]],
                ))
            for N in self.Nodes:
                print(N)
        self.Size = len(self.Nodes)

        self.TestMessages = [Message('M1', self.Nodes[0], self.Nodes[1])]

        # Creating routing tables
        for n in self.Nodes:
            n.CreateTable(self.Nodes, self.Neighbours(n))
Exemple #5
0
 def interaction(self, indiv, partner):
     " Interaction between individuals "
     PerceivedSignal = ET.noise_mult(partner.signal(), self['Noise'])
     PartnerPerceivedSignal = ET.noise_mult(indiv.signal(), self['Noise'])
     
     #indiv.get_friend(PerceivedSignal, partner, PartnerPerceivedSignal)
     # Suppression du gene Demande : bruit ??? 
     #return
     if PerceivedSignal >= indiv.demand() and PartnerPerceivedSignal >= partner.demand():
         indiv.acquainted(partner)
Exemple #6
0
	def NextNode(self, Target, deterministic=False):
		" determines the most attractive neighbouring node when heading to Target"
		if len(self.Table):
			if deterministic:
				return max([(self.Table[Target][n], n) for n in self.Table[Target]])[1]
			return self.Table[Target].keys()[ET.fortune_wheel(self.Table[Target].values())]
		return None
Exemple #7
0
 def NextNode(self, Target, deterministic=False):
     " determines the most attractive neighbouring node when heading to Target"
     if len(self.Table):
         if deterministic:
             return max([(self.Table[Target][n], n)
                         for n in self.Table[Target]])[1]
         return list(self.Table[Target].keys())[ET.fortune_wheel(
             self.Table[Target].values())]
     return None
Exemple #8
0
	def __init__(self, Size=100, NbNodes=0, NetworkFileName=None):
		self.TestMessages = []	# Messages used to test the efficiency of the network
		margin = 5 if Size > 20 else 0
		self.NodeNames = {}
		self.Nodes = []
		self.Links = []
		if Gbl.Parameter('RandomNetwork') and NbNodes > 1:
			self.Nodes = [Node('N%d' % i, (random.randint(margin, Size-margin), random.randint(margin, Size-margin))) for i in range(NbNodes)]
			if NbNodes > 1:
				for n in self.Nodes:
					OtherNodes = self.Nodes[:]
					OtherNodes.remove(n)	# does not need to be efficient
					if OtherNodes:
						self.Links.append((n, random.choice(OtherNodes)))
						self.Links.append((n, random.choice(OtherNodes)))
			self.Links = list(set(self.Links))	# to remove duplicates
			self.NodeNames = dict([(n.Name, n) for n in self.Nodes])
		else:	# loading network from file
			#	file format:
			#		Name1	x1	y1
			#		Name2	x2	y2
			#		...
			#		Link	NameA	NameB	C	(C = capacity)
			#		...
			#	('Link' = keyword)
			LinkDefinitions = []
			try:
				for Line in open(Gbl.Parameter('NetworkFileName'), 'r', 1):	# read one line at a time
					Link = re.match('(?i)link\s+(.*)', Line)
					if Link is not None:	LinkDefinitions.append(Link.group(1).split())
					elif Line:	
						NodeDef = Line.split()
						self.Nodes.append(Node(NodeDef[0], tuple(map(int, NodeDef[1:]))))
						self.NodeNames[NodeDef[0]] = self.Nodes[-1]
			except IOError:	ET.error('Unable to find Network description', Gbl.Parameter('NetworkFileName'))
			for L in LinkDefinitions:	
				self.Links.append((self.NodeNames[L[0]],self.NodeNames[L[1]],))
			for N in self.Nodes:	print N
		self.Size = len(self.Nodes)
		
		self.TestMessages = [Message('M1', self.Nodes[0], self.Nodes[1])]
		
		# Creating routing tables
		for n in self.Nodes:	n.CreateTable(self.Nodes, self.Neighbours(n))
Exemple #9
0
	def Sniff(self):
		" Looks for the next place to go "
		# The ant makes a biased choice of its next location
		# More probable links leading from neighbouring nodes to the ant's origin are more likely to be chosen
		Neighbours = self.location.Neighbours[:]
		if self.Origin in Neighbours: Neighbours.remove(self.Origin)
		Probabilities = [n.Table[self.Origin][self.location] for n in Neighbours]
		if Probabilities:
			NodeRank = ET.fortune_wheel(Probabilities)	# chooses a neighbour based on probabilities
			return Neighbours[NodeRank]
		return None
Exemple #10
0
	def learning(self):
		for agent in self.Pop:	agent.assessment()	# storing current scores (with possible cross-benefits)
		# some agents learn
		Learners = sample(self.Pop, ET.chances(self.Param('LearningProbability')/100.0, len(self.Pop)))	
		for agent in self.Pop:
			agent.wins(agent.Points)	# Stores points for learning
			if agent in Learners:
				if not agent.Learns(self.neighbours(agent), hot=self.Obs.hot_phase()):
					# agent.update()	# this is a newborn - update position for display
					pass
				agent.update()	# update position for display
	def learning(self):
		for agent in self.Pop:	agent.assessment()	# storing current scores (with possible cross-benefits)
		# some agents learn
		Learners = sample(self.Pop, ET.chances(self.Param('LearningProbability')/100.0, len(self.Pop)))	
		for agent in self.Pop:
			agent.wins(agent.Points)	# Stores points for learning
			if agent in Learners:
				if not agent.Learns(self.neighbours(agent), hot=self.Obs.hot_phase()):
					# agent.update()	# this is a newborn - update position for display
					pass
				agent.update()	# update position for display
Exemple #12
0
	def mutate(self, mutation_rate = -1):
		" computing the expected number of mutations "
		if mutation_rate < 0:	mutation_rate = self.Scenario.Parameter('MutationRate')
		mutation_number = Tools.chances(mutation_rate/1000.0, self.nb_nucleotides)
##        mutation_number =  (mutation_rate * self.nb_nucleotides) / 1000
##        if randint(1,1000) < 1 + ((mutation_rate * self.nb_nucleotides) % 1000) :
##            mutation_number += 1
		# performing mutations
		for mutation in range(mutation_number):
			pos = random.randint(0, self.nb_nucleotides - 1)
			self.__dna[pos] = 1 - self.__dna[pos]
		return mutation_number
Exemple #13
0
 def Sniff(self):
     " Looks for the next place to go "
     # The ant makes a biased choice of its next location
     # More probable links leading from neighbouring nodes to the ant's origin are more likely to be chosen
     Neighbours = self.location.Neighbours[:]
     if self.Origin in Neighbours: Neighbours.remove(self.Origin)
     Probabilities = [
         n.Table[self.Origin][self.location] for n in Neighbours
     ]
     if Probabilities:
         NodeRank = ET.fortune_wheel(
             Probabilities)  # chooses a neighbour based on probabilities
         return Neighbours[NodeRank]
     return None
Exemple #14
0
	def read_DNA(self, start, end, coding = None):
		" reads a chunk of DNA "
		if coding == None:	coding = self.Scenario.Parameter('GeneCoding')
		if coding in range(-1,3):
			# old numeric designation of coding
			coding = ['NoCoding', 'Weighted', 'Unweighted', 'Gray'][coding+1]
		value = 0
		if coding == 'NoCoding':
			return 0
		if coding not in ['Weighted', 'Unweighted', 'Gray']:
			Tools.error("DNA", 'unknown binary coding mode')
		try:
			for pos in range(start,end):
				if coding == 'Unweighted':
					value += self.__dna[pos]
				else:   # Weighted or Gray
##                    value += self.__dna[pos]* 2 ** (end - 1 - pos)
					value += (self.__dna[pos] << (end - 1 - pos))
			if coding == 'Gray':
				value = Tools.GrayTable.Gray2Int(value)
			return(value)
		except IndexError:
			Tools.error("DNA", "reading outside the DNA")
Exemple #15
0
	def Sniff(self):
		" Looks for the next place to go "
		DirectionToTarget = cmath.phase(t2c(self.Target) - t2c(self.location))   # argument 
		DirectionToTarget = ET.noise_add(DirectionToTarget, 0.02*cmath.pi * Gbl.Parameter('Noise'))
		# Distance0 = abs(DirectionToTarget)
		Neighbourhood = list(Land.neighbours(self.location, Gbl.Parameter('SniffingDistance')))
		random.shuffle(Neighbourhood) # to avoid anisotropy
		acceptable = None
		best = -Gbl.Parameter('Saturation')	# best == pheromone balance found so far
		for NewPos in Neighbourhood:
			if NewPos == self.location: continue
			# Target attractiveness
			Direction = cmath.phase(t2c(NewPos) - t2c(self.location))
			Value = Gbl.Parameter('TargetAttractiveness') * abs(cmath.pi - abs(DirectionToTarget - Direction))
			# looking for position with pheromone
			# attractiveness of pheromone
			Value += Gbl.Parameter('PheromoneAttractiveness') * float(Land.pheromone(NewPos)) / Gbl.Parameter('Saturation')
			# Value += Gbl.Parameter('PheromoneAttractiveness') * (Land.pheromone(NewPos))
			# aversion to climbing
			Value -= Gbl.Parameter('SlopeAversion') * abs(Land.Altitude(NewPos) - Land.Altitude(self.location))
			if Value > best:			  
				acceptable = NewPos
				best = Value
		return acceptable
Exemple #16
0
	def Sniff(self):
		" Looks for the next place to go "
		DirectionToTarget = cmath.phase(t2c(self.Target) - t2c(self.location))   # argument 
		DirectionToTarget = ET.noise_add(DirectionToTarget, 0.02*cmath.pi * Gbl.Parameter('Noise'))
		# Distance0 = abs(DirectionToTarget)
		Neighbourhood = Land.neighbours(self.location, Gbl.Parameter('SniffingDistance'))
		random.shuffle(Neighbourhood) # to avoid anisotropy
		acceptable = None
		best = -Gbl.Parameter('Saturation')	# best == pheromone balance found so far
		for NewPos in Neighbourhood:
			if NewPos == self.location: continue
			# Target attractiveness
			Direction = cmath.phase(t2c(NewPos) - t2c(self.location))
			Value = Gbl.Parameter('TargetAttractiveness') * abs(cmath.pi - abs(DirectionToTarget - Direction))
			# looking for position with pheromone
			# attractiveness of pheromone
			Value += Gbl.Parameter('PheromoneAttractiveness') * float(Land.pheromone(NewPos)) / Gbl.Parameter('Saturation')
			# Value += Gbl.Parameter('PheromoneAttractiveness') * (Land.pheromone(NewPos))
			# aversion to climbing
			Value -= Gbl.Parameter('SlopeAversion') * abs(Land.Altitude(NewPos) - Land.Altitude(self.location))
			if Value > best:			  
				acceptable = NewPos
				best = Value
		return acceptable
Exemple #17
0
import sys
from time import sleep
import random
		
sys.path.append('..')
sys.path.append('../../..')
import Evolife.Scenarii.Parameters			as EPar
import Evolife.Ecology.Observer				as EO
import Evolife.Ecology.Individual			as EI
import Evolife.Ecology.Group				as EG
import Evolife.Ecology.Population			as EP
import Evolife.QtGraphics.Evolife_Window	as EW
import Evolife.Tools.Tools					as ET

print(ET.boost())	# significantly accelerates python on some platforms


from Antnet import Antnet_Observer, Node, Network, Ant, Group, Population

#################################################
# Aspect of ants, food and pheromons on display
#################################################
LinkAspect = ('green5', 2)	# 2 = thickness
AntAspect = ('black', 5)	# 4 = size
AntAspectWhenOld = ('red5', 4)	# 4 = size
PPAspect = (17, 2)	# 17th colour
	
class City(Node):
	def __init__(self, Name, Location):
		Node.__init__(self, Name, Location)
# -------------------------------------------------------------------------- #
# License:  Creative Commons BY-NC-SA                                        #
##############################################################################
""" 2D Cellular Automaton with coloring mutation:
	Modified by Cybill Clerger
"""

import sys
sys.path.append('../../..')

import Evolife.Ecology.Observer as EO
import Evolife.QtGraphics.Evolife_Window as EW
import Evolife.Tools.Tools as ET
import Evolife.Scenarii.Parameters as EPar

print ET.boost(
)  # A technical trick that sometimes provides impressive speeding up

import random
import math


class Rule:
    " defines all possible automaton rules "

    def __init__(self, RuleNumber):
        " convert the rule number into a list of bits "
        # For each configuration number (9-bit for nine-cell neighbourhood --> 512 configurations),
        # the rule gives the new binary state of the cell.
        self.Rule = [int(b) for b in list(bin(RuleNumber)[2:].rjust(512, '0'))]
        self.Rule.reverse()
        # if this configuration is absent at the beginning, an all-0 state emerges.
		Evolife.QtGraphics.Evolife_Batch.Start(Population.One_Run, Observer)
		# writing header to result file
		open(Observer.get_info('ResultFile')+'.res','w').write(Observer.get_info('ResultHeader'))
		return

	####################
	# Interactive mode
	####################
	print __doc__
	" launching window "
	# Evolife.QtGraphics.Evolife_Window.Start(Pop.One_Run, Observer, Capabilities='FNCP', Options=[('BackGround','grey')])
	Evolife.QtGraphics.Evolife_Window.Start(Population.One_Run, Observer, Capabilities='FNCP', Options=[('BackGround','lightblue')])

	print "Bye......."
	sleep(2.1)	
	return
	


if __name__ == "__main__":
	ET.boost()   # A technical trick that sometimes provides impressive speeding up with Python up to 2.6
	Observer = Social_Observer(Gbl.Parameters)   # Observer contains statistics
	Observer.setOutputDir('___Results')
	Observer.recordInfo('DefaultViews',	['Field', 'Network'])	# Evolife should start with that window open
	Pop = Population(Gbl.Param('NbAgents'), Observer)   # population of agents
	Start(BatchMode=Gbl.Param('BatchMode'))



__author__ = 'Dessalles'
Exemple #20
0
 def recordChanges(self, Info, Slot='Positions'):
     # stores current changes
     # Info is a couple (InfoName, Position) and Position == (x,y) or a longer tuple
     if Slot == 'Positions': self.Positions.append(Info)
     elif Slot == 'Trajectories': self.Trajectories.append(Info)
     else: ET.error('Antnet Observer', 'unknown slot')
Exemple #21
0
	def recordChanges(self, Info, Slot='Positions'):
		# stores current changes
		# Info is a couple (InfoName, Position) and Position == (x,y) or a longer tuple
		if Slot ==  'Positions':	self.Positions.append(Info)
		elif Slot == 'Trajectories':	self.Trajectories.append(Info)
		else:	ET.error('Antnet Observer', 'unknown slot')
Exemple #22
0

""" Cellular Automaton:


"""

import sys
sys.path.append('../../..')

import Evolife.Ecology.Observer as EO
import Evolife.QtGraphics.Evolife_Window as EW
import Evolife.Tools.Tools as ET
import Evolife.Scenarii.Parameters as EPar

print ET.boost()   # A technical trick that sometimes provides impressive speeding up

	
import random

class Rule:
	" defines all possible automaton rules "
	def __init__(self, RuleNumber):
		" convert the rule number into a list of bits "
		# For each configuration number (3-bit for three-cell neighbourhood --> 8 configurations), 
		# the rule gives the new binary state of the cell.
		# Attention: the following line is only valid for 8 configurations
		self.Rule = [int(b) for b in list(bin(RuleNumber)[2:].rjust(8,'0'))]
		# example: rule 32 --> 00100000
		self.Rule.reverse()
		# example: rule 32 --> 00000100
Exemple #23
0
	def Neighbours(self, Node):
		if not Node in self.Nodes:	ET.error('Network', 'Non existing node has no neighbours')
		return [n for n in self.Nodes if (Node, n) in self.Links]
Exemple #24
0
            for M in Ntwrk.TestMessages:
                for link in M.erase():
                    Observer.recordChanges(
                        link, Slot='Trajectories')  # display of message route
                Route = M.draw(MaxPath=Ntwrk.Size)
                self.Observer.MsgLength[M] = len(Route)
                for link in Route:
                    Observer.recordChanges(
                        link, Slot='Trajectories')  # display of message route
        # print (year, self.AllMoved, Moves),
        return self.SimulationEnd > 0  # stops the simulation when True


if __name__ == "__main__":
    print(__doc__)
    print(ET.boost())  # significantly accelerates python on some platforms

    #############################
    # Global objects			#
    #############################
    Gbl = EPar.Parameters('_Params.evo')  # Loading global parameter values
    Observer = Antnet_Observer(Gbl)  # Observer contains statistics
    Ntwrk = Network(Size=Gbl.Parameter('DisplaySize'),
                    NbNodes=Gbl.Parameter('NumberOfNodes'))
    Pop = AntPopulation(Gbl, Observer, Ntwrk.nodes())  # Ant colony

    # Initial draw
    Observer.recordInfo('FieldWallpaper', 'yellow')
    Observer.recordInfo('TrajectoriesWallpaper', 'lightblue')
    Observer.recordInfo('DefaultViews', ['Field', 'Trajectories'])
    Observer.recordChanges(
Exemple #25
0
from time import sleep
import random
import cmath
		
sys.path.append('..')
sys.path.append('../../..')
import Evolife.Scenarii.Parameters			as EPar
import Evolife.Ecology.Observer				as EO
import Evolife.Ecology.Individual			as EI
import Evolife.Ecology.Group				as EG
import Evolife.Ecology.Population			as EP
import Evolife.QtGraphics.Evolife_Window	as EW
import Evolife.Tools.Tools					as ET
import Landscapes

print ET.boost()	# significWalkerly accelerates python on some platforms


# two functions to convert from complex numbers into (x,y) coordinates
c2t = lambda c: (int(round(c.real)),int(round(c.imag))) # converts a complex into a couple
t2c = lambda (x,y): complex(x,y) # converts a couple into a complex

#################################################
# Aspect of Walkers and pheromone on display
#################################################
# WalkerAspect = ('black', 6)	
# PheromonAspect = (17, 2)
WalkerAspect = ('white', 1)	
PheromonAspect = ('white', 4)