def generate_dag(optimal_indvidual, stage_name, num_nodes): # create nodes for the graph nodes = np.empty((0), dtype=np.str) for n in range(1, (num_nodes + 1)): nodes = np.append(nodes, ''.join([stage_name, "_", str(n)])) # initialize directed asyclic graph (DAG) and add nodes to it dag = DAG() for n in nodes: dag.add_node(n) # split best indvidual found via GA to identify vertices connections and connect them in DAG edges = np.split(optimal_indvidual, np.cumsum(range(num_nodes - 1)))[1:] v2 = 2 for e in edges: v1 = 1 for i in e: if i: dag.add_edge(''.join([stage_name, "_", str(v1)]), ''.join([stage_name, "_", str(v2)])) v1 += 1 v2 += 1 # delete nodes not connected to anyother node from DAG for n in nodes: if len(dag.predecessors(n)) == 0 and len(dag.downstream(n)) == 0: dag.delete_node(n) nodes = np.delete(nodes, np.where(nodes == n)[0][0]) return dag, nodes
def generate_dag(optimal_indvidual, stage_name, num_nodes): # optimal_individual为本stage的二进制字符串 # create nodes for the graph nodes = np.empty((0), dtype=np.str) # 给stage的节点命名,比如s1 stage,节点名字为s1_1,s1_2,... for n in range(1, (num_nodes + 1)): nodes = np.append(nodes, ''.join([stage_name, "_", str(n)])) # initialize directed asyclic graph (DAG) and add nodes to it # 加入所有节点 dag = DAG() for n in nodes: dag.add_node(n) # split best indvidual found via GA to identify vertices connections and connect them in DAG # cumsum累积和,cumsum([0, 1, 2, 3])返回[0, 1, 3, 6] # 在这里体现为比如有4个node,二进制字符串长度为6,切割成s[:0], s[0:1], s[1:3], s[3:6] # 即连接每个节点的二进制字符串 # 最后再删除第一个节点没有连的数据(上面的s[:0]) edges = np.split(optimal_indvidual, np.cumsum(range(num_nodes - 1)))[1:] v2 = 2 # 遍历所有节点的连接情况 for e in edges: v1 = 1 # 遍历这个节点的二进制字符串 # 如果是1,添加边到dag # 这里其实for循环替代v1会好看些 for i in e: if i: dag.add_edge(''.join([stage_name, "_", str(v1)]), ''.join([stage_name, "_", str(v2)])) v1 += 1 v2 += 1 # delete nodes not connected to anyother node from DAG # 删除孤立的点 for n in nodes: if len(dag.predecessors(n)) == 0 and len(dag.downstream(n)) == 0: dag.delete_node(n) nodes = np.delete(nodes, np.where(nodes == n)[0][0]) return dag, nodes