/
TikZWiringDiagrams.jl
412 lines (375 loc) · 12.9 KB
/
TikZWiringDiagrams.jl
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
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
""" Draw wiring diagrams using TikZ.
"""
module TikZWiringDiagrams
export to_tikz, layout_to_tikz
using DataStructures: OrderedDict
using MLStyle: @match
using GATlab: GATExpr, show_latex
using ...WiringDiagrams, ...WiringDiagrams.WiringDiagramSerialization
using ..WiringDiagramLayouts
using ..WiringDiagramLayouts: AbstractVector2D, Vector2D, BoxLayout, box_label,
wire_label, position, normal, tangent, port_sign, wire_points
import ..WiringDiagramLayouts: svector
import ..TikZ
# Data types
############
""" Internal data type for configurable options of Compose.jl wiring diagrams.
"""
Base.@kwdef struct TikZOptions
orientation::LayoutOrientation = LeftToRight
base_unit::String = "4mm"
labels::Bool = false
labels_pos::Union{String,Real} = 0.5
math_mode::Bool = true
arrowtip::Union{String,Nothing} = nothing
arrowtip_pos::Union{String,Real} = 0.5
rounded_boxes::Bool = true
props::AbstractVector = ["semithick"]
styles::AbstractDict = Dict()
libraries::Vector{String} = String[]
packages::Vector{String} = ["amssymb"]
used_node_styles::AbstractSet = Set{String}()
end
svector(opts::TikZOptions, args...) = svector(opts.orientation, args...)
# Wiring diagrams
#################
""" Draw a wiring diagram in TikZ.
"""
function to_tikz(args...; orientation::LayoutOrientation=LeftToRight, kw...)
layout_kw = filter(p -> first(p) ∉ fieldnames(TikZOptions), kw)
diagram = layout_diagram(args...; orientation=orientation, layout_kw...)
tikz_kw = filter(p -> first(p) ∈ fieldnames(TikZOptions), kw)
layout_to_tikz(diagram; orientation=orientation, tikz_kw...)
end
""" Draw a wiring diagram in TikZ using the given layout.
"""
function layout_to_tikz(diagram::WiringDiagram; kw...)::TikZ.Document
layout_to_tikz(diagram, TikZOptions(; kw...))
end
function layout_to_tikz(diagram::WiringDiagram, opts::TikZOptions)::TikZ.Document
stmts = tikz_box(diagram, Int[], opts)
styles, libraries = tikz_styles(opts)
props = [
[ # Define a unit length to be used for both TikZ coordinates and lengths.
# https://tex.stackexchange.com/a/454598
TikZ.Property("unit length/.code",
"{{\\newdimen\\$tikz_unit_command}\\setlength{\\$tikz_unit_command}{#1}}"),
TikZ.Property("unit length", opts.base_unit),
TikZ.Property("x", "\\$tikz_unit_command"),
TikZ.Property("y", "\\$tikz_unit_command") ];
TikZ.as_properties(opts.props);
[ TikZ.Property("$name/.style", TikZ.as_properties(props))
for (name, props) in styles ];
]
TikZ.Document(TikZ.Picture(stmts...; props=props);
libraries=unique!([ "calc"; libraries; opts.libraries ]),
packages=opts.packages)
end
""" Make TikZ node for a box.
"""
function tikz_box(diagram::WiringDiagram, vpath::Vector{Int}, opts::TikZOptions)
layout = diagram.value::BoxLayout
TikZ.Statement[
TikZ.Node(box_id(vpath),
props = [TikZ.Property("outer box"); tikz_size(layout.size)],
coord = tikz_coordinate(layout.position),
);
reduce(vcat, [ tikz_box(box(diagram, v), [vpath; v], opts)
for v in box_ids(diagram) ], init=[]);
[ tikz_edge(diagram, wire, opts) for wire in wires(diagram) ];
]
end
function tikz_box(box::AbstractBox, vpath::Vector{Int}, opts::TikZOptions)
layout = box.value::BoxLayout
style = tikz_node_style(layout, opts)
TikZ.Statement[
TikZ.Node(box_id(vpath),
props = [TikZ.Property(style); tikz_size(layout.size)],
coord = tikz_coordinate(layout.position),
content = layout.shape in (:junction, :invisible) ? "" :
tikz_node_label(layout.value, opts),
),
]
end
""" Make a TikZ edge/path for a wire.
"""
function tikz_edge(diagram::WiringDiagram, wire::Wire, opts::TikZOptions)::TikZ.Edge
src, src_angle = tikz_port(diagram, wire.source, opts)
tgt, tgt_angle = tikz_port(diagram, wire.target, opts)
exprs, prev_angle = TikZ.PathExpression[ src ], src_angle
for point in wire_points(wire)
v = tangent(point)
push!(exprs, TikZ.PathOperation("to"; props=[
TikZ.Property("out", string(prev_angle)),
TikZ.Property("in", string(tikz_angle(-v))),
]))
push!(exprs, tikz_coordinate(position(point)))
prev_angle = tikz_angle(v)
end
push!(exprs, TikZ.PathOperation("to"; props=[
TikZ.Property("out", string(prev_angle)),
TikZ.Property("in", string(tgt_angle)),
]))
push!(exprs, tgt)
# Use source port for wire label, following the Graphviz wiring diagrams.
src_layout = port_value(diagram, wire.source)
tgt_layout = port_value(diagram, wire.target)
wire_node = if opts.labels && src_layout.label_wires && tgt_layout.label_wires
props = [ TikZ.Property("anchor", tikz_anchor(svector(opts, 0, 1))) ]
content = tikz_edge_label(src_layout.value, opts)
node = TikZ.Node(; props=props, content=content)
string("{", sprint(TikZ.pprint, node), "}")
else
nothing
end
props = [ TikZ.Property("wire", wire_node) ]
if !isnothing(opts.arrowtip)
reversed = src_layout.reverse_wires && tgt_layout.reverse_wires
push!(props, TikZ.Property(reversed ? "<-" : "->"))
end
TikZ.Edge(exprs...; props=props)
end
""" Make TikZ coordinate and angle for a port.
"""
function tikz_port(diagram::WiringDiagram, port::Port, opts::TikZOptions)
name = box_id(diagram, [port.box])
parent_box = port.box in outer_ids(diagram) ? diagram : box(diagram, port.box)
shape = parent_box.value.shape
x, y = tikz_position(position(port_value(diagram, port)))
normal_angle = tikz_angle(normal(diagram, port))
anchor, (x, y) = if shape in (:rectangle, :triangle, :invtriangle,
:trapezium, :invtrapezium)
port_dir = svector(opts, port_sign(diagram, port, opts.orientation), 0)
e2 = svector(opts, 0, 1)
(tikz_anchor(port_dir), (e2[1]*x, e2[2]*y))
elseif shape in (:circle, :ellipse, :junction)
(normal_angle, (0,0))
elseif shape == :invisible
("center", (0,0))
else
# Fallback method. Always works when TikZ follows the layout's box size, but
# is the least robust to changes in node size.
("center", (x,y))
end
coord = if x == 0 && y == 0
"$name.$anchor"
else
"\$($name.$anchor)+($x,$y)\$"
end
(TikZ.NodeCoordinate(coord), normal_angle)
end
function tikz_node_label(value, opts::TikZOptions)
if opts.math_mode
box_label(MIME("text/latex"), value)
else
escape_latex(box_label(MIME("text/plain"), value))
end
end
function tikz_edge_label(value, opts::TikZOptions)
if opts.math_mode
wire_label(MIME("text/latex"), value)
else
escape_latex(wire_label(MIME("text/plain"), value))
end
end
""" Escape special LaTeX characters.
Reference: https://tex.stackexchange.com/a/34586/
"""
function escape_latex(s::AbstractString)
reduce(replace, [
"\\" => "\\textbackslash",
"~" => "\\textasciitilde",
"^" => "\\textasciicircum",
"&" => "\\&", "%" => "\\%", "\$" => "\\\$", "#" => "\\#",
"_" => "\\_", "{" => "\\{", "}" => "\\}",
], init=s)
end
# TikZ geometry
###############
function tikz_angle(v::AbstractVector2D)
tikz_number(rad2deg(angle(v[1] - v[2]*im)))
end
function tikz_position(position::AbstractVector2D)::Tuple
# TikZ's default coordinate system has the positive y-axis going upwards.
x, y = position
(tikz_number(x), tikz_number(-y))
end
function tikz_coordinate(position::AbstractVector2D)::TikZ.Coordinate
TikZ.Coordinate(tikz_position(position)...)
end
function tikz_size(size::AbstractVector2D)::Vector{TikZ.Property}
width, height = tikz_number(size[1]), tikz_number(size[2])
if width == 0 && height == 0
TikZ.Property[]
elseif width == height
[ TikZ.Property("minimum size", "$width\\$tikz_unit_command") ]
else
[ TikZ.Property("minimum width", "$width\\$tikz_unit_command"),
TikZ.Property("minimum height", "$height\\$tikz_unit_command") ]
end
end
const tikz_unit_command = "tikzunit"
tikz_anchor(v::AbstractVector2D) = tikz_anchors[Tuple(v)]
const tikz_anchors = Dict{Tuple{Int,Int},String}(
(0,0) => "center",
(1,0) => "east",
(-1,0) => "west",
(0,1) => "south",
(0,-1) => "north",
(1,1) => "south east",
(-1,1) => "south west",
(1,-1) => "north east",
(-1,-1) => "north west",
)
function tikz_number(x::Number; digits=3)::Number
x = round(x, digits=digits)
isinteger(x) ? Integer(x) : x
end
# TikZ styles
#############
""" Make TikZ style definitions for wiring diagram.
"""
function tikz_styles(opts::TikZOptions)
# Box style options.
styles = OrderedDict(
style => get(opts.styles, style) do; tikz_node_style(opts, style) end
for style in sort!([["outer box", "wire"]; collect(opts.used_node_styles)])
)
libraries = [ "shapes.geometric" ] # FIXME: Should use library only if needed.
# Wire style options.
if opts.labels
styles["wire"] = vcat(styles["wire"], tikz_decorate_markings([
"at position $(opts.labels_pos) with {#1}"
]))
push!(libraries, "decorations.markings")
end
if !isnothing(opts.arrowtip)
pos, arrowtip = opts.arrowtip_pos, opts.arrowtip
merge!(styles, OrderedDict(
"->" => tikz_decorate_markings([
"at position $pos with {\\arrow{$arrowtip}}"
]),
"<-" => tikz_decorate_markings([
"at position $pos with {\\arrow{$arrowtip[reversed]}}"
]),
))
append!(libraries, ["arrows.meta", "decorations.markings"])
end
(styles, libraries)
end
""" Get default TikZ style for given kind of node.
"""
function tikz_node_style(opts::TikZOptions, name::String)
rounded = TikZ.Property(opts.rounded_boxes ? "rounded corners" : "sharp corners")
@match name begin
"outer box" => [
TikZ.Property("draw", "none"),
]
"wire" => [
TikZ.Property("draw"),
]
"box" => [
TikZ.Property("rectangle"),
TikZ.Property("draw"), TikZ.Property("solid"), rounded,
]
"circular box" => [
TikZ.Property("circle"),
TikZ.Property("draw"), TikZ.Property("solid"),
]
"elliptical box" => [
TikZ.Property("ellipse"),
TikZ.Property("draw"), TikZ.Property("solid"),
]
"triangular box" => [
TikZ.Property("isosceles triangle"),
TikZ.Property("isosceles triangle stretches"),
TikZ.Property("shape border rotate", @match opts.orientation begin
&LeftToRight => "180"
&RightToLeft => "0"
&TopToBottom => "90"
&BottomToTop => "270"
end),
TikZ.Property("draw"), TikZ.Property("solid"), rounded,
TikZ.Property("inner sep", "0"),
]
"inverse triangular box" => [
TikZ.Property("isosceles triangle"),
TikZ.Property("isosceles triangle stretches"),
TikZ.Property("shape border rotate", @match opts.orientation begin
&LeftToRight => "0"
&RightToLeft => "180"
&TopToBottom => "270"
&BottomToTop => "90"
end),
TikZ.Property("draw"), TikZ.Property("solid"), rounded,
TikZ.Property("inner sep", "0"),
]
"trapezoidal box" => [
TikZ.Property("trapezium"), TikZ.Property("trapezium angle", "80"),
TikZ.Property("trapezium stretches body"),
TikZ.Property("shape border rotate", @match opts.orientation begin
&LeftToRight => "90"
&RightToLeft => "270"
&TopToBottom => "0"
&BottomToTop => "180"
end),
TikZ.Property("draw"), TikZ.Property("solid"), rounded,
]
"inverse trapezoidal box" => [
TikZ.Property("trapezium"), TikZ.Property("trapezium angle", "80"),
TikZ.Property("trapezium stretches body"),
TikZ.Property("shape border rotate", @match opts.orientation begin
&LeftToRight => "270"
&RightToLeft => "90"
&TopToBottom => "180"
&BottomToTop => "0"
end),
TikZ.Property("draw"), TikZ.Property("solid"), rounded,
]
"junction" => [
TikZ.Property("circle"),
TikZ.Property("draw"), TikZ.Property("fill"),
TikZ.Property("inner sep", "0"),
]
"variant junction" => [
TikZ.Property("circle"),
TikZ.Property("draw"), TikZ.Property("solid"),
TikZ.Property("inner sep", "0"),
]
"invisible" => [
TikZ.Property("draw", "none"),
TikZ.Property("inner sep", "0"),
]
_ => TikZ.Property[]
end
end
function tikz_decorate_markings(marks::Vector{TikZ.Property})
[ TikZ.Property("postaction", [ TikZ.Property("decorate") ]),
TikZ.Property("decoration", [ TikZ.Property("markings"); marks ]) ]
end
function tikz_decorate_markings(marks::Vector{String})
tikz_decorate_markings([ TikZ.Property("mark", mark) for mark in marks ])
end
""" Get TikZ style for box.
"""
function tikz_node_style(layout::BoxLayout, opts::TikZOptions)
style = if isnothing(layout.style)
tikz_shapes[layout.shape]
else
replace(string(layout.style), "_" => " ")
end
push!(opts.used_node_styles, style)
style
end
const tikz_shapes = Dict(
:rectangle => "box",
:circle => "circular box",
:ellipse => "elliptical box",
:triangle => "triangular box",
:invtriangle => "inverse triangular box",
:trapezium => "trapezoidal box",
:invtrapezium => "inverse trapezoidal box",
:junction => "junction",
:invisible => "invisible",
)
end