Exemple #1
0
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":
        goal_type = agentspeak.GoalType.achievement
        trigger = agentspeak.Trigger.addition
    else:
        raise agentspeak.AslError("unknown illocutionary force: %s" % ilf)

    # Prepare message.
    message = agentspeak.freeze(term.args[1], intention.scope, {})
    tagged_message = message.with_annotation(
        agentspeak.Literal("source", (agentspeak.Literal(agent.name), )))

    # Broadcast.
    for receiver in agent.env.agents.values():
        if receiver == agent:
            continue

        receiver.call(trigger, goal_type, tagged_message,
                      agentspeak.runtime.Intention())

    yield
Exemple #2
0
def _abolish(agent, term, intention):
    memo = {}
    pattern = agentspeak.freeze(term.args[0], intention.scope, memo)
    group = agent.beliefs[pattern.literal_group()]

    for old_belief in list(group):
        if agentspeak.unifies_annotated(old_belief, pattern):
            group.remove(old_belief)

    yield
Exemple #3
0
def _findall(agent, term, intention):
    pattern = agentspeak.evaluate(term.args[0], intention.scope)
    query = agentspeak.runtime.TermQuery(term.args[1])
    result = []

    memo = {}
    for _ in query.execute(agent, intention):
        result.append(agentspeak.freeze(pattern, intention.scope, memo))

    if agentspeak.unify(tuple(result), term.args[2], intention.scope,
                        intention.stack):
        yield
Exemple #4
0
 def _send(agent, term, intention):
     receivers = asp.grounded(term.args[0], intention.scope)
     if isinstance(receivers, str) or isinstance(receivers, asp.Literal):
         receivers = (receivers,)
     ilf = asp.grounded(term.args[1], intention.scope)
     if not asp.is_atom(ilf):
         return
     ilf_type = ilf.functor
     mdata = {"performative": "BDI", "ilf_type": ilf_type, }
     for receiver in receivers:
         body = asp.asl_str(asp.freeze(term.args[2], intention.scope, {}))
         msg = Message(to=str(receiver), body=body, metadata=mdata)
         self.agent.submit(self.send(msg))
     yield
Exemple #5
0
        async def run(self):
            """
            Coroutine run cyclic.
            """
            if self.agent.bdi_enabled:
                msg = await self.receive(timeout=0)
                if msg:
                    mdata = msg.metadata
                    ilf_type = mdata["ilf_type"]
                    if ilf_type == "tell":
                        goal_type = asp.GoalType.belief
                        trigger = asp.Trigger.addition
                    elif ilf_type == "untell":
                        goal_type = asp.GoalType.belief
                        trigger = asp.Trigger.removal
                    elif ilf_type == "achieve":
                        goal_type = asp.GoalType.achievement
                        trigger = asp.Trigger.addition
                    else:
                        raise asp.AslError(
                            "unknown illocutionary force: {}".format(ilf_type))

                    intention = asp.runtime.Intention()
                    functor, args = parse_literal(msg.body)

                    message = asp.Literal(functor, args)
                    message = asp.freeze(message, intention.scope, {})

                    tagged_message = message.with_annotation(
                        asp.Literal("source",
                                    (asp.Literal(str(msg.sender)), )))
                    self.agent.bdi_intention_buffer.append(
                        (trigger, goal_type, tagged_message, intention))

                if self.agent.bdi_intention_buffer:
                    temp_intentions = deque(self.agent.bdi_intention_buffer)
                    for trigger, goal_type, term, intention in temp_intentions:
                        self.agent.bdi_agent.call(trigger, goal_type, term,
                                                  intention)
                        '''self.agent.bdi_agent.step()'''
                        self.agent.bdi_intention_buffer.popleft()

                self.agent.bdi_agent.step()

            else:
                await asyncio.sleep(0.1)
