Example #1
0
def generate_state_graph(agent_def):
    assert type(agent_def) == AgentDefinition
    graph = Graph()
    agent_name = agent_def.name

    for idx, st in enumerate(agent_def.klass.state_transitions):
        st_from, tf, st_to = st
        if type(st_to) == str:  # basic state transition
            s0 = "[%s] %s" % (agent_name, st_from)
            s1 = "[%s] %s" % (agent_name, st_to)
            tf_name = "%s.%s" % (agent_name, tf)
            graph.add_edge(s0, s1, EDGE_ATTR["st_func"])
            graph.set_edge_attribute(s0, s1, "label", tf_name)
            graph.set_edge_attribute(s0, s1, "st_func", tf)
            graph.set_node_attributes(s0, NODE_ATTR["state"])
            graph.set_node_attributes(s1, NODE_ATTR["state"])
        else:
            assert type(st_to) in (list, tuple)
            branch = tf
            end_states = st_to

            # connect state_from to branch
            s0 = "[%s] %s" % (agent_name, st_from)
            sb = "%s.%s" % (agent_name, branch)
            graph.add_edge(s0, sb, EDGE_ATTR["branch_edge"])
            graph.set_node_attributes(s0, NODE_ATTR["state"])
            graph.set_node_attributes(sb, NODE_ATTR["branch"])
            graph.set_node_attribute(sb, "st_func", branch)

            # for each branching condition
            for tf, st_to, condition in end_states:
                # connect state_from to branch condition
                sc = "[%s] %s" % (agent_name, condition)
                graph.add_edge(sb, sc, EDGE_ATTR["branch_edge"])
                graph.set_node_attributes(sc, NODE_ATTR["branch_cond"])

                # connect branch condition to state_to
                s1 = "[%s] %s" % (agent_name, st_to)
                tf_name = "%s.%s" % (agent_name, tf)
                graph.add_edge(sc, s1, EDGE_ATTR["st_func"])
                graph.set_edge_attribute(sc, s1, "label", tf_name)
                graph.set_edge_attribute(sc, s1, "st_func", tf)
                graph.set_node_attributes(s1, NODE_ATTR["state"])

    return graph