Example #1
0
import argparse

from spade_bdi.bdi import BDIAgent

if __name__ == '__main__':
    parser = argparse.ArgumentParser(
        description='spade bdi master-server example')
    parser.add_argument('--server',
                        type=str,
                        default="localhost",
                        help='XMPP server address.')
    parser.add_argument('--password',
                        type=str,
                        default="bdipassword",
                        help='XMPP password for the agents.')
    args = parser.parse_args()

    a = BDIAgent("BDIReceiverAgent@" + args.server, args.password,
                 "receiver.asl")
    a.start()
Example #2
0
import argparse

from spade_bdi.bdi import BDIAgent

if __name__ == '__main__':
    parser = argparse.ArgumentParser(
        description='spade bdi master-server example')
    parser.add_argument('--server',
                        type=str,
                        default="localhost",
                        help='XMPP server address.')
    parser.add_argument('--password',
                        type=str,
                        default="bdipassword",
                        help='XMPP password for the agents.')
    args = parser.parse_args()

    a = BDIAgent("BDISenderAgent@" + args.server, args.password, "sender.asl")
    a.bdi.set_belief("receiver", "BDIReceiverAgent@" + args.server)
    a.start()
Example #3
0
from spade import quit_spade

from spade_bdi.bdi import BDIAgent

parser = argparse.ArgumentParser(description='spade bdi hello example')
parser.add_argument('--login',
                    type=str,
                    default="basicagent",
                    help='your UPV login.')
parser.add_argument('--server',
                    type=str,
                    default="localhost",
                    help='XMPP server address.')
parser.add_argument('--password',
                    type=str,
                    default="bdipassword",
                    help='XMPP password for the agents.')
args = parser.parse_args()

a = BDIAgent("HelloAgent_{}@{}".format(args.login, args.server), args.password,
             "hello.asl")

a.start()

import time
time.sleep(1)

a.stop().result()

quit_spade()
Example #4
0
import argparse

from spade_bdi.bdi import BDIAgent

parser = argparse.ArgumentParser(description='spade bdi master-server example')
parser.add_argument('--server', type=str, default="localhost", help='XMPP server address.')
parser.add_argument('--password', type=str, default="bdipassword", help='XMPP password for the agents.')
args = parser.parse_args()

a = BDIAgent("BasicAgent@" + args.server, args.password, "basic.asl")
a.start()

import time
time.sleep(1)

a.bdi.set_belief("car", "azul", "big")
a.bdi.print_beliefs()
print("GETTING FIRST CAR BELIEF")
print(a.bdi.get_belief("car"))
a.bdi.print_beliefs()
a.bdi.remove_belief("car", 'azul', "big")
a.bdi.print_beliefs()
print(a.bdi.get_beliefs())
a.bdi.set_belief("car", 'amarillo')
Example #5
0
def main(server, password):
    b = BDIAgent("slave_1@{}".format(server), password, "slave.asl")
    b.bdi.set_belief("master", "master@{}".format(server))
    future = b.start()
    future.result()

    c = BDIAgent("slave_2@{}".format(server), password, "slave.asl")
    c.pause_bdi()
    future = c.start()
    future.result()

    a = MasterAgent("master@{}".format(server), password, "master.asl")
    a.bdi.set_belief("slave1", "slave_1@{}".format(server))
    a.bdi.set_belief("slave2", "slave_2@{}".format(server))
    a.bdi.set_belief('type', 'dec')
    future = a.start()
    future.result()

    time.sleep(5)
    print("Enabling BDI for slave2")
    c.set_asl("slave.asl")
    c.bdi.set_belief("master", "master@{}".format(server))
    time.sleep(5)
    print("Disabling BDI for slave2")
    c.pause_bdi()
Example #6
0
parser = argparse.ArgumentParser(description='spade bdi basic example')
parser.add_argument('--server',
                    type=str,
                    default="localhost",
                    help='XMPP server address.')
parser.add_argument('--name',
                    type=str,
                    default="basicagent",
                    help='XMPP name for the agent.')
parser.add_argument('--password',
                    type=str,
                    default="bdipassword",
                    help='XMPP password for the agent.')
args = parser.parse_args()

a = BDIAgent("{}@{}".format(args.name, args.server), args.password,
             "basic.asl")
a.start()

import time
time.sleep(1)

