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

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

Added an option for defining colors of crossover / mutation lines from the command line

File size: 19.1 KB
RevLine 
[562]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
[571]8TIME = "" # BIRTHS / GENERATIONAL / REAL
9BALANCE = "" # MIN / DENSITY
[562]10
[571]11DOT_STYLE = "" # NONE / NORMAL / CLEAR
12
13JITTER = "" #
14
[562]15# ------SVG---------
16svg_file = 0
17
[577]18svg_line_style = 'stroke="rgb(90%,10%,16%)" stroke-width="1" stroke-opacity="0.7"'
[585]19svg_mutation_line_style = 'stroke-width="1"'
20svg_crossover_line_style = 'stroke-width="1"'
[577]21svg_spine_line_style = 'stroke="rgb(0%,90%,40%)" stroke-width="2" stroke-opacity="1"'
22svg_scale_line_style = 'stroke="black" stroke-width="0.5" stroke-opacity="1" stroke-dasharray="5, 5"'
23
[562]24svg_dot_style = 'r="2" stroke="black" stroke-width="0.2" fill="red"'
[571]25svg_clear_dot_style = 'r="2" stroke="black" stroke-width="0.4" fill="none"'
[562]26svg_spine_dot_style = 'r="1" stroke="black" stroke-width="0.2" fill="rgb(50%,50%,100%)"'
27
[576]28svg_scale_text_style = 'style="font-family: Arial; font-size: 12; fill: #000000;"'
29
[585]30def hex_to_style(hex):
31    if hex[0] == "#":
32        hex = hex[1:]
33
34    if len(hex) == 6 or len(hex) == 8:
35        try:
36            int(hex, 16)
37        except:
38            print("Wrong characters in the color's hex #" + hex + "! Assuming black.")
39            return ' stroke="black" stroke-opacity="0.5" '
40        red = 100*int(hex[0:2], 16)/255
41        green = 100*int(hex[2:4], 16)/255
42        blue = 100*int(hex[4:6], 16)/255
43        opacity = 0.5
44        if len(hex) == 8:
45            opacity = int(hex[6:8], 16)/255
46        return ' stroke="rgb(' +str(red)+ '%,' +str(green)+ '%,' +str(blue)+ '%)" stroke-opacity="' +str(opacity)+ '" '
47    else:
48        print("Wrong number of digits in the color's hex #" + hex + "! Assuming black.")
49        return ' stroke="black" stroke-opacity="0.5" '
50
[562]51def svg_add_line(from_pos, to_pos, style=svg_line_style):
52    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]) + '" />')
53
[576]54def svg_add_text(text, pos, anchor, style=svg_scale_text_style):
55    svg_file.write('<text ' + style + ' text-anchor="' + anchor + '" x="' + str(pos[0]) + '" y="' + str(pos[1]) + '" >' + text + '</text>')
56
[562]57def svg_add_dot(pos, style=svg_dot_style):
58    svg_file.write('<circle ' + style + ' cx="' + str(pos[0]) + '" cy="' + str(pos[1]) + '" />')
59
60def svg_generate_line_style(percent):
[564]61    # hotdog
[562]62    from_col = [100, 70, 0]
[564]63    to_col = [60, 0, 0]
[585]64    from_col = [0, 0, 0]
65    to_col = [80, 0, 80]
[571]66    # lava
67    # from_col = [100, 80, 0]
68    # to_col = [100, 0, 0]
[564]69    # neon
70    # from_col = [30, 200, 255]
71    # to_col = [240, 0, 220]
[562]72
[564]73    from_opa = 0.2
74    to_opa = 1.0
75    from_stroke = 1
76    to_stroke = 3
[562]77
[564]78    opa = from_opa*(1-percent) + to_opa*percent
79    stroke = from_stroke*(1-percent) + to_stroke*percent
80
81    percent = 1 - ((1-percent)**20)
82
[562]83    return 'stroke="rgb(' + str(from_col[0]*(1-percent) + to_col[0]*percent) + '%,' \
84           + str(from_col[1]*(1-percent) + to_col[1]*percent) + '%,' \
[564]85           + str(from_col[2]*(1-percent) + to_col[2]*percent) + '%)" stroke-width="' + str(stroke) + '" stroke-opacity="' + str(opa) + '"'
[562]86
[577]87def svg_generate_dot_style(kind):
88    kinds = ["red", "lawngreen", "royalblue", "magenta", "yellow", "cyan", "white", "black"]
[562]89
[577]90    r = min(2500/len(nodes), 10)
[562]91
[577]92    return 'fill="' + kinds[kind] + '" r="' + str(r) + '" stroke="black" stroke-width="' + str(r/10) + '" fill-opacity="1.0" ' \
93           'stroke-opacity="1.0"'
[564]94
[562]95# -------------------
96
97def load_data(dir):
[571]98    global firstnode, nodes, inv_nodes, time
[562]99    f = open(dir)
100    for line in f:
[571]101        sline = line.split(' ', 1)
102        if len(sline) == 2:
103            if sline[0] == "[OFFSPRING]":
104                creature = json.loads(sline[1])
[562]105                #print("B" +str(creature))
[563]106                if "FromIDs" in creature:
[572]107                    if not creature["ID"] in nodes:
108                        nodes[creature["ID"]] = {}
109                        # we assign to each parent its contribution to the genotype of the child
110                        for i in range(0, len(creature["FromIDs"])):
111                            inherited = 1 #(creature["Inherited"][i] if 'Inherited' in creature else 1) #ONLY FOR NOW
112                            nodes[creature["ID"]][creature["FromIDs"][i]] = inherited
113                    else:
114                        print("Doubled entry for " + creature["ID"])
115                        quit()
116
[563]117                    if not creature["FromIDs"][0] in nodes:
118                        firstnode = creature["FromIDs"][0]
[572]119
[566]120                if "Time" in creature:
121                    time[creature["ID"]] = creature["Time"]
[562]122
[577]123                if "Kind" in creature:
124                    kind[creature["ID"]] = creature["Kind"]
125
[562]126    for k, v in sorted(nodes.items()):
[572]127        for val in sorted(v):
128            inv_nodes[val] = inv_nodes.get(val, [])
129            inv_nodes[val].append(k)
[562]130
131
132def load_simple_data(dir):
133    global firstnode, nodes, inv_nodes
134    f = open(dir)
135    for line in f:
136        sline = line.split()
137        if len(sline) > 1:
138            #if int(sline[0]) > 15000:
139            #    break
140            if sline[0] == firstnode:
141                continue
142            nodes[sline[0]] = str(max(int(sline[1]), int(firstnode)))
143        else:
144            firstnode = sline[0]
145
146    for k, v in sorted(nodes.items()):
147        inv_nodes[v] = inv_nodes.get(v, [])
148        inv_nodes[v].append(k)
149
150    #print(str(inv_nodes))
151    #quit()
152
153def compute_depth(node):
154    my_depth = 0
155    if node in inv_nodes:
156        for c in inv_nodes[node]:
157            my_depth = max(my_depth, compute_depth(c)+1)
158    depth[node] = my_depth
159    return my_depth
160
161# ------------------------------------
162
163def xmin_crowd(x1, x2, y):
164    if BALANCE == "RANDOM":
165        return (x1 if random.randrange(2) == 0 else x2)
166    elif BALANCE == "MIN":
167        x1_closest = 999999
168        x2_closest = 999999
169        for pos in positions:
170            pos = positions[pos]
171            if pos[1] == y:
172                x1_closest = min(x1_closest, abs(x1-pos[0]))
173                x2_closest = min(x2_closest, abs(x2-pos[0]))
174        return (x1 if x1_closest > x2_closest else x2)
175    elif BALANCE == "DENSITY":
176        x1_dist = 0
177        x2_dist = 0
178        for pos in positions:
179            pos = positions[pos]
180            if pos[1] > y-10 or pos[1] < y+10:
181                dy = pos[1]-y
182                dx1 = pos[0]-x1
183                dx2 = pos[0]-x2
184
185                x1_dist += math.sqrt(dy**2 + dx1**2)
186                x2_dist += math.sqrt(dy**2 + dx2**2)
187        return (x1 if x1_dist > x2_dist else x2)
188
189# ------------------------------------
190
191def prepos_children_reccurent(node):
[572]192    global visited
[562]193    for c in inv_nodes[node]:
[572]194
195        # we want to visit the node just once, after all of its parents
196        if not all_parents_visited(c):
197            continue
[571]198        else:
[572]199            visited[c] = True
[571]200
[572]201        cy = 0
[566]202        if TIME == "BIRTHS":
[562]203            if c[0] == "c":
[572]204                cy = int(c[1:])
[562]205            else:
[572]206                cy = int(c)
[562]207        elif TIME == "GENERATIONAL":
[572]208            cy = positions[node][1]+1
[566]209        elif TIME == "REAL":
[572]210            cy = time[c]
[562]211
[572]212        if len(nodes[c]) == 1:
213            dissimilarity = 0
214            if JITTER == True:
215                dissimilarity = random.gauss(0,1)
216            else:
217                dissimilarity = 1
218            positions[c] = [xmin_crowd(positions[node][0]-dissimilarity, positions[node][0]+dissimilarity, cy), cy]
219        else:
220            vsum = sum([v for k, v in nodes[c].items()])
221            cx = sum([positions[k][0]*v/vsum for k, v in nodes[c].items()])
222
223            if JITTER == True:
224                positions[c] = [cx + random.gauss(0, 0.1), cy]
225            else:
226                positions[c] = [cx, cy]
227
228
[562]229        if c in inv_nodes:
230            prepos_children_reccurent(c)
231
232def prepos_children():
[572]233    global max_height, max_width, min_width, visited
[562]234
[566]235    if not bool(time):
236        print("REAL time requested, but no real time data provided. Assuming BIRTHS time instead.")
237        TIME = "BIRTHS"
238
[562]239    positions[firstnode] = [0, 0]
240
[572]241    visited = {}
242    visited[firstnode] = True
[562]243    prepos_children_reccurent(firstnode)
244
245    for pos in positions:
246        max_height = max(max_height, positions[pos][1])
247        max_width = max(max_width, positions[pos][0])
248        min_width = min(min_width, positions[pos][0])
249
250# ------------------------------------
251
[572]252def all_parents_visited(node):
253    apv = True
254    for k, v in sorted(nodes[node].items()):
255        if not k in visited:
256            apv = False
257            break
258    return apv
259# ------------------------------------
260
[562]261def draw_children_recurrent(node, max_depth):
[572]262    global visited
263
[562]264    for c in inv_nodes[node]:
[572]265
266        # we want to draw the node just once
267        if not all_parents_visited(c):
268            continue
269        else:
270            visited[c] = True
271
[562]272        if c in inv_nodes:
273            draw_children_recurrent(c, max_depth)
[564]274
[577]275        line_style = ""
276        if COLORING == "NONE":
277            line_style = svg_line_style
278        elif COLORING == "TYPE":
279            line_style = (svg_mutation_line_style if len(nodes[c]) == 1 else svg_crossover_line_style)
280        else: # IMPORTANCE, default
281            line_style = svg_generate_line_style(depth[c]/max_depth)
282
[572]283        for k, v in sorted(nodes[c].items()):
284            svg_add_line( (w_margin+w_no_margs*(positions[k][0]-min_width)/(max_width-min_width), h_margin+h_no_margs*positions[k][1]/max_height),
285                (w_margin+w_no_margs*(positions[c][0]-min_width)/(max_width-min_width), h_margin+h_no_margs*positions[c][1]/max_height), line_style)
[571]286
287        if DOT_STYLE == "NONE":
288            continue
[585]289        elif DOT_STYLE == "TYPE":
[577]290            dot_style = svg_generate_dot_style(kind[c] if c in kind else 0) #type
[571]291        else: # NORMAL, default
[577]292            dot_style = svg_clear_dot_style #svg_generate_dot_style(depth[c]/max_depth)
[564]293        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), dot_style)
[562]294def draw_children():
[572]295    global visited
296    visited = {}
297    visited[firstnode] = True
298
[562]299    max_depth = 0
300    for k, v in depth.items():
301            max_depth = max(max_depth, v)
302    draw_children_recurrent(firstnode, max_depth)
[571]303
304    if DOT_STYLE == "NONE":
305        return
[585]306    elif DOT_STYLE == "TYPE":
[577]307        dot_style = svg_generate_dot_style(kind[firstnode] if firstnode in kind else 0)
[571]308    else: # NORMAL, default
[577]309        dot_style = svg_clear_dot_style #svg_generate_dot_style(depth[c]/max_depth)
[564]310    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), dot_style)
[562]311
312def draw_spine_recurrent(node):
313    for c in inv_nodes[node]:
314        if depth[c] == depth[node] - 1:
315            if c in inv_nodes:
316                draw_spine_recurrent(c)
[564]317
318            line_style = svg_spine_line_style
[562]319            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),
[564]320                (w_margin+w_no_margs*(positions[c][0]-min_width)/(max_width-min_width), h_margin+h_no_margs*positions[c][1]/max_height), line_style)
[562]321            #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)
322def draw_spine():
323    draw_spine_recurrent(firstnode)
324    #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)
325
326def draw_skeleton_reccurent(node, max_depth):
327    for c in inv_nodes[node]:
328        if depth[c] >= min_skeleton_depth or depth[c] == max([depth[q] for q in inv_nodes[node]]):
329            if c in inv_nodes:
330                draw_skeleton_reccurent(c, max_depth)
[564]331
332            line_style = svg_spine_line_style
[562]333            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),
[564]334                (w_margin+w_no_margs*(positions[c][0]-min_width)/(max_width-min_width), h_margin+h_no_margs*positions[c][1]/max_height), line_style)
[562]335            #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),
336            #             svg_spine_dot_style)
337def draw_skeleton():
338    max_depth = 0
339    for k, v in depth.items():
340            max_depth = max(max_depth, v)
341
342    draw_skeleton_reccurent(firstnode, max_depth)
343    #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),
344    #             svg_spine_dot_style)
345
[576]346# ------------------------------------
[562]347
[576]348def draw_scale(filename ,type):
[562]349
[576]350    svg_add_text( "Generated from " + filename.split("\\")[-1], (5, 15), "start")
351
352    svg_add_line( (w*0.7, h_margin), (w, h_margin), svg_scale_line_style)
353    start_text = ""
354    if TIME == "BIRTHS":
355       start_text = "Birth #" + str(min([int(k[1:]) for k, v in nodes.items()]))
356    if TIME == "REAL":
357       start_text = "Time " + str(min([v for k, v in time.items()]))
358    if TIME == "GENERATIONAL":
359       start_text = "Depth " + str(min([v for k, v in depth.items()]))
360    svg_add_text( start_text, (w, h_margin + 15), "end")
361
362    svg_add_line( (w*0.7, h-h_margin), (w, h-h_margin), svg_scale_line_style)
363    end_text = ""
364    if TIME == "BIRTHS":
365       end_text = "Birth #" + str(max([int(k[1:]) for k, v in nodes.items()]))
366    if TIME == "REAL":
367       end_text = "Time " + str(max([v for k, v in time.items()]))
368    if TIME == "GENERATIONAL":
369       end_text = "Depth " + str(max([v for k, v in depth.items()]))
[577]370    svg_add_text( end_text, (w, h-h_margin + 15), "end")
[576]371
372
[562]373##################################################### main #####################################################
374
375args = 0
376
377h = 800
378w = 600
[576]379h_margin = 20
[562]380w_margin = 10
381h_no_margs = h - 2* h_margin
382w_no_margs = w - 2* w_margin
383
384max_height = 0
385max_width = 0
386min_width = 9999999999
387
388min_skeleton_depth = 0
389
390firstnode = ""
391nodes = {}
392inv_nodes = {}
393positions = {}
[572]394visited= {}
[562]395depth = {}
[566]396time = {}
[577]397kind = {}
[562]398
399def main():
[585]400    global svg_file, min_skeleton_depth, args, \
401        TIME, BALANCE, DOT_STYLE, COLORING, JITTER, \
402        svg_mutation_line_style, svg_crossover_line_style
[562]403
404    parser = argparse.ArgumentParser(description='Process some integers.')
[576]405    parser.add_argument('-i', '--in', dest='input', required=True, help='input file with stuctured evolutionary data')
406    parser.add_argument('-o', '--out', dest='output', required=True, help='output file for the evolutionary tree')
[562]407    draw_tree_parser = parser.add_mutually_exclusive_group(required=False)
408    draw_tree_parser.add_argument('--draw-tree', dest='draw_tree', action='store_true', help='whether drawing the full tree should be skipped')
409    draw_tree_parser.add_argument('--no-draw-tree', dest='draw_tree', action='store_false')
410
411    draw_skeleton_parser = parser.add_mutually_exclusive_group(required=False)
412    draw_skeleton_parser.add_argument('--draw-skeleton', dest='draw_skeleton', action='store_true', help='whether the skeleton of the tree should be drawn')
413    draw_skeleton_parser.add_argument('--no-draw-skeleton', dest='draw_skeleton', action='store_false')
414
415    draw_spine_parser = parser.add_mutually_exclusive_group(required=False)
416    draw_spine_parser.add_argument('--draw-spine', dest='draw_spine', action='store_true', help='whether the spine of the tree should be drawn')
417    draw_spine_parser.add_argument('--no-draw-spine', dest='draw_spine', action='store_false')
418
419    #TODO: better names for those parameters
[585]420    parser.add_argument('-t', '--time', default='GENERATIONAL', dest='time', help='values on vertical axis (BIRTHS/GENERATIONAL/REAL); '
[571]421                                                                      'BIRTHS: time measured as the number of births since the beggining; '
422                                                                      'GENERATIONAL: time measured as number of ancestors; '
423                                                                      'REAL: real time of the simulation')
[585]424    parser.add_argument('-b', '--balance', default='DENSITY', dest='balance', help='method of placing node in the tree (RANDOM/MIN/DENSITY)')
[577]425    parser.add_argument('-s', '--scale', default='NONE', dest='scale', help='type of timescale added to the tree (NONE/SIMPLE)')
426    parser.add_argument('-c', '--coloring', default='IMPORTANCE', dest="coloring", help='method of coloring the tree (NONE/IMPORTANCE/TYPE)')
[585]427    parser.add_argument('-d', '--dots', default='TYPE', dest='dots', help='method of drawing dots (individuals) (NONE/NORMAL/TYPE)')
[571]428    parser.add_argument('-j', '--jitter', dest="jitter", action='store_true', help='draw horizontal positions of children from the normal distribution')
429
[585]430    parser.add_argument('--color-mut', default="#000000", dest="color_mut", help='color of clone/mutation lines in rgba (e.g. #FF60B240) for TYPE coloring')
431    parser.add_argument('--color-cross', default="#660198", dest="color_cross", help='color of crossover lines in rgba (e.g. #FF60B240) for TYPE coloring')
432
[562]433    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')
434    parser.add_argument('--seed', type=int, dest='seed', help='seed for the random number generator (-1 for random)')
435
436    parser.add_argument('--simple-data', type=bool, dest='simple_data', help='input data are given in a simple format (#child #parent)')
437
438    parser.set_defaults(draw_tree=True)
439    parser.set_defaults(draw_skeleton=False)
440    parser.set_defaults(draw_spine=False)
441
442    parser.set_defaults(seed=-1)
443
444    args = parser.parse_args()
445
446    TIME = args.time
447    BALANCE = args.balance
[571]448    DOT_STYLE = args.dots
[577]449    COLORING = args.coloring
[571]450    JITTER = args.jitter
[562]451
[585]452    svg_mutation_line_style += hex_to_style(args.color_mut)
453    svg_crossover_line_style += hex_to_style(args.color_cross)
454
[562]455    dir = args.input
456    min_skeleton_depth = args.min_skeleton_depth
457    seed = args.seed
458    if seed == -1:
459        seed = random.randint(0, 10000)
460    random.seed(seed)
461    print("seed:", seed)
462
463    if args.simple_data:
464        load_simple_data(dir)
465    else:
466        load_data(dir)
467
468    compute_depth(firstnode)
469
470    svg_file = open(args.output, "w")
471    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" '
472                   'width="' + str(w) + '" height="' + str(h) + '">')
473
474    prepos_children()
475
476    if args.draw_tree:
477        draw_children()
478    if args.draw_skeleton:
479        draw_skeleton()
480    if args.draw_spine:
481        draw_spine()
482
[576]483    draw_scale(dir, args.scale)
484
[562]485    svg_file.write("</svg>")
486    svg_file.close()
487
488main()
489
Note: See TracBrowser for help on using the repository browser.