Exemple #6
0
def _send(agent, term, intention):
    # Find the receivers: By a string, atom or list of strings or atoms.
    receivers = agentspeak.grounded(term.args[0], intention.scope)
    if not agentspeak.is_list(receivers):
        receivers = [receivers]
    receiving_agents = []
    for receiver in receivers:
        if agentspeak.is_atom(receiver):
            receiving_agents.append(agent.env.agents[receiver.functor])
        else:
            receiving_agents.append(agent.env.agents[receiver])

    # Illocutionary force.
    ilf = agentspeak.grounded(term.args[1], 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":
        goal_type = agentspeak.GoalType.achievement
        trigger = agentspeak.Trigger.addition
    else:
        raise agentspeak.AslError("unknown illocutionary force: %s" % ilf)

    # TODO: unachieve, askOne, askAll, tellHow, untellHow, askHow

    # Prepare message.
    message = agentspeak.freeze(term.args[2], intention.scope, {})
    tagged_message = message.with_annotation(
        agentspeak.Literal("source", (agentspeak.Literal(agent.name), )))

    # Broadcast.
    for receiver in receiving_agents:
        receiver.call(trigger, goal_type, tagged_message,
                      agentspeak.runtime.Intention())

    yield
Exemple #7
0
def _print(agent, term, intention, _color_map={}, _current_color=[0]):
    if agent in _color_map:
        color = _color_map[agent]
    else:
        color = COLORS[_current_color[0]]
        _current_color[0] = (_current_color[0] + 1) % len(COLORS)
        _color_map[agent] = color

    memo = {}
    text = " ".join(
        asl_str(agentspeak.freeze(t, intention.scope, memo))
        for t in term.args)

    with colorama.colorama_text():
        print(color[0],
              color[1],
              agent.name,
              colorama.Fore.RESET,
              colorama.Back.RESET,
              " ",
              text,
              sep="")

    yield
Exemple #8
0
    def call(self, trigger, goal_type, term, calling_intention, delayed=False):
        # Modify beliefs.
        if goal_type == agentspeak.GoalType.belief:
            if trigger == agentspeak.Trigger.addition:
                self.add_belief(term, calling_intention.scope)
            else:
                found = self.remove_belief(term, calling_intention)
                if not found:
                    return True

        # Freeze with caller scope.
        frozen = agentspeak.freeze(term, calling_intention.scope, {})

        if not isinstance(frozen, agentspeak.Literal):
            raise AslError("expected literal")

        # Wake up waiting intentions.
        for intention_stack in self.intentions:
            if not intention_stack:
                continue
            intention = intention_stack[-1]

            if not intention.waiter or not intention.waiter.event:
                continue
            event = intention.waiter.event

            if event.trigger != trigger or event.goal_type != goal_type:
                continue

            if agentspeak.unifies_annotated(event.head, frozen):
                intention.waiter = None
        # fahid..... log plan trace here.....
        self.get_belief_base()
        applicable_plans = self.plans[(trigger, goal_type, frozen.functor,
                                       len(frozen.args))]
        applicable_plans_trace = []
        for plan in applicable_plans:
            """
            if type(plan.context) is list:
                print (">>>> list")
            else:
                print (">>>>> ", type(plan.context))
                if type(plan.context) is AndQuery:
                    print(".....")
                    print(plan.context.left)
                    print(plan.context.right)
                elif type(plan.context) is OrQuery:
                    print("////")
                    print(plan.context.left)

                    print(plan.context.right)
            """
            applicable_plans_trace.append({
                "IDENTIFIER":
                str(plan.head),
                "CONTEXT":
                flatten_context(
                    plan.context
                ),  #str(plan.context) if type(plan.context) is not type (NotQuery("")) else "not " + str(plan.context.query),
                "CODE_LINE":
                "",
                "CODE_FILE":
                ""
            })
        if len(applicable_plans_trace) > 0:
            Logger.log_plan_trace(agent=self.name,
                                  payload=applicable_plans_trace,
                                  bb_payload=self.get_belief_base())

        choicepoint = object()
        intention = Intention()
        # Find matching plan.
        counter = -1
        for plan in applicable_plans:
            counter += 1
            for _ in agentspeak.unify_annotated(plan.head, frozen,
                                                intention.scope,
                                                intention.stack):
                for _ in plan.context.execute(self, intention):
                    intention.head_term = frozen
                    intention.instr = plan.body
                    intention.calling_term = term

                    if not delayed and self.intentions:
                        for intention_stack in self.intentions:
                            if intention_stack[-1] == calling_intention:
                                intention_stack.append(intention)
                                # Fahid: log selected plan....
                                Logger.log_plan_selection(
                                    agent=self.name,
                                    payload=applicable_plans_trace[counter],
                                    bb_payload=self.get_belief_base())
                                return True

                    new_intention_stack = collections.deque()
                    new_intention_stack.append(intention)
                    self.intentions.append(new_intention_stack)
                    # Fahid: Log selected plan.....
                    Logger.log_plan_selection(
                        agent=self.name,
                        payload=applicable_plans_trace[counter],
                        bb_payload=self.get_belief_base())
                    return True

        #fahid: log not found...
        if goal_type == agentspeak.GoalType.achievement:
            raise AslError("no applicable plan for %s%s%s/%d" %
                           (trigger.value, goal_type.value, frozen.functor,
                            len(frozen.args)))
        elif goal_type == agentspeak.GoalType.test:
            return self.test_belief(term, calling_intention)

        return True
    def call(self, trigger, goal_type, term, calling_intention, delayed=False):
        # Modify beliefs.
        if goal_type == agentspeak.GoalType.belief:
            if trigger == agentspeak.Trigger.addition:
                self.add_belief(term, calling_intention.scope)
            else:
                found = self.remove_belief(term, calling_intention)
                if not found:
                    return True

        # Freeze with caller scope.
        frozen = agentspeak.freeze(term, calling_intention.scope, {})

        if not isinstance(frozen, agentspeak.Literal):
            raise AslError("expected literal")

        # Wake up waiting intentions.
        for intention_stack in self.intentions:
            if not intention_stack:
                continue
            intention = intention_stack[-1]

            if not intention.waiter or not intention.waiter.event:
                continue
            event = intention.waiter.event

            if event.trigger != trigger or event.goal_type != goal_type:
                continue

            if agentspeak.unifies_annotated(event.head, frozen):
                intention.waiter = None

        applicable_plans = self.plans[(trigger, goal_type, frozen.functor,
                                       len(frozen.args))]
        choicepoint = object()
        intention = Intention()

        # Find matching plan.
        for plan in applicable_plans:
            for _ in agentspeak.unify_annotated(plan.head, frozen,
                                                intention.scope,
                                                intention.stack):
                for _ in plan.context.execute(self, intention):
                    intention.head_term = frozen
                    intention.instr = plan.body
                    intention.calling_term = term

                    if not delayed and self.intentions:
                        for intention_stack in self.intentions:
                            if intention_stack[-1] == calling_intention:
                                intention_stack.append(intention)
                                return True

                    new_intention_stack = collections.deque()
                    new_intention_stack.append(intention)
                    self.intentions.append(new_intention_stack)
                    return True

        if goal_type == agentspeak.GoalType.achievement:
            raise AslError("no applicable plan for %s%s%s/%d" %
                           (trigger.value, goal_type.value, frozen.functor,
                            len(frozen.args)))
        elif goal_type == agentspeak.GoalType.test:
            return self.test_belief(term, calling_intention)

        return True