a.bdi.set_belief("car", "azul", "big")
a.bdi.print_beliefs()
print("GETTING FIRST CAR BELIEF")
print(a.bdi.get_belief("car"))
a.bdi.print_beliefs()
a.bdi.remove_belief("car", 'azul', "big")
a.bdi.print_beliefs()
print(a.bdi.get_beliefs())
a.bdi.set_belief("car", 'amarillo')
Example #7
0
    def __init__(self, jid, passwd, asl, actions=None, team=TEAM_NONE, map_path=None,
                 manager_jid="cmanager@localhost", service_jid="cservice@localhost", *args, **kwargs):

        self.service_types = []

        # Variable used to store the AID of Manager
        self.manager = manager_jid
        self.service = service_jid
        self.map_path = map_path

        # Variable indicating if this agent is carrying the objective pack (flag)
        self.is_objective_carried = False

        # List of objects in the agent's Field Of Vision
        self.fov_objects = []

        # Current aimed enemy
        self.aimed_agent = None  # Sight

        self.eclass = 0
        self.health = 0
        self.protection = 0
        self.stamina = 0
        self.power = 0
        self.ammo = 0

        # Variable indicating if agent is fighting at this moment
        self.is_fighting = False

        # Variable indicating if agent is escaping at this moment
        self.is_escaping = False

        # Current position, direction, and so on...
        self.movement = None  # CMobile

        self.soldiers_count = 0
        self.medics_count = 0
        self.engineers_count = 0
        self.fieldops_count = 0
        self.team_count = 0

        # Limits of some variables (to trigger some events)
        self.threshold = Threshold()

        # Current Map
        self.map = None  # TerrainMap

        # Destination Queue
        self.destinations = deque()

        if isinstance(actions, asp.Actions):
            troop_actions = actions
        else:
            troop_actions = asp.Actions(asp_action)

        @troop_actions.add_function(".create_control_points", (tuple, float, int))
        def _create_control_points(center, radius, n):
            """
            Calculates an array of positions for patrolling.
            When this action is called, it creates an array of n random positions.
            Expects args to be [x,y,z],radius and number of points
            """

            center_x = center[0]
            center_y = center[1]
            center_z = center[2]
            control_points = []
            for i in range(n):
                while True:
                    x = center_x + ((radius / 2) - (random.random() * radius))
                    x = max(0, x)
                    x = int(min(self.map.size_x - 1, x))
                    y = 0
                    z = center_z + ((radius / 2) - (random.random() * radius))
                    z = max(0, z)
                    z = int(min(self.map.size_z - 1, z))

                    if self.check_static_position(x, z):
                        if len(control_points):
                            if (x, y, z) != control_points[i - 1]:
                                control_points.append((x, y, z))
                                break
                        else:
                            control_points.append((x, y, z))
                            break
                logger.success("Control point generated {}".format((x, y, z)))
            return (tuple(control_points))

        @troop_actions.add(".goto", 1)
        def _goto(agent, term, intention):
            """Sets the PyGomas destination. Expects args to be x,y,z"""
            args = asp.grounded(term.args, intention.scope)
            self.movement.destination.x = args[0][0]
            self.movement.destination.y = args[0][1]
            self.movement.destination.z = args[0][2]
            start = (self.movement.position.x, self.movement.position.z)
            end = (self.movement.destination.x, self.movement.destination.z)
            path = self.path_finder.get_path(start, end)
            if path:
                self.destinations = deque(path)
                x, z = path[0]
                self.movement.calculate_new_orientation(Vector3D(x=x, y=0, z=z))
                self.bdi.set_belief(DESTINATION, tuple((args[0][0], args[0][1], args[0][2])))
                self.bdi.set_belief(VELOCITY, tuple((self.movement.velocity.x, self.movement.velocity.y, self.movement.velocity.z)))
                self.bdi.set_belief(HEADING, tuple((self.movement.heading.x, self.movement.heading.y, self.movement.heading.z)))
            else:
                self.destinations = deque()
                self.movement.destination.x = self.movement.position.x
                self.movement.destination.y = self.movement.position.y
                self.movement.destination.z = self.movement.position.z
            yield

        @troop_actions.add(".shoot", 2)
        def _shoot(agent, term, intention):
            """
             The agent shoots in the direction at which he is aiming.

             This method sends a FIPA INFORM message to Manager.
             Once message is sent, the variable ammo is decremented.

             :param shot_num: number of shots
             :param X,Y,Z: position at which to shoot
             :type shot_num: int
             :type X,Y,Z: list of float
             :returns True (shot done) | False (cannot shoot, has no ammo)
             :rtype bool
             """
            args = asp.grounded(term.args, intention.scope)

            shot_num = args[0]
            victim_x = args[1][0]
            victim_y = args[1][1]
            victim_z = args[1][2]

            class ShootBehaviour(OneShotBehaviour):
                async def run(self):
                    if self.agent.ammo <= MIN_AMMO:
                        return False

                    shots = min(self.agent.threshold.get_shot(), shot_num)
                    # Fill the REQUEST message
                    msg = Message()
                    msg.to = self.agent.manager
                    msg.set_metadata(PERFORMATIVE, PERFORMATIVE_SHOOT)
                    content = {NAME: self.agent.name,
                               AIM: self.agent.threshold.get_aim(),
                               SHOTS: shots,
                               X: victim_x,
                               Y: victim_y,
                               Z: victim_z}
                    logger.info("{} shot!".format(content[NAME]))
                    msg.body = json.dumps(content)
                    await self.send(msg)

                    self.agent.decrease_ammo(shots)
                    return True

            b = ShootBehaviour()
            self.add_behaviour(b)
            yield

        @troop_actions.add(".register_service", 1)
        def _register_service(agent, term, intention):
            """Register the service specified by <service>.

               :param service: service to register
               :type service: str

               """
            args = asp.grounded(term.args, intention.scope)
            service = str(args[0])
            self.register_service(service)
            yield

        @troop_actions.add(".get_service", 1)
        def _get_service(agent, term, intention):
            """Request for troop agents that offer the service specified by
               <service>. This action sends a FIPA REQUEST
               message to the service agent asking for those who offer the
               <service> service.

               :param service: service requested
               :type service: str

               """
            args = asp.grounded(term.args, intention.scope)
            service = str(args[0])

            class GetServiceBehaviour(OneShotBehaviour):
                async def run(self):
                    msg = Message()
                    msg.set_metadata(PERFORMATIVE, PERFORMATIVE_GET)
                    msg.to = self.agent.service_jid
                    msg.body = json.dumps({NAME: service, TEAM: self.agent.team})
                    await self.send(msg)
                    result = await self.receive(timeout=LONG_RECEIVE_WAIT)
                    if result:
                        result = json.loads(result.body)
                        logger.info("{} got {} troops that offer {} service: {}".format(self.agent.name, len(result), service, result))
                        self.agent.bdi.set_belief(service, tuple(result))
                    else:
                        self.agent.bdi.set_belief(service, tuple())

            t = Template()
            t.set_metadata(PERFORMATIVE, service)
            b = GetServiceBehaviour()
            self.add_behaviour(b, t)
            yield

        @troop_actions.add(".get_medics", 0)
        def _get_medics(agent, term, intention):
            """Request for medic agents. This action sends a FIPA REQUEST
               message to the service agent asking for those who offer the
               Medic service.
               """

            class GetMedicBehaviour(OneShotBehaviour):
                async def run(self):
                    msg = Message()
                    msg.set_metadata(PERFORMATIVE, PERFORMATIVE_GET)
                    msg.to = self.agent.service_jid
                    msg.body = json.dumps({NAME: MEDIC_SERVICE, TEAM: self.agent.team})
                    await self.send(msg)
                    result = await self.receive(timeout=LONG_RECEIVE_WAIT)
                    if result:
                        result = json.loads(result.body)
                        self.agent.medics_count = len(result)
                        logger.info("{} got {} medics: {}".format(self.agent.name, self.agent.medics_count, result))
                        self.agent.bdi.set_belief(MY_MEDICS, tuple(result))
                    else:
                        self.agent.bdi.set_belief(MY_MEDICS, tuple())
                        self.agent.medics_count = 0

            t = Template()
            t.set_metadata(PERFORMATIVE, PERFORMATIVE_CFM)
            b = GetMedicBehaviour()
            self.add_behaviour(b, t)
            yield

        @troop_actions.add(".get_fieldops", 0)
        def _get_fieldops(agent, term, intention):
            """Request for fieldop agents. This action sends a FIPA REQUEST
               message to the service agent asking for those who offer the
               Ammo service.
               """

            class GetFieldopsBehaviour(OneShotBehaviour):
                async def run(self):
                    msg = Message()
                    msg.set_metadata(PERFORMATIVE, PERFORMATIVE_GET)
                    msg.to = self.agent.service_jid
                    msg.body = json.dumps({NAME: AMMO_SERVICE, TEAM: self.agent.team})
                    await self.send(msg)
                    result = await self.receive(timeout=LONG_RECEIVE_WAIT)
                    if result:
                        result = json.loads(result.body)
                        self.agent.fieldops_count = len(result)
                        logger.info("{} got {} fieldops: {}".format(self.agent.name, self.agent.fieldops_count, result))
                        self.agent.bdi.set_belief(MY_FIELDOPS, tuple(result))
                    else:
                        self.agent.bdi.set_belief(MY_FIELDOPS, tuple())
                        self.agent.fieldops_count = 0

            t = Template()
            t.set_metadata(PERFORMATIVE, PERFORMATIVE_CFA)
            b = GetFieldopsBehaviour()
            self.add_behaviour(b, t)
            yield

        @troop_actions.add(".get_backups", 0)
        def _get_backups(agent, term, intention):
            """Request for backup agents. This action sends a FIPA REQUEST
               message to the service agent asking for those who offer the
               Backup service.
               """

            class GetBackupBehaviour(OneShotBehaviour):
                async def run(self):
                    msg = Message()
                    msg.set_metadata(PERFORMATIVE, PERFORMATIVE_GET)
                    msg.to = self.agent.service_jid
                    msg.body = json.dumps({NAME: BACKUP_SERVICE, TEAM: self.agent.team})
                    await self.send(msg)
                    result = await self.receive(timeout=LONG_RECEIVE_WAIT)
                    if result:
                        result = json.loads(result.body)
                        self.agent.soldiers_count = len(result)
                        logger.info("{} got {} fieldops: {}".format(self.agent.name, self.agent.soldiers_count, result))
                        self.agent.bdi.set_belief(MY_BACKUPS, tuple(result))
                    else:
                        self.agent.bdi.set_belief(MY_BACKUPS, tuple())
                        self.agent.soldiers_count = 0

            t = Template()
            t.set_metadata(PERFORMATIVE, PERFORMATIVE_CFB)
            b = GetBackupBehaviour()
            self.add_behaviour(b, t)
            yield

        @troop_actions.add(".turn", 1)
        def _turn(agent, term, intention):
            """
            Turns an agent orientation given an angle.

            :param angle: angle to turn, in radians.
            :type angle: float (from -pi to pi)

            """

            args = asp.grounded(term.args, intention.scope)
            angle = args[0]
            z = self.movement.heading.z
            x = self.movement.heading.x
            if z == 0 and x == 0:
                self.movement.heading.z = random.random()
                self.movement.heading.x = random.random()
            atan_angle = arctan2(z, x)
            atan_angle += angle
            norm = self.movement.heading.length()
            self.movement.heading.x = norm * cos(atan_angle)
            self.movement.heading.z = norm * sin(atan_angle)
            self.bdi.set_belief(HEADING, tuple((self.movement.heading.x, self.movement.heading.y, self.movement.heading.z)))
            yield

        @troop_actions.add(".stop", 0)
        def _stop(agent, term, intention):
            """Stops the PyGomas agent. """
            self.destinations = deque()
            self.movement.destination.x = self.movement.position.x
            self.movement.destination.y = self.movement.position.y
            self.movement.destination.z = self.movement.position.z
            yield

        AbstractAgent.__init__(self, jid, team=team, service_jid=service_jid)
        BDIAgent.__init__(self, jid=jid, password=passwd, asl=asl, actions=troop_actions, **kwargs)
