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

Last change on this file since 626 was 626, checked in by konrad, 7 years ago

Added multisampling (antialiasing) option for raster output

File size: 29.9 KB
Line 
1import json
2import math
3import random
4import argparse
5import bisect
6import time as timelib
7from PIL import Image, ImageDraw, ImageFont
8
9class LoadingError(Exception):
10    pass
11
12class Drawer:
13
14    def __init__(self, design, config_file, w=600, h=800, w_margin=10, h_margin=20):
15        self.design = design
16        self.width = w
17        self.height = h
18        self.w_margin = w_margin
19        self.h_margin = h_margin
20        self.w_no_margs = w - 2* w_margin
21        self.h_no_margs = h - 2* h_margin
22
23        self.colors = {
24            'black' :   {'r':0,     'g':0,      'b':0},
25            'red' :     {'r':100,   'g':0,      'b':0},
26            'green' :   {'r':0,     'g':100,    'b':0},
27            'blue' :    {'r':0,     'g':0,      'b':100},
28            'yellow' :  {'r':100,   'g':100,    'b':0},
29            'magenta' : {'r':100,   'g':0,      'b':100},
30            'cyan' :    {'r':0,     'g':100,    'b':100},
31            'orange':   {'r':100,   'g':50,     'b':0},
32            'purple':   {'r':50,    'g':0,      'b':100}
33        }
34
35        self.settings = {
36            'colors_of_kinds': ['red', 'green', 'blue', 'magenta', 'yellow', 'cyan', 'orange', 'purple'],
37            'dots': {
38                'color': {
39                    'meaning': 'depth',
40                    'start': 'purple',
41                    'end': 'green',
42                    'bias': 1
43                    },
44                'size': {
45                    'meaning': 'children',
46                    'start': 1,
47                    'end': 5,
48                    'bias': 0.5
49                    },
50                'opacity': {
51                    'meaning': 'children',
52                    'start': 0.3,
53                    'end': 0.8,
54                    'bias': 1
55                    }
56            },
57            'lines': {
58                'color': {
59                    'meaning': 'adepth',
60                    'start': 'black',
61                    'end': 'red',
62                    'bias': 3
63                    },
64                'width': {
65                    'meaning': 'adepth',
66                    'start': 1,
67                    'end': 4,
68                    'bias': 3
69                    },
70                'opacity': {
71                    'meaning': 'adepth',
72                    'start': 0.1,
73                    'end': 0.8,
74                    'bias': 5
75                    }
76            }
77        }
78
79        def merge(source, destination):
80            for key, value in source.items():
81                if isinstance(value, dict):
82                    node = destination.setdefault(key, {})
83                    merge(value, node)
84                else:
85                    destination[key] = value
86
87            return destination
88
89        if config_file != "":
90            with open(config_file) as config:
91                c = json.load(config)
92            self.settings = merge(c, self.settings)
93            #print(json.dumps(self.settings, indent=4, sort_keys=True))
94
95    def draw_dots(self, file, min_width, max_width, max_height):
96        for i in range(len(self.design.positions)):
97            node = self.design.positions[i]
98            if 'x' not in node:
99                continue
100            dot_style = self.compute_dot_style(node=i)
101            self.add_dot(file, (self.w_margin+self.w_no_margs*(node['x']-min_width)/(max_width-min_width),
102                               self.h_margin+self.h_no_margs*node['y']/max_height), dot_style)
103
104    def draw_lines(self, file, min_width, max_width, max_height):
105        for parent in range(len(self.design.positions)):
106            par_pos = self.design.positions[parent]
107            if not 'x' in par_pos:
108                continue
109            for child in self.design.tree.children[parent]:
110                chi_pos = self.design.positions[child]
111                if 'x' not in chi_pos:
112                    continue
113                line_style = self.compute_line_style(parent, child)
114                self.add_line(file, (self.w_margin+self.w_no_margs*(par_pos['x']-min_width)/(max_width-min_width),
115                                  self.h_margin+self.h_no_margs*par_pos['y']/max_height),
116                                  (self.w_margin+self.w_no_margs*(chi_pos['x']-min_width)/(max_width-min_width),
117                                  self.h_margin+self.h_no_margs*chi_pos['y']/max_height), line_style)
118
119    def draw_scale(self, file, filename):
120        self.add_text(file, "Generated from " + filename.split("\\")[-1], (5, 5), "start")
121
122        start_text = ""
123        end_text = ""
124        if self.design.TIME == "BIRTHS":
125           start_text = "Birth #0"
126           end_text = "Birth #" + str(len(self.design.positions)-1)
127        if self.design.TIME == "REAL":
128           start_text = "Time " + str(min(self.design.tree.time))
129           end_text = "Time " + str(max(self.design.tree.time))
130        if self.design.TIME == "GENERATIONAL":
131           start_text = "Depth " + str(self.design.props['adepth']['min'])
132           end_text = "Depth " + str(self.design.props['adepth']['max'])
133
134        self.add_dashed_line(file, (self.width*0.7, self.h_margin), (self.width, self.h_margin))
135        self.add_text(file, start_text, (self.width, self.h_margin), "end")
136        self.add_dashed_line(file, (self.width*0.7, self.height-self.h_margin), (self.width, self.height-self.h_margin))
137        self.add_text(file, end_text, (self.width, self.height-self.h_margin), "end")
138
139    def compute_property(self, part, prop, node):
140        start = self.settings[part][prop]['start']
141        end = self.settings[part][prop]['end']
142        value = (self.design.props[self.settings[part][prop]['meaning']][node]
143                 if self.settings[part][prop]['meaning'] in self.design.props else 0 )
144        bias = self.settings[part][prop]['bias']
145        if prop == "color":
146            return self.compute_color(start, end, value, bias)
147        else:
148            return self.compute_value(start, end, value, bias)
149
150    def compute_color(self, start, end, value, bias=1):
151        if isinstance(value, str):
152            value = int(value)
153            r = self.colors[self.settings['colors_of_kinds'][value]]['r']
154            g = self.colors[self.settings['colors_of_kinds'][value]]['g']
155            b = self.colors[self.settings['colors_of_kinds'][value]]['b']
156        else:
157            start_color = self.colors[start]
158            end_color = self.colors[end]
159            value = 1 - (1-value)**bias
160            r = start_color['r']*(1-value)+end_color['r']*value
161            g = start_color['g']*(1-value)+end_color['g']*value
162            b = start_color['b']*(1-value)+end_color['b']*value
163        return (r, g, b)
164
165    def compute_value(self, start, end, value, bias=1):
166        value = 1 - (1-value)**bias
167        return start*(1-value) + end*value
168
169class PngDrawer(Drawer):
170
171    def scale_up(self):
172        self.width *= self.multi
173        self.height *= self.multi
174        self.w_margin *= self.multi
175        self.h_margin *= self.multi
176        self.h_no_margs *= self.multi
177        self.w_no_margs *= self.multi
178
179    def scale_down(self):
180        self.width /= self.multi
181        self.height /= self.multi
182        self.w_margin /= self.multi
183        self.h_margin /= self.multi
184        self.h_no_margs /= self.multi
185        self.w_no_margs /= self.multi
186
187    def draw_design(self, filename, input_filename, multi=1, scale="SIMPLE"):
188        print("Drawing...")
189
190        self.multi=multi
191        self.scale_up()
192
193        back = Image.new('RGBA', (self.width, self.height), (255,255,255,0))
194
195        min_width = min([x['x'] for x in self.design.positions if 'x' in x])
196        max_width = max([x['x'] for x in self.design.positions if 'x' in x])
197        max_height = max([x['y'] for x in self.design.positions if 'y' in x])
198
199        self.draw_lines(back, min_width, max_width, max_height)
200        self.draw_dots(back, min_width, max_width, max_height)
201
202        if scale == "SIMPLE":
203            self.draw_scale(back, input_filename)
204
205        #back.show()
206        self.scale_down()
207
208        back.thumbnail((self.width, self.height), Image.ANTIALIAS)
209
210        back.save(filename)
211
212    def add_dot(self, file, pos, style):
213        x, y = int(pos[0]), int(pos[1])
214        r = style['r']*self.multi
215        offset = (int(x - r), int(y - r))
216        size = (2*int(r), 2*int(r))
217
218        c = style['color']
219
220        img = Image.new('RGBA', size)
221        ImageDraw.Draw(img).ellipse((1, 1, size[0]-1, size[1]-1),
222                                    (int(2.55*c[0]), int(2.55*c[1]), int(2.55*c[2]), int(255*style['opacity'])))
223        file.paste(img, offset, mask=img)
224
225    def add_line(self, file, from_pos, to_pos, style):
226        fx, fy, tx, ty = int(from_pos[0]), int(from_pos[1]), int(to_pos[0]), int(to_pos[1])
227        w = int(style['width'])*self.multi
228
229        offset = (min(fx-w, tx-w), min(fy-w, ty-w))
230        size = (abs(fx-tx)+2*w, abs(fy-ty)+2*w)
231
232        c = style['color']
233
234        img = Image.new('RGBA', size)
235        ImageDraw.Draw(img).line((w, w, size[0]-w, size[1]-w) if (fx-tx)*(fy-ty)>0 else (size[0]-w, w, w, size[1]-w),
236                                  (int(2.55*c[0]), int(2.55*c[1]), int(2.55*c[2]), int(255*style['opacity'])), w)
237        file.paste(img, offset, mask=img)
238
239    def add_dashed_line(self, file, from_pos, to_pos):
240        style = {'color': (0,0,0), 'width': 1, 'opacity': 1}
241        sublines = 50
242        # TODO could be faster: compute delta and only add delta each time (but currently we do not use it often)
243        for i in range(sublines):
244            from_pos_sub = (self.compute_value(from_pos[0], to_pos[0], 2*i/(2*sublines-1), 1),
245                            self.compute_value(from_pos[1], to_pos[1], 2*i/(2*sublines-1), 1))
246            to_pos_sub = (self.compute_value(from_pos[0], to_pos[0], (2*i+1)/(2*sublines-1), 1),
247                          self.compute_value(from_pos[1], to_pos[1], (2*i+1)/(2*sublines-1), 1))
248            self.add_line(file, from_pos_sub, to_pos_sub, style)
249
250    def add_text(self, file, text, pos, anchor, style=''):
251        font = ImageFont.truetype("Vera.ttf", 16*self.multi)
252
253        img = Image.new('RGBA', (self.width, self.height))
254        draw = ImageDraw.Draw(img)
255        txtsize = draw.textsize(text, font=font)
256        pos = pos if anchor == "start" else (pos[0]-txtsize[0], pos[1])
257        draw.text(pos, text, (0,0,0), font=font)
258        file.paste(img, (0,0), mask=img)
259
260    def compute_line_style(self, parent, child):
261        return {'color': self.compute_property('lines', 'color', child),
262                'width': self.compute_property('lines', 'width', child),
263                'opacity': self.compute_property('lines', 'opacity', child)}
264
265    def compute_dot_style(self, node):
266        return {'color': self.compute_property('dots', 'color', node),
267                'r': self.compute_property('dots', 'size', node),
268                'opacity': self.compute_property('dots', 'opacity', node)}
269
270class SvgDrawer(Drawer):
271    def draw_design(self, filename, input_filename, multi=1, scale="SIMPLE"):
272        print("Drawing...")
273        file = open(filename, "w")
274
275        min_width = min([x['x'] for x in self.design.positions if 'x' in x])
276        max_width = max([x['x'] for x in self.design.positions if 'x' in x])
277        max_height = max([x['y'] for x in self.design.positions if 'y' in x])
278
279        file.write('<svg xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" '
280                   'xmlns:xlink="http://www.w3.org/1999/xlink" version="1.0" '
281                   'width="' + str(self.width) + '" height="' + str(self.height) + '">')
282
283        self.draw_lines(file, min_width, max_width, max_height)
284        self.draw_dots(file, min_width, max_width, max_height)
285
286        if scale == "SIMPLE":
287            self.draw_scale(file, input_filename)
288
289        file.write("</svg>")
290        file.close()
291
292    def add_text(self, file, text, pos, anchor, style=''):
293        style = (style if style != '' else 'style="font-family: Arial; font-size: 12; fill: #000000;"')
294        file.write('<text ' + style + ' text-anchor="' + anchor + '" x="' + str(pos[0]) + '" y="' + str(pos[1]) + '" >' + text + '</text>')
295
296    def add_dot(self, file, pos, style):
297        file.write('<circle ' + style + ' cx="' + str(pos[0]) + '" cy="' + str(pos[1]) + '" />')
298
299    def add_line(self, file, from_pos, to_pos, style):
300        file.write('<line ' + style + ' x1="' + str(from_pos[0]) + '" x2="' + str(to_pos[0]) +
301                       '" y1="' + str(from_pos[1]) + '" y2="' + str(to_pos[1]) + '"  fill="none"/>')
302
303    def add_dashed_line(self, file, from_pos, to_pos):
304        style = 'stroke="black" stroke-width="0.5" stroke-opacity="1" stroke-dasharray="5, 5"'
305        self.add_line(file, from_pos, to_pos, style)
306
307    def compute_line_style(self, parent, child):
308        return self.compute_stroke_color('lines', child) + ' ' \
309               + self.compute_stroke_width('lines', child) + ' ' \
310               + self.compute_stroke_opacity(child)
311
312    def compute_dot_style(self, node):
313        return self.compute_dot_size(node) + ' ' \
314               + self.compute_fill_opacity(node) + ' ' \
315               + self.compute_dot_fill(node)
316
317    def compute_stroke_color(self, part, node):
318        color = self.compute_property(part, 'color', node)
319        return 'stroke="rgb(' + str(color[0]) + '%,' + str(color[1]) + '%,' + str(color[2]) + '%)"'
320
321    def compute_stroke_width(self, part, node):
322        return 'stroke-width="' + str(self.compute_property(part, 'width', node)) + '"'
323
324    def compute_stroke_opacity(self, node):
325        return 'stroke-opacity="' + str(self.compute_property('lines', 'opacity', node)) + '"'
326
327    def compute_fill_opacity(self, node):
328        return 'fill-opacity="' + str(self.compute_property('dots', 'opacity', node)) + '"'
329
330    def compute_dot_size(self, node):
331        return 'r="' + str(self.compute_property('dots', 'size', node)) + '"'
332
333    def compute_dot_fill(self, node):
334        color = self.compute_property('dots', 'color', node)
335        return 'fill="rgb(' + str(color[0]) + '%,' + str(color[1]) + '%,' + str(color[2]) + '%)"'
336
337class Designer:
338
339    def __init__(self, tree, jitter=False, time="GENERATIONAL", balance="DENSITY"):
340        self.props = {}
341
342        self.tree = tree
343
344        self.TIME = time
345        self.JITTER = jitter
346
347        if balance == "RANDOM":
348            self.xmin_crowd = self.xmin_crowd_random
349        elif balance == "MIN":
350            self.xmin_crowd = self.xmin_crowd_min
351        elif balance == "DENSITY":
352            self.xmin_crowd = self.xmin_crowd_density
353        else:
354            raise ValueError("Error, the value of BALANCE does not match any expected value.")
355
356    def calculate_measures(self):
357        print("Calculating measures...")
358        self.compute_adepth()
359        self.compute_depth()
360        self.compute_children()
361        self.compute_kind()
362        self.compute_time()
363        self.compute_custom()
364
365    def xmin_crowd_random(self, x1, x2, y):
366        return (x1 if random.randrange(2) == 0 else x2)
367
368    def xmin_crowd_min(self, x1, x2, y):
369        x1_closest = 999999
370        x2_closest = 999999
371        miny = y-3
372        maxy = y+3
373        i = bisect.bisect_left(self.y_sorted, miny)
374        while True:
375            if len(self.positions_sorted) <= i or self.positions_sorted[i]['y'] > maxy:
376                break
377            pos = self.positions_sorted[i]
378
379            x1_closest = min(x1_closest, abs(x1-pos['x']))
380            x2_closest = min(x2_closest, abs(x2-pos['x']))
381
382            i += 1
383        return (x1 if x1_closest > x2_closest else x2)
384
385    def xmin_crowd_density(self, x1, x2, y):
386        x1_dist = 0
387        x2_dist = 0
388        miny = y-500
389        maxy = y+500
390        i_left = bisect.bisect_left(self.y_sorted, miny)
391        i_right = bisect.bisect_right(self.y_sorted, maxy)
392        # print("i " + str(i) + " len " + str(len(self.positions)))
393        #
394        # i = bisect.bisect_left(self.y_sorted, y)
395        # i_left = max(0, i - 25)
396        # i_right = min(len(self.y_sorted), i + 25)
397
398        def include_pos(pos):
399            nonlocal x1_dist, x2_dist
400
401            dysq = (pos['y']-y)**2
402            dx1 = pos['x']-x1
403            dx2 = pos['x']-x2
404
405            x1_dist += math.sqrt(dysq + dx1**2)
406            x2_dist += math.sqrt(dysq + dx2**2)
407
408        # optimized to draw from all the nodes, if less than 10 nodes in the range
409        if len(self.positions_sorted) > i_left:
410            if i_right - i_left < 10:
411                for j in range(i_left, i_right):
412                    include_pos(self.positions_sorted[j])
413            else:
414                for j in range(10):
415                    pos = self.positions_sorted[random.randrange(i_left, i_right)]
416                    include_pos(pos)
417
418        return (x1 if x1_dist > x2_dist else x2)
419        #print(x1_dist, x2_dist)
420        #x1_dist = x1_dist**2
421        #x2_dist = x2_dist**2
422        #return x1 if x1_dist+x2_dist==0 else (x1*x1_dist + x2*x2_dist) / (x1_dist+x2_dist) + random.gauss(0, 0.01)
423        #return (x1 if random.randint(0, int(x1_dist+x2_dist)) < x1_dist else x2)
424
425    def calculate_node_positions(self, ignore_last=0):
426        print("Calculating positions...")
427
428        current_node = 0
429
430        def add_node(node):
431            nonlocal current_node
432            index = bisect.bisect_left(self.y_sorted, node['y'])
433            self.y_sorted.insert(index, node['y'])
434            self.positions_sorted.insert(index, node)
435            self.positions[node['id']] = node
436
437        self.positions_sorted = [{'x':0, 'y':0, 'id':0}]
438        self.y_sorted = [0]
439        self.positions = [{} for x in range(len(self.tree.parents))]
440        self.positions[0] = {'x':0, 'y':0, 'id':0}
441
442        nodes_to_visit = [0]
443        visited = [False] * len(self.tree.parents)
444        visited[0] = True
445
446        node_counter = 0
447        start_time = timelib.time()
448
449        while True:
450
451            node_counter += 1
452            if node_counter%1000 == 0:
453                print(str(node_counter) + " " + str(timelib.time()-start_time))
454                start_time = timelib.time()
455
456            current_node = nodes_to_visit[0]
457
458            for child in self.tree.children[current_node]:
459                if not visited[child] and self.props['adepth'][child] >= ignore_last/self.props['adepth_max']:
460                    nodes_to_visit.append(child)
461                    visited[child] = True
462
463                    ypos = 0
464                    if self.TIME == "BIRTHS":
465                        ypos = child
466                    elif self.TIME == "GENERATIONAL":
467                        ypos = self.positions[current_node]['y']+1
468                    elif self.TIME == "REAL":
469                        ypos = self.tree.time[child]
470
471                    if len(self.tree.parents[child]) == 1:
472                    # if current_node is the only parent
473                        if self.JITTER:
474                            dissimilarity = random.gauss(0, 0.5)
475                        else:
476                            dissimilarity = 1
477                        add_node({'id':child, 'y':ypos, 'x':
478                                 self.xmin_crowd(self.positions[current_node]['x']-dissimilarity,
479                                  self.positions[current_node]['x']+dissimilarity, ypos)})
480                    else:
481                        total_inheretance = sum([v for k, v in self.tree.parents[child].items()])
482                        xpos = sum([self.positions[k]['x']*v/total_inheretance
483                                   for k, v in self.tree.parents[child].items()])
484                        if self.JITTER:
485                            add_node({'id':child, 'y':ypos, 'x':xpos + random.gauss(0, 0.1)})
486                        else:
487                            add_node({'id':child, 'y':ypos, 'x':xpos})
488
489            nodes_to_visit = nodes_to_visit[1:]
490            # if none left, we can stop
491            if len(nodes_to_visit) == 0:
492                print("done")
493                break
494
495    def compute_custom(self):
496        for prop in self.tree.props:
497            self.props[prop] = [None for x in range(len(self.tree.children))]
498
499            for i in range(len(self.props[prop])):
500                self.props[prop][i] = self.tree.props[prop][i]
501
502            self.normalize_prop(prop)
503
504    def compute_time(self):
505        # simple rewrite from the tree
506        self.props["time"] = [0 for x in range(len(self.tree.children))]
507
508        for i in range(len(self.props['time'])):
509            self.props['time'][i] = self.tree.time[i]
510
511        self.normalize_prop('time')
512
513    def compute_kind(self):
514        # simple rewrite from the tree
515        self.props["kind"] = [0 for x in range(len(self.tree.children))]
516
517        for i in range (len(self.props['kind'])):
518            self.props['kind'][i] = str(self.tree.kind[i])
519
520    def compute_depth(self):
521        self.props["depth"] = [999999999 for x in range(len(self.tree.children))]
522
523        nodes_to_visit = [0]
524        self.props["depth"][0] = 0
525        while True:
526            for child in self.tree.children[nodes_to_visit[0]]:
527                nodes_to_visit.append(child)
528                self.props["depth"][child] = min([self.props["depth"][d] for d in self.tree.parents[child]])+1
529            nodes_to_visit = nodes_to_visit[1:]
530            if len(nodes_to_visit) == 0:
531                break
532
533        self.normalize_prop('depth')
534
535    def compute_adepth(self):
536        self.props["adepth"] = [0 for x in range(len(self.tree.children))]
537
538        def compute_local_adepth(node):
539            my_adepth = 0
540            for c in self.tree.children[node]:
541                my_adepth = max(my_adepth, compute_local_adepth(c)+1)
542            self.props["adepth"][node] = my_adepth
543            return my_adepth
544
545        compute_local_adepth(0)
546        self.normalize_prop('adepth')
547
548    def compute_children(self):
549        self.props["children"] = [0 for x in range(len(self.tree.children))]
550        for i in range (len(self.props['children'])):
551            self.props['children'][i] = len(self.tree.children[i])
552
553        self.normalize_prop('children')
554
555    def normalize_prop(self, prop):
556        noneless = [v for v in self.props[prop] if type(v)==int or type(v)==float]
557        if len(noneless) > 0:
558            max_val = max(noneless)
559            min_val = min(noneless)
560            self.props[prop +'_max'] = max_val
561            self.props[prop +'_min'] = min_val
562            for i in range(len(self.props[prop])):
563                if self.props[prop][i] is not None:
564                    self.props[prop][i] = (self.props[prop][i] - min_val) / max_val
565
566
567class TreeData:
568    simple_data = None
569
570    children = []
571    parents = []
572    time = []
573    kind = []
574
575    def __init__(self): #, simple_data=False):
576        #self.simple_data = simple_data
577        pass
578
579    def load(self, filename, max_nodes=0):
580        print("Loading...")
581
582        CLI_PREFIX = "Script.Message:"
583        default_props = ["Time", "FromIDs", "ID", "Operation", "Inherited"]
584
585        ids = {}
586        def get_id(id):
587            if not id in ids:
588                ids[id] = len(ids)
589            return ids[id]
590
591        file = open(filename)
592
593        # counting the number of expected nodes
594        nodes = 0
595        for line in file:
596            line_arr = line.split(' ', 1)
597            if len(line_arr) == 2:
598                if line_arr[0] == CLI_PREFIX:
599                    line_arr = line_arr[1].split(' ', 1)
600                if line_arr[0] == "[OFFSPRING]":
601                    nodes += 1
602
603        nodes = min(nodes, max_nodes if max_nodes != 0 else nodes)+1
604        self.parents = [{} for x in range(nodes)]
605        self.children = [[] for x in range(nodes)]
606        self.time = [0] * nodes
607        self.kind = [0] * nodes
608        self.props = {}
609
610        print(len(self.parents))
611
612        file.seek(0)
613        loaded_so_far = 0
614        lasttime = timelib.time()
615        for line in file:
616            line_arr = line.split(' ', 1)
617            if len(line_arr) == 2:
618                if line_arr[0] == CLI_PREFIX:
619                    line_arr = line_arr[1].split(' ', 1)
620                if line_arr[0] == "[OFFSPRING]":
621                    creature = json.loads(line_arr[1])
622                    if "FromIDs" in creature:
623
624                        # make sure that ID's of parents are lower than that of their children
625                        for i in range(0, len(creature["FromIDs"])):
626                            get_id(creature["FromIDs"][i])
627
628                        creature_id = get_id(creature["ID"])
629
630                        # debug
631                        if loaded_so_far%1000 == 0:
632                            #print(". " + str(creature_id) + " " + str(timelib.time() - lasttime))
633                            lasttime = timelib.time()
634
635                        # we assign to each parent its contribution to the genotype of the child
636                        for i in range(0, len(creature["FromIDs"])):
637                            parent_id = get_id(creature["FromIDs"][i])
638                            inherited = 1 #(creature["Inherited"][i] if 'Inherited' in creature else 1) #ONLY FOR NOW
639                            self.parents[creature_id][parent_id] = inherited
640
641                        if "Time" in creature:
642                            self.time[creature_id] = creature["Time"]
643
644                        if "Kind" in creature:
645                            self.kind[creature_id] = creature["Kind"]
646
647                        for prop in creature:
648                            if prop not in default_props:
649                                if prop not in self.props:
650                                    self.props[prop] = [None for i in range(nodes)]
651                                self.props[prop][creature_id] = creature[prop]
652
653                        loaded_so_far += 1
654                    else:
655                        raise LoadingError("[OFFSPRING] misses the 'FromIDs' field!")
656
657            if loaded_so_far >= max_nodes and max_nodes != 0:
658                break
659
660        for k in range(len(self.parents)):
661            v = self.parents[k]
662            for val in self.parents[k]:
663                self.children[val].append(k)
664
665depth = {}
666kind = {}
667
668def main():
669
670    parser = argparse.ArgumentParser(description='Draws a genealogical tree (generates a SVG file) based on parent-child relationship '
671                                                 'information from a text file. Supports files generated by Framsticks experiments.')
672    parser.add_argument('-i', '--in', dest='input', required=True, help='input file name with stuctured evolutionary data')
673    parser.add_argument('-o', '--out', dest='output', required=True, help='output file name for the evolutionary tree (SVG/PNG/JPG/BMP)')
674    parser.add_argument('-c', '--config', dest='config', default="", help='config file name ')
675
676    parser.add_argument('-W', '--width', default=600, type=int, dest='width', help='width of the output image (600 by default)')
677    parser.add_argument('-H', '--height', default=800, type=int, dest='height', help='height of the output image (800 by default)')
678    parser.add_argument('-m', '--multi', default=1, type=int, dest='multi', help='multisampling factor (applicable only for raster images)')
679
680    parser.add_argument('-t', '--time', default='GENERATIONAL', dest='time', help='values on vertical axis (BIRTHS/GENERATIONAL(d)/REAL); '
681                                                                      'BIRTHS: time measured as the number of births since the beginning; '
682                                                                      'GENERATIONAL: time measured as number of ancestors; '
683                                                                      'REAL: real time of the simulation')
684    parser.add_argument('-b', '--balance', default='DENSITY', dest='balance', help='method of placing nodes in the tree (RANDOM/MIN/DENSITY(d))')
685    parser.add_argument('-s', '--scale', default='SIMPLE', dest='scale', help='type of timescale added to the tree (NONE(d)/SIMPLE)')
686    parser.add_argument('-j', '--jitter', dest="jitter", action='store_true', help='draw horizontal positions of children from the normal distribution')
687    parser.add_argument('-p', '--skip', dest="skip", type=int, default=0, help='skip last P levels of the tree (0 by default)')
688    parser.add_argument('-x', '--max-nodes', type=int, default=0, dest='max_nodes', help='maximum number of nodes drawn (starting from the first one)')
689    parser.add_argument('--seed', type=int, dest='seed', help='seed for the random number generator (-1 for random)')
690
691    parser.set_defaults(draw_tree=True)
692    parser.set_defaults(draw_skeleton=False)
693    parser.set_defaults(draw_spine=False)
694
695    parser.set_defaults(seed=-1)
696
697    args = parser.parse_args()
698
699    TIME = args.time.upper()
700    BALANCE = args.balance.upper()
701    SCALE = args.scale.upper()
702    JITTER = args.jitter
703    if not TIME in ['BIRTHS', 'GENERATIONAL', 'REAL']\
704        or not BALANCE in ['RANDOM', 'MIN', 'DENSITY']\
705        or not SCALE in ['NONE', 'SIMPLE']:
706        print("Incorrect value of one of the parameters! Closing the program.") #TODO don't be lazy, figure out which parameter is wrong...
707        return
708
709    dir = args.input
710    seed = args.seed
711    if seed == -1:
712        seed = random.randint(0, 10000)
713    random.seed(seed)
714    print("seed:", seed)
715
716    tree = TreeData()
717    tree.load(dir, max_nodes=args.max_nodes)
718
719    designer = Designer(tree, jitter=JITTER, time=TIME, balance=BALANCE)
720    designer.calculate_measures()
721    designer.calculate_node_positions(ignore_last=args.skip)
722
723    if args.output.endswith(".svg"):
724        drawer = SvgDrawer(designer, args.config, w=args.width, h=args.height)
725    else:
726        drawer = PngDrawer(designer, args.config, w=args.width, h=args.height)
727    drawer.draw_design(args.output, args.input, multi=args.multi, scale=SCALE)
728
729
730main()
Note: See TracBrowser for help on using the repository browser.