def getsize(fig, w, h): "use inkscape to calculate the width and height of fig" import tempfile, commands, os, sys fname = tempfile.mktemp(suffix=".svg") svg = fig.SVG() vb = "%s %s %s %s" % (0, 0, w, h) svgfig.canvas(svg, width=w, height=h, viewBox=vb).save(fname) #svg.save(fname) width = float(commands.getoutput("inkscape -W '%s'" % fname)) height = float(commands.getoutput("inkscape -H '%s'" % fname)) os.remove(fname) return width, height
def toSVG(self): from svgfig import SVG, canvas w = self.view.width h = self.view.height svg = canvas(width='%dpx' % w, height='%dpx' % h, viewBox='0 0 %d %d' % (w, h), enable_background='new 0 0 %d %d' % (w, h), style='stroke-width:0.7pt; stroke-linejoin: round; stroke:#444; fill:#eee;') g = SVG('g', id="states") for circle in self.circles: c = SVG('circle',cx=circle.x, cy=circle.y, r=circle.r) c['data-key'] = circle.id c['data-population'] = circle.value g.append(c) meta = SVG('metadata') views = SVG('views') view = SVG('view', padding="80", w=w, h=h) proj = self.globe.toXML() bbox = self.bbox bbox = SVG('bbox', x=round(bbox.left,2), y=round(bbox.top,2), w=round(bbox.width,2), h=round(bbox.height,2)) views.append(view) view.append(proj) view.append(bbox) meta.append(views) svg.append(meta) svg.append(g) svg.firefox()
def create_svg(bounds, sizes=None, labels=None, scale=120, font_size=50): """ Create a SVG figure from the bounds. """ import svgfig as S fig = S.Fig() colors = ["purple", "blue", "green", "yellow"] min_x = bounds[:,:,0].min() min_y = bounds[:,:,1].min() max_x = bounds[:,:,0].max() max_y = bounds[:,:,1].max() for rect, color in zip(bounds, colors): fig.d.append( S.SVG( "rect", x=scale*rect[0,0], y=scale*rect[0,1], width=scale*(rect[1,0]-rect[0,0]), height=scale*(rect[1,1]-rect[0,1]), fill=color, fill_opacity=".2", rx=10, ry=10, stroke_width=2 ) ) if None != labels: fig.d.append(S.Text(scale*bounds[0, 0, 0], scale*bounds[0, 0, 1], labels[0], font_size=font_size, text_anchor="start")) fig.d.append(S.Text(scale*bounds[1, 1, 0], scale*bounds[1, 0, 1], labels[1], font_size=font_size, text_anchor="end")) fig.d.append(S.Text(scale*bounds[2, 1, 0], scale*bounds[2, 1, 1]+font_size, labels[2], font_size=font_size, text_anchor="end")) fig.d.append(S.Text(scale*bounds[3, 0, 0], scale*bounds[3, 1, 1]+font_size, labels[3], font_size=font_size, text_anchor="start")) return S.canvas( fig.SVG(), height="800px", width="800px", viewBox="%d %d %d %d" % (scale*min_x-font_size, scale*min_y-font_size, scale*(max_x-min_x)+2*font_size, scale*(max_y-min_y)+2*font_size))
def toSVG(self): from svgfig import SVG, canvas w = self.view.width h = self.view.height svg = canvas(width='%dpx' % w, height='%dpx' % h, viewBox='0 0 %d %d' % (w, h), enable_background='new 0 0 %d %d' % (w, h), style='stroke-width:0.7pt; stroke-linejoin: round; stroke:#444; fill:#eee;') g = SVG('g', id="gemeinden") for circle in self.circles: c = SVG('circle',cx=circle.x, cy=circle.y, r=circle.r) c['data-key'] = circle.id c['data-population'] = circle.value g.append(c) meta = SVG('metadata') views = SVG('views') view = SVG('view', padding="80", w=w, h=h) proj = self.globe.toXML() bbox = self.bbox bbox = SVG('bbox', x=round(bbox.left,2), y=round(bbox.top,2), w=round(bbox.width,2), h=round(bbox.height,2)) views.append(view) view.append(proj) view.append(bbox) meta.append(views) svg.append(meta) svg.append(g) svg.save('cartogram.svg')
def show(self, **kwargs): """ kwargs: width=400, height=400, viewBox="0 0 2000 2000" """ s = svg.Fig(*self.lines).SVG() c = svg.canvas(s, **kwargs) c.inkview() return self
def draw_shapes(self): # really ugly redraw everything self.scene.clear() self.webview = QGraphicsWebView() self.webview.setZoomFactor(3.0) self.scene.setBackgroundBrush(Qt.black) self.scene.addItem(self.webview) w = self.width()*.5 h = self.height()*.5 width = "%spx" % (w) height = "%spx" % (h) dx = (int(self.parent.gl_dx + 1)/2)*2 dy = (int(self.parent.gl_dy + 1)/2)*2 vx = dx dy = dy self.dx = dx self.dy = dy print dx, dy # TODO: clever viewbox calculation viewbox = "%d %d %d %d" % (-self.q*dx/2, -self.q*dy/2, self.q*dx, self.q*dy) rect = svgfig.Rect(-dx/2,-dy/2,dx/2,dy/2, fill='black', stroke=None).SVG(trans=self.trans) dot_field = self.draw_dot_field() #print self.box.contentsRect() print width, height, viewbox svg_g = svgfig.SVG("g") svg_g.append(rect) for x in dot_field: svg_g.append(x) for shape in self.shapes: self.set_color(shape['type']) if 'shape' in shape: dispatch = { 'circle': self.circle, 'disc': self.disc, 'label': self.label, 'line': self.vertex, 'vertex': self.vertex, 'octagon': self.octagon, 'rect': self.rect, 'polygon': self.polygon, 'hole': self.hole, } shape_svg = dispatch.get(shape['shape'], self.skip)(shape) #print shape_svg for x in shape_svg: svg_g.append(x) #print subs canvas = svgfig.canvas(svg_g, width=width, height=height, viewBox=viewbox) xml = canvas.standalone_xml() #print xml self.webview.setContent(QtCore.QByteArray(xml))
def draw_shapes(self): # really ugly redraw everything self.scene.clear() self.webview = QGraphicsWebView() self.webview.setZoomFactor(3.0) self.scene.setBackgroundBrush(Qt.black) self.scene.addItem(self.webview) w = self.width()*.5 h = self.height()*.5 width = "%spx" % (w) height = "%spx" % (h) dx = (int(self.parent.gl_dx + 1)/2)*2 dy = (int(self.parent.gl_dy + 1)/2)*2 vx = dx dy = dy self.dx = dx self.dy = dy print dx, dy # TODO: clever viewbox calculation viewbox = "%d %d %d %d" % (-self.q*dx/2, -self.q*dy/2, self.q*dx, self.q*dy) rect = svgfig.Rect(-dx/2,-dy/2,dx/2,dy/2, fill='black', stroke=None).SVG(trans=self.trans) dot_field = self.draw_dot_field() print self.box.contentsRect() print width, height, viewbox svg_g = svgfig.SVG("g") svg_g.append(rect) for x in dot_field: svg_g.append(x) for shape in self.shapes: self.set_color(shape['type']) if 'shape' in shape: dispatch = { 'circle': self.circle, 'disc': self.disc, 'label': self.label, 'line': self.vertex, 'vertex': self.vertex, 'octagon': self.octagon, 'rect': self.rect, 'polygon': self.polygon, 'hole': self.hole, } shape_svg = dispatch.get(shape['shape'], self.skip)(shape) print shape_svg for x in shape_svg: svg_g.append(x) #print subs canvas = svgfig.canvas(svg_g, width=width, height=height, viewBox=viewbox) xml = canvas.standalone_xml() print xml self.webview.setContent(QtCore.QByteArray(xml))
def __init__( self ): self.canvas = svgfig.canvas( style="stroke:black; fill:none; stroke-width:1px; stroke-linejoin:round; text-anchor:left" ) self.text = svgfig.SVG( "g" ) self.connectors = svgfig.SVG( "g" ) self.boxes = svgfig.SVG( "g" ) svgfig.Text.defaults[ "font-size" ] = "10px" self.in_pos = {} self.out_pos = {} self.widths = {} self.max_x = 0 self.max_y = 0 self.max_width = 0 self.data = []
def draw_trailer(rr, rt, d1, d2, d3, d4, d5): layout = svg.canvas() layout.attr['width'] = '40in' layout.attr['height'] = '60in' layout.attr['viewBox'] = '0 0 40 60' # draw the wheels rwheel = svg.SVG("circle", cx=0., cy=rr, r=rr) twheel = svg.SVG("circle", cx=d2+d4, cy=rt, r=rt) # draw the trailer hitch hitch1 = svg.SVG('line', x1=0., y1=rr, x2=0., y2=rr-d1) hitch2 = svg.SVG('line', x1=0., y1=rr-d1, x2=d2, y2=rr-d1) hitch = svg.SVG('g', hitch1, hitch2) # draw the trailer tr = [] tr.append(svg.SVG("line", x1=d2, y1=rr-d1, x2=d2, y2=rr-d1-d3)) tr.append(svg.SVG("line", x1=d2, y1=rr-d1-d3, x2=d2+d4, y2=rr-d1-d3)) tr.append(svg.SVG('line', x1=d2+d4, y1=rr-d1-d3, x2=d2+d4, y2=rt)) trailer = svg.SVG('g', tr[0], tr[1], tr[2]) # add some dots for the joints j1 = svg.SVG('circle', cx=d2, cy=rr-d1, r=0.2) j2 = svg.SVG('circle', cx=d2+d4, cy=rt, r=0.2) j = svg.SVG('g', j1, j2, stroke='blue', fill='blue') # draw a rectangle for the pot joint potrev = svg.SVG('rect', x=(d2+d4)/2, y=rr-d1-d3, width="2", height="1",) # draw some coordinate axes start = svg.make_marker('start', 'arrow_start') end = svg.make_marker('end', 'arrow_end') newtonian = svg.SVG('path', d='M -10,0 0,0 0,-10', marker_start='url(#start)', marker_end='url(#end)') group = svg.SVG("g", rwheel, twheel, hitch, trailer, j, potrev, newtonian, start, end, transform="translate(15, 15)")# rotate(180)") layout.append(group) layout.save() layout.inkview() return layout
def init_svg_canvas(self, view, bbox, globe): """ prepare a blank new svg file """ from svgfig import canvas, SVG options = self.options w = view.width h = view.height+2 svg = canvas(width='%dpx' % w, height='%dpx' % h, viewBox='0 0 %d %d' % (w, h), enable_background='new 0 0 %d %d' % (w, h), style='stroke-width:0.7pt; stroke-linejoin: round; stroke:#444; fill:white;') css = 'path { fill-rule: evenodd; }\n#context path { fill: #eee; stroke: #bbb; } ' if options.graticule: css += '#graticule path { fill: none; stroke-width:0.25pt; } #graticule .equator { stroke-width: 0.5pt } ' svg.append(SVG('defs', SVG('style', css, type='text/css'))) meta = SVG('metadata') views = SVG('views') view = SVG('view', padding=str(options.out_padding), w=w, h=h) proj = globe.toXML() bbox = SVG('bbox', x=round(bbox.left,2), y=round(bbox.top,2), w=round(bbox.width,2), h=round(bbox.height,2)) ll = options.llbbox llbbox = SVG('llbbox', lon0=ll[0],lon1=ll[2],lat0=ll[1],lat1=ll[3]) views.append(view) view.append(proj) view.append(bbox) view.append(llbbox) meta.append(views) svg.append(meta) return svg
def init_svg_canvas(self, opts, proj, view, bbox): """ prepare a blank new svg file """ from svgfig import canvas, SVG w = view.width h = view.height + 2 svg = canvas(width='%dpx' % w, height='%dpx' % h, viewBox='0 0 %d %d' % (w, h), enable_background='new 0 0 %d %d' % (w, h), style='stroke-width:0.7pt; stroke-linejoin: round; stroke:#000; fill:#f3f3f0;') css = 'path { fill-rule: evenodd; }\n#context path { fill: #eee; stroke: #bbb; } ' #if options.graticule: # css += '#graticule path { fill: none; stroke-width:0.25pt; } #graticule .equator { stroke-width: 0.5pt } ' svg.append(SVG('defs', SVG('style', css, type='text/css'))) meta = SVG('metadata') views = SVG('views') view = SVG('view', padding=str(opts['bounds']['padding']), w=w, h=h) proj_ = proj.toXML() bbox = SVG('bbox', x=round(bbox.left, 2), y=round(bbox.top, 2), w=round(bbox.width, 2), h=round(bbox.height, 2)) ll = [-180, -90, 180, 90] if opts['bounds']['mode'] == "bbox": ll = opts['bounds']['data'] llbbox = SVG('llbbox', lon0=ll[0], lon1=ll[2], lat0=ll[1], lat1=ll[3]) views.append(view) view.append(proj_) view.append(bbox) view.append(llbbox) meta.append(views) svg.append(meta) return svg
def main(): usage = "usage: %prog [options] inputfile outputfile traitfile" parser = OptionParser(usage=usage) parser.add_option("-c", "--count", default=config.COUNT, help="Number of SNPs to draw") parser.add_option("-o", "--offset", default=config.OFFSET, help="Offset of SNPs to skip") parser.add_option("-v", "--viewport", default=config.CANVAS_VIEWPORT, help="Viewport to draw", metavar="WIDTHxHEIGHT") parser.add_option("-m", "--multiply", default=1, help="Multiply the viewport sizes", metavar="FACTOR") parser.add_option("-s", "--stroke", default=config.STROKE, help="Stroke width", metavar="X.Xpt") (options, args) = parser.parse_args() if len(args) != 3: parser.error("incorrect number of arguments") # options count = int(options.count) offset = int(options.offset) viewport = options.viewport multiply = int(options.multiply) stroke = options.stroke viewport = [int(d)*multiply for d in viewport.split('x')] input_file = open(args[0], "r") trait_file = open(args[2], "r") dna_drawer = dna.DNADrawer(input_file, trait_file, count, offset, viewport[0], viewport[1]) svg_filters = dna_drawer.get_filters() dnasvg = dna_drawer.get_svg() input_file.close() trait_file.close() canvas_width = "%dpx" % viewport[0] canvas_height = "%dpx" % viewport[1] canvas_viewbox = "0 0 %d %d" % (viewport[0], viewport[1]) svgcanvas = svgfig.canvas(svg_filters, dnasvg, width=canvas_width, height=canvas_height, viewBox=canvas_viewbox, style="stroke:white; fill:cornsilk; stroke-width:%s; stroke-linejoin:round; text-anchor:middle" % stroke) svgcanvas.save(args[1])
def draw(self, filename, graphshape = None, width = 1280, height = 720, show_labels = False): """This does the drawing. It starts by getting a function for the bottom most layer. As descrbed in Byron & Wattenberg this will control the overall shape of the graph. It then it prints a stacked graph on top of that bottom line, whatever shape it is. """ # Preprocess some stuff aspect_ratio = float(width) / float(height) self.canvas_aspect = aspect_ratio x_offset = int( -((100 * aspect_ratio) - 100) / 2.0 ) # Get a g_0 depending in desired shape g_0 = self.themeRiver() # Default (fallbacks) y_offset = 0 if str(graphshape) == "Stacked_Graph" : g_0 = self.stackedGraph() y_offset = 0 if str(graphshape) == "Theme_River" : g_0 = self.themeRiver() y_offset = -50 if str(graphshape) == "Wiggle" : g_0 = self.wiggle() y_offset = -50 if str(graphshape) == "Weighted_Wiggle" : g_0 = self.weighted_wiggle() y_offset = -50 # Initilize a streamgraph groups in SVG. graph = svgfig.SVG("g", id="StreamGraph") labels = svgfig.SVG("g", id="Labels") # Initilize a SVG Window object to do the transormations on each object window = svgfig.window(self.x_min, self.x_max, 0, self.y_max * 1.3, x_offset, y_offset, int(100 * aspect_ratio), 100) # Loop through each layer for layer in range(self.n_layers): points = [] point_range = range(self.n_points) # Forwards; draw top of the shape for i in point_range: x = self.data[layer][i][0] y = self.data[layer][i][1] # Start with g_0 and stack y_stacked = g_0[i] + y # Stack! for l in range(layer): y_stacked += self.data[l][i][1] # Add the points to the shape points.append((x, y_stacked)) # Backwards; draw bottom of the shape point_range.reverse() for i in point_range: x = self.data[layer][i][0] # This time we don't include this layer y_stacked = g_0[i] # Stack! for l in range(layer): y_stacked += self.data[l][i][1] points.append((x,y_stacked)) # Shapes poly = svgfig.Poly(points, "smooth", stroke="#eeeeee", fill=self.rgb2hex(self.colors[layer]), stroke_width="0.05") graph.append(poly.SVG(window)) if show_labels: #label = self.placeLabel(points, layer) #label = self.test_placeLabel(points, layer) #label = self.test2_placeLabel(points, layer, window) label = self.placeLabel2(points, layer) #for l in label: # labels.append(l) labels.append(label.SVG(window)) # End Loop # Add objects to the canvas and save it w = str(int(width)) + "px" h = str(int(height)) + "px" canv = svgfig.canvas(graph, labels, width=w, height=h) canv.save(filename)
def main(opts, args): s = svg.SVG('g', id='viewport') # display legend for i, b in enumerate(bases): bt = svg.SVG("tspan", b, style="font-family:Verdana;font-size:20%") s.append( svg.SVG("text", bt, x=12 + (i * 10), y=3, stroke="none", fill="black")) s.append( svg.SVG("rect", x=14 + (i * 10), y=0, width=4, height=3, stroke="none", fill=colors[b], fill_opacity=0.5)) reader = open(opts.input_file, 'U') samples = [] for i in range(int(len(args) / 3)): index = i * 3 samples.append( dict(name=args[index], a_col=args[index + 1], totals_col=args[index + 2])) if opts.zoom == 'interactive': y = 35 else: y = 25 for i, sample in enumerate(samples): x = 23 + (i * (WIDTH + GAP)) t = svg.SVG("text", svg.SVG("tspan", sample['name'], style="font-family:Verdana;font-size:25%"), x=x, y=y, transform="rotate(-90 %i,%i)" % (x, y), stroke="none", fill="black") s.append(t) count = 1 for line in reader: row = line.split('\t') highlighted_position = False show_pos = True position = row[int(opts.position_col) - 1] ref = row[int(opts.ref_col) - 1].strip().upper() # validate if ref not in bases: stop_error( "The reference column (col%s) contains invalid character '%s' at row %i of the dataset." % (opts.ref_col, ref, count)) # display positions if opts.zoom == 'interactive': textx = 0 else: textx = 7 bt = svg.SVG("tspan", str(position), style="font-family:Verdana;font-size:25%") s.append( svg.SVG("text", bt, x=textx, y=34 + (count * (HEIGHT + GAP)), stroke="none", fill="black")) s.append( svg.SVG("rect", x=0, y=30 + (count * (HEIGHT + GAP)), width=14, height=HEIGHT, stroke='none', fill=colors[ref.upper()], fill_opacity=0.2)) for sample_index, sample in enumerate(samples): n_a = int(row[int(sample['a_col']) - 1]) n_c = int(row[int(sample['a_col']) + 1 - 1]) n_g = int(row[int(sample['a_col']) + 2 - 1]) n_t = int(row[int(sample['a_col']) + 3 - 1]) total = int(row[int(sample['totals_col']) - 1]) # validate base_error = validate_bases(n_a, n_c, n_g, n_t, total) if base_error: stop_error( "For sample %i (%s), the number of base %s reads is more than the coverage on row %i." % (sample_index + 1, sample['name'], base_error, count)) if total: x = 16 + (sample_index * (WIDTH + GAP)) y = 30 + (count * (HEIGHT + GAP)) width = WIDTH height = HEIGHT if count % 2: s.append( svg.SVG("rect", x=x, y=y, width=width, height=height, stroke='none', fill='grey', fill_opacity=0.25)) else: s.append( svg.SVG("rect", x=x, y=y, width=width, height=height, stroke='none', fill='grey', fill_opacity=0.25)) for base, value in enumerate([n_a, n_c, n_g, n_t]): width = int(math.ceil(value / total * WIDTH)) s.append( svg.SVG("rect", x=x, y=y, width=width, height=BAR_WIDTH, stroke='none', fill=colors[bases[base]], fill_opacity=0.6)) y = y + BAR_WIDTH count = count + 1 if opts.zoom == 'interactive': canv = svg.canvas(s) canv.save(opts.output_file) import fileinput flag = False for line in fileinput.input(opts.output_file, inplace=1): if line.startswith('<svg'): print '<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1">' flag = True continue else: if flag: print '<script type="text/javascript">%s</script>' % SVGPan flag = False print line, else: zoom = int(opts.zoom) w = "%ipx" % (x * (10 + zoom)) h = "%ipx" % (y * (2 + zoom)) canv = svg.canvas(s, width=w, height=h, viewBox="0 0 %i %i" % (x + 100, y + 100)) canv.save(opts.output_file)
points.append((x, y)) if len(points) > 3: poly = Polygon.Polygon(points) #poly = poly & cropRect if poly.overlaps(cropRect): polys.append(poly) #polys.append(cropRect) print "exporting SVG" #Polygon.IO.writeSVG('cropped.svg', polys) import svgfig h = str((y1 - y2) * scale * -1) svg = svgfig.canvas(width='2000px', height=h + 'px', viewBox='0 0 2000 ' + h, style='stroke-width:0.5pt,fill:#fbf5ed') svg.append( SVG('rect', width='2000px', height=h + 'px', fill='#006179', stroke='none')) def view(x, y): x = (x - x1) * scale y = (y - y2) * scale * -1 return (x, y) # equator
def main(opts, args): s = svg.SVG('g', id='viewport') # display legend for i, b in enumerate( bases ): bt = svg.SVG("tspan", b, style="font-family:Verdana;font-size:20%") s.append(svg.SVG("text", bt, x=12+(i*10), y=3, stroke="none", fill="black")) s.append(svg.SVG("rect", x=14+(i*10), y=0, width=4, height=3, stroke="none", fill=colors[b], fill_opacity=0.5)) reader = open(opts.input_file, 'U') samples = [] for i in range(int(len(args)/3)): index = i*3 samples.append(dict(name=args[index], a_col=args[index+1], totals_col=args[index+2])) if opts.zoom == 'interactive': y = 35 else: y = 25 for i, sample in enumerate(samples): x = 23+(i*(WIDTH+GAP)) t = svg.SVG("text", svg.SVG("tspan", sample['name'], style="font-family:Verdana;font-size:25%"), x=x, y=y, transform="rotate(-90 %i,%i)" % (x, y), stroke="none", fill="black") s.append(t) count=1 for line in reader: row = line.split('\t') highlighted_position = False show_pos = True position = row[int(opts.position_col)-1] ref = row[int(opts.ref_col)-1].strip().upper() # validate if ref not in bases: stop_error( "The reference column (col%s) contains invalid character '%s' at row %i of the dataset." % ( opts.ref_col, ref, count ) ) # display positions if opts.zoom == 'interactive': textx = 0 else: textx = 7 bt = svg.SVG("tspan", str(position), style="font-family:Verdana;font-size:25%") s.append(svg.SVG("text", bt, x=textx, y=34+(count*(HEIGHT+GAP)), stroke="none", fill="black")) s.append(svg.SVG("rect", x=0, y=30+(count*(HEIGHT+GAP)), width=14, height=HEIGHT, stroke='none', fill=colors[ref.upper()], fill_opacity=0.2)) for sample_index, sample in enumerate(samples): n_a = int(row[int(sample['a_col'])-1]) n_c = int(row[int(sample['a_col'])+1-1]) n_g = int(row[int(sample['a_col'])+2-1]) n_t = int(row[int(sample['a_col'])+3-1]) total = int(row[int(sample['totals_col'])-1]) # validate base_error = validate_bases(n_a, n_c, n_g, n_t, total) if base_error: stop_error("For sample %i (%s), the number of base %s reads is more than the coverage on row %i." % (sample_index+1, sample['name'], base_error, count)) if total: x = 16+(sample_index*(WIDTH+GAP)) y = 30+(count*(HEIGHT+GAP)) width = WIDTH height = HEIGHT if count%2: s.append(svg.SVG("rect", x=x, y=y, width=width, height=height, stroke='none', fill='grey', fill_opacity=0.25)) else: s.append(svg.SVG("rect", x=x, y=y, width=width, height=height, stroke='none', fill='grey', fill_opacity=0.25)) for base, value in enumerate([n_a, n_c, n_g, n_t]): width = int(math.ceil(value / total * WIDTH)) s.append(svg.SVG("rect", x=x, y=y, width=width, height=BAR_WIDTH, stroke='none', fill=colors[bases[base]], fill_opacity=0.6)) y = y + BAR_WIDTH count=count+1 if opts.zoom == 'interactive': canv = svg.canvas(s) canv.save(opts.output_file) import fileinput flag = False for line in fileinput.input(opts.output_file, inplace=1): if line.startswith('<svg'): print '<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1">' flag = True continue else: if flag: print '<script type="text/javascript">%s</script>' % SVGPan flag = False print line, else: zoom = int(opts.zoom) w = "%ipx" % (x*(10+zoom)) h = "%ipx" % (y*(2+zoom)) canv = svg.canvas(s, width=w, height=h, viewBox="0 0 %i %i" %(x+100, y+100)) canv.save(opts.output_file)
def generate_workflow_image( self, trans, repository_metadata_id, workflow_name, webapp='community' ): repository_metadata = get_repository_metadata_by_id( trans, repository_metadata_id ) repository_id = trans.security.encode_id( repository_metadata.repository_id ) changeset_revision = repository_metadata.changeset_revision metadata = repository_metadata.metadata workflow_name = decode( workflow_name ) # metadata[ 'workflows' ] is a list of tuples where each contained tuple is # [ <relative path to the .ga file in the repository>, <exported workflow dict> ] for workflow_tup in metadata[ 'workflows' ]: workflow_dict = workflow_tup[1] if workflow_dict[ 'name' ] == workflow_name: break if 'tools' in metadata: tools_metadata = metadata[ 'tools' ] else: tools_metadata = [] workflow, missing_tool_tups = self.__workflow_from_dict( trans, workflow_dict, tools_metadata, repository_id, changeset_revision ) data = [] canvas = svgfig.canvas( style="stroke:black; fill:none; stroke-width:1px; stroke-linejoin:round; text-anchor:left" ) text = svgfig.SVG( "g" ) connectors = svgfig.SVG( "g" ) boxes = svgfig.SVG( "g" ) svgfig.Text.defaults[ "font-size" ] = "10px" in_pos = {} out_pos = {} margin = 5 # Spacing between input/outputs. line_px = 16 # Store px width for boxes of each step. widths = {} max_width, max_x, max_y = 0, 0, 0 for step in workflow.steps: step.upgrade_messages = {} module = module_factory.from_workflow_step( trans, repository_id, changeset_revision, tools_metadata, step ) tool_errors = module.type == 'tool' and not module.tool module_data_inputs = self.__get_data_inputs( step, module ) module_data_outputs = self.__get_data_outputs( step, module, workflow.steps ) step_dict = { 'id' : step.order_index, 'data_inputs' : module_data_inputs, 'data_outputs' : module_data_outputs, 'position' : step.position, 'tool_errors' : tool_errors } input_conn_dict = {} for conn in step.input_connections: input_conn_dict[ conn.input_name ] = dict( id=conn.output_step.order_index, output_name=conn.output_name ) step_dict[ 'input_connections' ] = input_conn_dict data.append( step_dict ) x, y = step.position[ 'left' ], step.position[ 'top' ] count = 0 module_name = self.__get_name( module, missing_tool_tups ) max_len = len( module_name ) * 1.5 text.append( svgfig.Text( x, y + 20, module_name, **{ "font-size": "14px" } ).SVG() ) y += 45 for di in module_data_inputs: cur_y = y + count * line_px if step.order_index not in in_pos: in_pos[ step.order_index ] = {} in_pos[ step.order_index ][ di[ 'name' ] ] = ( x, cur_y ) text.append( svgfig.Text( x, cur_y, di[ 'label' ] ).SVG() ) count += 1 max_len = max( max_len, len( di[ 'label' ] ) ) if len( module.get_data_inputs() ) > 0: y += 15 for do in module_data_outputs: cur_y = y + count * line_px if step.order_index not in out_pos: out_pos[ step.order_index ] = {} out_pos[ step.order_index ][ do[ 'name' ] ] = ( x, cur_y ) text.append( svgfig.Text( x, cur_y, do[ 'name' ] ).SVG() ) count += 1 max_len = max( max_len, len( do['name' ] ) ) widths[ step.order_index ] = max_len * 5.5 max_x = max( max_x, step.position[ 'left' ] ) max_y = max( max_y, step.position[ 'top' ] ) max_width = max( max_width, widths[ step.order_index ] ) for step_dict in data: tool_unavailable = step_dict[ 'tool_errors' ] width = widths[ step_dict[ 'id' ] ] x, y = step_dict[ 'position' ][ 'left' ], step_dict[ 'position' ][ 'top' ] if tool_unavailable: fill = "#EBBCB2" else: fill = "#EBD9B2" boxes.append( svgfig.Rect( x - margin, y, x + width - margin, y + 30, fill=fill ).SVG() ) box_height = ( len( step_dict[ 'data_inputs' ] ) + len( step_dict[ 'data_outputs' ] ) ) * line_px + margin # Draw separator line. if len( step_dict[ 'data_inputs' ] ) > 0: box_height += 15 sep_y = y + len( step_dict[ 'data_inputs' ] ) * line_px + 40 text.append( svgfig.Line( x - margin, sep_y, x + width - margin, sep_y ).SVG() ) # Define an input/output box. boxes.append( svgfig.Rect( x - margin, y + 30, x + width - margin, y + 30 + box_height, fill="#ffffff" ).SVG() ) for conn, output_dict in step_dict[ 'input_connections' ].iteritems(): in_coords = in_pos[ step_dict[ 'id' ] ][ conn ] # out_pos_index will be a step number like 1, 2, 3... out_pos_index = output_dict[ 'id' ] # out_pos_name will be a string like 'o', 'o2', etc. out_pos_name = output_dict[ 'output_name' ] if out_pos_index in out_pos: # out_conn_index_dict will be something like: # 7: {'o': (824.5, 618)} out_conn_index_dict = out_pos[ out_pos_index ] if out_pos_name in out_conn_index_dict: out_conn_pos = out_pos[ out_pos_index ][ out_pos_name ] else: # Take any key / value pair available in out_conn_index_dict. # A problem will result if the dictionary is empty. if out_conn_index_dict.keys(): key = out_conn_index_dict.keys()[0] out_conn_pos = out_pos[ out_pos_index ][ key ] adjusted = ( out_conn_pos[ 0 ] + widths[ output_dict[ 'id' ] ], out_conn_pos[ 1 ] ) text.append( svgfig.SVG( "circle", cx=out_conn_pos[ 0 ] + widths[ output_dict[ 'id' ] ] - margin, cy=out_conn_pos[ 1 ] - margin, r = 5, fill="#ffffff" ) ) connectors.append( svgfig.Line( adjusted[ 0 ], adjusted[ 1 ] - margin, in_coords[ 0 ] - 10, in_coords[ 1 ], arrow_end = "true" ).SVG() ) canvas.append( connectors ) canvas.append( boxes ) canvas.append( text ) width, height = ( max_x + max_width + 50 ), max_y + 300 canvas[ 'width' ] = "%s px" % width canvas[ 'height' ] = "%s px" % height canvas[ 'viewBox' ] = "0 0 %s %s" % ( width, height ) trans.response.set_content_type( "image/svg+xml" ) return canvas.standalone_xml()
def generate_workflow_image( trans, workflow_name, repository_metadata_id=None, repository_id=None ): """ Return an svg image representation of a workflow dictionary created when the workflow was exported. This method is called from both Galaxy and the tool shed. When called from the tool shed, repository_metadata_id will have a value and repository_id will be None. When called from Galaxy, repository_metadata_id will be None and repository_id will have a value. """ workflow_name = encoding_util.tool_shed_decode( workflow_name ) if trans.webapp.name == 'community': # We're in the tool shed. repository_metadata = suc.get_repository_metadata_by_id( trans, repository_metadata_id ) repository_id = trans.security.encode_id( repository_metadata.repository_id ) changeset_revision = repository_metadata.changeset_revision metadata = repository_metadata.metadata else: # We're in Galaxy. repository = suc.get_tool_shed_repository_by_id( trans, repository_id ) changeset_revision = repository.changeset_revision metadata = repository.metadata # metadata[ 'workflows' ] is a list of tuples where each contained tuple is # [ <relative path to the .ga file in the repository>, <exported workflow dict> ] for workflow_tup in metadata[ 'workflows' ]: workflow_dict = workflow_tup[1] if workflow_dict[ 'name' ] == workflow_name: break if 'tools' in metadata: tools_metadata = metadata[ 'tools' ] else: tools_metadata = [] workflow, missing_tool_tups = get_workflow_from_dict( trans=trans, workflow_dict=workflow_dict, tools_metadata=tools_metadata, repository_id=repository_id, changeset_revision=changeset_revision ) data = [] canvas = svgfig.canvas( style="stroke:black; fill:none; stroke-width:1px; stroke-linejoin:round; text-anchor:left" ) text = svgfig.SVG( "g" ) connectors = svgfig.SVG( "g" ) boxes = svgfig.SVG( "g" ) svgfig.Text.defaults[ "font-size" ] = "10px" in_pos = {} out_pos = {} margin = 5 # Spacing between input/outputs. line_px = 16 # Store px width for boxes of each step. widths = {} max_width, max_x, max_y = 0, 0, 0 for step in workflow.steps: step.upgrade_messages = {} module = module_factory.from_workflow_step( trans, repository_id, changeset_revision, tools_metadata, step ) tool_errors = module.type == 'tool' and not module.tool module_data_inputs = get_workflow_data_inputs( step, module ) module_data_outputs = get_workflow_data_outputs( step, module, workflow.steps ) step_dict = { 'id' : step.order_index, 'data_inputs' : module_data_inputs, 'data_outputs' : module_data_outputs, 'position' : step.position, 'tool_errors' : tool_errors } input_conn_dict = {} for conn in step.input_connections: input_conn_dict[ conn.input_name ] = dict( id=conn.output_step.order_index, output_name=conn.output_name ) step_dict[ 'input_connections' ] = input_conn_dict data.append( step_dict ) x, y = step.position[ 'left' ], step.position[ 'top' ] count = 0 module_name = get_workflow_module_name( module, missing_tool_tups ) max_len = len( module_name ) * 1.5 text.append( svgfig.Text( x, y + 20, module_name, **{ "font-size": "14px" } ).SVG() ) y += 45 for di in module_data_inputs: cur_y = y + count * line_px if step.order_index not in in_pos: in_pos[ step.order_index ] = {} in_pos[ step.order_index ][ di[ 'name' ] ] = ( x, cur_y ) text.append( svgfig.Text( x, cur_y, di[ 'label' ] ).SVG() ) count += 1 max_len = max( max_len, len( di[ 'label' ] ) ) if len( module.get_data_inputs() ) > 0: y += 15 for do in module_data_outputs: cur_y = y + count * line_px if step.order_index not in out_pos: out_pos[ step.order_index ] = {} out_pos[ step.order_index ][ do[ 'name' ] ] = ( x, cur_y ) text.append( svgfig.Text( x, cur_y, do[ 'name' ] ).SVG() ) count += 1 max_len = max( max_len, len( do['name' ] ) ) widths[ step.order_index ] = max_len * 5.5 max_x = max( max_x, step.position[ 'left' ] ) max_y = max( max_y, step.position[ 'top' ] ) max_width = max( max_width, widths[ step.order_index ] ) for step_dict in data: tool_unavailable = step_dict[ 'tool_errors' ] width = widths[ step_dict[ 'id' ] ] x, y = step_dict[ 'position' ][ 'left' ], step_dict[ 'position' ][ 'top' ] # Only highlight missing tools if displaying in the tool shed. if trans.webapp.name == 'community' and tool_unavailable: fill = "#EBBCB2" else: fill = "#EBD9B2" boxes.append( svgfig.Rect( x - margin, y, x + width - margin, y + 30, fill=fill ).SVG() ) box_height = ( len( step_dict[ 'data_inputs' ] ) + len( step_dict[ 'data_outputs' ] ) ) * line_px + margin # Draw separator line. if len( step_dict[ 'data_inputs' ] ) > 0: box_height += 15 sep_y = y + len( step_dict[ 'data_inputs' ] ) * line_px + 40 text.append( svgfig.Line( x - margin, sep_y, x + width - margin, sep_y ).SVG() ) # Define an input/output box. boxes.append( svgfig.Rect( x - margin, y + 30, x + width - margin, y + 30 + box_height, fill="#ffffff" ).SVG() ) for conn, output_dict in step_dict[ 'input_connections' ].iteritems(): in_coords = in_pos[ step_dict[ 'id' ] ][ conn ] # out_pos_index will be a step number like 1, 2, 3... out_pos_index = output_dict[ 'id' ] # out_pos_name will be a string like 'o', 'o2', etc. out_pos_name = output_dict[ 'output_name' ] if out_pos_index in out_pos: # out_conn_index_dict will be something like: # 7: {'o': (824.5, 618)} out_conn_index_dict = out_pos[ out_pos_index ] if out_pos_name in out_conn_index_dict: out_conn_pos = out_pos[ out_pos_index ][ out_pos_name ] else: # Take any key / value pair available in out_conn_index_dict. # A problem will result if the dictionary is empty. if out_conn_index_dict.keys(): key = out_conn_index_dict.keys()[0] out_conn_pos = out_pos[ out_pos_index ][ key ] adjusted = ( out_conn_pos[ 0 ] + widths[ output_dict[ 'id' ] ], out_conn_pos[ 1 ] ) text.append( svgfig.SVG( "circle", cx=out_conn_pos[ 0 ] + widths[ output_dict[ 'id' ] ] - margin, cy=out_conn_pos[ 1 ] - margin, r = 5, fill="#ffffff" ) ) connectors.append( svgfig.Line( adjusted[ 0 ], adjusted[ 1 ] - margin, in_coords[ 0 ] - 10, in_coords[ 1 ], arrow_end = "true" ).SVG() ) canvas.append( connectors ) canvas.append( boxes ) canvas.append( text ) width, height = ( max_x + max_width + 50 ), max_y + 300 canvas[ 'width' ] = "%s px" % width canvas[ 'height' ] = "%s px" % height canvas[ 'viewBox' ] = "0 0 %s %s" % ( width, height ) trans.response.set_content_type( "image/svg+xml" ) return canvas.standalone_xml()
style += "font-weight:bold;" else: style += "font-weight:normal;" if italic: style += "font-style:italic;" else: style += "font-style:normal;" style += "font-family:%s" % name #t1 = SVG("text", content, x=0, y=line_height, style=style) t1 = SVG("text", content, x=-128, y=300, style=style) counter += 1 g.append(t1) svg = canvas() width = 90 svg.attr['viewBox'] = "0 0 %s %s" % (width, line_height*counter) svg.attr['width'] = width svg.attr['height'] = line_height svg.sub.append(g) svg.save("%s.svg" % content) #this works: #g = SVG("g", *collection, fill_opacity="50%") #g.save("tmp.svg") #main.save("tmp.svg")
from grapefruit import Color from svgfig import SVG,canvas,Text w = 522 h = 800 svg = canvas(width='%dpx' % w, height='%dpx' % h, viewBox='0 0 %d %d' % (w, h), enable_background='new 0 0 %d %d' % (w, h), style='stroke:none;') yo = 10 for k in Color.NAMED_COLOR: c = Color.NewFromHtml(Color.NAMED_COLOR[k], wref=Color.WHITE_REFERENCE['std_D50']) out = [k] out.append(c.html) r,g,b = c.rgb out.append([int(r*255),int(g*255),int(b*255)]) out.append(list(c.hsv)) out.append(list(c.hsl)) l,a,b = c.lab out.append([l/100.0,a,b]) #print 'colors.push( ' + str(out) +' );' print 'colors.'+k+' = "'+c.html+'"' svg.append(Text(23,yo+15,k,style='font-size:12px').SVG()) svg.append(SVG('rect',10,y=yo,width=20,height=20,fill=c.html)) yo += 24 svg.firefox()
if groups[groupID]["timeEnd"] < link["time"]: groups[groupID]["timeEnd"] = link["time"] if groups[groupID]["nodeStart"] > min(link["from"], link["to"]): groups[groupID]["nodeStart"] = min(link["from"], link["to"]) if groups[groupID]["nodeEnd"] < max(link["from"], link["to"]): groups[groupID]["nodeEnd"] = max(link["from"], link["to"]) # Draw groups # for group in groups: # print "Time start : " + str(groups[group]["timeStart"]*hoffset) # print "Time end : " + str(groups[group]["timeEnd"]*hoffset) # print "Node start : " + str(groups[group]["nodeStart"]) # print "Node end : " + str(groups[group]["nodeEnd"]) # g.append(svgfig.SVG("rect", x=str(groups[group]["timeStart"]*hoffset), y=str(groups[group]["nodeStart"]*voffset), width=str(groups[group]["timeEnd"]*hoffset - groups[group]["timeStart"]*hoffset - 21), height=str(groups[group]["nodeEnd"]*voffset - groups[group]["nodeStart"]*voffset), style="fill:blue;stroke:blue;stroke-width:1;fill-opacity:0;stroke-opacity:0.9")) # Save to svg file if argv.get("output") is not None: svgfig.canvas(g, viewBox="0 0 " + str(width) + " " + str(height)).save( argv["output"]) if not argv["silent"]: sys.stderr.write("Output generated to " + str(argv["output"]) + ".\n") else: svgfig.canvas(g, viewBox="0 0 " + str(width) + " " + str(height)).save("out.svg") if not argv["silent"]: sys.stderr.write(" Output generated to out.svg.\n")
## bbox = svgfig.Rect(1,1,w-1,h-1) branches = [] labels = [] for n, c in n2c.items(): if n.parent: pc = n2c[n.parent] d = ((c.x, c.y), (pc.x, c.y), (pc.x, pc.y)) line = svgfig.Poly(d) branches.append(line) if n.label: label = svgfig.Text(c.x, c.y, n.label, font_size=fontsize) label.attr["text-anchor"] = "start" # this should vertically align the point to the middle of the # text, but doesn't: # label.attr["alignment-baseline"] ="middle" # so shift y down label.y += fontsize / 3 labels.append(label) fig = svgfig.Fig(svgfig.Fig(*branches), svgfig.Fig(*labels)) w = getwidth(fig, w, h) svg = fig.SVG() vb = "%s %s %s %s" % (-10, -10, w + 10, h + 10) ## print svgfig.canvas(svg, width=w, height=h, viewBox=vb).xml() ## svgfig.canvas(svg, width=w, height=h, viewBox=vb).save() svgfig.canvas(svg, width=w, height=h, viewBox=vb).inkscape() ## svgfig.canvas(svg, width=w, height=h, viewBox=vb).firefox()
def generate_workflow_image(trans, workflow_name, repository_metadata_id=None, repository_id=None): """ Return an svg image representation of a workflow dictionary created when the workflow was exported. This method is called from both Galaxy and the tool shed. When called from the tool shed, repository_metadata_id will have a value and repository_id will be None. When called from Galaxy, repository_metadata_id will be None and repository_id will have a value. """ workflow_name = encoding_util.tool_shed_decode(workflow_name) if trans.webapp.name == "tool_shed": # We're in the tool shed. repository_metadata = metadata_util.get_repository_metadata_by_id(trans, repository_metadata_id) repository_id = trans.security.encode_id(repository_metadata.repository_id) changeset_revision = repository_metadata.changeset_revision metadata = repository_metadata.metadata else: # We're in Galaxy. repository = suc.get_tool_shed_repository_by_id(trans, repository_id) changeset_revision = repository.changeset_revision metadata = repository.metadata # metadata[ 'workflows' ] is a list of tuples where each contained tuple is # [ <relative path to the .ga file in the repository>, <exported workflow dict> ] for workflow_tup in metadata["workflows"]: workflow_dict = workflow_tup[1] if workflow_dict["name"] == workflow_name: break if "tools" in metadata: tools_metadata = metadata["tools"] else: tools_metadata = [] workflow, missing_tool_tups = get_workflow_from_dict( trans=trans, workflow_dict=workflow_dict, tools_metadata=tools_metadata, repository_id=repository_id, changeset_revision=changeset_revision, ) data = [] canvas = svgfig.canvas(style="stroke:black; fill:none; stroke-width:1px; stroke-linejoin:round; text-anchor:left") text = svgfig.SVG("g") connectors = svgfig.SVG("g") boxes = svgfig.SVG("g") svgfig.Text.defaults["font-size"] = "10px" in_pos = {} out_pos = {} margin = 5 # Spacing between input/outputs. line_px = 16 # Store px width for boxes of each step. widths = {} max_width, max_x, max_y = 0, 0, 0 for step in workflow.steps: step.upgrade_messages = {} module = module_factory.from_workflow_step(trans, repository_id, changeset_revision, tools_metadata, step) tool_errors = module.type == "tool" and not module.tool module_data_inputs = get_workflow_data_inputs(step, module) module_data_outputs = get_workflow_data_outputs(step, module, workflow.steps) step_dict = { "id": step.order_index, "data_inputs": module_data_inputs, "data_outputs": module_data_outputs, "position": step.position, "tool_errors": tool_errors, } input_conn_dict = {} for conn in step.input_connections: input_conn_dict[conn.input_name] = dict(id=conn.output_step.order_index, output_name=conn.output_name) step_dict["input_connections"] = input_conn_dict data.append(step_dict) x, y = step.position["left"], step.position["top"] count = 0 module_name = get_workflow_module_name(module, missing_tool_tups) max_len = len(module_name) * 1.5 text.append(svgfig.Text(x, y + 20, module_name, **{"font-size": "14px"}).SVG()) y += 45 for di in module_data_inputs: cur_y = y + count * line_px if step.order_index not in in_pos: in_pos[step.order_index] = {} in_pos[step.order_index][di["name"]] = (x, cur_y) text.append(svgfig.Text(x, cur_y, di["label"]).SVG()) count += 1 max_len = max(max_len, len(di["label"])) if len(module.get_data_inputs()) > 0: y += 15 for do in module_data_outputs: cur_y = y + count * line_px if step.order_index not in out_pos: out_pos[step.order_index] = {} out_pos[step.order_index][do["name"]] = (x, cur_y) text.append(svgfig.Text(x, cur_y, do["name"]).SVG()) count += 1 max_len = max(max_len, len(do["name"])) widths[step.order_index] = max_len * 5.5 max_x = max(max_x, step.position["left"]) max_y = max(max_y, step.position["top"]) max_width = max(max_width, widths[step.order_index]) for step_dict in data: tool_unavailable = step_dict["tool_errors"] width = widths[step_dict["id"]] x, y = step_dict["position"]["left"], step_dict["position"]["top"] # Only highlight missing tools if displaying in the tool shed. if trans.webapp.name == "tool_shed" and tool_unavailable: fill = "#EBBCB2" else: fill = "#EBD9B2" boxes.append(svgfig.Rect(x - margin, y, x + width - margin, y + 30, fill=fill).SVG()) box_height = (len(step_dict["data_inputs"]) + len(step_dict["data_outputs"])) * line_px + margin # Draw separator line. if len(step_dict["data_inputs"]) > 0: box_height += 15 sep_y = y + len(step_dict["data_inputs"]) * line_px + 40 text.append(svgfig.Line(x - margin, sep_y, x + width - margin, sep_y).SVG()) # Define an input/output box. boxes.append(svgfig.Rect(x - margin, y + 30, x + width - margin, y + 30 + box_height, fill="#ffffff").SVG()) for conn, output_dict in step_dict["input_connections"].iteritems(): in_coords = in_pos[step_dict["id"]][conn] # out_pos_index will be a step number like 1, 2, 3... out_pos_index = output_dict["id"] # out_pos_name will be a string like 'o', 'o2', etc. out_pos_name = output_dict["output_name"] if out_pos_index in out_pos: # out_conn_index_dict will be something like: # 7: {'o': (824.5, 618)} out_conn_index_dict = out_pos[out_pos_index] if out_pos_name in out_conn_index_dict: out_conn_pos = out_pos[out_pos_index][out_pos_name] else: # Take any key / value pair available in out_conn_index_dict. # A problem will result if the dictionary is empty. if out_conn_index_dict.keys(): key = out_conn_index_dict.keys()[0] out_conn_pos = out_pos[out_pos_index][key] adjusted = (out_conn_pos[0] + widths[output_dict["id"]], out_conn_pos[1]) text.append( svgfig.SVG( "circle", cx=out_conn_pos[0] + widths[output_dict["id"]] - margin, cy=out_conn_pos[1] - margin, r=5, fill="#ffffff", ) ) connectors.append( svgfig.Line(adjusted[0], adjusted[1] - margin, in_coords[0] - 10, in_coords[1], arrow_end="true").SVG() ) canvas.append(connectors) canvas.append(boxes) canvas.append(text) width, height = (max_x + max_width + 50), max_y + 300 canvas["width"] = "%s px" % width canvas["height"] = "%s px" % height canvas["viewBox"] = "0 0 %s %s" % (width, height) trans.response.set_content_type("image/svg+xml") return canvas.standalone_xml()
if groups[groupID]["timeStart"] > link["time"]: groups[groupID]["timeStart"] = link["time"] if groups[groupID]["timeEnd"] < link["time"]: groups[groupID]["timeEnd"] = link["time"] if groups[groupID]["nodeStart"] > min(link["from"], link["to"]): groups[groupID]["nodeStart"] = min(link["from"], link["to"]) if groups[groupID]["nodeEnd"] < max(link["from"], link["to"]): groups[groupID]["nodeEnd"] = max(link["from"], link["to"]) # Draw groups # for group in groups: # print "Time start : " + str(groups[group]["timeStart"]*hoffset) # print "Time end : " + str(groups[group]["timeEnd"]*hoffset) # print "Node start : " + str(groups[group]["nodeStart"]) # print "Node end : " + str(groups[group]["nodeEnd"]) # g.append(svgfig.SVG("rect", x=str(groups[group]["timeStart"]*hoffset), y=str(groups[group]["nodeStart"]*voffset), width=str(groups[group]["timeEnd"]*hoffset - groups[group]["timeStart"]*hoffset - 21), height=str(groups[group]["nodeEnd"]*voffset - groups[group]["nodeStart"]*voffset), style="fill:blue;stroke:blue;stroke-width:1;fill-opacity:0;stroke-opacity:0.9")) # Save to svg file if argv.get("output") is not None: svgfig.canvas(g, viewBox="0 0 " + str(width) + " " + str(height)).save(argv["output"]) if not argv["silent"]: sys.stderr.write("Output generated to "+ str(argv["output"]) + ".\n") else: svgfig.canvas(g, viewBox="0 0 " + str(width) + " " + str(height)).save("out.svg") if not argv["silent"]: sys.stderr.write(" Output generated to out.svg.\n")
## bbox = svgfig.Rect(1,1,w-1,h-1) branches = [] labels = [] for n, c in n2c.items(): if n.parent: pc = n2c[n.parent] d = ((c.x, c.y), (pc.x, c.y), (pc.x, pc.y)) line = svgfig.Poly(d) branches.append(line) if n.label: label = svgfig.Text(c.x, c.y, n.label, font_size=fontsize) label.attr["text-anchor"] = "start" # this should vertically align the point to the middle of the # text, but doesn't: # label.attr["alignment-baseline"] ="middle" # so shift y down label.y += fontsize/3 labels.append(label) fig = svgfig.Fig(svgfig.Fig(*branches),svgfig.Fig(*labels)) w = getwidth(fig, w, h) svg = fig.SVG() vb = "%s %s %s %s" % (-10, -10, w+10,h+10) ## print svgfig.canvas(svg, width=w, height=h, viewBox=vb).xml() ## svgfig.canvas(svg, width=w, height=h, viewBox=vb).save() svgfig.canvas(svg, width=w, height=h, viewBox=vb).inkscape() ## svgfig.canvas(svg, width=w, height=h, viewBox=vb).firefox()
from grapefruit import Color from svgfig import SVG, canvas, Text w = 522 h = 800 svg = canvas(width='%dpx' % w, height='%dpx' % h, viewBox='0 0 %d %d' % (w, h), enable_background='new 0 0 %d %d' % (w, h), style='stroke:none;') yo = 10 for k in Color.NAMED_COLOR: c = Color.NewFromHtml(Color.NAMED_COLOR[k], wref=Color.WHITE_REFERENCE['std_D50']) out = [k] out.append(c.html) r, g, b = c.rgb out.append([int(r * 255), int(g * 255), int(b * 255)]) out.append(list(c.hsv)) out.append(list(c.hsl)) l, a, b = c.lab out.append([l / 100.0, a, b]) #print 'colors.push( ' + str(out) +' );' print 'colors.' + k + ' = "' + c.html + '"' svg.append(Text(23, yo + 15, k, style='font-size:12px').SVG()) svg.append(SVG('rect', 10, y=yo, width=20, height=20, fill=c.html)) yo += 24
def save(self, name, **kwargs): s = svg.Fig(*self.lines).SVG() c = svg.canvas(s, **kwargs) c.save(name) return self
def draw(self, outputFile): self.findOrder() offset = 1.5 * self.ppux # Define dimensions label_margin = 5 * self.max_label_len origleft = label_margin + 1 * self.ppux right_margin = self.ppux width = origleft + self.ppux * math.ceil(self.max_time) + right_margin svgfig._canvas_defaults["width"] = str(width) + 'px' arrow_of_time_height = 5 height = 5 + 10 * int(self.nodeID.size() + 1) + arrow_of_time_height svgfig._canvas_defaults["height"] = str(height) + 'px' origtop = 10 ################ # Draw background lines for node in self.nodeID.lookUp: horizonta_axe = self.ppux * self.nodeID.get(node) + origtop self.g.append( svgfig.SVG("text", str(node), x=str(label_margin), y=horizonta_axe + 2, fill="black", stroke_width=0, text_anchor="end", font_size="6")) self.g.append( svgfig.SVG("line", stroke_dasharray="2,2", stroke_width=0.5, x1=str(origleft - 5), y1=horizonta_axe, x2=width - right_margin, y2=horizonta_axe)) # Add timearrow self.g.append( svgfig.SVG("line", stroke_width=0.5, x1=self.ppux, y1=10 * (self.nodeID.size() + 1), x2=width - 5, y2=10 * (self.nodeID.size() + 1))) self.g.append( svgfig.SVG("line", stroke_width=0.5, x1=width - 8, y1=10 * (self.nodeID.size() + 1) - 3, x2=width - 5, y2=10 * (self.nodeID.size() + 1))) self.g.append( svgfig.SVG("line", stroke_width=0.5, x1=width - 8, y1=10 * (self.nodeID.size() + 1) + 3, x2=width - 5, y2=10 * (self.nodeID.size() + 1))) self.g.append( svgfig.SVG("text", str("Time"), x=width - 19, y=10 * (self.nodeID.size() + 1) - 3, fill="black", stroke_width=0, font_size="6")) # # Add time ticks for i in range(0, int(math.ceil(self.max_time) + 1), 5): x_tick = i * self.ppux + origleft self.g.append( svgfig.SVG("line", stroke_width=0.5, x1=str(x_tick), y1=10 * (self.nodeID.size() + 1) - 3, x2=str(x_tick), y2=10 * (self.nodeID.size() + 1) + 3)) self.g.append( svgfig.SVG("text", str(i), x=str(x_tick), y=10 * (self.nodeID.size() + 1) + 7, fill="black", stroke_width=0, font_size="6")) for link in self.links: ts = link.t node_1 = min(self.nodeID.get(link.u), self.nodeID.get(link.v)) node_2 = max(self.nodeID.get(link.u), self.nodeID.get(link.v)) offset = ts * self.ppux + origleft y_node1 = 10 * node_1 + origtop y_node2 = 10 * node_2 + origtop # Add nodes self.g.append( svgfig.SVG("circle", cx=offset, cy=y_node1, r=1, fill=link.color)) self.g.append( svgfig.SVG("circle", cx=offset, cy=y_node2, r=1, fill=link.color)) x = 0.2 * ( (10 * node_2 - 10 * node_1) / math.tan(math.pi / 3)) + offset y = (y_node1 + y_node2) / 2 param_d = "M" + str(offset) + "," + str(y_node1) +\ " C" + str(x) + "," + str(y) + " " + str(x) + "," + str(y) +\ " " + str(offset) + "," + str(y_node2) self.g.append(svgfig.SVG("path", stroke=link.color, d=param_d)) self.addDuration({ "x": x, "y": (y_node1 + y_node2) / 2 }, link.duration, link.duration_color) # Save to svg file viewBoxparam = "0 0 " + str(width) + " " + str(height) svgfig.canvas(self.g, viewBox=viewBoxparam).save(outputFile)
def draw_kakuro_svg(): import svgfig x_size = 8 y_size = 9 puzzle = (0, 0, 0, 0, 0, 0, (0, 16), (0, 3), 0, 0, 0, 0, 0, (8, 6), 1, 1, 0, (0, 16), (0, 6), 0, (14, 30), 1, 1, 1, (11, 0), 1, 1, (7, 0), 1, 1, (0, 6), 0, (10, 0), 1, 1, (13, 7), 1, 1, 1, (0, 16), 0, (14, 0), 1, 1, 1, (8, 0), 1, 1, 0, (0, 4), (9, 17), 1, 1, (11, 0), 1, 1, (12, 0), 1, 1, 1, 0, 0, 0, 0, (10, 0), 1, 1, 0, 0, 0, 0, 0) cells = [] CELL_WIDTH = 20 CELL_HEIGHT = 20 def draw_cell(cell_data): out = [] if cell_data == 0: out.append(svgfig.Rect(0, 0, CELL_WIDTH, CELL_HEIGHT, fill="black")) elif type(cell_data) == type(1): out.append(svgfig.Rect(0, 0, CELL_WIDTH, CELL_HEIGHT)) out.append( svgfig.Text( 10, 10, cell_data, text_anchor="middle", font_size=12, font_weight=600, dominant_baseline="middle", fill="brown", )) elif type(cell_data) == type(()): across = cell_data[0] down = cell_data[1] out.append(svgfig.Rect(0, 0, CELL_WIDTH, CELL_HEIGHT)) out.append( svgfig.Line( 0, 0, CELL_WIDTH, CELL_HEIGHT, stroke_width=1, )) if down == 0: points = ((0, 0), (0, CELL_HEIGHT), (CELL_WIDTH, CELL_HEIGHT)) out.append(svgfig.Poly(points, "lines", fill="black")) else: out.append( svgfig.Text( 2, 18, down, text_anchor="start", font_size=7, alignment_baseline="middle", )) if across == 0: points = ((0, 0), (CELL_WIDTH, 0), (CELL_WIDTH, CELL_HEIGHT)) out.append(svgfig.Poly(points, "lines", fill="black")) else: out.append( svgfig.Text( 19, 7, across, text_anchor="end", font_size=7, )) else: raise Exception("") return out def cell(x, y, cell_data): def t(xi, yi): return 1 + xi + x * (CELL_WIDTH), 1 + yi + y * (CELL_HEIGHT) fig = svgfig.Fig(*draw_cell(cell_data), trans=t) return fig.SVG() for y in range(y_size): for x in range(x_size): cells.append(cell(x, y, puzzle[y * x_size + x])) g = svgfig.SVG("g", *cells) c = svgfig.canvas(g, width="400px", height="400px", font_family='Arial Black', viewBox="0 0 %d %d" % (x_size * CELL_WIDTH + 2, y_size * CELL_HEIGHT + 2)) c.save('tmp.svg')
def draw_svgfig(self, outputFile): self.findOrder() offset = 1.5 * self.ppux # Define dimensions label_margin = 5 * self.max_label_len origleft = label_margin + 1 * self.ppux right_margin = self.ppux width = origleft + self.ppux * math.ceil(self.max_time) + right_margin svgfig._canvas_defaults["width"] = str(width) + 'px' arrow_of_time_height = 5 height = 5 + 10 * int(self.nodeID.size() + 1) + arrow_of_time_height svgfig._canvas_defaults["height"] = str(height) + 'px' origtop = 10 ################ # Draw background lines for node in self.nodeID.lookUp: horizonta_axe = self.ppux * self.nodeID.get(node) + origtop self.g.append(svgfig.SVG("text", str(node), x=str(label_margin), y=horizonta_axe + 2, fill="black", stroke_width=0, text_anchor="end", font_size="6")) self.g.append(svgfig.SVG("line", stroke_dasharray="2,2", stroke_width=0.5, x1=str(origleft-5), y1=horizonta_axe, x2=width - right_margin, y2=horizonta_axe)) # Add timearrow self.g.append(svgfig.SVG("line", stroke_width=0.5, x1=self.ppux , y1=10*(self.nodeID.size()+1), x2=width-5, y2=10*(self.nodeID.size()+1))) self.g.append(svgfig.SVG("line", stroke_width=0.5, x1=width-8, y1=10*(self.nodeID.size()+1)-3, x2=width-5, y2=10*(self.nodeID.size()+1))) self.g.append(svgfig.SVG("line", stroke_width=0.5, x1=width-8, y1=10*(self.nodeID.size()+1)+3, x2=width-5, y2=10*(self.nodeID.size()+1))) self.g.append(svgfig.SVG("text", str("Time"), x=width-19, y=10*(self.nodeID.size()+1)-3, fill="black", stroke_width=0, font_size="6")) # # Add time ticks for i in range(0, int(math.ceil(self.max_time)+1), 5): x_tick = i * self.ppux + origleft self.g.append(svgfig.SVG("line", stroke_width=0.5, x1=str(x_tick), y1=10*(self.nodeID.size()+1)-3, x2=str(x_tick), y2=10*(self.nodeID.size()+1)+3)) self.g.append(svgfig.SVG("text", str(i), x=str(x_tick), y=10*(self.nodeID.size()+1)+7, fill="black", stroke_width=0, font_size="6")) for link in self.links: ts = link.t node_1 = min(self.nodeID.get(link.u), self.nodeID.get(link.v)) node_2 = max(self.nodeID.get(link.u), self.nodeID.get(link.v)) offset = ts * self.ppux + origleft y_node1 = 10 * node_1 + origtop y_node2 = 10 * node_2 + origtop # Add nodes self.g.append(svgfig.SVG("circle", cx=offset, cy=y_node1, r=1, fill=link.color)) self.g.append(svgfig.SVG("circle", cx=offset, cy=y_node2, r=1, fill=link.color)) x = 0.2 * ((10 * node_2 - 10 * node_1) / math.tan(math.pi / 3)) + offset y = (y_node1 + y_node2) / 2 param_d = "M" + str(offset) + "," + str(y_node1) +\ " C" + str(x) + "," + str(y) + " " + str(x) + "," + str(y) +\ " " + str(offset) + "," + str(y_node2) self.g.append(svgfig.SVG("path", stroke=link.color, d=param_d)) self.addDuration({"x": x, "y": (y_node1+y_node2)/2}, link.duration, link.duration_color) # Save to svg file viewBoxparam = "0 0 " + str(width) + " " + str(height) svgfig.canvas(self.g, viewBox=viewBoxparam).save(outputFile)
def draw(self, filename, graphshape=None, width=1280, height=720, show_labels=False): """This does the drawing. It starts by getting a function for the bottom most layer. As descrbed in Byron & Wattenberg this will control the overall shape of the graph. It then it prints a stacked graph on top of that bottom line, whatever shape it is. """ # Preprocess some stuff aspect_ratio = float(width) / float(height) self.canvas_aspect = aspect_ratio x_offset = int(-((100 * aspect_ratio) - 100) / 2.0) # Get a g_0 depending in desired shape g_0 = self.themeRiver() # Default (fallbacks) y_offset = 0 if str(graphshape) == "Stacked_Graph": g_0 = self.stackedGraph() y_offset = 0 if str(graphshape) == "Theme_River": g_0 = self.themeRiver() y_offset = -50 if str(graphshape) == "Wiggle": g_0 = self.wiggle() y_offset = -50 if str(graphshape) == "Weighted_Wiggle": g_0 = self.weighted_wiggle() y_offset = -50 # Initilize a streamgraph groups in SVG. graph = svgfig.SVG("g", id="StreamGraph") labels = svgfig.SVG("g", id="Labels") # Initilize a SVG Window object to do the transormations on each object window = svgfig.window(self.x_min, self.x_max, 0, self.y_max * 1.3, x_offset, y_offset, int(100 * aspect_ratio), 100) # Loop through each layer for layer in range(self.n_layers): points = [] point_range = range(self.n_points) # Forwards; draw top of the shape for i in point_range: x = self.data[layer][i][0] y = self.data[layer][i][1] # Start with g_0 and stack y_stacked = g_0[i] + y # Stack! for l in range(layer): y_stacked += self.data[l][i][1] # Add the points to the shape points.append((x, y_stacked)) # Backwards; draw bottom of the shape #point_range.reverse() point_range = reversed(point_range) for i in point_range: x = self.data[layer][i][0] # This time we don't include this layer y_stacked = g_0[i] # Stack! for l in range(layer): y_stacked += self.data[l][i][1] points.append((x, y_stacked)) # Shapes poly = svgfig.Poly(points, "smooth", stroke="#eeeeee", fill=self.rgb2hex(self.colors[layer]), stroke_width="0.05") graph.append(poly.SVG(window)) if show_labels: #label = self.placeLabel(points, layer) #label = self.test_placeLabel(points, layer) #label = self.test2_placeLabel(points, layer, window) label = self.placeLabel2(points, layer) #for l in label: # labels.append(l) labels.append(label.SVG(window)) # End Loop # Add objects to the canvas and save it w = str(int(width)) + "px" h = str(int(height)) + "px" canv = svgfig.canvas(graph, labels, width=w, height=h) canv.save(filename)
def svgPathString(self): return 'M' + 'L'.join(map(str, self.points)) if __name__ == '__main__': from gisutils import Bounds2D, Point bbox = Bounds2D(left=0, top=0,width=600,height=400) from svgfig import canvas, SVG from random import randint, random from noise import pnoise1 w = 1000 h = 600 svg = canvas(width='%dpx' % w, height='%dpx' % h, viewBox='0 0 %d %d' % (w, h), enable_background='new 0 0 %d %d' % (w, h), style='stroke-width:1px; stroke-linejoin: round;') svg.append(SVG('rect', x=bbox.xmin, y=bbox.ymin, width=bbox.width, height=bbox.height, fill="#eee")) clip = CohenSutherland().clip for i in range(60): x0 = randint(0,600) x1 = randint(0,600) y0 = randint(0,400) y1 = randint(0,400) svg.append(SVG('line', x1=x0, y1=y0, x2=x1, y2=y1, stroke='#999', stroke_width='0.2px')) try: x0,y0,x1,y1 = clip(bbox, x0,y0,x1,y1) svg.append(SVG('line', x1=x0, y1=y0, x2=x1, y2=y1, stroke='#c33', stroke_width='.2px'))
x,y = p(lng, lat) points.append((x,y)) if len(points) > 3: poly = Polygon.Polygon(points) #poly = poly & cropRect if poly.overlaps(cropRect): polys.append(poly) #polys.append(cropRect) print "exporting SVG" #Polygon.IO.writeSVG('cropped.svg', polys) import svgfig h = str((y1-y2)*scale*-1) svg = svgfig.canvas(width='2000px', height=h+'px', viewBox='0 0 2000 '+h, style='stroke-width:0.5pt,fill:#fbf5ed') svg.append(SVG('rect', width='2000px', height=h+'px', fill='#006179', stroke='none')) def view(x,y): x = (x - x1) * scale y = (y - y2) * scale * -1 return (x,y) # equator grid = SVG('g') for lat in range(0,90,10): p_str = '' for lng in range(gcrop[1], gcrop[3]):
def draw_kakuro_svg(): import svgfig x_size = 8 y_size = 9 puzzle = (0,0,0,0,0,0,(0,16),(0,3), 0,0,0,0,0,(8,6),1,1, 0,(0,16),(0,6),0,(14,30),1,1,1, (11,0),1,1,(7,0),1,1,(0,6),0, (10,0),1,1,(13,7),1,1,1,(0,16), 0,(14,0),1,1,1,(8,0),1,1, 0,(0,4),(9,17),1,1,(11,0),1,1, (12,0),1,1,1,0,0,0,0, (10,0),1,1,0,0,0,0,0 ) cells = [] CELL_WIDTH = 20 CELL_HEIGHT = 20 def draw_cell(cell_data): out = [] if cell_data == 0: out.append(svgfig.Rect(0, 0, CELL_WIDTH, CELL_HEIGHT, fill="black")) elif type(cell_data) == type(1): out.append(svgfig.Rect(0, 0, CELL_WIDTH, CELL_HEIGHT)) out.append(svgfig.Text(10, 10, cell_data, text_anchor="middle", font_size=12, font_weight=600, dominant_baseline="middle", fill="brown", )) elif type(cell_data) == type(()): across = cell_data[0] down = cell_data[1] out.append(svgfig.Rect(0, 0, CELL_WIDTH, CELL_HEIGHT)) out.append(svgfig.Line(0, 0, CELL_WIDTH, CELL_HEIGHT, stroke_width=1, )) if down == 0: points = ((0,0),(0,CELL_HEIGHT),(CELL_WIDTH,CELL_HEIGHT)) out.append(svgfig.Poly(points, "lines", fill="black")) else: out.append(svgfig.Text(2, 18, down, text_anchor="start", font_size=7, alignment_baseline="middle", )) if across == 0: points = ((0,0),(CELL_WIDTH,0),(CELL_WIDTH,CELL_HEIGHT)) out.append(svgfig.Poly(points, "lines", fill="black")) else: out.append(svgfig.Text(19, 7, across, text_anchor="end", font_size=7, )) else: raise Exception("") return out def cell(x, y, cell_data): def t(xi,yi): return 1+xi+x*(CELL_WIDTH), 1+yi+y*(CELL_HEIGHT) fig = svgfig.Fig( *draw_cell(cell_data), trans=t) return fig.SVG() for y in range(y_size): for x in range(x_size): cells.append(cell(x, y, puzzle[y*x_size+x])) g = svgfig.SVG("g", *cells) c = svgfig.canvas(g, width="400px", height="400px", font_family='Arial Black', viewBox="0 0 %d %d" % (x_size * CELL_WIDTH + 2, y_size * CELL_HEIGHT + 2)) c.save('tmp.svg')
import svgfig svgfig.canvas(svgfig.Frame(-0.2, 1.2, 0, 3, svgfig.Line(0, 0.20, 1, 1.65), svgfig.Line(0, 1.7, 1, 2.26), xticks={ 0: "tuned APEs", 1: "infinite APEs" }, xminiticks=[], height=35, yticks=-7).SVG(), viewBox="0 0 100 35").save("statsyst.svg")