pythontex 拼图

pythontex 拼图

对于大型矩阵,我很难输入tikz矩阵表达式。我用 Python 编写了一些代码来帮我完成这项工作。代码打印出表达式tikz,然后我将其复制/粘贴到tex文件中。但后来我发现有一个很棒的包,pythontex它实际上允许用户直接从 tex 文件运行代码。所以我将代码复制到 tex 文件中并运行它……不幸的是它不起作用。它似乎认为我漏掉了一个括号:

Missing } inserted.
<inserted text> 
                }
l.454 \end{tikzpicture}

我知道我没有,因为完全相同的代码打印了一个在tex文件中编译的表达式。

这是tex文件pythontex

\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{fit,shapes.geometric,calc,matrix,math}
\usepackage{pythontex}
\usepackage{tensor}

\begin{document}

\begin{pycode}
import numpy as np

def indexTable(a):
    l = 1
    for x in a:
        l=l*x
    t = np.zeros((l,len(a)))

    for i in range(l):
        index=i
        for j in range(len(a)):
            t[i,-j-1]=index%a[-j-1]+1
            index = index // a[-j-1]
            
    return t

def printTensor(a,ai,b,bi,f):
    t = indexTable(a)
    s = indexTable(b)

    l , h = t.shape
    r , u = s.shape

    print(r"\begin{tikzpicture}")
    print(r"\matrix(m) [matrix of nodes, column sep=3ex, nodes={minimum height=5ex, anchor=center}] { ")
    for i in range(u):
        for j in range(h):
            print(r" & ",end='')
        for j in range(r-1):
            print(r" \mbox{\tiny $%s = %d$} & " % (bi[i],s[j,i]),end='')
        print(r" \mbox{\tiny $%s = %d$} \\" % (bi[i],s[r-1,i]))

    for i in range(l):
        for j in range(h):
            print(r" \mbox{\tiny $%s = %d$} &" % (ai[j],t[i,j]),end='')
        for j in range(r-1):
            eq = f(t[i,:],s[j,:])
            print(" " + eq + " & ",end='')   
        eq = f(t[i,:],s[r-1,:])         
        print(eq, end='')
        print(r" \\")
    
    print(r"};")
    print(r"\end{tikzpicture}")

def simpleTensor(subs,sups):
    eq = r"$\tensor{X}{"

    for x in sups:
        eq = eq + "^" + str(int(x))
    
    for x in subs:
        eq = eq + "_" + str(int(x))
    
    eq = eq + "}$"

    return eq

\end{pycode}


\pyc{printTensor([2,3,2],['i','j','k'],[3,3,3],['p','q','r'],simpleTensor)}

\end{document}

我在(10.15.7)LaTeX上运行。我使用安装。我使用(LaTeX-Workshop 是 latex 扩展)编译文件。maOSCatalinaTeX LivetexVisual Studio Code

任何帮助,将不胜感激!

相关内容