Пример #1
0
    def add_belief(self, term, scope):
        term = term.grounded(scope)

        if term.functor is None:
            raise AslError("expected belief literal")

        self.beliefs[(term.functor, len(term.args))].add(term)
Пример #2
0
    def step(self):
        while self.intentions and not self.intentions[0]:
            self.intentions.popleft()

        for intention_stack in self.intentions:
            intention = intention_stack[-1]

            # Suspended / waiting.
            if intention.waiter is not None:
                if intention.waiter.poll(self.env):
                    intention.waiter = None
                else:
                    continue

            break
        else:
            return False

        instr = intention.instr
        #fahid

        if not instr:
            intention_stack.pop()
            if not intention_stack:
                self.intentions.remove(intention_stack)
            elif intention.calling_term:
                frozen = intention.head_term.freeze(intention.scope, {})
                calling_intention = intention_stack[-1]
                if not agentspeak.unify(intention.calling_term, frozen,
                                        calling_intention.scope,
                                        calling_intention.stack):
                    raise RuntimeError("back unification failed")
            return True

        try:
            if instr.f(self, intention):
                #fahid.... note....
                intention.instr = instr.success
            else:
                intention.instr = instr.failure
                if not intention.instr:
                    raise AslError("plan failure")
        except AslError as err:
            log = agentspeak.Log(LOGGER)
            raise log.error("%s",
                            err,
                            loc=instr.loc,
                            extra_locs=instr.extra_locs)
        except Exception as err:
            log = agentspeak.Log(LOGGER)
            raise log.exception("agent %r raised python exception: %r",
                                self.name,
                                err,
                                loc=instr.loc,
                                extra_locs=instr.extra_locs)

        return True
Пример #3
0
    def test_belief(self, term, intention):
        term = agentspeak.evaluate(term, intention.scope)

        if not isinstance(term, agentspeak.Literal):
            raise AslError("expected belief literal, got: '%s'" % term)

        query = TermQuery(term)

        try:
            next(query.execute(self, intention))
            return True
        except StopIteration:
            return False
Пример #4
0
    def remove_belief(self, term, intention):
        term = agentspeak.evaluate(term, intention.scope)

        try:
            group = term.literal_group()
        except AttributeError:
            raise AslError("expected belief literal, got: '%s'" % term)

        choicepoint = object()

        relevant_beliefs = self.beliefs[group]

        for belief in relevant_beliefs:
            intention.stack.append(choicepoint)

            if agentspeak.unify(term, belief, intention.scope,
                                intention.stack):
                relevant_beliefs.remove(belief)
                return True

            agentspeak.reroll(intention.scope, intention.stack, choicepoint)

        return False
Пример #5
0
    def execute(self, agent, intention):
        # Boolean constants.
        term = agentspeak.evaluate(self.term, intention.scope)
        if term is True:
            yield
            return
        elif term is False:
            return

        try:
            group = term.literal_group()
        except AttributeError:
            raise AslError(
                "expected boolean or literal in query context, got: '%s'" %
                term)

        # Query on the belief base.
        for belief in agent.beliefs[group]:
            for _ in agentspeak.unify_annotated(term, belief, intention.scope,
                                                intention.stack):
                yield

        choicepoint = object()

        # Follow rules.
        for rule in agent.rules[group]:
            rule = copy.deepcopy(rule)

            intention.stack.append(choicepoint)

            if agentspeak.unify(term, rule.head, intention.scope,
                                intention.stack):
                for _ in rule.query.execute(agent, intention):
                    yield

            agentspeak.reroll(intention.scope, intention.stack, choicepoint)
Пример #6
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
Пример #7
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

        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