Example #8
0
                    default="basicagent",
                    help='your UPV login.')
parser.add_argument('--server',
                    type=str,
                    default="localhost",
                    help='XMPP server address.')
parser.add_argument('--password',
                    type=str,
                    default="bdipassword",
                    help='XMPP password for the agents.')
parser.add_argument('--asl',
                    type=str,
                    default="default.asl",
                    help='asl file with JASON code.')
parser.add_argument('--time',
                    type=int,
                    default=1,
                    help='duration time (in seconds) of the execution.')
args = parser.parse_args()

a = BDIAgent("Agent_{}@{}".format(args.login, args.server), args.password,
             args.asl)

a.start()

import time
time.sleep(args.time)

a.stop().result()

quit_spade()
Example #9
0
parser = argparse.ArgumentParser(description='spade bdi basic example')
parser.add_argument('--login',
                    type=str,
                    default="basicagent",
                    help='your UPV login.')
parser.add_argument('--server',
                    type=str,
                    default="localhost",
                    help='XMPP server address.')
parser.add_argument('--password',
                    type=str,
                    default="bdipassword",
                    help='XMPP password for the agents.')
args = parser.parse_args()

a = BDIAgent("BasicAgent_{}@{}".format(args.login, args.server), args.password,
             "basic.asl")

a.start()

import time
time.sleep(1)

a.bdi.set_belief("car", "azul", "big")
a.bdi.print_beliefs()
print("GETTING FIRST CAR BELIEF")
print(a.bdi.get_belief("car"))
a.bdi.print_beliefs()
a.bdi.remove_belief("car", 'azul', "big")
a.bdi.print_beliefs()
print(a.bdi.get_beliefs())
a.bdi.set_belief("car", 'amarillo')