source: mds-and-trees/tree-genealogy.py @ 563

Last change on this file since 563 was 563, checked in by konrad, 8 years ago

updated to the new input format

File size: 12.6 KB
Line 
1# Draws a genealogical tree (generates a SVG file) based on parent-child relationship information.
2
3import json
4import random
5import math
6import argparse
7
8TIME = "GENERATIONAL"
9BALANCE = "MIN"
10
11# ------SVG---------
12svg_file = 0
13
14svg_line_style = 'stroke="rgb(90%,10%,16%)" stroke-width="1" stroke-opacity="0.8"'
15svg_dot_style = 'r="2" stroke="black" stroke-width="0.2" fill="red"'
16svg_spine_line_style = 'stroke="rgb(0%,0%,80%)" stroke-width="2" stroke-opacity="1"'
17#svg_spine_dot_style = 'r="3" stroke="black" stroke-width="0.4" fill="rgb(50%,50%,100%)"'
18svg_spine_dot_style = 'r="1" stroke="black" stroke-width="0.2" fill="rgb(50%,50%,100%)"'
19
20def svg_add_line(from_pos, to_pos, style=svg_line_style):
21    svg_file.write('<line ' + style + ' x1="' + str(from_pos[0]) + '" x2="' + str(to_pos[0]) + '" y1="' + str(from_pos[1]) + '" y2="' + str(to_pos[1]) + '" />')
22
23def svg_add_dot(pos, style=svg_dot_style):
24    svg_file.write('<circle ' + style + ' cx="' + str(pos[0]) + '" cy="' + str(pos[1]) + '" />')
25
26def svg_generate_line_style(percent):
27    from_col = [100, 70, 0]
28    to_col = [100, 0, 0]
29    # from_col = [0, 100, 50]
30    # to_col = [20, 0, 100]
31
32    percent = 1 - ((1-percent)**10)
33
34    return 'stroke="rgb(' + str(from_col[0]*(1-percent) + to_col[0]*percent) + '%,' \
35           + str(from_col[1]*(1-percent) + to_col[1]*percent) + '%,' \
36           + str(from_col[2]*(1-percent) + to_col[2]*percent) + '%)" stroke-width="1" stroke-opacity="0.8"'
37
38def svg_generate_dot_style(percent):
39    from_col = [100, 90, 0]
40    to_col = [100, 0, 0]
41    # from_col = [0, 100, 50]
42    # to_col = [20, 0, 100]
43
44    percent = 1 - ((1-percent)**10)
45
46    return 'fill="rgb(' + str(from_col[0]*(1-percent) + to_col[0]*percent) + '%,' \
47           + str(from_col[1]*(1-percent) + to_col[1]*percent) + '%,' \
48           + str(from_col[2]*(1-percent) + to_col[2]*percent) + '%)" r="1.5" stroke="black" stroke-width="0.2"' #fill-opacity="0.5"'
49
50# -------------------
51
52def load_data(dir):
53    global firstnode, nodes, inv_nodes
54    f = open(dir)
55    for line in f:
56        sline = line.split(' ', 2)
57        if len(sline) == 3:
58            if sline[1] == "[OFFSPRING]":
59                creature = json.loads(sline[2])
60                #print("B" +str(creature))
61                if "FromIDs" in creature:
62                    nodes[creature["ID"]] = creature["FromIDs"][0]
63                    if not creature["FromIDs"][0] in nodes:
64                        firstnode = creature["FromIDs"][0]
65
66    for k, v in sorted(nodes.items()):
67        inv_nodes[v] = inv_nodes.get(v, [])
68        inv_nodes[v].append(k)
69
70
71def load_simple_data(dir):
72    global firstnode, nodes, inv_nodes
73    f = open(dir)
74    for line in f:
75        sline = line.split()
76        if len(sline) > 1:
77            #if int(sline[0]) > 15000:
78            #    break
79            if sline[0] == firstnode:
80                continue
81            nodes[sline[0]] = str(max(int(sline[1]), int(firstnode)))
82        else:
83            firstnode = sline[0]
84
85    for k, v in sorted(nodes.items()):
86        inv_nodes[v] = inv_nodes.get(v, [])
87        inv_nodes[v].append(k)
88
89    #print(str(inv_nodes))
90    #quit()
91
92def compute_depth(node):
93    my_depth = 0
94    if node in inv_nodes:
95        for c in inv_nodes[node]:
96            my_depth = max(my_depth, compute_depth(c)+1)
97    depth[node] = my_depth
98    return my_depth
99
100# ------------------------------------
101
102def xmin_crowd(x1, x2, y):
103    if BALANCE == "RANDOM":
104        return (x1 if random.randrange(2) == 0 else x2)
105    elif BALANCE == "MIN":
106        x1_closest = 999999
107        x2_closest = 999999
108        for pos in positions:
109            pos = positions[pos]
110            if pos[1] == y:
111                x1_closest = min(x1_closest, abs(x1-pos[0]))
112                x2_closest = min(x2_closest, abs(x2-pos[0]))
113        return (x1 if x1_closest > x2_closest else x2)
114    elif BALANCE == "DENSITY":
115        x1_dist = 0
116        x2_dist = 0
117        for pos in positions:
118            pos = positions[pos]
119            if pos[1] > y-10 or pos[1] < y+10:
120                dy = pos[1]-y
121                dx1 = pos[0]-x1
122                dx2 = pos[0]-x2
123
124                x1_dist += math.sqrt(dy**2 + dx1**2)
125                x2_dist += math.sqrt(dy**2 + dx2**2)
126        return (x1 if x1_dist > x2_dist else x2)
127
128# ------------------------------------
129
130def prepos_children_reccurent(node):
131    for c in inv_nodes[node]:
132        #print(node + "->" + c)
133        dissimilarity = random.gauss(0,0.3)
134        if TIME == "REAL":
135            id = ""
136            if c[0] == "c":
137                id = int(c[1:])
138            else:
139                id = int(c)
140            positions[c] = [xmin_crowd(positions[node][0]-dissimilarity, positions[node][0]+dissimilarity, id), id]
141        elif TIME == "GENERATIONAL":
142            positions[c] = [xmin_crowd(positions[node][0]-dissimilarity, positions[node][0]+dissimilarity, positions[node][1]+1), positions[node][1]+1]
143
144    for c in inv_nodes[node]:
145        if c in inv_nodes:
146            prepos_children_reccurent(c)
147
148def prepos_children():
149    global max_height, max_width, min_width
150
151    positions[firstnode] = [0, 0]
152
153    prepos_children_reccurent(firstnode)
154
155    for pos in positions:
156        max_height = max(max_height, positions[pos][1])
157        max_width = max(max_width, positions[pos][0])
158        min_width = min(min_width, positions[pos][0])
159
160# ------------------------------------
161
162def draw_children_recurrent(node, max_depth):
163    global max_height, max_width, min_width
164    for c in inv_nodes[node]:
165        if c in inv_nodes:
166            draw_children_recurrent(c, max_depth)
167        svg_add_line( (w_margin+w_no_margs*(positions[node][0]-min_width)/(max_width-min_width), h_margin+h_no_margs*positions[node][1]/max_height),
168            (w_margin+w_no_margs*(positions[c][0]-min_width)/(max_width-min_width), h_margin+h_no_margs*positions[c][1]/max_height),
169                      (svg_line_style if args.mono_tree else svg_generate_line_style(depth[c]/max_depth)))
170        svg_add_dot( (w_margin+w_no_margs*(positions[c][0]-min_width)/(max_width-min_width), h_margin+h_no_margs*positions[c][1]/max_height),
171                     (svg_dot_style if args.mono_tree else svg_generate_dot_style(depth[c]/max_depth)))
172def draw_children():
173    max_depth = 0
174    for k, v in depth.items():
175            max_depth = max(max_depth, v)
176    draw_children_recurrent(firstnode, max_depth)
177    svg_add_dot( (w_margin+w_no_margs*(positions[firstnode][0]-min_width)/(max_width-min_width), h_margin+h_no_margs*positions[firstnode][1]/max_height),
178                 (svg_dot_style if args.mono_tree else svg_generate_dot_style(depth[firstnode]/max_depth)))
179
180def draw_spine_recurrent(node):
181    global max_height, max_width, min_width
182    for c in inv_nodes[node]:
183        if depth[c] == depth[node] - 1:
184            if c in inv_nodes:
185                draw_spine_recurrent(c)
186            svg_add_line( (w_margin+w_no_margs*(positions[node][0]-min_width)/(max_width-min_width), h_margin+h_no_margs*positions[node][1]/max_height),
187                (w_margin+w_no_margs*(positions[c][0]-min_width)/(max_width-min_width), h_margin+h_no_margs*positions[c][1]/max_height), svg_spine_line_style)
188            #svg_add_dot( (w_margin+w_no_margs*(positions[c][0]-min_width)/(max_width-min_width), h_margin+h_no_margs*positions[c][1]/max_height), svg_spine_dot_style)
189def draw_spine():
190    draw_spine_recurrent(firstnode)
191    #svg_add_dot( (w_margin+w_no_margs*(positions[firstnode][0]-min_width)/(max_width-min_width), h_margin+h_no_margs*positions[firstnode][1]/max_height), svg_spine_dot_style)
192
193def draw_skeleton_reccurent(node, max_depth):
194    global max_height, max_width, min_width
195    for c in inv_nodes[node]:
196        if depth[c] >= min_skeleton_depth or depth[c] == max([depth[q] for q in inv_nodes[node]]):
197            if c in inv_nodes:
198                draw_skeleton_reccurent(c, max_depth)
199            svg_add_line( (w_margin+w_no_margs*(positions[node][0]-min_width)/(max_width-min_width), h_margin+h_no_margs*positions[node][1]/max_height),
200                (w_margin+w_no_margs*(positions[c][0]-min_width)/(max_width-min_width), h_margin+h_no_margs*positions[c][1]/max_height),
201                          svg_spine_line_style)
202            #svg_add_dot( (w_margin+w_no_margs*(positions[c][0]-min_width)/(max_width-min_width), h_margin+h_no_margs*positions[c][1]/max_height),
203            #             svg_spine_dot_style)
204def draw_skeleton():
205    max_depth = 0
206    for k, v in depth.items():
207            max_depth = max(max_depth, v)
208
209    draw_skeleton_reccurent(firstnode, max_depth)
210    #svg_add_dot( (w_margin+w_no_margs*(positions[firstnode][0]-min_width)/(max_width-min_width), h_margin+h_no_margs*positions[firstnode][1]/max_height),
211    #             svg_spine_dot_style)
212
213
214
215
216##################################################### main #####################################################
217
218args = 0
219
220h = 800
221w = 600
222h_margin = 10
223w_margin = 10
224h_no_margs = h - 2* h_margin
225w_no_margs = w - 2* w_margin
226
227max_height = 0
228max_width = 0
229min_width = 9999999999
230
231min_skeleton_depth = 0
232
233firstnode = ""
234nodes = {}
235inv_nodes = {}
236positions = {}
237depth = {}
238
239def main():
240    global svg_file, min_skeleton_depth, args, TIME, BALANCE
241
242    parser = argparse.ArgumentParser(description='Process some integers.')
243    parser.add_argument('--in', dest='input', required=True, help='input file with stuctured evolutionary data')
244    parser.add_argument('--out', dest='output', required=True, help='output file for the evolutionary tree')
245    draw_tree_parser = parser.add_mutually_exclusive_group(required=False)
246    draw_tree_parser.add_argument('--draw-tree', dest='draw_tree', action='store_true', help='whether drawing the full tree should be skipped')
247    draw_tree_parser.add_argument('--no-draw-tree', dest='draw_tree', action='store_false')
248
249    draw_skeleton_parser = parser.add_mutually_exclusive_group(required=False)
250    draw_skeleton_parser.add_argument('--draw-skeleton', dest='draw_skeleton', action='store_true', help='whether the skeleton of the tree should be drawn')
251    draw_skeleton_parser.add_argument('--no-draw-skeleton', dest='draw_skeleton', action='store_false')
252
253    draw_spine_parser = parser.add_mutually_exclusive_group(required=False)
254    draw_spine_parser.add_argument('--draw-spine', dest='draw_spine', action='store_true', help='whether the spine of the tree should be drawn')
255    draw_spine_parser.add_argument('--no-draw-spine', dest='draw_spine', action='store_false')
256
257    #TODO: better names for those parameters
258    parser.add_argument('--time', default='REAL', dest='time', help='values on vertical axis (REAL/GENERATIONAL)')
259    parser.add_argument('--balance', default='MIN',dest='balance', help='method of placing node in the tree (RANDOM/MIN/DENSITY)')
260
261    mono_tree_parser = parser.add_mutually_exclusive_group(required=False)
262    mono_tree_parser.add_argument('--mono-tree', dest='mono_tree', action='store_true', help='whether the tree should be drawn with a single color')
263    mono_tree_parser.add_argument('--no-mono-tree', dest='mono_tree', action='store_false')
264
265    parser.add_argument('--min-skeleton-depth', type=int, default=2, dest='min_skeleton_depth', help='minimal distance from the leafs for the nodes in the skeleton')
266    parser.add_argument('--seed', type=int, dest='seed', help='seed for the random number generator (-1 for random)')
267
268    parser.add_argument('--simple-data', type=bool, dest='simple_data', help='input data are given in a simple format (#child #parent)')
269
270    parser.set_defaults(mono_tree=False)
271    parser.set_defaults(draw_tree=True)
272    parser.set_defaults(draw_skeleton=False)
273    parser.set_defaults(draw_spine=False)
274
275    parser.set_defaults(seed=-1)
276
277    args = parser.parse_args()
278
279    TIME = args.time
280    BALANCE = args.balance
281
282    dir = args.input
283    min_skeleton_depth = args.min_skeleton_depth
284    seed = args.seed
285    if seed == -1:
286        seed = random.randint(0, 10000)
287    random.seed(seed)
288    print("seed:", seed)
289
290    if args.simple_data:
291        load_simple_data(dir)
292    else:
293        load_data(dir)
294
295    compute_depth(firstnode)
296
297    svg_file = open(args.output, "w")
298    svg_file.write('<svg xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.0" '
299                   'width="' + str(w) + '" height="' + str(h) + '">')
300
301    prepos_children()
302
303    if args.draw_tree:
304        draw_children()
305    if args.draw_skeleton:
306        draw_skeleton()
307    if args.draw_spine:
308        draw_spine()
309
310    svg_file.write("</svg>")
311    svg_file.close()
312
313main()
314
Note: See TracBrowser for help on using the repository browser.