예제 #1
0
def takeRoad(self, term, intention):
    node = pyson.grounded(term.args[0], intention.scope)
    nextNode = pyson.grounded(term.args[1], intention.scope)
    if not G.has_edge(node, nextNode):
        yield False
    state = agentStates[self.name]
    if state["road"] in [(node, nextNode), (nextNode, node)]:
        # stay on road
        road = state["road"]
        roadData = G[node][nextNode]
        state["roadProgress"] += calculateRoadProgress(trafficData[(node,
                                                                    nextNode)])
        if state["roadProgress"] >= roadData["length"]:
            trafficData[(node, nextNode)] -= 1
            state["node"] = road[1]
            state["path"].append(road[1])
            state["road"] = None
            state["roadProgress"] = 0
        yield
    # check if road is passable
    if G[node][nextNode]["bridge"] and not G[node][nextNode]["bridge"]["open"]:
        yield False
    print("Agent {} using road ({},{})".format(self.name, node, nextNode))
    trafficData[(node, nextNode)] += 1
    roadUsedCounter[(str(node), str(nextNode))] += 1
    state["node"] = None
    state["road"] = (node, nextNode)
    state["roadProgress"] = 0
    yield
예제 #2
0
def bridgeStatus(self, term, intention):
    node1 = pyson.grounded(term.args[0], intention.scope)
    node2 = pyson.grounded(term.args[1], intention.scope)
    result = G.get_edge_data(node1, node2)["bridge"]["open"]
    if pyson.unify(term.args[2], pyson.Literal("open", (result, )),
                   intention.scope, intention.stack):
        yield
예제 #3
0
 def submit_issue(self, term, intention):
     issue = Issue()
     issue.author = self.name
     issue.type = pyson.grounded(term.args[0], intention.scope)
     issue.patch = pyson.grounded(term.args[1], intention.scope)
     issue.priority = pyson.grounded(term.args[1], intention.scope)
     self.env.issues.insert(0, issue)
     yield
예제 #4
0
파일: stdlib.py 프로젝트: felipe84841/pyson
def _substring(agent, term, intention):
    needle = pyson_str(pyson.grounded(term.args[0], intention.scope))
    haystack = pyson_str(pyson.grounded(term.args[1], intention.scope))

    choicepoint = object()

    pos = haystack.find(needle)
    while pos != -1:
        intention.stack.append(choicepoint)

        if pyson.unify(term.args[2], pos, intention.scope, intention.stack):
            yield

        pyson.reroll(intention.scope, intention.stack, choicepoint)
        pos = haystack.find(needle, pos + 1)
예제 #5
0
파일: stdlib.py 프로젝트: felipe84841/pyson
def _broadcast(agent, term, intention):
    # Illocutionary force.
    ilf = pyson.grounded(term.args[0], intention.scope)
    if not pyson.is_atom(ilf):
        return
    if ilf.functor == "tell":
        goal_type = pyson.GoalType.belief
    elif ilf.functor == "achieve":
        goal_type = pyson.GoalType.achievement
    else:
        raise pyson.PysonError("unknown illocutionary force: %s" % ilf)

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

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

        receiver.call(pyson.Trigger.addition, goal_type, tagged_message,
                      pyson.runtime.Intention())

    yield
예제 #6
0
def nextSteps(self, term, intention):
    position = pyson.grounded(term.args[0], intention.scope)
    destination = pyson.grounded(term.args[1], intention.scope)
    results = []
    resetWeights()
    for edge in G.edges(position):
        road = G[edge[0]][edge[1]]
        road["w"] = 1000
    for neighbor in G.neighbors(position):
        path_length = nx.shortest_path_length(G, neighbor, destination,
                                              "w") + G.get_edge_data(
                                                  position, neighbor)["length"]
        results.append(pyson.Literal("road", (neighbor, path_length)))
    results.sort(key=lambda x: x.args[1])
    if pyson.unify(term.args[2], tuple(results), intention.scope,
                   intention.stack):
        yield
예제 #7
0
    def make_patch(self, term, intention):
        klass = pyson.grounded(term.args[0], intention.scope)

        patch = Patch()
        patch.removed.add(klass)
        patch.added.add(klass)

        if pyson.unify(term.args[1], patch, intention.scope, intention.stack):
            yield
예제 #8
0
파일: stdlib.py 프로젝트: felipe84841/pyson
def _range_2(agent, term, intention):
    choicepoint = object()

    for i in range(int(pyson.grounded(term.args[0], intention.scope))):
        intention.stack.append(choicepoint)

        if pyson.unify(term.args[1], i, intention.scope, intention.stack):
            yield

        pyson.reroll(intention.scope, intention.stack, choicepoint)
