[562] | 1 | import json
|
---|
[624] | 2 | import math
|
---|
[562] | 3 | import random
|
---|
| 4 | import argparse
|
---|
[624] | 5 | import bisect
|
---|
| 6 | import time as timelib
|
---|
| 7 | from PIL import Image, ImageDraw, ImageFont
|
---|
[562] | 8 |
|
---|
[624] | 9 | class LoadingError(Exception):
|
---|
| 10 | pass
|
---|
[562] | 11 |
|
---|
[624] | 12 | class Drawer:
|
---|
[571] | 13 |
|
---|
[624] | 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
|
---|
[571] | 22 |
|
---|
[624] | 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 | }
|
---|
[562] | 34 |
|
---|
[624] | 35 | self.settings = {
|
---|
| 36 | 'colors_of_kinds': ['red', 'green', 'blue', 'magenta', 'yellow', 'cyan', 'orange', 'purple'],
|
---|
| 37 | 'dots': {
|
---|
| 38 | 'color': {
|
---|
[628] | 39 | 'meaning': 'Lifespan',
|
---|
| 40 | 'start': 'red',
|
---|
[624] | 41 | 'end': 'green',
|
---|
| 42 | 'bias': 1
|
---|
| 43 | },
|
---|
| 44 | 'size': {
|
---|
[628] | 45 | 'meaning': 'EnergyEaten',
|
---|
[624] | 46 | 'start': 1,
|
---|
[628] | 47 | 'end': 6,
|
---|
[624] | 48 | 'bias': 0.5
|
---|
| 49 | },
|
---|
| 50 | 'opacity': {
|
---|
[628] | 51 | 'meaning': 'EnergyEaten',
|
---|
| 52 | 'start': 0.2,
|
---|
| 53 | 'end': 1,
|
---|
[624] | 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',
|
---|
[627] | 66 | 'start': 0.1,
|
---|
[624] | 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 | }
|
---|
[577] | 78 |
|
---|
[624] | 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
|
---|
[562] | 86 |
|
---|
[624] | 87 | return destination
|
---|
[576] | 88 |
|
---|
[624] | 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))
|
---|
[586] | 94 |
|
---|
[624] | 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)
|
---|
[585] | 103 |
|
---|
[624] | 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)
|
---|
[585] | 118 |
|
---|
[624] | 119 | def draw_scale(self, file, filename):
|
---|
[626] | 120 | self.add_text(file, "Generated from " + filename.split("\\")[-1], (5, 5), "start")
|
---|
[562] | 121 |
|
---|
[624] | 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'])
|
---|
[576] | 133 |
|
---|
[626] | 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")
|
---|
[624] | 136 | self.add_dashed_line(file, (self.width*0.7, self.height-self.h_margin), (self.width, self.height-self.h_margin))
|
---|
[626] | 137 | self.add_text(file, end_text, (self.width, self.height-self.h_margin), "end")
|
---|
[562] | 138 |
|
---|
[624] | 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)
|
---|
[562] | 149 |
|
---|
[624] | 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)
|
---|
[562] | 164 |
|
---|
[624] | 165 | def compute_value(self, start, end, value, bias=1):
|
---|
| 166 | value = 1 - (1-value)**bias
|
---|
| 167 | return start*(1-value) + end*value
|
---|
[564] | 168 |
|
---|
[624] | 169 | class PngDrawer(Drawer):
|
---|
[626] | 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"):
|
---|
[624] | 188 | print("Drawing...")
|
---|
[564] | 189 |
|
---|
[626] | 190 | self.multi=multi
|
---|
| 191 | self.scale_up()
|
---|
| 192 |
|
---|
[624] | 193 | back = Image.new('RGBA', (self.width, self.height), (255,255,255,0))
|
---|
[562] | 194 |
|
---|
[624] | 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])
|
---|
[562] | 198 |
|
---|
[624] | 199 | self.draw_lines(back, min_width, max_width, max_height)
|
---|
| 200 | self.draw_dots(back, min_width, max_width, max_height)
|
---|
[562] | 201 |
|
---|
[624] | 202 | if scale == "SIMPLE":
|
---|
| 203 | self.draw_scale(back, input_filename)
|
---|
[564] | 204 |
|
---|
[626] | 205 | #back.show()
|
---|
| 206 | self.scale_down()
|
---|
| 207 |
|
---|
| 208 | back.thumbnail((self.width, self.height), Image.ANTIALIAS)
|
---|
| 209 |
|
---|
[624] | 210 | back.save(filename)
|
---|
[562] | 211 |
|
---|
[624] | 212 | def add_dot(self, file, pos, style):
|
---|
| 213 | x, y = int(pos[0]), int(pos[1])
|
---|
[626] | 214 | r = style['r']*self.multi
|
---|
[624] | 215 | offset = (int(x - r), int(y - r))
|
---|
| 216 | size = (2*int(r), 2*int(r))
|
---|
[622] | 217 |
|
---|
[624] | 218 | c = style['color']
|
---|
[572] | 219 |
|
---|
[624] | 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)
|
---|
[572] | 224 |
|
---|
[624] | 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])
|
---|
[626] | 227 | w = int(style['width'])*self.multi
|
---|
[562] | 228 |
|
---|
[624] | 229 | offset = (min(fx-w, tx-w), min(fy-w, ty-w))
|
---|
| 230 | size = (abs(fx-tx)+2*w, abs(fy-ty)+2*w)
|
---|
[577] | 231 |
|
---|
[624] | 232 | c = style['color']
|
---|
[622] | 233 |
|
---|
[624] | 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),
|
---|
[626] | 236 | (int(2.55*c[0]), int(2.55*c[1]), int(2.55*c[2]), int(255*style['opacity'])), w)
|
---|
[624] | 237 | file.paste(img, offset, mask=img)
|
---|
[562] | 238 |
|
---|
[624] | 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)
|
---|
[562] | 249 |
|
---|
[624] | 250 | def add_text(self, file, text, pos, anchor, style=''):
|
---|
[626] | 251 | font = ImageFont.truetype("Vera.ttf", 16*self.multi)
|
---|
[621] | 252 |
|
---|
[624] | 253 | img = Image.new('RGBA', (self.width, self.height))
|
---|
| 254 | draw = ImageDraw.Draw(img)
|
---|
| 255 | txtsize = draw.textsize(text, font=font)
|
---|
[626] | 256 | pos = pos if anchor == "start" else (pos[0]-txtsize[0], pos[1])
|
---|
[624] | 257 | draw.text(pos, text, (0,0,0), font=font)
|
---|
| 258 | file.paste(img, (0,0), mask=img)
|
---|
[622] | 259 |
|
---|
[624] | 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 |
|
---|
| 270 | class SvgDrawer(Drawer):
|
---|
[626] | 271 | def draw_design(self, filename, input_filename, multi=1, scale="SIMPLE"):
|
---|
[624] | 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;"')
|
---|
[628] | 294 | # assuming font size 12, it should be taken from the style string!
|
---|
| 295 | file.write('<text ' + style + ' text-anchor="' + anchor + '" x="' + str(pos[0]) + '" y="' + str(pos[1]+12) + '" >' + text + '</text>')
|
---|
[624] | 296 |
|
---|
| 297 | def add_dot(self, file, pos, style):
|
---|
| 298 | file.write('<circle ' + style + ' cx="' + str(pos[0]) + '" cy="' + str(pos[1]) + '" />')
|
---|
| 299 |
|
---|
| 300 | def add_line(self, file, from_pos, to_pos, style):
|
---|
| 301 | file.write('<line ' + style + ' x1="' + str(from_pos[0]) + '" x2="' + str(to_pos[0]) +
|
---|
| 302 | '" y1="' + str(from_pos[1]) + '" y2="' + str(to_pos[1]) + '" fill="none"/>')
|
---|
| 303 |
|
---|
| 304 | def add_dashed_line(self, file, from_pos, to_pos):
|
---|
| 305 | style = 'stroke="black" stroke-width="0.5" stroke-opacity="1" stroke-dasharray="5, 5"'
|
---|
| 306 | self.add_line(file, from_pos, to_pos, style)
|
---|
| 307 |
|
---|
| 308 | def compute_line_style(self, parent, child):
|
---|
| 309 | return self.compute_stroke_color('lines', child) + ' ' \
|
---|
| 310 | + self.compute_stroke_width('lines', child) + ' ' \
|
---|
| 311 | + self.compute_stroke_opacity(child)
|
---|
| 312 |
|
---|
| 313 | def compute_dot_style(self, node):
|
---|
| 314 | return self.compute_dot_size(node) + ' ' \
|
---|
| 315 | + self.compute_fill_opacity(node) + ' ' \
|
---|
| 316 | + self.compute_dot_fill(node)
|
---|
| 317 |
|
---|
| 318 | def compute_stroke_color(self, part, node):
|
---|
| 319 | color = self.compute_property(part, 'color', node)
|
---|
| 320 | return 'stroke="rgb(' + str(color[0]) + '%,' + str(color[1]) + '%,' + str(color[2]) + '%)"'
|
---|
| 321 |
|
---|
| 322 | def compute_stroke_width(self, part, node):
|
---|
| 323 | return 'stroke-width="' + str(self.compute_property(part, 'width', node)) + '"'
|
---|
| 324 |
|
---|
| 325 | def compute_stroke_opacity(self, node):
|
---|
| 326 | return 'stroke-opacity="' + str(self.compute_property('lines', 'opacity', node)) + '"'
|
---|
| 327 |
|
---|
| 328 | def compute_fill_opacity(self, node):
|
---|
| 329 | return 'fill-opacity="' + str(self.compute_property('dots', 'opacity', node)) + '"'
|
---|
| 330 |
|
---|
| 331 | def compute_dot_size(self, node):
|
---|
| 332 | return 'r="' + str(self.compute_property('dots', 'size', node)) + '"'
|
---|
| 333 |
|
---|
| 334 | def compute_dot_fill(self, node):
|
---|
| 335 | color = self.compute_property('dots', 'color', node)
|
---|
| 336 | return 'fill="rgb(' + str(color[0]) + '%,' + str(color[1]) + '%,' + str(color[2]) + '%)"'
|
---|
| 337 |
|
---|
| 338 | class Designer:
|
---|
| 339 |
|
---|
| 340 | def __init__(self, tree, jitter=False, time="GENERATIONAL", balance="DENSITY"):
|
---|
| 341 | self.props = {}
|
---|
| 342 |
|
---|
| 343 | self.tree = tree
|
---|
| 344 |
|
---|
| 345 | self.TIME = time
|
---|
| 346 | self.JITTER = jitter
|
---|
| 347 |
|
---|
| 348 | if balance == "RANDOM":
|
---|
| 349 | self.xmin_crowd = self.xmin_crowd_random
|
---|
| 350 | elif balance == "MIN":
|
---|
| 351 | self.xmin_crowd = self.xmin_crowd_min
|
---|
| 352 | elif balance == "DENSITY":
|
---|
| 353 | self.xmin_crowd = self.xmin_crowd_density
|
---|
[562] | 354 | else:
|
---|
[624] | 355 | raise ValueError("Error, the value of BALANCE does not match any expected value.")
|
---|
[562] | 356 |
|
---|
[624] | 357 | def calculate_measures(self):
|
---|
| 358 | print("Calculating measures...")
|
---|
| 359 | self.compute_adepth()
|
---|
| 360 | self.compute_depth()
|
---|
| 361 | self.compute_children()
|
---|
| 362 | self.compute_kind()
|
---|
| 363 | self.compute_time()
|
---|
| 364 | self.compute_custom()
|
---|
[622] | 365 |
|
---|
[624] | 366 | def xmin_crowd_random(self, x1, x2, y):
|
---|
| 367 | return (x1 if random.randrange(2) == 0 else x2)
|
---|
[562] | 368 |
|
---|
[624] | 369 | def xmin_crowd_min(self, x1, x2, y):
|
---|
| 370 | x1_closest = 999999
|
---|
| 371 | x2_closest = 999999
|
---|
| 372 | miny = y-3
|
---|
| 373 | maxy = y+3
|
---|
| 374 | i = bisect.bisect_left(self.y_sorted, miny)
|
---|
| 375 | while True:
|
---|
| 376 | if len(self.positions_sorted) <= i or self.positions_sorted[i]['y'] > maxy:
|
---|
| 377 | break
|
---|
| 378 | pos = self.positions_sorted[i]
|
---|
[562] | 379 |
|
---|
[624] | 380 | x1_closest = min(x1_closest, abs(x1-pos['x']))
|
---|
| 381 | x2_closest = min(x2_closest, abs(x2-pos['x']))
|
---|
[562] | 382 |
|
---|
[624] | 383 | i += 1
|
---|
| 384 | return (x1 if x1_closest > x2_closest else x2)
|
---|
[562] | 385 |
|
---|
[624] | 386 | def xmin_crowd_density(self, x1, x2, y):
|
---|
| 387 | x1_dist = 0
|
---|
| 388 | x2_dist = 0
|
---|
| 389 | miny = y-500
|
---|
| 390 | maxy = y+500
|
---|
| 391 | i_left = bisect.bisect_left(self.y_sorted, miny)
|
---|
| 392 | i_right = bisect.bisect_right(self.y_sorted, maxy)
|
---|
| 393 | # print("i " + str(i) + " len " + str(len(self.positions)))
|
---|
| 394 | #
|
---|
| 395 | # i = bisect.bisect_left(self.y_sorted, y)
|
---|
| 396 | # i_left = max(0, i - 25)
|
---|
| 397 | # i_right = min(len(self.y_sorted), i + 25)
|
---|
[562] | 398 |
|
---|
[624] | 399 | def include_pos(pos):
|
---|
| 400 | nonlocal x1_dist, x2_dist
|
---|
[622] | 401 |
|
---|
[624] | 402 | dysq = (pos['y']-y)**2
|
---|
| 403 | dx1 = pos['x']-x1
|
---|
| 404 | dx2 = pos['x']-x2
|
---|
[562] | 405 |
|
---|
[623] | 406 | x1_dist += math.sqrt(dysq + dx1**2)
|
---|
| 407 | x2_dist += math.sqrt(dysq + dx2**2)
|
---|
| 408 |
|
---|
[624] | 409 | # optimized to draw from all the nodes, if less than 10 nodes in the range
|
---|
| 410 | if len(self.positions_sorted) > i_left:
|
---|
| 411 | if i_right - i_left < 10:
|
---|
| 412 | for j in range(i_left, i_right):
|
---|
| 413 | include_pos(self.positions_sorted[j])
|
---|
| 414 | else:
|
---|
| 415 | for j in range(10):
|
---|
| 416 | pos = self.positions_sorted[random.randrange(i_left, i_right)]
|
---|
| 417 | include_pos(pos)
|
---|
[562] | 418 |
|
---|
[624] | 419 | return (x1 if x1_dist > x2_dist else x2)
|
---|
| 420 | #print(x1_dist, x2_dist)
|
---|
| 421 | #x1_dist = x1_dist**2
|
---|
| 422 | #x2_dist = x2_dist**2
|
---|
| 423 | #return x1 if x1_dist+x2_dist==0 else (x1*x1_dist + x2*x2_dist) / (x1_dist+x2_dist) + random.gauss(0, 0.01)
|
---|
| 424 | #return (x1 if random.randint(0, int(x1_dist+x2_dist)) < x1_dist else x2)
|
---|
[571] | 425 |
|
---|
[624] | 426 | def calculate_node_positions(self, ignore_last=0):
|
---|
| 427 | print("Calculating positions...")
|
---|
[562] | 428 |
|
---|
[624] | 429 | current_node = 0
|
---|
[572] | 430 |
|
---|
[624] | 431 | def add_node(node):
|
---|
| 432 | nonlocal current_node
|
---|
| 433 | index = bisect.bisect_left(self.y_sorted, node['y'])
|
---|
| 434 | self.y_sorted.insert(index, node['y'])
|
---|
| 435 | self.positions_sorted.insert(index, node)
|
---|
| 436 | self.positions[node['id']] = node
|
---|
[572] | 437 |
|
---|
[624] | 438 | self.positions_sorted = [{'x':0, 'y':0, 'id':0}]
|
---|
| 439 | self.y_sorted = [0]
|
---|
| 440 | self.positions = [{} for x in range(len(self.tree.parents))]
|
---|
| 441 | self.positions[0] = {'x':0, 'y':0, 'id':0}
|
---|
[572] | 442 |
|
---|
[624] | 443 | nodes_to_visit = [0]
|
---|
| 444 | visited = [False] * len(self.tree.parents)
|
---|
| 445 | visited[0] = True
|
---|
[562] | 446 |
|
---|
[624] | 447 | node_counter = 0
|
---|
| 448 | start_time = timelib.time()
|
---|
[566] | 449 |
|
---|
[624] | 450 | while True:
|
---|
[562] | 451 |
|
---|
[624] | 452 | node_counter += 1
|
---|
| 453 | if node_counter%1000 == 0:
|
---|
| 454 | print(str(node_counter) + " " + str(timelib.time()-start_time))
|
---|
| 455 | start_time = timelib.time()
|
---|
[562] | 456 |
|
---|
[624] | 457 | current_node = nodes_to_visit[0]
|
---|
[621] | 458 |
|
---|
[624] | 459 | for child in self.tree.children[current_node]:
|
---|
| 460 | if not visited[child] and self.props['adepth'][child] >= ignore_last/self.props['adepth_max']:
|
---|
| 461 | nodes_to_visit.append(child)
|
---|
| 462 | visited[child] = True
|
---|
[621] | 463 |
|
---|
[624] | 464 | ypos = 0
|
---|
| 465 | if self.TIME == "BIRTHS":
|
---|
| 466 | ypos = child
|
---|
| 467 | elif self.TIME == "GENERATIONAL":
|
---|
| 468 | ypos = self.positions[current_node]['y']+1
|
---|
| 469 | elif self.TIME == "REAL":
|
---|
| 470 | ypos = self.tree.time[child]
|
---|
[621] | 471 |
|
---|
[624] | 472 | if len(self.tree.parents[child]) == 1:
|
---|
| 473 | # if current_node is the only parent
|
---|
| 474 | if self.JITTER:
|
---|
| 475 | dissimilarity = random.gauss(0, 0.5)
|
---|
[621] | 476 | else:
|
---|
| 477 | dissimilarity = 1
|
---|
[624] | 478 | add_node({'id':child, 'y':ypos, 'x':
|
---|
| 479 | self.xmin_crowd(self.positions[current_node]['x']-dissimilarity,
|
---|
| 480 | self.positions[current_node]['x']+dissimilarity, ypos)})
|
---|
[621] | 481 | else:
|
---|
[624] | 482 | total_inheretance = sum([v for k, v in self.tree.parents[child].items()])
|
---|
| 483 | xpos = sum([self.positions[k]['x']*v/total_inheretance
|
---|
| 484 | for k, v in self.tree.parents[child].items()])
|
---|
| 485 | if self.JITTER:
|
---|
| 486 | add_node({'id':child, 'y':ypos, 'x':xpos + random.gauss(0, 0.1)})
|
---|
[621] | 487 | else:
|
---|
[624] | 488 | add_node({'id':child, 'y':ypos, 'x':xpos})
|
---|
[621] | 489 |
|
---|
[624] | 490 | nodes_to_visit = nodes_to_visit[1:]
|
---|
| 491 | # if none left, we can stop
|
---|
| 492 | if len(nodes_to_visit) == 0:
|
---|
| 493 | print("done")
|
---|
| 494 | break
|
---|
[621] | 495 |
|
---|
[624] | 496 | def compute_custom(self):
|
---|
| 497 | for prop in self.tree.props:
|
---|
| 498 | self.props[prop] = [None for x in range(len(self.tree.children))]
|
---|
[621] | 499 |
|
---|
[624] | 500 | for i in range(len(self.props[prop])):
|
---|
| 501 | self.props[prop][i] = self.tree.props[prop][i]
|
---|
[621] | 502 |
|
---|
[624] | 503 | self.normalize_prop(prop)
|
---|
[562] | 504 |
|
---|
[624] | 505 | def compute_time(self):
|
---|
| 506 | # simple rewrite from the tree
|
---|
| 507 | self.props["time"] = [0 for x in range(len(self.tree.children))]
|
---|
[562] | 508 |
|
---|
[624] | 509 | for i in range(len(self.props['time'])):
|
---|
| 510 | self.props['time'][i] = self.tree.time[i]
|
---|
[572] | 511 |
|
---|
[624] | 512 | self.normalize_prop('time')
|
---|
[617] | 513 |
|
---|
[624] | 514 | def compute_kind(self):
|
---|
| 515 | # simple rewrite from the tree
|
---|
| 516 | self.props["kind"] = [0 for x in range(len(self.tree.children))]
|
---|
[617] | 517 |
|
---|
[624] | 518 | for i in range (len(self.props['kind'])):
|
---|
| 519 | self.props['kind'][i] = str(self.tree.kind[i])
|
---|
[617] | 520 |
|
---|
[624] | 521 | def compute_depth(self):
|
---|
| 522 | self.props["depth"] = [999999999 for x in range(len(self.tree.children))]
|
---|
[617] | 523 |
|
---|
[624] | 524 | nodes_to_visit = [0]
|
---|
| 525 | self.props["depth"][0] = 0
|
---|
| 526 | while True:
|
---|
| 527 | for child in self.tree.children[nodes_to_visit[0]]:
|
---|
| 528 | nodes_to_visit.append(child)
|
---|
| 529 | self.props["depth"][child] = min([self.props["depth"][d] for d in self.tree.parents[child]])+1
|
---|
| 530 | nodes_to_visit = nodes_to_visit[1:]
|
---|
| 531 | if len(nodes_to_visit) == 0:
|
---|
| 532 | break
|
---|
[617] | 533 |
|
---|
[624] | 534 | self.normalize_prop('depth')
|
---|
[617] | 535 |
|
---|
[624] | 536 | def compute_adepth(self):
|
---|
| 537 | self.props["adepth"] = [0 for x in range(len(self.tree.children))]
|
---|
[617] | 538 |
|
---|
[624] | 539 | def compute_local_adepth(node):
|
---|
| 540 | my_adepth = 0
|
---|
| 541 | for c in self.tree.children[node]:
|
---|
| 542 | my_adepth = max(my_adepth, compute_local_adepth(c)+1)
|
---|
| 543 | self.props["adepth"][node] = my_adepth
|
---|
| 544 | return my_adepth
|
---|
[617] | 545 |
|
---|
[624] | 546 | compute_local_adepth(0)
|
---|
| 547 | self.normalize_prop('adepth')
|
---|
[594] | 548 |
|
---|
[624] | 549 | def compute_children(self):
|
---|
| 550 | self.props["children"] = [0 for x in range(len(self.tree.children))]
|
---|
| 551 | for i in range (len(self.props['children'])):
|
---|
| 552 | self.props['children'][i] = len(self.tree.children[i])
|
---|
[562] | 553 |
|
---|
[624] | 554 | self.normalize_prop('children')
|
---|
[564] | 555 |
|
---|
[624] | 556 | def normalize_prop(self, prop):
|
---|
| 557 | noneless = [v for v in self.props[prop] if type(v)==int or type(v)==float]
|
---|
| 558 | if len(noneless) > 0:
|
---|
| 559 | max_val = max(noneless)
|
---|
| 560 | min_val = min(noneless)
|
---|
| 561 | self.props[prop +'_max'] = max_val
|
---|
| 562 | self.props[prop +'_min'] = min_val
|
---|
| 563 | for i in range(len(self.props[prop])):
|
---|
| 564 | if self.props[prop][i] is not None:
|
---|
[628] | 565 | self.props[prop][i] = 0 if max_val == 0 else (self.props[prop][i] - min_val) / max_val
|
---|
[594] | 566 |
|
---|
| 567 |
|
---|
[624] | 568 | class TreeData:
|
---|
| 569 | simple_data = None
|
---|
[615] | 570 |
|
---|
[624] | 571 | children = []
|
---|
| 572 | parents = []
|
---|
| 573 | time = []
|
---|
| 574 | kind = []
|
---|
[562] | 575 |
|
---|
[624] | 576 | def __init__(self): #, simple_data=False):
|
---|
| 577 | #self.simple_data = simple_data
|
---|
| 578 | pass
|
---|
[562] | 579 |
|
---|
[624] | 580 | def load(self, filename, max_nodes=0):
|
---|
| 581 | print("Loading...")
|
---|
[576] | 582 |
|
---|
[624] | 583 | CLI_PREFIX = "Script.Message:"
|
---|
| 584 | default_props = ["Time", "FromIDs", "ID", "Operation", "Inherited"]
|
---|
[576] | 585 |
|
---|
[624] | 586 | ids = {}
|
---|
[628] | 587 | def get_id(id, createOnError = True):
|
---|
| 588 | if createOnError:
|
---|
| 589 | if id not in ids:
|
---|
| 590 | ids[id] = len(ids)
|
---|
| 591 | else:
|
---|
| 592 | if id not in ids:
|
---|
| 593 | return None
|
---|
[624] | 594 | return ids[id]
|
---|
[576] | 595 |
|
---|
[624] | 596 | file = open(filename)
|
---|
[576] | 597 |
|
---|
[624] | 598 | # counting the number of expected nodes
|
---|
| 599 | nodes = 0
|
---|
| 600 | for line in file:
|
---|
| 601 | line_arr = line.split(' ', 1)
|
---|
| 602 | if len(line_arr) == 2:
|
---|
| 603 | if line_arr[0] == CLI_PREFIX:
|
---|
| 604 | line_arr = line_arr[1].split(' ', 1)
|
---|
| 605 | if line_arr[0] == "[OFFSPRING]":
|
---|
| 606 | nodes += 1
|
---|
[562] | 607 |
|
---|
[624] | 608 | nodes = min(nodes, max_nodes if max_nodes != 0 else nodes)+1
|
---|
| 609 | self.parents = [{} for x in range(nodes)]
|
---|
| 610 | self.children = [[] for x in range(nodes)]
|
---|
| 611 | self.time = [0] * nodes
|
---|
| 612 | self.kind = [0] * nodes
|
---|
[628] | 613 | self.life_lenght = [0] * nodes
|
---|
[624] | 614 | self.props = {}
|
---|
[562] | 615 |
|
---|
[624] | 616 | print(len(self.parents))
|
---|
[562] | 617 |
|
---|
[624] | 618 | file.seek(0)
|
---|
| 619 | loaded_so_far = 0
|
---|
| 620 | lasttime = timelib.time()
|
---|
| 621 | for line in file:
|
---|
| 622 | line_arr = line.split(' ', 1)
|
---|
| 623 | if len(line_arr) == 2:
|
---|
| 624 | if line_arr[0] == CLI_PREFIX:
|
---|
| 625 | line_arr = line_arr[1].split(' ', 1)
|
---|
| 626 | if line_arr[0] == "[OFFSPRING]":
|
---|
| 627 | creature = json.loads(line_arr[1])
|
---|
| 628 | if "FromIDs" in creature:
|
---|
[562] | 629 |
|
---|
[624] | 630 | # make sure that ID's of parents are lower than that of their children
|
---|
| 631 | for i in range(0, len(creature["FromIDs"])):
|
---|
[627] | 632 | if creature["FromIDs"][i] not in ids:
|
---|
| 633 | get_id("virtual_parent")
|
---|
[562] | 634 |
|
---|
[624] | 635 | creature_id = get_id(creature["ID"])
|
---|
| 636 |
|
---|
| 637 | # debug
|
---|
| 638 | if loaded_so_far%1000 == 0:
|
---|
| 639 | #print(". " + str(creature_id) + " " + str(timelib.time() - lasttime))
|
---|
| 640 | lasttime = timelib.time()
|
---|
| 641 |
|
---|
| 642 | # we assign to each parent its contribution to the genotype of the child
|
---|
| 643 | for i in range(0, len(creature["FromIDs"])):
|
---|
[627] | 644 | if creature["FromIDs"][i] in ids:
|
---|
| 645 | parent_id = get_id(creature["FromIDs"][i])
|
---|
| 646 | else:
|
---|
| 647 | parent_id = get_id("virtual_parent")
|
---|
[624] | 648 | inherited = 1 #(creature["Inherited"][i] if 'Inherited' in creature else 1) #ONLY FOR NOW
|
---|
| 649 | self.parents[creature_id][parent_id] = inherited
|
---|
| 650 |
|
---|
| 651 | if "Time" in creature:
|
---|
| 652 | self.time[creature_id] = creature["Time"]
|
---|
| 653 |
|
---|
| 654 | if "Kind" in creature:
|
---|
| 655 | self.kind[creature_id] = creature["Kind"]
|
---|
| 656 |
|
---|
| 657 | for prop in creature:
|
---|
| 658 | if prop not in default_props:
|
---|
| 659 | if prop not in self.props:
|
---|
[628] | 660 | self.props[prop] = [0 for i in range(nodes)]
|
---|
[624] | 661 | self.props[prop][creature_id] = creature[prop]
|
---|
| 662 |
|
---|
| 663 | loaded_so_far += 1
|
---|
| 664 | else:
|
---|
| 665 | raise LoadingError("[OFFSPRING] misses the 'FromIDs' field!")
|
---|
[628] | 666 | if line_arr[0] == "[DIED]":
|
---|
| 667 | creature = json.loads(line_arr[1])
|
---|
| 668 | creature_id = get_id(creature["ID"], False)
|
---|
| 669 | if creature_id is not None:
|
---|
| 670 | for prop in creature:
|
---|
| 671 | if prop not in default_props:
|
---|
| 672 | if prop not in self.props:
|
---|
| 673 | self.props[prop] = [0 for i in range(nodes)]
|
---|
| 674 | self.props[prop][creature_id] = creature[prop]
|
---|
[624] | 675 |
|
---|
[628] | 676 |
|
---|
[624] | 677 | if loaded_so_far >= max_nodes and max_nodes != 0:
|
---|
| 678 | break
|
---|
| 679 |
|
---|
| 680 | for k in range(len(self.parents)):
|
---|
| 681 | v = self.parents[k]
|
---|
| 682 | for val in self.parents[k]:
|
---|
| 683 | self.children[val].append(k)
|
---|
| 684 |
|
---|
[562] | 685 | depth = {}
|
---|
[577] | 686 | kind = {}
|
---|
[562] | 687 |
|
---|
| 688 | def main():
|
---|
| 689 |
|
---|
[624] | 690 | parser = argparse.ArgumentParser(description='Draws a genealogical tree (generates a SVG file) based on parent-child relationship '
|
---|
| 691 | 'information from a text file. Supports files generated by Framsticks experiments.')
|
---|
[615] | 692 | parser.add_argument('-i', '--in', dest='input', required=True, help='input file name with stuctured evolutionary data')
|
---|
[624] | 693 | parser.add_argument('-o', '--out', dest='output', required=True, help='output file name for the evolutionary tree (SVG/PNG/JPG/BMP)')
|
---|
| 694 | parser.add_argument('-c', '--config', dest='config', default="", help='config file name ')
|
---|
[562] | 695 |
|
---|
[624] | 696 | parser.add_argument('-W', '--width', default=600, type=int, dest='width', help='width of the output image (600 by default)')
|
---|
[626] | 697 | parser.add_argument('-H', '--height', default=800, type=int, dest='height', help='height of the output image (800 by default)')
|
---|
| 698 | parser.add_argument('-m', '--multi', default=1, type=int, dest='multi', help='multisampling factor (applicable only for raster images)')
|
---|
[562] | 699 |
|
---|
[620] | 700 | parser.add_argument('-t', '--time', default='GENERATIONAL', dest='time', help='values on vertical axis (BIRTHS/GENERATIONAL(d)/REAL); '
|
---|
[614] | 701 | 'BIRTHS: time measured as the number of births since the beginning; '
|
---|
[571] | 702 | 'GENERATIONAL: time measured as number of ancestors; '
|
---|
| 703 | 'REAL: real time of the simulation')
|
---|
[620] | 704 | parser.add_argument('-b', '--balance', default='DENSITY', dest='balance', help='method of placing nodes in the tree (RANDOM/MIN/DENSITY(d))')
|
---|
[624] | 705 | parser.add_argument('-s', '--scale', default='SIMPLE', dest='scale', help='type of timescale added to the tree (NONE(d)/SIMPLE)')
|
---|
[571] | 706 | parser.add_argument('-j', '--jitter', dest="jitter", action='store_true', help='draw horizontal positions of children from the normal distribution')
|
---|
[624] | 707 | parser.add_argument('-p', '--skip', dest="skip", type=int, default=0, help='skip last P levels of the tree (0 by default)')
|
---|
| 708 | parser.add_argument('-x', '--max-nodes', type=int, default=0, dest='max_nodes', help='maximum number of nodes drawn (starting from the first one)')
|
---|
[562] | 709 | parser.add_argument('--seed', type=int, dest='seed', help='seed for the random number generator (-1 for random)')
|
---|
| 710 |
|
---|
| 711 | parser.set_defaults(draw_tree=True)
|
---|
| 712 | parser.set_defaults(draw_skeleton=False)
|
---|
| 713 | parser.set_defaults(draw_spine=False)
|
---|
| 714 |
|
---|
| 715 | parser.set_defaults(seed=-1)
|
---|
| 716 |
|
---|
| 717 | args = parser.parse_args()
|
---|
| 718 |
|
---|
[620] | 719 | TIME = args.time.upper()
|
---|
| 720 | BALANCE = args.balance.upper()
|
---|
| 721 | SCALE = args.scale.upper()
|
---|
[571] | 722 | JITTER = args.jitter
|
---|
[620] | 723 | if not TIME in ['BIRTHS', 'GENERATIONAL', 'REAL']\
|
---|
| 724 | or not BALANCE in ['RANDOM', 'MIN', 'DENSITY']\
|
---|
| 725 | or not SCALE in ['NONE', 'SIMPLE']:
|
---|
| 726 | print("Incorrect value of one of the parameters! Closing the program.") #TODO don't be lazy, figure out which parameter is wrong...
|
---|
| 727 | return
|
---|
[562] | 728 |
|
---|
| 729 | dir = args.input
|
---|
| 730 | seed = args.seed
|
---|
| 731 | if seed == -1:
|
---|
| 732 | seed = random.randint(0, 10000)
|
---|
| 733 | random.seed(seed)
|
---|
| 734 | print("seed:", seed)
|
---|
| 735 |
|
---|
[624] | 736 | tree = TreeData()
|
---|
| 737 | tree.load(dir, max_nodes=args.max_nodes)
|
---|
[562] | 738 |
|
---|
[624] | 739 | designer = Designer(tree, jitter=JITTER, time=TIME, balance=BALANCE)
|
---|
| 740 | designer.calculate_measures()
|
---|
| 741 | designer.calculate_node_positions(ignore_last=args.skip)
|
---|
[562] | 742 |
|
---|
[624] | 743 | if args.output.endswith(".svg"):
|
---|
| 744 | drawer = SvgDrawer(designer, args.config, w=args.width, h=args.height)
|
---|
| 745 | else:
|
---|
| 746 | drawer = PngDrawer(designer, args.config, w=args.width, h=args.height)
|
---|
[626] | 747 | drawer.draw_design(args.output, args.input, multi=args.multi, scale=SCALE)
|
---|
[562] | 748 |
|
---|
| 749 |
|
---|
| 750 | main()
|
---|