Commit 40c500ab by serfrape

Allow BDI behaviour to be enabled/disabled

parent 013d3b92
...@@ -25,8 +25,11 @@ class BossAgent(BDIAgent): ...@@ -25,8 +25,11 @@ class BossAgent(BDIAgent):
b = BDIAgent("slave_1@localhost", "bdisimple", "slave.asl") b = BDIAgent("slave_1@localhost", "bdisimple", "slave.asl")
b.start() b.start()
c = BDIAgent("slave_2@localhost", "bdisimple3", "slave.asl") c = BDIAgent("slave_2@localhost", "bdisimple3")
c.start() c.start()
a = BossAgent("Boss@localhost", "bdiboss", "boss.asl") a = BossAgent("Boss@localhost", "bdiboss", "boss.asl")
a.start() a.start()
print("started") import time
time.sleep(5)
print("Enabling BDI for slave2")
c.set_asl("slave.asl")
...@@ -22,20 +22,34 @@ class BDIAgent(Agent): ...@@ -22,20 +22,34 @@ class BDIAgent(Agent):
self.add_behaviour(self.BDIBehaviour(), template) self.add_behaviour(self.BDIBehaviour(), template)
def add_behaviour(self, behaviour, template=None): def add_behaviour(self, behaviour, template=None):
# print("OVERRIDEN")
if type(behaviour) == self.BDIBehaviour: if type(behaviour) == self.BDIBehaviour:
self.bdi = behaviour self.bdi = behaviour
# print("ADDING BDI BEHAVIOUR")
super().add_behaviour(behaviour, template) super().add_behaviour(behaviour, template)
def __init__(self, jid, password, asl, *args, **kwargs): def set_asl(self, asl):
self.asl_file = asl self.asl_file = asl
# print("instantiated") if self.asl_file == None:
self.bdi_enabled = False
else:
with open(self.asl_file) as source:
self.bdi_agent = self.bdi_env.build_agent(
source, self.bdi_actions)
self.bdi_agent.name = self.jid
self.bdi_enabled = True
def set_env(self):
self.bdi_env = pyson.runtime.Environment()
self.bdi_actions = pyson.Actions(pyson.stdlib.actions)
self.bdi.add_actions()
def __init__(self, jid, password, asl=None, *args, **kwargs):
self.asl_file = asl
self.bdi_enabled = False
super().__init__(jid, password, *args, **kwargs) super().__init__(jid, password, *args, **kwargs)
class BDIBehaviour(CyclicBehaviour): class BDIBehaviour(CyclicBehaviour):
def add_actions(self): def add_actions(self):
@self.actions.add(".send", 3) @self.agent.bdi_actions.add(".send", 3)
def _send(agent, term, intention): def _send(agent, term, intention):
receiver = pyson.grounded(term.args[0], intention.scope) receiver = pyson.grounded(term.args[0], intention.scope)
ilf = pyson.grounded(term.args[1], intention.scope) ilf = pyson.grounded(term.args[1], intention.scope)
...@@ -48,20 +62,19 @@ class BDIAgent(Agent): ...@@ -48,20 +62,19 @@ class BDIAgent(Agent):
"args": str(term.args[2].args)}) "args": str(term.args[2].args)})
msg = Message(to=receiver, body=body, metadata=mdata) msg = Message(to=receiver, body=body, metadata=mdata)
self.agent.submit(self.send(msg)) self.agent.submit(self.send(msg))
# print("SENT!!!")
yield yield
@self.actions.add(".custom_action", 1) @self.agent.bdi_actions.add(".custom_action", 1)
def _custom_action(agent, term, intention): def _custom_action(agent, term, intention):
arg_0 = pyson.grounded(term.args[0], intention.scope) arg_0 = pyson.grounded(term.args[0], intention.scope)
print(arg_0) print(arg_0)
yield yield
@self.actions.add_function(".a_function", (int,)) @self.agent.bdi_actions.add_function(".a_function", (int,))
def _a_function(x): def _a_function(x):
return x**4 return x**4
@self.actions.add_function("literal_function", (pyson.Literal,)) @self.agent.bdi_actions.add_function("literal_function", (pyson.Literal,))
def _literal_function(x): def _literal_function(x):
return x return x
...@@ -75,15 +88,15 @@ class BDIAgent(Agent): ...@@ -75,15 +88,15 @@ class BDIAgent(Agent):
new_args += (x,) new_args += (x,)
term = pyson.Literal(name, tuple(new_args), PERCEPT_TAG) term = pyson.Literal(name, tuple(new_args), PERCEPT_TAG)
found = False found = False
for belief in list(self.bdi_agent.beliefs[term.literal_group()]): for belief in list(self.agent.bdi_agent.beliefs[term.literal_group()]):
if pyson.unifies(term, belief): if pyson.unifies(term, belief):
found = True found = True
else: else:
self.bdi_agent.call(pyson.Trigger.removal, pyson.GoalType.belief, belief, self.agent.bdi_agent.call(pyson.Trigger.removal, pyson.GoalType.belief, belief,
pyson.runtime.Intention()) pyson.runtime.Intention())
if not found: if not found:
self.bdi_agent.call(pyson.Trigger.addition, pyson.GoalType.belief, term, self.agent.bdi_agent.call(pyson.Trigger.addition, pyson.GoalType.belief, term,
pyson.runtime.Intention()) pyson.runtime.Intention())
def remove_belief(self, name, *args): def remove_belief(self, name, *args):
"""Remove an existing agent's belief.""" """Remove an existing agent's belief."""
...@@ -94,18 +107,18 @@ class BDIAgent(Agent): ...@@ -94,18 +107,18 @@ class BDIAgent(Agent):
else: else:
new_args += (x,) new_args += (x,)
term = pyson.Literal(name, tuple(new_args), PERCEPT_TAG) term = pyson.Literal(name, tuple(new_args), PERCEPT_TAG)
self.bdi_agent.call(pyson.Trigger.removal, pyson.GoalType.belief, term, self.agent.bdi_agent.call(pyson.Trigger.removal, pyson.GoalType.belief, term,
pyson.runtime.Intention()) pyson.runtime.Intention())
def get_belief(self, key, pyson_format=False): def get_belief(self, key, pyson_format=False):
"""Get an agent's existing belief. The first belief matching """Get an agent's existing belief. The first belief matching
<key> is returned. Keep <pyson_format> False to strip pyson <key> is returned. Keep <pyson_format> False to strip pyson
formatting.""" formatting."""
key = str(key) key = str(key)
for beliefs in self.bdi_agent.beliefs: for beliefs in self.agent.bdi_agent.beliefs:
if beliefs[0] == key: if beliefs[0] == key:
raw_belief = ( raw_belief = (
str(list(self.bdi_agent.beliefs[beliefs])[0])) str(list(self.agent.bdi_agent.beliefs[beliefs])[0]))
if ')[source' in raw_belief and not pyson_format: if ')[source' in raw_belief and not pyson_format:
raw_belief = raw_belief.split( raw_belief = raw_belief.split(
'[')[0].replace('"', '') '[')[0].replace('"', '')
...@@ -126,10 +139,10 @@ class BDIAgent(Agent): ...@@ -126,10 +139,10 @@ class BDIAgent(Agent):
"""Get agent's beliefs.Keep <pyson_format> False to strip pyson """Get agent's beliefs.Keep <pyson_format> False to strip pyson
formatting.""" formatting."""
belief_list = [] belief_list = []
for beliefs in self.bdi_agent.beliefs: for beliefs in self.agent.bdi_agent.beliefs:
try: try:
raw_belief = ( raw_belief = (
str(list(self.bdi_agent.beliefs[beliefs])[0])) str(list(self.agent.bdi_agent.beliefs[beliefs])[0]))
if ')[source(' in raw_belief and not pyson_format: if ')[source(' in raw_belief and not pyson_format:
raw_belief = raw_belief.split('[')[0].replace('"', '') raw_belief = raw_belief.split('[')[0].replace('"', '')
belief_list.append(raw_belief) belief_list.append(raw_belief)
...@@ -141,7 +154,7 @@ class BDIAgent(Agent): ...@@ -141,7 +154,7 @@ class BDIAgent(Agent):
"""Print agent's beliefs.Keep <pyson_format> False to strip pyson """Print agent's beliefs.Keep <pyson_format> False to strip pyson
formatting.""" formatting."""
print("PRINTING BELIEFS") print("PRINTING BELIEFS")
for beliefs in self.bdi_agent.beliefs.values(): for beliefs in self.agent.bdi_agent.beliefs.values():
for belief in beliefs: for belief in beliefs:
if ')[source(' in str(belief) and not pyson_format: if ')[source(' in str(belief) and not pyson_format:
belief = str(belief).split('[')[0].replace('"', '') belief = str(belief).split('[')[0].replace('"', '')
...@@ -151,49 +164,48 @@ class BDIAgent(Agent): ...@@ -151,49 +164,48 @@ class BDIAgent(Agent):
""" """
Coroutine called before the behaviour is started. Coroutine called before the behaviour is started.
""" """
self.env = pyson.runtime.Environment() self.agent.set_env()
self.actions = pyson.Actions(pyson.stdlib.actions) if self.agent.asl_file:
self.add_actions() self.agent.set_asl(self.agent.asl_file)
with open(self.agent.asl_file) as source: else:
self.bdi_agent = self.env.build_agent( print("No ASL specified.")
source, self.actions)
self.bdi_agent.name = self.agent.jid
async def run(self): async def run(self):
""" """
Coroutine run cyclic. Coroutine run cyclic.
""" """
msg = await self.receive(timeout=0.1) if self.agent.bdi_enabled:
if msg: msg = await self.receive(timeout=0.1)
received = json.loads(msg.body) if msg:
mdata = msg.metadata received = json.loads(msg.body)
ilf_type = mdata["ilf_type"] mdata = msg.metadata
if ilf_type == "tell": ilf_type = mdata["ilf_type"]
goal_type = pyson.GoalType.belief if ilf_type == "tell":
trigger = pyson.Trigger.addition goal_type = pyson.GoalType.belief
elif ilf_type == "untell": trigger = pyson.Trigger.addition
goal_type = pyson.GoalType.belief elif ilf_type == "untell":
trigger = pyson.Trigger.removal goal_type = pyson.GoalType.belief
elif ilf_type == "achieve": trigger = pyson.Trigger.removal
goal_type = pyson.GoalType.achievement elif ilf_type == "achieve":
trigger = pyson.Trigger.addition goal_type = pyson.GoalType.achievement
else: trigger = pyson.Trigger.addition
raise pyson.PysonError( else:
"unknown illocutionary force: %s" % ilf_type) raise pyson.PysonError(
intention = pyson.runtime.Intention() "unknown illocutionary force: %s" % ilf_type)
args = literal_eval(received["args"]) intention = pyson.runtime.Intention()
args = literal_eval(received["args"])
if args != tuple():
message = pyson.Literal( if args != tuple():
received["functor"], args) message = pyson.Literal(
else: received["functor"], args)
message = pyson.Literal(received["functor"]) else:
message = pyson.freeze(message, intention.scope, {}) message = pyson.Literal(received["functor"])
tagged_message = message.with_annotation( message = pyson.freeze(message, intention.scope, {})
pyson.Literal("source", (pyson.Literal(str(msg.sender)), ))) tagged_message = message.with_annotation(
self.bdi_agent.call(trigger, goal_type, pyson.Literal("source", (pyson.Literal(str(msg.sender)), )))
tagged_message, intention) self.agent.bdi_agent.call(trigger, goal_type,
self.bdi_agent.step() tagged_message, intention)
self.agent.bdi_agent.step()
async def on_end(self): async def on_end(self):
""" """
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment