Package teamwork :: Package multiagent :: Module Multiagent
[hide private]
[frames] | no frames]

Source Code for Module teamwork.multiagent.Multiagent

 1  from xml.dom.minidom import * 
 2   
3 -class MultiagentSystem(dict):
4 """Base class for a generic collection of agents""" 5
6 - def __init__(self,agents=[]):
7 """Initializes a collection to contain the given list of agents""" 8 if isinstance(agents,dict): 9 agents = agents.values() 10 for agent in agents: 11 self.addMember(agent)
12
13 - def initialize(self):
14 """Do any necessary preparation before doing whatever 15 """ 16 pass
17
18 - def members(self):
19 """ 20 @return: a list of the member agents, in decreasing order according to whatever comparison function has been defined on the agent class 21 @rtype: C{L{teamwork.agent.Agent}[]} 22 """ 23 return self.values()
24
25 - def addMember(self,agent):
26 """Adds the agent to this collection 27 @param agent: the agent to add 28 @type agent: L{teamwork.agent.Agent} 29 @warning: will clobber any pre-existing agent with the same name 30 """ 31 self[agent.name] = agent
32
33 - def getMember(self,agent):
34 """ 35 @warning: Deprecated, use C{self[name]} instead 36 @return: the member agent contained in this team that corresponds to the specified agent object or string name 37 """ 38 raise DeprecationWarning,\ 39 'Use __getitem__ instead (e.g., "entities[%s]")' % \ 40 (agent)
41
42 - def save(self,name):
43 """Stores this MAS at the specified file location. The storage format is based on the file extension: 44 - C{xml}: Store in PsychSim's XML format 45 - C{scn}: compressed XML (default) 46 @param name: the string filename 47 @type name: C{str}""" 48 doc = self.__xml__() 49 if name[-3:] == 'xml': 50 f = open(name,'w') 51 else: 52 import bz2 53 f = bz2.BZ2File(name,'w') 54 f.write(doc.toxml()) 55 f.close()
56
57 - def __str__(self):
58 content = '' 59 for agent in self.members(): 60 content += str(agent) 61 return content
62
63 - def __xml__(self):
64 doc = Document() 65 root = doc.createElement('multiagent') 66 root.setAttribute('type',self.__class__.__name__) 67 doc.appendChild(root) 68 for agent in self.members(): 69 root.appendChild(agent.__xml__().documentElement) 70 return doc
71
72 - def parse(self,element,agentClass=None):
73 child = element.firstChild 74 while child: 75 if child.nodeType == Node.ELEMENT_NODE: 76 if child.tagName == 'agent': 77 agent = agentClass(None) 78 agent.parse(child) 79 self.addMember(agent) 80 child = child.nextSibling
81