Ejemplo n.º 1
0
    def __init__(self,
                 jid: str,
                 password: str,
                 asl: str,
                 actions=None,
                 *args,
                 **kwargs):
        self.asl_file = asl
        self.bdi_enabled = False
        self.bdi_intention_buffer = deque()
        self.bdi = None
        self.bdi_agent = None

        super().__init__(jid, password, *args, **kwargs)
        while not self.loop:
            time.sleep(0.01)

        template = Template(metadata={"performative": "BDI"})
        self.add_behaviour(self.BDIBehaviour(), template)

        self.bdi_env = asp.runtime.Environment()
        self.bdi_actions = asp.Actions(
            asp.stdlib.actions) if not actions else actions
        self.bdi.add_actions()
        self.add_custom_actions(self.bdi_actions)
        self._load_asl()
Ejemplo n.º 2
0
class Creator(Developer, agentspeak.runtime.Agent):

    actions = agentspeak.Actions(actions)

    def __init__(self, env, name, beliefs=None, rules=None, plans=None):
        Developer.__init__(self, name)
        agentspeak.runtime.Agent.__init__(self, env, name, beliefs, rules,
                                          plans)
        self.days = 6

    @actions.add(".do_work")
    def do_work(self, term, intention):
        category = random.choice(CATEGORY_NAMES)
        c, d = self.compute_change_probability()

        if schedule.tick >= START_TICK_LAST_STAGE:
            num_deleted = numpy.random.geometric(min(1, 1 / d * 2.2))
            num_updated = numpy.random.geometric(0.35)
            num_created = numpy.random.geometric(min(1, 1 / c))
        else:
            num_deleted = numpy.random.geometric(min(1, 1 / d * 1.6))
            num_updated = numpy.random.geometric(0.425)
            num_created = numpy.random.geometric(min(1, 1 / c * 1.7475))

        changed = []
        self.delete_files(num_deleted, category)
        changed += self.update_files(num_updated, category)
        changed += self.create_files(num_created, category)

        self.create_coupling(changed)

        self.bugfix()
        yield

    @actions.add(".do_update")
    def do_update(self, term, intention):
        num_updated = numpy.random.geometric(0.3275)
        category = random.choice(CATEGORY_NAMES)
        updated = self.update_files(num_updated, category)
        self.create_coupling(updated)
        yield

    def bugfix(self):
        bug = self.get_random_bug()
        if not bug:
            return

        p_fix = random.random()
        if p_fix <= 0.75:
            bug.closed = schedule.tick
        elif self.is_owner(bug) and p_fix <= 0.95:
            bug.closed = schedule.tick
Ejemplo n.º 3
0
from __future__ import print_function

import agentspeak
import agentspeak.runtime
import agentspeak.stdlib
import math
import random
import sys
import os
import os.path

# Actions

files = set()

actions = agentspeak.Actions(agentspeak.stdlib.actions)

actions.add_function(".sin", float, math.sin)


@actions.add_function(".f", float)
def f(val):
    return val * 3


@actions.add_function(".add_file", ())
def add_file():
    global files
    filename = "".join(random.choice("abcdefghij") for _ in range(10))
    files.add(filename)
    return filename
Ejemplo n.º 4
0
#   - .drop_all_desires
#   - .drop_all_events
#   - .drop_all_intentions
#   - .drop_desire
#   - .drop_event
#   - .drop_intention
#   - .fail_goal
#   - .intend
#   - .succeed_goal
#   - .add_anot
#   - .at
#   - .create_agent
#   - .kill_agent
#   - .perceive

actions = agentspeak.Actions()


@actions.add(".broadcast", 2)
def _broadcast(agent, term, intention):
    # Illocutionary force.
    ilf = agentspeak.grounded(term.args[0], intention.scope)
    if not agentspeak.is_atom(ilf):
        return
    if ilf.functor == "tell":
        goal_type = agentspeak.GoalType.belief
        trigger = agentspeak.Trigger.addition
    elif ilf.functor == "untell":
        goal_type = agentspeak.GoalType.belief
        trigger = agentspeak.Trigger.removal
    elif ilf.functor == "achieve":
Ejemplo n.º 5
0
import asyncio

from lxml import etree

from heapq import heapify, heappop

import agentspeak
import agentspeak.runtime
import agentspeak.ext_stdlib

LOGGER = agentspeak.get_logger(__name__)

actions = agentspeak.Actions(agentspeak.ext_stdlib.actions)

PERCEPT_TAG = frozenset(
    [agentspeak.Literal("source", (agentspeak.Literal("percept"), ))])


class Environment(agentspeak.runtime.Environment):
    def time(self):
        return asyncio.get_event_loop().time()

    def run(self):
        super(Environment, self).run()
        self.dispatch_wait_until()

    def dispatch_wait_until(self):
        earliest = None
        for agent in self.agents.values():
            for intention_stack in agent.intentions:
                wait = intention_stack[-1].wait_until
Ejemplo n.º 6
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)