def parse(self,element): assert element.tagName == 'tree' node = element.firstChild plane = None children = {} while node: if node.nodeType == node.ELEMENT_NODE: if node.tagName == 'vector': if node.getAttribute('key'): # Vector leaf key = eval(node.getAttribute('key')) children[key] = KeyedVector(node) else: # Branch plane = KeyedPlane(node) elif node.tagName == 'plane': plane = KeyedPlane(node) elif node.tagName == 'matrix': key = eval(node.getAttribute('key')) children[key] = KeyedMatrix(node) elif node.tagName == 'tree': key = eval(node.getAttribute('key')) children[key] = KeyedTree(node) elif node.tagName == 'distribution': children = TreeDistribution(node) elif node.tagName == 'bool': key = eval(node.getAttribute('key')) children[key] = eval(node.getAttribute('value')) elif node.tagName == 'action': key = eval(node.getAttribute('key')) children[key] = Action(node) elif node.tagName == 'str': key = eval(node.getAttribute('key')) children[key] = str(node.firstChild.data).strip() elif node.tagName == 'int': key = int(node.getAttribute('key')) children[key] = KeyedTree(node) elif node.tagName == 'none': key = eval(node.getAttribute('key')) children[key] = None node = node.nextSibling if plane: self.makeBranch(plane,children) elif isinstance(children,Distribution): self.makeProbabilistic(children) else: self.makeLeaf(children[None])
def getAction(world, form): """ Extract an action from form submission """ state = world.state.domain()[0] verb = form.getvalue('verb') action = None if verb: table = {'verb': str(verb), 'subject': str(form.getvalue('subject'))} for option in world.agents[table['subject']].getActions(state): atom = option.match(table) if atom: if atom.has_key('object'): table['object'] = atom['object'] for key in atom.getParameters(): # Make sure all parameters are specified if form.getvalue(key): try: table[key] = int(form.getvalue(key)) continue except TypeError: # Invalid value break except ValueError: # Maybe a float? try: table[key] = int( float(form.getvalue(key)) + 0.5) except ValueError: break else: # Empty value break else: # All parameters specified action = Action(table) break return action
def __init__(self, turnOrder): self.maxRounds = 8 self.world = World() totals = {'apple': 1, 'pear': 2} batna_prePref = totals['apple'] + totals['pear'] stacy = Agent('Stacy') david = Agent('David') agts = [stacy, david] # Player state, actions and parameters common to both players for i in range(2): me = agts[i] other = agts[1 - i] self.world.addAgent(me) # State self.world.defineState(me.name, 'appleOwned', int, lo=0, hi=totals['apple']) me.setState('appleOwned', 0) self.world.defineState(me.name, 'appleOffered', int, lo=0, hi=totals['apple']) me.setState('appleOffered', 0) self.world.defineState(me.name, 'pearOwned', int, lo=0, hi=totals['pear']) me.setState('pearOwned', 0) self.world.defineState(me.name, 'pearOffered', int, lo=0, hi=totals['pear']) me.setState('pearOffered', 0) self.world.defineState(me.name, 'Batna', int, lo=0, hi=10) me.setState('Batna', batna_prePref) self.world.defineState(me.name, 'BatnaOwned', int, lo=0, hi=10) me.setState('BatnaOwned', 0) self.world.defineState(me.name, 'agree', bool) me.setState('agree', False) # Actions me.addAction({'verb': 'do nothing'}) for amt in range(totals['apple'] + 1): tmp = me.addAction({ 'verb': 'offerApple', 'object': other.name, 'amount': amt }) me.setLegal( tmp, makeTree({ 'if': trueRow(stateKey(None, 'agreement')), False: { 'if': trueRow(stateKey(None, 'rejectedNegotiation')), True: False, False: True }, True: False })) for amt in range(totals['pear'] + 1): tmp = me.addAction({ 'verb': 'offerPear', 'object': other.name, 'amount': amt }) me.setLegal( tmp, makeTree({ 'if': trueRow(stateKey(None, 'agreement')), False: { 'if': trueRow(stateKey(None, 'rejectedNegotiation')), True: False, False: True }, True: False })) meReject = me.addAction({ 'verb': 'rejectNegotiation', 'object': other.name }) me.setLegal( meReject, makeTree({ 'if': trueRow(stateKey(None, 'agreement')), False: { 'if': trueRow(stateKey(None, 'rejectedNegotiation')), True: False, False: True }, True: False })) meAccept = me.addAction({ 'verb': 'accept offer', 'object': other.name }) me.setLegal( meAccept, makeTree({ 'if': trueRow(stateKey(None, 'appleOffer')), True: { 'if': trueRow(stateKey(None, 'pearOffer')), True: { 'if': trueRow(stateKey(None, 'agreement')), False: { 'if': trueRow(stateKey(None, 'rejectedNegotiation')), True: False, False: True }, True: False }, False: False }, False: False })) # Parameters me.setHorizon(6) me.setParameter('discount', 0.9) # Levels of belief david.setRecursiveLevel(3) stacy.setRecursiveLevel(3) # Turn order: Uncomment the following if you want agents to act in parallel # world.setOrder([{agts[0].name,agts[1].name}]) # Turn order: Uncomment the following if you want agents to act sequentially self.world.setOrder(turnOrder) # World state self.world.defineState(None, 'agreement', bool) self.world.setState(None, 'agreement', False) self.world.defineState(None, 'appleOffer', bool) self.world.setState(None, 'appleOffer', False) self.world.defineState(None, 'pearOffer', bool) self.world.setState(None, 'pearOffer', False) self.world.defineState( None, 'round', int, description='The current round of the negotiation') self.world.setState(None, 'round', 0) self.world.defineState( None, 'rejectedNegotiation', bool, description='Have one of the players walked out?') self.world.setState(None, 'rejectedNegotiation', False) # dont terminate so agent sees benefit of early agreement # world.addTermination(makeTree({'if': trueRow(stateKey(None,'agreement')), # True: True, # False: False})) # world.addTermination(makeTree({'if': trueRow(stateKey(None,'rejectedNegotiation')), # True: True, # False: False})) self.world.addTermination( makeTree({ 'if': thresholdRow(stateKey(None, 'round'), self.maxRounds), True: True, False: False })) # Dynamics of offers agents = [david.name, stacy.name] for i in range(2): for fruit in ['apple', 'pear']: atom = Action({ 'subject': agents[i], 'verb': 'offer%s' % (fruit.capitalize()), 'object': agents[1 - i] }) parties = [atom['subject'], atom['object']] for j in range(2): # Set offer amount offer = stateKey(parties[j], '%sOffered' % (fruit)) amount = actionKey('amount') if j == 1 else '%d-%s' % ( totals[fruit], actionKey('amount')) tree = makeTree(setToConstantMatrix(offer, amount)) self.world.setDynamics(parties[j], '%sOffered' % (fruit), atom, tree) # reset agree flags whenever an offer is made agreeFlag = stateKey(parties[j], 'agree') tree = makeTree(setFalseMatrix(agreeFlag)) self.world.setDynamics(parties[j], 'agree', atom, tree) # Offers set offer flag in world state tree = makeTree( setTrueMatrix(stateKey(None, '%sOffer' % (fruit)))) self.world.setDynamics(None, '%sOffer' % (fruit), atom, tree) # agents = [david.name,stacy.name] # Dynamics of agreements for i in range(2): atom = Action({ 'subject': agents[i], 'verb': 'accept offer', 'object': agents[1 - i] }) # accept offer sets accept tree = makeTree(setTrueMatrix(stateKey(atom['subject'], 'agree'))) self.world.setDynamics(atom['subject'], 'agree', atom, tree) # accept offer sets agreement if object has accepted tree = makeTree({ 'if': trueRow(stateKey(atom['object'], 'agree')), True: setTrueMatrix(stateKey(None, 'agreement')), False: noChangeMatrix(stateKey(None, 'agreement')) }) self.world.setDynamics(None, 'agreement', atom, tree) # Accepting offer sets ownership parties = [atom['subject'], atom['object']] for fruit in ['apple', 'pear']: # atom = Action({'subject': agents[i],'verb': 'accept offer', 'object': agents[1-i]}) for j in range(2): offer = stateKey(parties[j], '%sOffered' % (fruit)) owned = stateKey(parties[j], '%sOwned' % (fruit)) tree = makeTree({ 'if': trueRow(stateKey(atom['object'], 'agree')), False: noChangeMatrix(owned), True: setToFeatureMatrix(owned, offer) }) self.world.setDynamics(parties[j], '%sOwned' % (fruit), atom, tree) # rejecting give us batna and ends negotiation atom = Action({ 'subject': agents[i], 'verb': 'rejectNegotiation', 'object': agents[1 - i] }) tree = makeTree( setToFeatureMatrix(stateKey(atom['subject'], 'BatnaOwned'), stateKey(atom['subject'], 'Batna'))) self.world.setDynamics(atom['subject'], 'BatnaOwned', atom, tree) tree = makeTree( setToFeatureMatrix(stateKey(atom['object'], 'BatnaOwned'), stateKey(atom['object'], 'Batna'))) self.world.setDynamics(atom['object'], 'BatnaOwned', atom, tree) tree = makeTree( setTrueMatrix(stateKey(None, 'rejectedNegotiation'))) self.world.setDynamics(None, 'rejectedNegotiation', atom, tree) for action in stacy.actions | david.actions: tree = makeTree(incrementMatrix(stateKey(None, 'round'), 1)) self.world.setDynamics(None, 'round', action, tree) for agent in self.world.agents.values(): agent.addModel('pearLover', R={}, level=2, rationality=0.01) agent.addModel('appleLover', R={}, level=2, rationality=0.01)
def parseGDELT(fname, targets=[]): """ Extracts events from a single GDELT CSV file """ # Parse filename root, ext = os.path.splitext(os.path.basename(fname)) assert ext == '.csv', 'CSV file expected instead of %s' % (fname) if len(root) == 4: year = int(root) month = 0 else: assert len( root) == 6, 'Filename not in YYYY.csv or YYYYMM.csv format: %s' % ( fname) year = int(root[:4]) month = int(root[4:]) # Initialize storage result = { 'month': month, 'year': year, 'agents': {}, 'matrix': {}, 'calendar': {}, } today = None start = time.time() lines = 0 for line in fileinput.input(fname): lines += 1 # Extract the event fields elements = map(lambda x: x.strip(), line.split('\t')) event = {} for index in range(len(elements)): if len(elements[index]) == 0: event[headings[index]] = None elif headings[index] in intHeadings: event[headings[index]] = int(elements[index]) elif headings[index] in floatHeadings: event[headings[index]] = float(elements[index]) else: event[headings[index]] = elements[index].strip() if event['SQLDATE'] != today: today = event['SQLDATE'] events = [] result['calendar'][event['SQLDATE']] = events print >> sys.stderr, today if event['Actor1Code'] is None: # No actor? event['Actor1Code'] = 'Unknown' if lines % 10000 == 0 and events: print >> sys.stderr,'\t%dK (%d events,%d agents)' % \ (lines/1000,len(events),len(result['agents'])) if matchActor(event['Actor1Code'],targets) or \ matchActor(event['Actor2Code'],targets): # Event matching our target events.append(event) if not result['agents'].has_key(event['Actor1Code']): agent = Agent(event['Actor1Code']) result['agents'][agent.name] = agent event['action'] = Action({ 'subject': event['Actor1Code'], 'verb': cameo[event['EventCode']] }) if event['Actor2Code']: if not result['agents'].has_key(event['Actor2Code']): agent = Agent(event['Actor2Code']) result['agents'][agent.name] = agent event['action']['object'] = event['Actor2Code'] # Update relationship matrix if event['Actor1Code'] < event['Actor2Code']: key = '%s,%s' % (event['Actor1Code'], event['Actor2Code']) else: key = '%s,%s' % (event['Actor2Code'], event['Actor1Code']) try: result['matrix'][key].append(event) except KeyError: result['matrix'][key] = [event] return result
goal = maximizeFeature(stateKey(stacy.name, 'pearsOwned')) stacy.setReward(goal, 2.) # Goals for David goal = maximizeFeature(stateKey(david.name, 'applesOwned')) david.setReward(goal, 2.) goal = minimizeFeature(stateKey(david.name, 'pearsOwned')) david.setReward(goal, 1.) # Dynamics of offers agents = [david.name, stacy.name] for fruit in ['apple', 'pear']: for i in range(2): atom = Action({ 'subject': agents[i], 'verb': 'offer%s' % (fruit.capitalize()), 'object': agents[1 - i] }) offer = stateKey(atom['object'], '%ssOffered' % (fruit)) amount = actionKey('amount') tree = makeTree({ 'if': trueRow('agreement'), True: noChangeMatrix(offer), False: setToConstantMatrix(offer, amount) }) world.setDynamics(atom['object'], '%ssOffered' % (fruit), atom, tree) offer = stateKey(atom['subject'], '%ssOffered' % (fruit)) tree = makeTree({
# Turn order: Uncomment the following if you want agents to act in parallel actors = world.agents.keys() # actors = set(actors) # print actors # actors.discard('door') # actors.discard('fire') # world.setOrder([actors]) actors.remove('door') actors.remove('fire') world.setOrder([set(actors)]) print actors for agt in actors: atom = Action({'subject': agt,'verb': 'runAway', 'object':'fire'}) tree = makeTree(incrementMatrix(stateKey(atom['subject'],'fire_dist'),.1)) world.setDynamics(agt,'fire_dist',atom,tree) atom = Action({'subject': agt,'verb': 'runTowards', 'object':'door'}) tree = makeTree(incrementMatrix(stateKey(atom['subject'],'door_dist'),-.1)) world.setDynamics(agt,'door_dist',atom,tree) atom = Action({'subject': agt,'verb': 'runClosest'}) tree = makeTree(incrementMatrix(stateKey(atom['subject'],'closest_dist'),-.1)) world.setDynamics(agt,'door_dist',atom,tree) # Save scenario to compressed XML file world.save('default.psy')
def __init__(self): self.world = World() stacy = Agent('Stacy') david = Agent('David') agts = [stacy, david] totalAmt = 4 # Player state, actions and parameters common to both players for i in range(2): me = agts[i] other = agts[1 - i] self.world.addAgent(me) self.world.defineState(me.name, 'offered', int, lo=0, hi=totalAmt) self.world.defineState(me.name, 'money', int, lo=0, hi=totalAmt) me.setState('offered', 0) me.setState('money', 0) if (me.name == 'Stacy'): for amt in range(totalAmt + 1): me.addAction({ 'verb': 'offer', 'object': other.name, 'amount': amt }) else: mePass = me.addAction({'verb': 'accept', 'object': other.name}) mePass = me.addAction({'verb': 'reject', 'object': other.name}) # Parameters me.setHorizon(2) me.setParameter('discount', 0.9) # me.setParameter('discount',1.0) # Levels of belief david.setRecursiveLevel(3) stacy.setRecursiveLevel(3) self.world.setOrder(['Stacy', 'David']) # World state self.world.defineState(None, 'gameOver', bool, description='The current round') self.world.setState(None, 'gameOver', False) self.world.addTermination( makeTree({ 'if': trueRow(stateKey(None, 'gameOver')), True: True, False: False })) # offer dynamics atom = Action({'subject': 'Stacy', 'verb': 'offer', 'object': 'David'}) parties = [atom['subject'], atom['object']] for j in range(2): offer = stateKey(parties[j], 'offered') amount = actionKey('amount') if j == 1 else '%d-%s' % ( totalAmt, actionKey('amount')) tree = makeTree(setToConstantMatrix(offer, amount)) self.world.setDynamics(parties[j], 'offered', atom, tree) # accept dynamics atom = Action({ 'subject': 'David', 'verb': 'accept', 'object': 'Stacy' }) parties = [atom['subject'], atom['object']] for j in range(2): offer = stateKey(parties[j], 'offered') money = stateKey(parties[j], 'money') tree = makeTree(setToFeatureMatrix(money, offer)) self.world.setDynamics(parties[j], 'money', atom, tree) tree = makeTree(setTrueMatrix(stateKey(None, 'gameOver'))) self.world.setDynamics(None, 'gameOver', atom, tree) # reject dynamics atom = Action({ 'subject': 'David', 'verb': 'reject', 'object': 'Stacy' }) tree = makeTree(setTrueMatrix(stateKey(None, 'gameOver'))) self.world.setDynamics(None, 'gameOver', atom, tree) # really need to ask david about these levels - if adding modesl with levels, can # the true model point to these but have a different level for agent in self.world.agents.values(): agent.addModel('Christian', R={}, level=2, rationality=25., selection='distribution') agent.addModel('Capitalist', R={}, level=2, rationality=25., selection='distribution')