LaTeX 中的 Python:奇怪的 Networkx/Graphviz 错误

LaTeX 中的 Python:奇怪的 Networkx/Graphviz 错误

很难给出一个最小的例子,因为需要 Python3 和一些包。我想从 LaTeX 调用 Python,下面是我想要如何做的一个示例(需要 --shell-escape):

\documentclass[]{article}
\usepackage{tikz}
\begin{document}
    \input{|python3 ./core/dijkstra_automated_exercise.py}
\end{document}

现在我想调用一个 Python 脚本,它会自动打印一个图表:

import networkx as nx
import numpy as np
import string
import random
import pygraphviz

def draw_digraph(adj_matrix):
    # Drawing the graph
    n = len(adj_matrix)
    G = nx.DiGraph(np.matrix(adj_matrix))
    layout = nx.planar_layout(G)
    layout = nx.nx_agraph.graphviz_layout(G, prog='neato')
    
    layout = {i: ([layout[i][0]//10, layout[i][1]//10]) for i in layout}
    # General tikz options
    tikz_opt = 'scale = 1, font= \Large'

    # Node Options
    default_node_opt = 'shape=circle, draw, line width=1.5pt'
    char_labels = list(string.ascii_uppercase)[0:n]
    node_labels = {i: char_labels[i] for i in range(0,n)}
    node_opt = {i: "circle, draw" for i in range(0,n)}

    # Edge Options
    default_edge_opt = "bend left=20, line width=1.5pt"
    edge_opt = {}
    edge_labels = nx.get_edge_attributes(G,'weight')
    edge_label_opt= {(i,j): "fill=white, circle, draw, very near start, font=\large" for i in range(0,n) for j in range (0,n)}

    # General to_latex_raw documentation
    # to_latex_raw(G, pos='pos', tikz_options='', default_node_options='', node_options='node_options', node_label='label', 
    # default_edge_options='', edge_options='edge_options', edge_label='label', edge_label_options='edge_label_options')
    return nx.to_latex_raw(G, 
                           pos = layout,
                           tikz_options = tikz_opt, 
                           default_node_options = default_node_opt,
                           node_options=node_opt,
                           node_label = node_labels, 
                           default_edge_options = default_edge_opt, 
                           edge_options = edge_opt,
                           edge_label=edge_labels,
                           edge_label_options = edge_label_opt
                           )

def generate_random_digraph(V, E):
    adj_matrix = [[0 for j in range(V)] for i in range(V)]
    edges = set()
    while len(edges) < E:
        start_node, end_node = random.randint(0, V-1), random.randint(0, V-1)
        if start_node != end_node:
            edges.add((start_node, end_node))
    for start_node, end_node in edges:
        adj_matrix[start_node][end_node] = 1
    return adj_matrix

adj_matrix = generate_random_digraph(6,6)

print("\\section{The First}\n")
print((draw_digraph(adj_matrix)))

现在我有一个问题,我不明白。layout = nx.planar_layout(G)有效,但结果很糟糕。所以我想打电话layout = nx.nx_agraph.graphviz_layout(G, prog='neato')在这行之后,LaTeX 无法访问/获取 python 脚本的输出。我真的不明白为什么会出现这个错误。脚本的终端输出仍然正确,我可以将此输出包含在 LaTeX 中并且它可以工作,但这样的解决方案并不像我希望的那样优雅。有人可以解释一下,为什么我不能直接从 LaTeX 访问输出以及如何修复它吗?

相关内容