-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathleiwand.py
More file actions
230 lines (196 loc) · 7.9 KB
/
leiwand.py
File metadata and controls
230 lines (196 loc) · 7.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
from planar import Polygon
import sys
#I spü mit System, schreib ma immer Ollas auf
#Des muasst mochn, weil sunst host ka Chance
docstring="""
Use this script like this
Use with 'mathematica' string
python leiwand.py mathematica={{weight,vertex1,mode1,vertex2,mode2},{weight,vertex1,mode1,vertex2,mode2}}
Or get the data into a file which list the data of the edges like:
weight vertex1 mode1 vertex2 mode2
weight vertex1 mode1 vertex2 mode2
python leiwand.py in=filename
You can call the script with several options like this
python leiwand.py in=filename key1=value1 key2=value2
option keys are the following
"""
variables = {
"line_width": 2.0,
"color0": "{RGB}{0,0,204}",
"color1": "{RGB}{0,204,0}",
"color2": "{RGB}{204,0,0}",
"vertexcolor": "{RGB}{250,250,250}",
"fontcolor": "{RGB}{0,0,0}",
"bend00":"-5",
"bend11":"5",
"bend22":"0",
"bend01":"-10",
"bend10":"10",
"bend02":"-15",
"bend20":"15",
"bend12":"-20",
"bend21":"20",
"angle":180,
"vertices": None,
"whitespace": "10pt"
}
def leiwand(args):
poly={}
filename = "data.txt"
output = "graph"
for arg in args:
if "in=" in arg:
filename = arg.split("=")[1]
if "out=" in arg:
output = arg.split("=")[1]
if "coord" in arg:
tmp = arg.split("_")[1].split("=")
name = tmp[0]
coord = tmp[1].split(",")
coord = [float(coord[0]),float(coord[1])]
poly[name] = coord
elif "=" in arg:
tmp = arg.split("=")
variables[tmp[0]] = tmp[1]
if "bendall" in variables:
for x in ["00", "11", "22", "01", "10", "02", "20", "21", "12"]:
variables["bend"+x] = variables["bendall"]
external_vertices = None
if variables['vertices'] is not None:
external_vertices = variables["vertices"].split(' ')
# reverse order (drawing is counter-clockwise)
external_vertices = list(reversed(external_vertices))
print("got vertices: ", external_vertices)
whitespace = None
if variables["whitespace"] is not None:
whitespace = variables["whitespace"]
with open(output + ".tex", "w") as outf:
data = []
if "mathematica" in data:
lines = data["mathematica"].split("{")
for line in lines:
if "}" in line:
tmp = line.split("}")
data.append(
(float(tmp[0]), str(tmp[1]).strip(), int(tmp[2]), str(tmp[3]).strip(), int(tmp[4].strip("}"))))
else:
with open(filename, "r") as f:
for line in f:
if line == "\n":
print("caught blanc line")
continue
line = line.strip()
line = line.strip(",") # remove trailing comma
tmp = line.split(",")
data.append([float(tmp[0]), str(tmp[1]).strip(), int(tmp[2]), str(tmp[3]).strip(), int(tmp[4])])
optionmap = {
(0, 0): "color=zerocol, bend right="+variables["bend00"],
(1, 1): "color=onecol, bend right="+variables["bend11"],
(2, 2): "color=twocol, bend right="+variables["bend22"],
(0, 1): "bicolor={zerocol}{onecol}, bend left="+variables["bend01"],
(1, 0): "bicolor={onecol}{zerocol}, bend right="+variables["bend10"],
(0, 2): "bicolor={zerocol}{twocol}, bend left="+variables["bend20"],
(2, 0): "bicolor={green}{zerocol}, bend right="+variables["bend02"],
(1, 2): "bicolor={onecol}{twocol}, bend left="+variables["bend12"],
(2, 1): "bicolor={twocol}{onecol}, bend right="+variables["bend21"],
}
if whitespace is not None:
print("\documentclass[border={}]{}".format(whitespace, r"{standalone}"), file=outf)
else:
print(r"\documentclass{standalone}", file=outf)
print(r"""
\usepackage{tikz}
\usepackage{verbatim}
\usetikzlibrary{decorations.markings}
\begin{document}
\pagestyle{empty}
""",file=outf)
colors=r"\definecolor{vertexcol}"+variables["vertexcolor"]
colors+=r"\definecolor{onecol}"+variables["color0"]
colors+=r"\definecolor{twocol}"+variables["color1"]
colors+=r"\definecolor{zerocol}"+variables["color2"]
colors+=r"\definecolor{fontcolor}" + variables["fontcolor"]
print(colors, file=outf)
print(r"""
\newlength\mylen
% check https://tex.stackexchange.com/questions/270001/tikz-coloring-edge-segments-with-different-colors
\tikzset{
bicolor/.style n args={2}{
decoration={
markings,
mark=at position 0.5 with {
\node[draw=none,inner sep=0pt,fill=none,text width=0pt,minimum size=0pt] {\global\setlength\mylen{\pgfdecoratedpathlength}};
},
},
draw=#1,
dash pattern=on 0.5\mylen off 1.0\mylen,
preaction={decorate},
postaction={
draw=#2,
dash pattern=on 0.5\mylen off 0.5\mylen,dash phase=0.5\mylen
},
}
}
\begin{tikzpicture}
\tikzstyle{vertex}=[circle, draw=black, ultra thick ,fill=vertexcol!80,minimum size=15pt]\textbf{}
""", file=outf)
vertices = []
weights = []
for d in data:
weights.append(abs(d[0]))
vertices.append(d[1])
vertices.append(d[3])
vertices = list(set(vertices))
max_weight = max(weights)
# check if vertices where specified manually
if external_vertices is not None:
print("replacing: ", vertices)
print("with external vertices: ", external_vertices)
vertices = external_vertices
else:
#sort vertices alphabetically
vertices = list(reversed(sorted(vertices)))
if len(poly) < len(vertices):
poly = Polygon.regular(len(vertices), radius=5, angle=float(variables["angle"]))
else:
# sort alphabetically
poly = reversed(list(dict(sorted(poly.items(), key=lambda x:x[0])).values()))
for i, coord in enumerate(poly):
print(r"\node[vertex] ({name}) at ({x},{y}) {xname};".format(name=vertices[i], xname=r"{\color{fontcolor}" + vertices[i] + "}", x=coord[0], y=coord[1]), file=outf)
edge_string = r"\path ({v1}) edge[{options}, opacity={opacity}] ({v2});"
for d in data:
assert (len(d) == 5)
weight = d[0]
v1 = d[1]
t1 = d[2]
v2 = d[3]
t2 = d[4]
opacity = max(0.3, abs(weight) / max_weight)
print(edge_string.format(v1=v1, v2=v2,
options="line width={lw},".format(lw=variables["line_width"]) + optionmap[(t1, t2)],
opacity=opacity), file=outf)
print(r"""
\end{tikzpicture}
\end{document}
""", file=outf)
print("created {}.tex".format(output))
print("trying to compile with pdflatex ... might be caught in endless loop")
import subprocess
from shutil import which
system_has_pdflatex = which("pdflatex") is not None
if not system_has_pdflatex:
raise Exception("You need pdflatex in order to export circuits to pdfs")
with open(output + ".log", "w") as file:
subprocess.call(["pdflatex", output + ".tex"], stdout=file)
print("created {}.pdf".format(output))
if __name__ == "__main__":
print(docstring)
for k,v in variables.items():
print("{}={}".format(k,v))
print("""
Additional options are:
bendall=value | set all bendxx angles to same value
"""
)
print("calling with: ", sys.argv)
leiwand(sys.argv)