예제 #9
0
파일: stdlib.py 프로젝트: felipe84841/pyson
def _concat(agent, term, intention):
    args = [pyson.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 pyson.unify(term.args[-1], result, intention.scope, intention.stack):
        yield
예제 #10
0
def getDetour(self, term, intention):
    target = pyson.grounded(term.args[0], intention.scope)
    position = agentStates[self.name]["node"]
    edgeData = G.get_edge_data(position, target)
    length = edgeData["length"]
    edgeData["length"] = 10000
    path = nx.shortest_path(G, position, target, "length")[1:]
    edgeData["length"] = length
    if pyson.unify(term.args[1], tuple(path), intention.scope,
                   intention.stack):
        yield
예제 #11
0
파일: stdlib.py 프로젝트: mikepsn/pyson
def _send(agent, term, intention):
    # Find the receivers: By a string, atom or list of strings or atoms.
    receivers = pyson.grounded(term.args[0], intention.scope)
    if not pyson.is_list(receivers):
        receivers = [receivers]
    receiving_agents = []
    for receiver in receivers:
        if pyson.is_atom(receiver):
            receiving_agents.append(agent.env.agents[receiver.functor])
        else:
            receiving_agents.append(agent.env.agents[receiver])

    # Illocutionary force.
    ilf = pyson.grounded(term.args[1], intention.scope)
    if not pyson.is_atom(ilf):
        return
    if ilf.functor == "tell":
        goal_type = pyson.GoalType.belief
        trigger = pyson.Trigger.addition
    elif ilf.functor == "untell":
        goal_type = pyson.GoalType.belief
        trigger = pyson.Trigger.removal
    elif ilf.functor == "achieve":
        goal_type = pyson.GoalType.achievement
        trigger = pyson.Trigger.addition
    else:
        raise pyson.PysonError("unknown illocutionary force: %s" % ilf)

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

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

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

    yield
예제 #12
0
def _send(agent, recipient, ils, term):
    group = ils.literal_group()
    if group == ("tell", 0):
        frozen = pyson.grounded(term, {}).with_annotation(pyson.Literal("source", (agent.name, )))
        agent.emit(recipient, functools.partial(pyson.runtime.add_belief, frozen))
    elif group == ("achieve", 0):
        frozen = term.with_annotation(pyson.Literal("source", (agent.name, )))
        agent.emit(recipient, functools.partial(pyson.runtime.call,
                                                pyson.Trigger.addition,
                                                pyson.GoalType.achievement,
                                                frozen))
    else:
        raise pyson.PysonError("unsupported illocutionary force: %s/%d" % (group[0], group[1]))

    return True
예제 #13
0
파일: stdlib.py 프로젝트: t-ah/pyson
def _wait(agent, term, intention):
    # Handle optional arguments.
    args = [pyson.grounded(arg, intention.scope) for arg in term.args]
    if len(args) == 2:
        event, millis = args
    else:
        if pyson.is_number(args[0]):
            millis = args[0]
            event = None
        else:
            millis = None
            event = args[0]

    # Type checks.
    if not (millis is None or pyson.is_number(millis)):
        raise pyson.PysonError("expected timeout for .wait to be numeric")
    if not (event is None or pyson.is_string(event)):
        raise pyson.PysonError("expected event for .wait to be a string")

    # Event.
    if event is not None:
        # Parse event.
        if not event.endswith("."):
            event += "."
        log = pyson.Log(LOGGER, 1)
        tokens = pyson.lexer.TokenStream(pyson.StringSource("<.wait>", event),
                                         log)
        tok, ast_event = pyson.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(pyson.runtime.BuildEventVisitor(log))

    # Timeout.
    if millis is None:
        until = None
    else:
        until = agent.env.time() + millis / 1000

    # Create waiter.
    intention.waiter = pyson.runtime.Waiter(event=event, until=until)
    yield
예제 #14
0
파일: mapc2017.py 프로젝트: t-ah/pyson
    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 = pyson.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
예제 #15
0
def getTraffic(self, term, intention):
    target = pyson.grounded(term.args[0], intention.scope)
    position = agentStates[self.name]["node"]
    destination = agentStates[self.name]["destination"]
    road = G[position][target]
    state = agentStates[self.name]
    resetWeights()
    for edge in G.edges(position):
        # update information for all incident roads
        state["traffic"][edge] = G[edge[0]][
            edge[1]]["length"] / calculateRoadProgress(
                trafficData[(edge[0], edge[1])])
        state["traffic"][(
            edge[1],
            edge[0])] = G[edge[1]][edge[0]]["length"] / calculateRoadProgress(
                trafficData[(edge[1], edge[0])])
    for edge, w in state["traffic"].items():
        # use agent's known traffic info
        G[edge[0]][edge[1]]["w"] = w
    path_length = nx.shortest_path_length(G, target, destination,
                                          "w") + road["w"]
    if pyson.unify(term.args[1], path_length, intention.scope,
                   intention.stack):
        yield
예제 #16
0
 def commit(self, term, intention):
     patch = pyson.grounded(term.args[0], intention.scope)
     print("Committing patch", patch)
     yield
예제 #17
0
파일: stdlib.py 프로젝트: felipe84841/pyson
def _wait(agent, term, intention):
    millis = pyson.grounded(term.args[0], intention.scope)
    intention.wait_until = agent.env.time() + millis / 1000
    yield
예제 #18
0
def logStep(self, term, intention):
    content = pyson.grounded(term.args[0], intention.scope)
    traces[self.name].append(content)
    yield
예제 #19
0
def distance(self, term, intention):
    n1 = pyson.grounded(term.args[0], intention.scope)
    n2 = pyson.grounded(term.args[1], intention.scope)
    if pyson.unify(term.args[2], nx.shortest_path_length(G, n1, n2),
                   intention.scope, intention.stack):
        yield