Commit 2ba6129e by jpalanca

Initial commit

parents
[[source]]
url = "https://pypi.org/simple"
verify_ssl = true
name = "pypi"
[dev-packages]
[packages]
spade = "*"
scibag = "*"
click = "*"
taxi-simulator = "*"
[requires]
python_version = "3.6"
from spade import agent
class DummyAgent(agent.Agent):
async def setup(self):
print("Hello World! I'm agent {}".format(str(self.jid)))
dummy = DummyAgent("agent_test_base_198124@localhost", "test")
dummy.start()
dummy.stop()
import time
import asyncio
from spade.agent import Agent
from spade.behaviour import CyclicBehaviour
class DummyAgent(Agent):
class MyBehav(CyclicBehaviour):
async def on_start(self):
print("Starting behaviour . . .")
self.counter = 0
async def run(self):
print("Counter: {}".format(self.counter))
self.counter += 1
await asyncio.sleep(1)
async def setup(self):
print("Agent starting . . .")
b = self.MyBehav()
self.add_behaviour(b)
if __name__ == "__main__":
dummy = DummyAgent("agent_base_test_8723@localhost", "test")
dummy.start()
print("Wait until user interrupts with ctrl+C")
while True:
try:
time.sleep(1)
except KeyboardInterrupt:
break
dummy.stop()
import time
import asyncio
from spade.agent import Agent
from spade.behaviour import CyclicBehaviour
class DummyAgent(Agent):
class MyBehav(CyclicBehaviour):
async def on_start(self):
print("Starting behaviour . . .")
self.counter = 0
async def run(self):
print("Counter: {}".format(self.counter))
self.counter += 1
if self.counter >= 3:
self.kill(exit_code=10)
return
await asyncio.sleep(1)
async def on_end(self):
print("Behaviour finished with exit code {}.".format(self.exit_code))
async def setup(self):
print("Agent starting . . .")
self.my_behav = self.MyBehav()
self.add_behaviour(self.my_behav)
if __name__ == "__main__":
dummy = DummyAgent("agent_base_test_28745@localhost", "test")
dummy.start()
# wait until user interrupts with ctrl+C
while not dummy.my_behav.is_killed():
try:
time.sleep(1)
except KeyboardInterrupt:
break
dummy.stop()
import time
from spade.agent import Agent
from spade.behaviour import OneShotBehaviour
from spade.message import Message
class SenderAgent(Agent):
class InformBehav(OneShotBehaviour):
async def run(self):
print("InformBehav running")
msg = Message(to="receiver_9876@localhost") # Instantiate the message
msg.set_metadata("performative", "inform") # Set the "inform" FIPA performative
msg.set_metadata("ontology", "myOntology") # Set the ontology of the message content
msg.set_metadata("language", "OWL-S") # Set the language of the message content
msg.body = "Hello World" # Set the message content
await self.send(msg)
print("Message sent!")
# set exit_code for the behaviour
self.exit_code = "Job Finished!"
# stop agent from behaviour
self.agent.stop()
async def setup(self):
print("SenderAgent started")
self.b = self.InformBehav()
self.add_behaviour(self.b)
if __name__ == "__main__":
agent = SenderAgent("sender_9876@localhost", "sender_password")
agent.start()
while agent.is_alive():
try:
time.sleep(1)
except KeyboardInterrupt:
agent.stop()
break
print("Agent finished with exit code: {}".format(agent.b.exit_code))
import time
from spade.agent import Agent
from spade.behaviour import OneShotBehaviour
from spade.message import Message
from spade.template import Template
class SenderAgent(Agent):
class InformBehav(OneShotBehaviour):
async def run(self):
print("InformBehav running")
msg = Message(to="receiver_987654321@localhost") # Instantiate the message
msg.set_metadata("performative", "inform") # Set the "inform" FIPA performative
msg.body = "Hello World" # Set the message content
await self.send(msg)
print("Message sent!")
# stop agent from behaviour
self.agent.stop()
async def setup(self):
print("SenderAgent started")
b = self.InformBehav()
self.add_behaviour(b)
class ReceiverAgent(Agent):
class RecvBehav(OneShotBehaviour):
async def run(self):
print("RecvBehav running")
msg = await self.receive(timeout=10) # wait for a message for 10 seconds
if msg:
print("Message received with content: {}".format(msg.body))
else:
print("Did not received any message after 10 seconds")
# stop agent from behaviour
self.agent.stop()
def setup(self):
print("ReceiverAgent started")
b = self.RecvBehav()
template = Template()
template.set_metadata("performative", "inform")
self.add_behaviour(b, template)
if __name__ == "__main__":
receiveragent = ReceiverAgent("receiver_987654321@localhost", "receiver_password")
receiveragent.start()
time.sleep(2) # wait for receiver agent to be prepared. In next sections we'll use presence notification.
senderagent = SenderAgent("sender_987654321@localhost", "sender_password")
senderagent.start()
while receiveragent.is_alive():
try:
time.sleep(1)
except KeyboardInterrupt:
senderagent.stop()
receiveragent.stop()
break
print("Agents finished")
import time
import datetime
from spade.agent import Agent
from spade.behaviour import CyclicBehaviour, PeriodicBehaviour
from spade.message import Message
class PeriodicSenderAgent(Agent):
class InformBehav(PeriodicBehaviour):
async def run(self):
print(f"PeriodicSenderBehaviour running at {datetime.datetime.now().time()}: {self.counter}")
msg = Message(to="receiver_987654321@localhost") # Instantiate the message
msg.body = "Hello World" # Set the message content
await self.send(msg)
print("Message sent!")
if self.counter == 5:
self.kill()
self.counter += 1
async def on_end(self):
# stop agent from behaviour
self.agent.stop()
async def on_start(self):
self.counter = 0
async def setup(self):
print(f"PeriodicSenderAgent started at {datetime.datetime.now().time()}")
start_at = datetime.datetime.now() + datetime.timedelta(seconds=5)
b = self.InformBehav(period=2, start_at=start_at)
self.add_behaviour(b)
class ReceiverAgent(Agent):
class RecvBehav(CyclicBehaviour):
async def run(self):
print("RecvBehav running")
msg = await self.receive(timeout=10) # wait for a message for 10 seconds
if msg:
print("Message received with content: {}".format(msg.body))
else:
print("Did not received any message after 10 seconds")
self.kill()
async def on_end(self):
self.agent.stop()
async def setup(self):
print("ReceiverAgent started")
b = self.RecvBehav()
self.add_behaviour(b)
if __name__ == "__main__":
receiveragent = ReceiverAgent("receiver_987654321@localhost", "receiver_password")
receiveragent.start()
time.sleep(1) # wait for receiver agent to be prepared. In next sections we'll use presence notification.
senderagent = PeriodicSenderAgent("sender_987654321@localhost", "sender_password")
senderagent.start()
while receiveragent.is_alive():
try:
time.sleep(1)
except KeyboardInterrupt:
senderagent.stop()
receiveragent.stop()
break
print("Agents finished")
import time
import datetime
from spade.agent import Agent
from spade.behaviour import CyclicBehaviour, TimeoutBehaviour
from spade.message import Message
class TimeoutSenderAgent(Agent):
class InformBehav(TimeoutBehaviour):
async def run(self):
print(f"TimeoutSenderBehaviour running at {datetime.datetime.now().time()}")
msg = Message(to="receiver_987654321@localhost") # Instantiate the message
msg.body = "Hello World" # Set the message content
await self.send(msg)
async def on_end(self):
self.agent.stop()
async def setup(self):
print(f"TimeoutSenderAgent started at {datetime.datetime.now().time()}")
start_at = datetime.datetime.now() + datetime.timedelta(seconds=5)
b = self.InformBehav(start_at=start_at)
self.add_behaviour(b)
class ReceiverAgent(Agent):
class RecvBehav(CyclicBehaviour):
async def run(self):
msg = await self.receive(timeout=10) # wait for a message for 10 seconds
if msg:
print("Message received with content: {}".format(msg.body))
else:
print("Did not received any message after 10 seconds")
self.kill()
async def on_end(self):
self.agent.stop()
async def setup(self):
b = self.RecvBehav()
self.add_behaviour(b)
if __name__ == "__main__":
receiveragent = ReceiverAgent("receiver_987654321@localhost", "receiver_password")
receiveragent.start()
time.sleep(1) # wait for receiver agent to be prepared. In next sections we'll use presence notification.
senderagent = TimeoutSenderAgent("sender_987654321@localhost", "sender_password")
senderagent.start()
while receiveragent.is_alive():
try:
time.sleep(1)
except KeyboardInterrupt:
senderagent.stop()
receiveragent.stop()
break
print("Agents finished")
import time
from spade.agent import Agent
from spade.message import Message
from spade.behaviour import FSMBehaviour, State
STATE_ONE = "STATE_ONE"
STATE_TWO = "STATE_TWO"
STATE_THREE = "STATE_THREE"
class ExampleFSMBehaviour(FSMBehaviour):
async def on_start(self):
print(f"FSM starting at initial state {self.current_state}")
async def on_end(self):
print(f"FSM finished at state {self.current_state}")
self.agent.stop()
class StateOne(State):
async def run(self):
print("I'm at state one (initial state)")
msg = Message(to="fsm_987654321@localhost")
msg.body = "msg_from_state_one_to_state_three"
await self.send(msg)
self.set_next_state(STATE_TWO)
class StateTwo(State):
async def run(self):
print("I'm at state two")
self.set_next_state(STATE_THREE)
class StateThree(State):
async def run(self):
print("I'm at state three (final state)")
msg = await self.receive(timeout=5)
print(f"State Three received message {msg.body}")
# no final state is setted, since this is a final state
class FSMAgent(Agent):
async def setup(self):
fsm = ExampleFSMBehaviour()
fsm.add_state(name=STATE_ONE, state=StateOne(), initial=True)
fsm.add_state(name=STATE_TWO, state=StateTwo())
fsm.add_state(name=STATE_THREE, state=StateThree())
fsm.add_transition(source=STATE_ONE, dest=STATE_TWO)
fsm.add_transition(source=STATE_TWO, dest=STATE_THREE)
self.add_behaviour(fsm)
if __name__ == "__main__":
fsmagent = FSMAgent("fsm_987654321@localhost", "your_password")
fsmagent.start()
while fsmagent.is_alive():
try:
time.sleep(1)
except KeyboardInterrupt:
fsmagent.stop()
break
print("Agent finished")
import time
import getpass
from spade.agent import Agent
from spade.behaviour import OneShotBehaviour
class Agent1(Agent):
async def setup(self):
print("Agent {} running".format(self.name))
self.add_behaviour(self.Behav1())
class Behav1(OneShotBehaviour):
def on_available(self, jid, stanza):
print("[{}] Agent {} is available.".format(self.agent.name, jid.split("@")[0]))
def on_subscribed(self, jid):
print("[{}] Agent {} has accepted the subscription.".format(self.agent.name, jid.split("@")[0]))
print("[{}] Contacts List: {}".format(self.agent.name, self.agent.presence.get_contacts()))
def on_subscribe(self, jid):
print("[{}] Agent {} asked for subscription. Let's aprove it.".format(self.agent.name, jid.split("@")[0]))
self.presence.approve(jid)
async def run(self):
self.presence.on_subscribe = self.on_subscribe
self.presence.on_subscribed = self.on_subscribed
self.presence.on_available = self.on_available
self.presence.set_available()
self.presence.subscribe(self.agent.jid2)
class Agent2(Agent):
async def setup(self):
print("Agent {} running".format(self.name))
self.add_behaviour(self.Behav2())
class Behav2(OneShotBehaviour):
def on_available(self, jid, stanza):
print("[{}] Agent {} is available.".format(self.agent.name, jid.split("@")[0]))
def on_subscribed(self, jid):
print("[{}] Agent {} has accepted the subscription.".format(self.agent.name, jid.split("@")[0]))
print("[{}] Contacts List: {}".format(self.agent.name, self.agent.presence.get_contacts()))
def on_subscribe(self, jid):
print("[{}] Agent {} asked for subscription. Let's aprove it.".format(self.agent.name, jid.split("@")[0]))
self.presence.approve(jid)
self.presence.subscribe(jid)
async def run(self):
self.presence.set_available()
self.presence.on_subscribe = self.on_subscribe
self.presence.on_subscribed = self.on_subscribed
self.presence.on_available = self.on_available
if __name__ == "__main__":
jid1 = input("Agent1 JID> ")
passwd1 = getpass.getpass()
jid2 = input("Agent2 JID> ")
passwd2 = getpass.getpass()
agent2 = Agent2(jid2, passwd2)
agent1 = Agent1(jid1, passwd1)
agent1.jid2 = jid2
agent2.jid1 = jid1
agent2.start()
agent1.start()
while True:
try:
time.sleep(1)
except KeyboardInterrupt:
break
agent1.stop()
agent2.stop()
import datetime
import json
import random
import time
import click
import spade
class PullAgent(spade.agent.Agent):
async def setup(self):
self.value = random.randint(1, 1000)
self.value_time = time.time()
self.values = {self.name: {"value": self.value, "timestamp": self.value_time}}
start_at = datetime.datetime.now() + datetime.timedelta(seconds=5)
self.add_behaviour(self.PullBehaviour(period=2, start_at=start_at))
template = spade.template.Template(metadata={"performative": "PULL"})
self.add_behaviour(self.RecvPullBehaviour(), template)
template = spade.template.Template(metadata={"performative": "REPLY"})
self.add_behaviour(self.RecvReplyBehaviour(), template)
print("{} ready.".format(self.name))
def add_value(self, jid, data):
if jid in self.values:
if self.values[jid]["timestamp"] < data["timestamp"]:
self.values[jid] = data
else:
self.values[jid] = data
def add_contacts(self, contact_list):
self.contacts = [c.jid for c in contact_list if c.jid != self.jid]
# print("Adding contacts to {}: {}".format(self.name, self.contacts))
self.length = len(self.contacts)
class PullBehaviour(spade.behaviour.PeriodicBehaviour):
async def run(self):
k = random.randint(1, self.agent.length)
print("{} period with k={}!".format(self.agent.name, k))
random_contacts = random.sample(self.agent.contacts, k)
print("{} sending to {}".format(self.agent.name, [x.localpart for x in random_contacts]))
for jid in random_contacts:
timestamp = self.agent.values[jid.localpart]["timestamp"] if jid.localpart in self.agent.values else None
body = json.dumps({"timestamp": timestamp})
msg = spade.message.Message(to=str(jid), body=body, metadata={"performative": "PULL"})
await self.send(msg)
class RecvPullBehaviour(spade.behaviour.CyclicBehaviour):
async def run(self):
msg = await self.receive(timeout=2)
if msg:
body = json.loads(msg.body)
if body["timestamp"] is None or self.agent.value_time > body["timestamp"]:
body = json.dumps({"value": self.agent.value, "timestamp": self.agent.value_time})
msg = spade.message.Message(to=str(msg.sender), body=body, metadata={"performative": "REPLY"})
await self.send(msg)
class RecvReplyBehaviour(spade.behaviour.CyclicBehaviour):
async def run(self):
msg = await self.receive(timeout=2)
if msg:
body = json.loads(msg.body)
self.agent.add_value(msg.sender.localpart, body)
print("[{}] <{}>".format(self.agent.name, [x["value"] for x in self.agent.values.values()]))
@click.command()
@click.option('--count', default=10, help='Number of agents.')
def main(count):
agents = []
print("Creating {} agents...".format(count))
for x in range(1, count + 1):
print("Creating agent {}...".format(x))
agents.append(PullAgent("pull_agent_17264_{}@localhost".format(x), "test"))
for ag in agents:
ag.add_contacts(agents)
ag.values = {}
for ag in agents:
ag.start()
while True:
try:
time.sleep(1)
if all([len(ag.values) == count for ag in agents]):
print("Gossip done.")
break
except KeyboardInterrupt:
break
for ag in agents:
ag.stop()
print("Agents finished")
if __name__ == '__main__':
main()
import datetime
import json
import random
import time
import click
import spade
class PullAgent(spade.agent.Agent):
async def setup(self):
self.value = random.randint(1, 1000)
start_at = datetime.datetime.now() + datetime.timedelta(seconds=5)
self.add_behaviour(self.PullBehaviour(period=2, start_at=start_at))
template = spade.template.Template(metadata={"performative": "PULL"})
self.add_behaviour(self.RecvPullBehaviour(), template)
template = spade.template.Template(metadata={"performative": "REPLY"})
self.add_behaviour(self.RecvReplyBehaviour(), template)
print("{} ready.".format(self.name))
def add_value(self, value):
self.value = max(self.value, value)
def add_contacts(self, contact_list):
self.contacts = [c.jid for c in contact_list if c.jid != self.jid]
# print("Adding contacts to {}: {}".format(self.name, self.contacts))
self.length = len(self.contacts)
class PullBehaviour(spade.behaviour.PeriodicBehaviour):
async def run(self):
k = random.randint(1, self.agent.length)
# print("{} period with k={}!".format(self.agent.name, k))
random_contacts = random.sample(self.agent.contacts, k)
# print("{} sending to {}".format(self.agent.name, [x.localpart for x in random_contacts]))
for jid in random_contacts:
body = json.dumps({"value": self.agent.value})
msg = spade.message.Message(to=str(jid), body=body, metadata={"performative": "PULL"})
await self.send(msg)
class RecvPullBehaviour(spade.behaviour.CyclicBehaviour):
async def run(self):
msg = await self.receive(timeout=2)
if msg:
body = json.loads(msg.body)
if self.agent.value > body["value"]:
body = json.dumps({"value": self.agent.value})
msg = spade.message.Message(to=str(msg.sender), body=body, metadata={"performative": "REPLY"})
await self.send(msg)
class RecvReplyBehaviour(spade.behaviour.CyclicBehaviour):
async def run(self):
msg = await self.receive(timeout=2)
if msg:
body = json.loads(msg.body)
self.agent.add_value(body["value"])
# print("[{}] <{}>".format(self.agent.name, self.agent.value))
@click.command()
@click.option('--count', default=10, help='Number of agents.')
def main(count):
agents = []
print("Creating {} agents...".format(count))
for x in range(1, count + 1):
print("Creating agent {}...".format(x))
agents.append(PullAgent("pushpull_agent_12875_{}@localhost".format(x), "test"))
for ag in agents:
ag.add_contacts(agents)
ag.value = 0
for ag in agents:
ag.start()
while True:
try:
time.sleep(1)
status = [ag.value for ag in agents]
print("STATUS: {}".format(status))
if len(set(status)) <= 1:
print("Gossip done.")
break
except KeyboardInterrupt:
break
for ag in agents:
ag.stop()
print("Agents finished")
if __name__ == '__main__':
main()
import datetime
import json
import random
import time
import click
import spade
class PushAgent(spade.agent.Agent):
async def setup(self):
self.value = random.randint(1, 1000)
self.values = {self.name: {"value": self.value, "timestamp": time.time()}}
start_at = datetime.datetime.now() + datetime.timedelta(seconds=5)
self.add_behaviour(self.PushBehaviour(period=2, start_at=start_at))
template = spade.template.Template(metadata={"performative": "PUSH"})
self.add_behaviour(self.RecvBehaviour(), template)
print("{} ready.".format(self.name))
def add_value(self, jid, data):
if jid in self.values:
if self.values[jid]["timestamp"] < data["timestamp"]:
self.values[jid] = data
else:
self.values[jid] = data
def add_contacts(self, contact_list):
self.contacts = [c.jid for c in contact_list if c.jid != self.jid]
self.length = len(self.contacts)
class PushBehaviour(spade.behaviour.PeriodicBehaviour):
async def run(self):
k = random.randint(1, self.agent.length)
print("{} period with k={}!".format(self.agent.name, k))
random_contacts = random.sample(self.agent.contacts, k)
print("{} sending to {}".format(self.agent.name, [x.localpart for x in random_contacts]))
for jid in random_contacts:
body = json.dumps({"value": self.agent.value, "timestamp": time.time()})
msg = spade.message.Message(to=str(jid), body=body, metadata={"performative": "PUSH"})
await self.send(msg)
class RecvBehaviour(spade.behaviour.CyclicBehaviour):
async def run(self):
msg = await self.receive(timeout=2)
if msg:
body = json.loads(msg.body)
self.agent.add_value(msg.sender.localpart, body)
print("[{}] <{}>".format(self.agent.name, [x["value"] for x in self.agent.values.values()]))
@click.command()
@click.option('--count', default=10, help='Number of agents.')
def main(count):
agents = []
print("Creating {} agents...".format(count))
for x in range(1, count + 1):
print("Creating agent {}...".format(x))
agents.append(PushAgent("push_agent_1625_{}@localhost".format(x), "test"))
for ag in agents:
ag.add_contacts(agents)
ag.values = {}
for ag in agents:
ag.start()
while True:
try:
time.sleep(1)
if all([len(ag.values) == count for ag in agents]):
print("Gossip done.")
break
except KeyboardInterrupt:
break
for ag in agents:
ag.stop()
print("Agents finished")
if __name__ == '__main__':
main()
import datetime
import json
import random
import time
import click
import spade
class PullAgent(spade.agent.Agent):
async def setup(self):
self.value = random.randint(1, 1000)
start_at = datetime.datetime.now() + datetime.timedelta(seconds=5)
self.add_behaviour(self.PushPullBehaviour(period=2, start_at=start_at))
template = spade.template.Template(metadata={"performative": "PUSHPULL"})
self.add_behaviour(self.RecvPushPullBehaviour(), template)
template = spade.template.Template(metadata={"performative": "REPLY"})
self.add_behaviour(self.RecvReplyBehaviour(), template)
print("{} ready.".format(self.name))
def add_value(self, value):
self.value = max(self.value, value)
def add_contacts(self, contact_list):
self.contacts = [c.jid for c in contact_list if c.jid != self.jid]
# print("Adding contacts to {}: {}".format(self.name, self.contacts))
self.length = len(self.contacts)
class PushPullBehaviour(spade.behaviour.PeriodicBehaviour):
async def run(self):
k = random.randint(1, self.agent.length)
# print("{} period with k={}!".format(self.agent.name, k))
random_contacts = random.sample(self.agent.contacts, k)
# print("{} sending to {}".format(self.agent.name, [x.localpart for x in random_contacts]))
for jid in random_contacts:
body = json.dumps({"value": self.agent.value})
msg = spade.message.Message(to=str(jid), body=body, metadata={"performative": "PUSHPULL"})
await self.send(msg)
class RecvPushPullBehaviour(spade.behaviour.CyclicBehaviour):
async def run(self):
msg = await self.receive(timeout=2)
if msg:
body = json.loads(msg.body)
if self.agent.value > body["value"]:
body = json.dumps({"value": self.agent.value})
msg = spade.message.Message(to=str(msg.sender), body=body, metadata={"performative": "REPLY"})
await self.send(msg)
else:
self.agent.add_value(body["value"])
class RecvReplyBehaviour(spade.behaviour.CyclicBehaviour):
async def run(self):
msg = await self.receive(timeout=2)
if msg:
body = json.loads(msg.body)
self.agent.add_value(body["value"])
# print("[{}] <{}>".format(self.agent.name, self.agent.value))
@click.command()
@click.option('--count', default=10, help='Number of agents.')
def main(count):
agents = []
print("Creating {} agents...".format(count))
for x in range(1, count + 1):
print("Creating agent {}...".format(x))
agents.append(PullAgent("pushpull_agent_9264_{}@localhost".format(x), "test"))
for ag in agents:
ag.add_contacts(agents)
ag.value = 0
for ag in agents:
ag.start()
while True:
try:
time.sleep(1)
status = [ag.value for ag in agents]
print("STATUS: {}".format(status))
if len(set(status)) <= 1:
print("Gossip done.")
break
except KeyboardInterrupt:
break
for ag in agents:
ag.stop()
print("Agents finished")
if __name__ == '__main__':
main()
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