-
Notifications
You must be signed in to change notification settings - Fork 34
/
draw_nary.py
106 lines (85 loc) · 2.53 KB
/
draw_nary.py
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
from math import atan, sin, cos, pi
from PIL import Image, ImageDraw
from demo_trees import trees
from reingold_thread import reingold_tilford as rt
# from reingold_naive import reingold_tilford as rt
from buchheim import buchheim
def mirror(t):
if len(t.children) > 1:
t.children = tuple(reversed(t.children))
for c in t.children:
mirror(c)
return t
t = buchheim(trees[8])
# t = buchheim(trees[9])
# t = rt(trees[4])
DIAMETER = 30
SPACING_VERTICAL = DIAMETER * 1.5
SPACING_HORIZONTAL = DIAMETER * 1.5
def drawt(draw, root, depth):
draw.ellipse(
[
root.x * SPACING_HORIZONTAL,
depth * SPACING_VERTICAL,
root.x * SPACING_HORIZONTAL + DIAMETER,
depth * SPACING_VERTICAL + DIAMETER,
],
fill=(225),
outline=(0),
)
for child in root.children:
drawt(draw, child, depth + 1)
def drawconn(draw, root, depth):
for child in root.children:
draw.line(
[
root.x * SPACING_HORIZONTAL + (DIAMETER / 2),
depth * SPACING_VERTICAL + (DIAMETER / 2),
child.x * SPACING_HORIZONTAL + (DIAMETER / 2),
(depth + 1) * SPACING_VERTICAL + (DIAMETER / 2),
],
fill=(0),
)
drawconn(draw, child, depth + 1)
def sign(x):
if x == 0:
return 0
if x > 0:
return 1
else:
return -1
def dottedline(draw, x1, y1, x2, y2):
segment = 5
if x2 == x1:
theta = pi / 2
elif x2 - x1 > 0:
theta = atan(float(y2 - y1) / float(x2 - x1))
else:
theta = pi + atan(float(y2 - y1) / float(x2 - x1))
dx = cos(theta) * segment
dy = sin(theta) * segment
xdir = x1 < x2
ydir = y1 < y2
while 1:
if xdir != (x1 < x2) or ydir != (y1 < y2):
break
draw.line([x1, y1, x1 + dx, y1 + dy], fill=(0))
x1, y1 = x1 + 2 * dx, y1 + 2 * dy
def drawthreads(draw, root, depth):
for child in root.children:
c = child.thread
if c:
dottedline(
draw,
child.x * SPACING_HORIZONTAL + (DIAMETER / 2),
(depth + 1) * SPACING_VERTICAL + (DIAMETER / 2),
c.x * SPACING_HORIZONTAL + (DIAMETER / 2),
(depth + 2) * SPACING_VERTICAL + (DIAMETER / 2),
)
drawthreads(draw, child, depth + 1)
im = Image.new("L", (1000, 550), (255))
draw = ImageDraw.Draw(im)
drawconn(draw, t, 0)
drawthreads(draw, t, 0)
drawt(draw, t, 0)
im.save("draw_nary.png")