Commit 54799e60 by serfrape

Will add some functionalities and example

parent b07b6dea
contador(8).
tipo(dec).
!inicio.
+!inicio
<-
.print("Iniciando....");
!obj2.
+!obj2: tipo(inc)
<-
.print("Incrementando");
?contador(X);
-+contador(X+1);
.wait(2000);
!obj2.
+!obj2: tipo(dec)
<-
.print("Decrementando");
?contador(X);
-+contador(X-1);
.wait(2000);
!obj2.
+!obj2: not tipo(_)
<-
.print("Esperando");
.wait(2000);
!obj2.
\ No newline at end of file
from spade_bdi.bdi import BDIAgent
from spade.template import Template
from spade.behaviour import PeriodicBehaviour
from datetime import datetime
from spade.agent import Agent
class ExampleAgent(BDIAgent):
def setup(self):
template = Template(metadata={"performative": "BDI"})
self.add_behaviour(self.BDIBehaviour(), template)
template = Template(metadata={"performative": "B1"})
self.add_behaviour(self.Behav1(
period=1, start_at=datetime.now()), template)
template = Template(metadata={"performative": "B2"})
self.add_behaviour(self.Behav2(
period=5, start_at=datetime.now()), template)
template = Template(metadata={"performative": "B3"})
self.add_behaviour(self.Behav3(
period=10, start_at=datetime.now()), template)
class Behav1(PeriodicBehaviour):
async def on_start(self):
self.contador = self.agent.bdi.get_belief_value("contador")[0]
async def run(self):
if self.contador != self.agent.bdi.get_belief_value("contador")[0]:
self.contador = self.agent.bdi.get_belief_value("contador")[
0]
print(self.agent.bdi.get_belief("contador"))
class Behav2(PeriodicBehaviour):
async def run(self):
self.agent.bdi.set_belief('contador', 0)
class Behav3(PeriodicBehaviour):
async def run(self):
tipo = self.agent.bdi.get_belief_value("tipo")[0]
if tipo == 'inc':
self.agent.bdi.set_belief('tipo', 'dec')
# else:
# self.agent.bdi.set_belief('tipo', 'inc')
a = ExampleAgent("Agent@localhost", "bditest", "ejemplo.asl")
a.start()
import time
time.sleep(1)
print("started")
...@@ -22,14 +22,16 @@ class BDIAgent(Agent): ...@@ -22,14 +22,16 @@ class BDIAgent(Agent):
def add_behaviour(self, behaviour, template=None): def add_behaviour(self, behaviour, template=None):
# print("OVERRIDEN") # print("OVERRIDEN")
self.bdi = behaviour if type(behaviour) == self.BDIBehaviour:
self.bdi = behaviour
super().add_behaviour(behaviour, template) super().add_behaviour(behaviour, template)
def __init__(self, jid, password, asl, *args, **kwargs): def __init__(self, jid, password, asl, *args, **kwargs):
self.asl_file = asl self.asl_file = asl
# print("instantiated")
super().__init__(jid, password, *args, **kwargs) super().__init__(jid, password, *args, **kwargs)
class BDIBehaviour(CyclicBehaviour, metaclass=ABCMeta): class BDIBehaviour(CyclicBehaviour):
def add_actions(self): def add_actions(self):
@self.actions.add(".send", 3) @self.actions.add(".send", 3)
def _send(agent, term, intention): def _send(agent, term, intention):
...@@ -61,12 +63,14 @@ class BDIAgent(Agent): ...@@ -61,12 +63,14 @@ class BDIAgent(Agent):
def _literal_function(x): def _literal_function(x):
return x return x
# def set_belief(self, agent, term, intention):
def set_belief(self, name, *args): def set_belief(self, name, *args):
"""Set an agent's belief. If it already exists, updates it.""" """Set an agent's belief. If it already exists, updates it."""
new_args = () new_args = ()
for x in args: for x in args:
new_args += (pyson.Literal(x),) if type(x) == str:
new_args += (pyson.Literal(x),)
else:
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.bdi_agent.beliefs[term.literal_group()]):
...@@ -83,44 +87,61 @@ class BDIAgent(Agent): ...@@ -83,44 +87,61 @@ class BDIAgent(Agent):
"""Remove an existing agent's belief.""" """Remove an existing agent's belief."""
new_args = () new_args = ()
for x in args: for x in args:
new_args += (pyson.Literal(x),) if type(x) == str:
new_args += (pyson.Literal(x),)
else:
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.bdi_agent.call(pyson.Trigger.removal, pyson.GoalType.belief, term,
pyson.runtime.Intention()) pyson.runtime.Intention())
def get_belief(self, key): def get_belief(self, key, pyson_format=False):
"""Get an existing agent's belief. The first belief matching """Get an agent's existing belief. The first belief matching
<key> is returned """ <key> is returned. Keep <pyson_format> False to strip pyson
formatting."""
key = str(key) key = str(key)
for beliefs in self.bdi_agent.beliefs: for beliefs in self.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.bdi_agent.beliefs[beliefs])[0]))
if '")[source' in raw_belief: if ')[source' in raw_belief and not pyson_format:
raw_belief = raw_belief.split('[')[0].replace('"', '') raw_belief = raw_belief.split(
'[')[0].replace('"', '')
belief = raw_belief belief = raw_belief
break return belief
return belief return None
def get_beliefs(self): def get_belief_value(self, key):
"""Get agent's beliefs.""" """Get an agent's existing value or values of the <key> belief. The first belief matching
<key> is returned"""
belief = self.get_belief(key)
if belief:
return tuple(belief.split('(')[1].split(')')[0].split(','))
else:
return None
def get_beliefs(self, pyson_format=False):
"""Get agent's beliefs.Keep <pyson_format> False to strip pyson
formatting."""
belief_list = [] belief_list = []
for beliefs in self.bdi_agent.beliefs: for beliefs in self.bdi_agent.beliefs:
try: try:
raw_belief = ( raw_belief = (
str(list(self.bdi_agent.beliefs[beliefs])[0])) str(list(self.bdi_agent.beliefs[beliefs])[0]))
if ')[source(' in raw_belief: 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)
except IndexError: except IndexError:
pass pass
return belief_list return belief_list
def print_beliefs(self): def print_beliefs(self, pyson_format=False):
"""Print agent's beliefs.Keep <pyson_format> False to strip pyson
formatting."""
print("PRINTING BELIEFS") print("PRINTING BELIEFS")
for beliefs in self.bdi_agent.beliefs.values(): for beliefs in self.bdi_agent.beliefs.values():
for belief in beliefs: for belief in beliefs:
if ')[source(' in str(belief): if ')[source(' in str(belief) and not pyson_format:
belief = str(belief).split('[')[0].replace('"', '') belief = str(belief).split('[')[0].replace('"', '')
print(belief) print(belief)
......
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