def submit_issue(self, term, intention): issue = Issue() issue.author = self.name issue.type = agentspeak.grounded(term.args[0], intention.scope) issue.patch = agentspeak.grounded(term.args[1], intention.scope) issue.priority = agentspeak.grounded(term.args[1], intention.scope) self.env.issues.insert(0, issue) yield
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
def _reinforce(agent, term, intention): """Same as a .goto""" args = grounded(term.args, intention.scope) self.movement.destination.x = args[0] self.movement.destination.y = args[1] self.movement.destination.z = args[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, args[0], args[1], args[2]) self.bdi.set_belief(VELOCITY, self.movement.velocity.x, self.movement.velocity.y, self.movement.velocity.z) self.bdi.set_belief(HEADING, 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
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
def _substring(agent, term, intention): needle = asl_str(agentspeak.grounded(term.args[0], intention.scope)) haystack = asl_str(agentspeak.grounded(term.args[1], intention.scope)) choicepoint = object() pos = haystack.find(needle) while pos != -1: intention.stack.append(choicepoint) if agentspeak.unify(term.args[2], pos, intention.scope, intention.stack): yield agentspeak.reroll(intention.scope, intention.stack, choicepoint) pos = haystack.find(needle, pos + 1)
def _string2term(agent, term, intention): string = asp.grounded(term.args[0], intention.scope) result = asp.Literal(string) logger.success("[DBG] {} -> {}".format(string, result)) if asp.unify(term.args[-1], result, intention.scope, intention.stack): yield
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
def make_patch(self, term, intention): klass = agentspeak.grounded(term.args[0], intention.scope) patch = Patch() patch.removed.add(klass) patch.added.add(klass) if agentspeak.unify(term.args[1], patch, intention.scope, intention.stack): yield
def _range_2(agent, term, intention): choicepoint = object() for i in range(int(agentspeak.grounded(term.args[0], intention.scope))): intention.stack.append(choicepoint) if agentspeak.unify(term.args[1], i, intention.scope, intention.stack): yield agentspeak.reroll(intention.scope, intention.stack, choicepoint)
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
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
def _concat(agent, term, intention): args = [ agentspeak.grounded(arg, intention.scope) for arg in term.args[:-1] ] if all(isinstance(arg, (tuple, list)) for arg in args): result = tuple(el for arg in args for el in arg) else: result = "".join(str(arg) for arg in args) if agentspeak.unify(term.args[-1], result, intention.scope, intention.stack): yield
def _wait(agent, term, intention): # Handle optional arguments. args = [agentspeak.grounded(arg, intention.scope) for arg in term.args] if len(args) == 2: event, millis = args else: if agentspeak.is_number(args[0]): millis = args[0] event = None else: millis = None event = args[0] # Type checks. if not (millis is None or agentspeak.is_number(millis)): raise agentspeak.AslError("expected timeout for .wait to be numeric") if not (event is None or agentspeak.is_string(event)): raise agentspeak.AslError("expected event for .wait to be a string") # Event. if event is not None: # Parse event. if not event.endswith("."): event += "." log = agentspeak.Log(LOGGER, 1) tokens = agentspeak.lexer.TokenStream( agentspeak.StringSource("<.wait>", event), log) tok, ast_event = agentspeak.parser.parse_event(tokens.next(), tokens, log) if tok.lexeme != ".": raise log.error( "expected no further tokens after event for .wait, got: '%s'", tok.lexeme, loc=tok.loc) # Build term. event = ast_event.accept(agentspeak.runtime.BuildEventVisitor(log)) # Timeout. if millis is None: until = None else: until = agent.env.time() + millis / 1000 # Create waiter. intention.waiter = agentspeak.runtime.Waiter(event=event, until=until) yield
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
def _mapc_action(self, term, intention): if self.action_id is None: LOGGER.warning("%s already did an action in this step", self.name) return message = etree.Element("message") action = etree.SubElement(message, "action", type=term.functor.lstrip("."), id=str(self.action_id)) for param in term.args: p = agentspeak.grounded(param, intention.scope) if isinstance(p, float) and p.is_integer(): p = int(p) etree.SubElement(action, "p").text = str(p) self.send_message(message) self.action_id = None yield
def _send(agent, recipient, ils, term): group = ils.literal_group() if group == ("tell", 0): frozen = agentspeak.grounded(term, {}).with_annotation( agentspeak.Literal("source", (agent.name, ))) agent.emit(recipient, functools.partial(agentspeak.runtime.add_belief, frozen)) elif group == ("achieve", 0): frozen = term.with_annotation( agentspeak.Literal("source", (agent.name, ))) agent.emit( recipient, functools.partial(agentspeak.runtime.call, agentspeak.Trigger.addition, agentspeak.GoalType.achievement, frozen)) else: raise agentspeak.PysonError("unsupported illocutionary force: %s/%d" % (group[0], group[1])) return True
def _getClosestPoint(agent, term, intention): agentPos = tuple((self.movement.position.x, self.movement.position.y, self.movement.position.z,)) backUpPos = asp.grounded(term.args[0], intention.scope) logger.success( "[{}] Recieved Positions: {}".format(self.jid.localpart, backUpPos) ) closestIndex = 0 minDist = 10000000 i = 0 while i < len(backUpPos): pos = backUpPos[i] x = (pos[0] - agentPos[0]) * (pos[0] - agentPos[0]) y = (pos[1] - agentPos[1]) * (pos[1] - agentPos[1]) z = (pos[2] - agentPos[2]) * (pos[2] - agentPos[2]) realDist = math.sqrt(x+y+z) if(realDist < minDist): minDist = realDist closestIndex = i i+=1 if asp.unify(term.args[-1], closestIndex, intention.scope, intention.stack): yield
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
def getDropPoint(agent,term,intention): dist = asp.grounded(term.args[0], intention.scope); tx = self.movement.position.x + self.movement.heading.x * dist; ty = self.movement.position.y; tz = self.movement.position.z + self.movement.heading.z * dist; #busca drop point valido tx = math.floor(tx); ty = math.floor(ty); tz = math.floor(tz); alpha = 0.0; while (alpha <= 2*math.pi and False == self.map.can_walk(tx, tz)): alpha += 0.05; tx = math.cos(alpha) * self.movement.heading.x * dist; tx += self.movement.position.x ; tz = math.sin(alpha) * self.movement.heading.z * dist; tz += self.movement.position.z; tx = math.floor(tx); tz = math.floor(tz); ## targetPos = tuple((tx,ty,tz)); if asp.unify(term.args[-1], targetPos, intention.scope, intention.stack): yield
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
def _my_action(agent, term, intention): arg = agentspeak.grounded(term.args[0], intention.scope) print(arg) yield
def _custom_action(agent, term, intention): asp.grounded(term.args[0], intention.scope) yield
def commit(self, term, intention): patch = agentspeak.grounded(term.args[0], intention.scope) print("Committing patch", patch) yield