Esempio n. 1
0
 def _get_font_style(self, size, anchor, dash_array):
     style = StyleBuilder()
     style.setStrokeDashArray(dash_array)
     style.setFontFamily(fontfamily="Verdana")
     style.setFontSize("%dpx" % size)
     style.setTextAnchor(anchor)
     return style
Esempio n. 2
0
 def image(self):
     style_line = StyleBuilder()
     style_line.setStrokeWidth(self.dim_x / 100)
     return pysvg.shape.rect(self.pos_x - self.dim_x / 2,
                             self.pos_y - self.dim_y / 2,
                             self.dim_x,
                             self.dim_y,
                             stroke='black',
                             fill='white',
                             style=style_line.getStyle())
Esempio n. 3
0
 def image(self):
     style_line = StyleBuilder()
     style_line.setStrokeWidth(self.dim_x / 100)
     return pysvg.shape.rect(self.pos_x - self.dim_x / 2,
                             self.pos_y - self.dim_y / 2,
                             self.dim_x,
                             self.dim_y,
                             stroke='black',
                             fill='white',
                             style=style_line.getStyle())
Esempio n. 4
0
File: svg.py Progetto: ncqgm/gnumed
 def _get_font_style(self, size, anchor, dash_array):
     style = StyleBuilder()
     style.setStrokeDashArray(dash_array)
     style.setFontFamily(fontfamily="Verdana")
     style.setFontSize("%dpx" % size)
     style.setTextAnchor(anchor)
     return style
def rev_path(x1, y1, x2, y2, txt=None):
    elements = []
    # x1, y1 = r1.get_cx(), r1.get_cy()
    # x2, y2 = r2.get_cx(), r2.get_cy(),
    l = line(x1, y1, x2, y2)
    elements.append(l)
    style = 'stroke-width:{0};stroke:{1}'.format(16, ALUM_6)
    l.set_style(style)
    if txt:
        x, y = middle(x1, y1, x2, y2)
        style2 = StyleBuilder()
        #style2.setFontFamily('envy code r')
        style2.setFontFamily('arial')
        style2.setFontWeight('bold')
        style2.setFilling(ALUM_1)
        # shift text left and up by a bit
        # whole alphabet in this font is 167 px width
        per_char = 167. / 26
        t = text(txt, -len(txt) / 2 * per_char, 4)
        t.set_style(style2.getStyle())

        #import pdb; pdb.set_trace()
        group = rotate([t], slope_angle(x1, y1, x2, y2))
        group = translate([group], x, y)
        elements.append(group)

    return elements
Esempio n. 6
0
 def draw(self):
     rectangleStyle = StyleBuilder()
     rectangleStyle.setStroke('black')
     rectangleStyle.setStrokeWidth(2)
     rectangleStyle.setFilling(self.color)
     self.view = Rect(self.gridCoord[0], self.gridCoord[1], self.dimA*SCALING_FACTOR, self.dimB*SCALING_FACTOR)
     self.view.set_style(rectangleStyle.getStyle())
     return self.view
Esempio n. 7
0
 def __init__(self, x, y, width, height, map_container, unit, step=1, factor=1, style=None):
     Container.__init__(self, x, y, width, height)
     self.has_content = True
     self.map_container = map_container
     self.unit = unit
     self.step = step
     self.factor = factor
     self.style = StyleBuilder({'font-family': 'Helvetica', 'font-size': '8pt', 'font-weight': 'normal'})
     if style != None:
         self.style = StyleBuilder(style)
     self.style.style_dict['text-anchor'] = 'middle'
     self.style.style_dict['text-align'] = 'center'
Esempio n. 8
0
def words(txt, family='arial', weight='bold', color=ALUM_1):
    style2 = StyleBuilder()
    #style2.setFontFamily('envy code r')
    style2.setFontFamily('arial')
    style2.setFontWeight('bold')
    style2.setFilling(ALUM_1)
    t = text(txt, 0, 0)
    t.set_style(style2.getStyle())
    return t
Esempio n. 9
0
    def create_rectangle(self, bounds, outline):

        r = Rect(
                x= bounds[0], 
                y= bounds[1],
                width= bounds[2] - bounds[0],
                height= bounds[3] - bounds[1]
            )
        myStyle = StyleBuilder({'fill':None, 'stroke-width':0.5, 'stroke':outline})
        r.set_style(myStyle.getStyle())

        self.svg.addElement(
            r)
Esempio n. 10
0
 def legend(self, elem, x, y, width, height, label_style):
     n = len(self.colors.colors)
     box_height = int(np.floor(float(height) / (n+2)))
     box_width = min(8, width/2)
     mark_style = StyleBuilder(self.mark_style)
     textsize = int(re.findall('([0-9]+)',
         label_style.get('font-size', "8")
     )[0])
     label_x = x + box_width + self.mark_length + 1
     for i in range(n):
         box = rect(
             x = mm_to_px(x), 
             y = mm_to_px(y + (n-i-1)*box_height),
             width = mm_to_px(box_width),
             height = mm_to_px(box_height)
         )
         s = deepcopy(self.styles[i].style_dict)
         s['stroke'] = 'black'
         box.set_style(StyleBuilder(s).getStyle())
         elem.addElement(box)
         
         if i < (n-1):
             mark = line(
                 X1=mm_to_px(x+box_width), 
                 Y1=mm_to_px(y+(n-i-1)*box_height),
                 X2=mm_to_px(x+box_width+self.mark_length),
                 Y2=mm_to_px(y+(n-i-1)*box_height)
             )
             mark.set_style(mark_style.getStyle())
             elem.addElement(mark)
             label = text(
                 content="%0.*f" % (self.ndecimals, self.limits[i]), 
                 x=mm_to_px(label_x), y=mm_to_px(y+(n-i-1)*box_height)+(textsize/2)
             )
             label.set_style(StyleBuilder(label_style).getStyle())
             elem.addElement(label)
      
     label = text(
         content="Min: %0.*f" % (self.ndecimals, np.min(self.values)), 
         x=mm_to_px(label_x), y=mm_to_px(y+n*box_height)+(textsize/2)
     )
     label.set_style(StyleBuilder(label_style).getStyle())
     elem.addElement(label)
     
     label = text(
         content="Max: %0.*f" % (self.ndecimals, np.max(self.values)), 
         x=mm_to_px(label_x), y=mm_to_px(y+0*box_height)+(textsize/2)
     )
     label.set_style(StyleBuilder(label_style).getStyle())
     elem.addElement(label)
def rev_path(x1,y1, x2,y2, txt=None):
    elements = []
    # x1, y1 = r1.get_cx(), r1.get_cy()
    # x2, y2 = r2.get_cx(), r2.get_cy(),
    l = line(x1, y1,
             x2, y2)
    elements.append(l)
    style = 'stroke-width:{0};stroke:{1}'.format(16, ALUM_6)
    l.set_style(style)
    if txt:
        x, y = middle(x1, y1, x2, y2)
        style2 = StyleBuilder()
        #style2.setFontFamily('envy code r')
        style2.setFontFamily('arial')
        style2.setFontWeight('bold')
        style2.setFilling(ALUM_1)
        # shift text left and up by a bit
        # whole alphabet in this font is 167 px width
        per_char = 167./26
        t = text(txt, -len(txt)/2*per_char, 4)
        t.set_style(style2.getStyle())

        #import pdb; pdb.set_trace()
        group = rotate([t], slope_angle(x1, y1, x2, y2))
        group = translate([group], x, y)
        elements.append(group)


    return elements
Esempio n. 12
0
class SimpleSurfaceStyle(object):
    """
    A simple style for polygons.
    """
    def __init__(self, style=None):
        # Provide a default style if none is specified
        if style == None:
            style = {
                'fill': '#cccccc',
                'fill-opacity': 0.7,
                'stroke': 'black',
                'stroke-width': 0.3
            }
        self.style = StyleBuilder(style)
    
    def style_feature(self, feature, elem):
        """
        Styles the provided feature.
        """
        elem.set_style(self.style.getStyle())
    
    def needs_statistics(self):
        return False
    
    def init_statistics(self):
        pass
    
    def update_statistics(self, feat):
        pass
    
    def finalize_statistics(self):
        pass
    
    def legend(self, elem, x, y, width, height, label_style):
        pass
Esempio n. 13
0
def words(txt, family='arial', weight='bold', color=ALUM_1):
    style2 = StyleBuilder()
    #style2.setFontFamily('envy code r')
    style2.setFontFamily('arial')
    style2.setFontWeight('bold')
    style2.setFilling(ALUM_1)
    t = text(txt, 0, 0)
    t.set_style(style2.getStyle())
    return t
Esempio n. 14
0
    def genHoneycomb(self):
        outComb = G()
        circleStyle = StyleBuilder()
        #circleStyle.setStrokeWidth(0.5)
        circleStyle.setStroke('orange')
        circleStyle.setFilling('#edd239')
        CORNER = self.hCSlice.getBottomRight()

        circleY = []
        circleY.append(CORNER[1] + (ROW_SPACE - CIRCLE_RADIUS))
        for g in range(0, self.row):
            circleX = CORNER[0] - CIRCLE_RADIUS
            if (g != 0 and g % 2 != 0):
                circleY.append(circleY[g-1] + 2*CIRCLE_RADIUS)
            elif (g!= 0 and g % 2 == 0):
                circleY.append(circleY[g-1] + 2*(ROW_SPACE - CIRCLE_RADIUS))

            #initCircle = Circle(circleX, circleY[g], CIRCLE_RADIUS)
            #outComb.addElement(initCircle)
            for i in range(0, self.col):
                newShift = TransformBuilder()
                xShift = -i*CIRCLE_RADIUS*math.sqrt(3)
                yShift = 0
                if i % 2 != 0 and g % 2 != 0:
                    yShift = CIRCLE_RADIUS
                elif i % 2 != 0 and g % 2 == 0:
                    yShift = -1*CIRCLE_RADIUS
                newShift.setTranslation(str(xShift) + ' ' + str(yShift))
                a = Circle(circleX, circleY[g], CIRCLE_RADIUS)
                a.set_transform(newShift.getTransform())
                outComb.addElement(a)

        outComb.set_style(circleStyle.getStyle())
        return outComb
Esempio n. 15
0
    def makerow(self):
        frameStyle = StyleBuilder()
        frameStyle.setStrokeWidth(1.5)
        frameStyle.setStroke('black')
        frameStyle.setFilling('white')
        out = G()
        yCoord = 10 + (FRAMELEN + 20) * self.i
        for z in range(0, 4):
            newFrame = Rect(10 + (FRAMELEN + 20) * z, yCoord, FRAMELEN,
                            FRAMELEN)
            newFrame.set_style(frameStyle.getStyle())
            out.addElement(newFrame)
            self.rowCoords.append([10 + (FRAMELEN + 20) * z, yCoord])

        return out
Esempio n. 16
0
 def __init__(self, style=None):
     # Provide a default style if none is specified
     if style == None:
         style = {
             'fill': '#cccccc',
             'fill-opacity': 0.7,
             'stroke': 'black',
             'stroke-width': 0.3
         }
     self.style = StyleBuilder(style)
Esempio n. 17
0
 def __init__(self, x, y, width, height):
     self.needs_clipping = False
     self.has_background = False
     self.has_content = False
     self.has_labels = False
     self.has_contour = False
     self.x = x
     self.y = y
     self.width = width
     self.height = height
     self.sb = ShapeBuilder()
     # Create a default background style
     self.bg_style = StyleBuilder({
         'fill': 'none', 'stroke-width': 0, 'stroke': 'none'
     })
     # Create a default contour style
     self.contour_style = StyleBuilder({
         'fill': 'none', 'stroke-width': 0, 'stroke': 'none'
     })
Esempio n. 18
0
 def image(self):
     style_line = StyleBuilder()
     style_line.setStrokeWidth(self.type.dim_x / 100)
     if self.type.shape == 'ellipse':
         return pysvg.shape.ellipse(self.pos_x,
                                    self.pos_y,
                                    self.type.dim_x / 2,
                                    self.type.dim_y / 2,
                                    stroke='black',
                                    fill=self.type.color,
                                    style=style_line.getStyle())
     elif self.type.shape == 'rectangle':
         return pysvg.shape.rect(self.pos_x - self.type.dim_x / 2,
                                 self.pos_y - self.type.dim_y / 2,
                                 self.type.dim_x,
                                 self.type.dim_y,
                                 stroke='black',
                                 fill=self.type.color,
                                 style=style_line.getStyle())
def draw_tree(width, height):
    global nameStyle

    nameStyle = StyleBuilder()
    nameStyle.setFontFamily(fontfamily=dc.nameFont)
    nameStyle.setFontSize("%spt" % dc.nameFontSize)
    nameStyle.setTextAnchor("left")
    nameStyle = nameStyle.getStyle()

    svg = Svg(width=width, height=height)

    # draw nodes

    for depth in depthToNames:
        for name in depthToNames[depth]:
            node = nameToNode[name]
            draw_node(svg, node, name)

    # draw branches

    for depth in depthToNames:
        for name in depthToNames[depth]:
            node = nameToNode[name]
            isLeaf = (node.children == [])
            if (isLeaf): continue

            numChildren = len(node.children)
            for (i, child) in enumerate(node.children):
                rootFrac = 0.4 + (0.2 * i) / (numChildren - 1)
                sinkFrac = 0.5

                if (orientation == "T2B"):
                    (rootX, rootY) = (node.x + rootFrac * dc.nodeWdt,
                                      node.y + dc.nodeHgt)
                    (sinkX, sinkY) = (child.x + sinkFrac * dc.nodeWdt, child.y)
                    draw_vert_branch(svg, "%s_branch_%d" % (name, i), rootX,
                                     rootY, sinkX, sinkY)
                else:  # if (orientation == "L2R"):
                    (rootX, rootY) = (node.x + dc.nodeWdt,
                                      node.y + rootFrac * dc.nodeHgt)
                    (sinkX, sinkY) = (child.x, child.y + sinkFrac * dc.nodeHgt)
                    draw_horz_branch(svg, "%s_branch_%d" % (name, i), rootX,
                                     rootY, sinkX, sinkY)

    return svg
Esempio n. 20
0
class ScaleBar(Container):
    def __init__(self, x, y, width, height, map_container, unit, step=1, factor=1, style=None):
        Container.__init__(self, x, y, width, height)
        self.has_content = True
        self.map_container = map_container
        self.unit = unit
        self.step = step
        self.factor = factor
        self.style = StyleBuilder({'font-family': 'Helvetica', 'font-size': '8pt', 'font-weight': 'normal'})
        if style != None:
            self.style = StyleBuilder(style)
        self.style.style_dict['text-anchor'] = 'middle'
        self.style.style_dict['text-align'] = 'center'
    
    def draw_content(self, elem):
        # Create a new group
        grp = g()
        grp.setAttribute('id', 'scalebar')
        # Find the amount of available width
        bbox = self.map_container.bbox
        step_length = (float(self.step) * self.factor)
        c = [[bbox[0], 0], [bbox[0] + step_length, 0]]
        px = self.map_container.geo_to_local_coords(c)
        step_px = abs(px[1][0] - px[0][0])
        nsteps = int(floor(float(self.width) / step_px))
        # Draw the horizontal line
        l = path(pathData="M %f %f L %f %f" % (
            mm_to_px(self.x), mm_to_px(self.y + self.height),
            mm_to_px(self.x + nsteps*step_px), mm_to_px(self.y + self.height)
        ), style=StyleBuilder({'stroke': 'black', 'stroke-width': 0.3}).getStyle())
        grp.addElement(l)
        # Draw the vertical lines and write the text
        # textsize = int(re.findall('([0-9]+)',
        #             self.style.style_dict.get('font-size', "12")
        #         )[0])
        for i in range(nsteps+1):
            l = path(pathData="M %f %f L %f %f" % (
                mm_to_px(self.x + i*step_px), mm_to_px(self.y + self.height),
                mm_to_px(self.x + i*step_px), mm_to_px(self.y + self.height - 3)
            ), style=StyleBuilder({'stroke': 'black', 'stroke-width': 0.3}).getStyle())
            grp.addElement(l)
            content = str(i*self.step)
            if i == nsteps: content += ' ' + self.unit
            t = text(
                content=content, 
                x=mm_to_px(self.x + i*step_px), y=mm_to_px(self.y + self.height - 5)
            )
            t.set_style(self.style.getStyle())
            grp.addElement(t)
        elem.addElement(grp)
Esempio n. 21
0
def Scalebars(smin, smax, xmin, xmax):
		
	c_lines = StyleBuilder(config['scaleline_style'])
	c_times = StyleBuilder(config['scale_style'])
	c_times.setFontSize(str(config['scale_font_height']) + 'px')
	
	g_scale = G()
	g_scale_lines = G()
	g_scale_times = G()
	g_scale_lines.set_style(c_lines.getStyle())
	g_scale_times.set_style(c_times.getStyle())
	
	g_scale_times.setAttribute('xml:space', 'preserve')
	
	# seconds value of largest minute smaller than first time
	start = (int(smin) / 60) * 60
	
	# seconds value of smallest minute larger than last time
	end = 60 + ((int(smax) / 60) * 60)
	
	# if the max time wasn't exactly on a minute interval, add one more
	if end < smax + 60:
		end += 60;
	
	# one scale bar for each minute in the range, including last
	for s in range(start, end, 60):
		y = config['vscale'] * (s - smin)
		sline = Line(xmin, y, xmax, y)
		if config['scaleleft']:
			# note hard coded expectation of 7 char max scale label
			lx = xmin - 5 - (7 * config['scale_font_width'])
		else:
			lx = xmax + 5
		stime = Text(time(s), lx, y + 6)
		g_scale_lines.addElement(sline)
		g_scale_times.addElement(stime)
	
	g_scale.addElement(g_scale_lines)
	g_scale.addElement(g_scale_times)
	return g_scale
Esempio n. 22
0
    def __init__(self, conf):

        self.__shapeBuilder = ShapeBuilder()

        self.__fontSize = conf['frame']['font']['size'];
        self.__fontFamily = conf['frame']['font']['name'];
        self.__alignment = conf['frame']['font']['align'];

        self.__frameThickness = conf['frame']['thickness'];
        self.__frameWidth = conf['frame']['width'];
        self.__framePadding = conf['frame']['padding'];

        self.__separatorWidth = conf['frame']['separator']['width'];

        self.__textStyle = StyleBuilder()
        self.__textStyle.setFontFamily(self.__fontFamily)
        self.__textStyle.setFontSize(self.__fontSize.__str__() + 'px')

        self.__LINE_SEPARATOR = 5;
        
        self.__resolver = BBCodeResolver();
Esempio n. 23
0
class Text(Container):
    def __init__(self, x, y, width, height, text, style=None):
        Container.__init__(self, x, y, width, height)
        self.has_content = True
        self.text = text
        if style != None:
            self.style = StyleBuilder(style)
    
    def draw_content(self, elem):
        textsize = int(re.findall('([0-9]+)',
            self.style.style_dict.get('font-size', "12")
        )[0])
        txt = self.text.split('\n')
        for i in range(len(txt)):
            y = mm_to_px(self.y) + textsize + i*1.8*textsize
            t = text(
                content=txt[i], 
                x=mm_to_px(self.x), y=y
            )
            t.set_style(self.style.getStyle())
            elem.addElement(t)
Esempio n. 24
0
 def __init__(self, attr, colors, quantiles, default_color=Color((220,220,220)), style=None):
     # Store the attributes
     self.attr = attr
     self.colors = colors
     self.quantiles = np.array(quantiles)
     self.quantiles.sort()
     self.mark_style = {'fill': 'none', 'stroke-width': 0.25, 'stroke': 'black'}
     self.mark_length = 1
     self.ndecimals = 4
     # Provide a default style if none is specified
     if style == None:
         style = {
             'fill-opacity': 0.7,
             'stroke': 'black',
             'stroke-width': 0.3,
         }
     style['fill'] = default_color.hex
     self.default_style = StyleBuilder(deepcopy(style))
     self.styles = []
     for c in self.colors.colors:
         style['fill'] = c.hex
         self.styles.append(StyleBuilder(deepcopy(style)))
Esempio n. 25
0
 def image(self):
     style_line = StyleBuilder()
     style_line.setStrokeWidth(self.type.dim_x / 100)
     if self.type.shape == 'ellipse':
         return pysvg.shape.ellipse(self.pos_x,
                                    self.pos_y,
                                    self.type.dim_x / 2,
                                    self.type.dim_y / 2,
                                    stroke='black',
                                    fill=self.type.color,
                                    style=style_line.getStyle())
     elif self.type.shape == 'rectangle':
         return pysvg.shape.rect(self.pos_x - self.type.dim_x / 2,
                                 self.pos_y - self.type.dim_y / 2,
                                 self.type.dim_x,
                                 self.type.dim_y,
                                 stroke='black',
                                 fill=self.type.color,
                                 style=style_line.getStyle())
Esempio n. 26
0
def command(num_txt, cmd, explanation, color):
    x = 0
    y = 0
    elems = [scale(num(num_txt, color), 2)]
    cmd_txt = text(cmd, x + 40, y + 12)
    s = StyleBuilder()
    s.setFontWeight('bold')
    s.setFontFamily('Bitstream Vera Sans Mono')
    cmd_txt.set_style(s.getStyle())
    elems.append(cmd_txt)

    exp_txt = text(explanation, x + 45, y + 27)
    s = StyleBuilder()
    #s.setFontWeight('bold')
    s.setFontFamily('Bitstream Vera Serif')
    s.setFontSize('10px')
    exp_txt.set_style(s.getStyle())
    elems.append(exp_txt)
    return elems
Esempio n. 27
0
 def genHoneyRect(self):
     rectangleStyle = StyleBuilder()
     rectangleStyle.setFilling('blue')
     rectangleStyle.setStroke('black') # temp
     self.hCSlice.set_style(rectangleStyle.getStyle())
     return(self.hCSlice)
Esempio n. 28
0
    def genLabels(self):
        labels = G()
        labelStyle = StyleBuilder()
        labelStyle.setTextAnchor('middle')
        labelStyle.setFontSize(10)
        lineStyle = StyleBuilder()
        lineStyle.setStroke('#a9a9a9')
        dimLabelA = str(self.dimA) + ' nm'
        dimLabelB = str(self.dimB) + ' nm'
        # horizontal label
        cornerHL = self.view.getTopLeft()
        cornerHR = self.view.getTopRight()

        hLabelStart = [cornerHL[0], cornerHL[1] + 5]
        hLabelEnd = [cornerHR[0], cornerHR[1] + 5]

        hLine = Line(hLabelStart[0], hLabelStart[1], hLabelEnd[0], hLabelEnd[1])
        hLabel = Text(dimLabelA, (hLabelStart[0] + hLabelEnd[0])/2, hLabelEnd[1] + 20)
        hLine.set_style(lineStyle.getStyle())
        hLabel.set_style(labelStyle.getStyle())

        cornerVL = self.view.getTopLeft()
        cornerVR = self.view.getBottomLeft()

        vLabelStart = [cornerVL[0] - 5, cornerVL[1]]
        vLabelEnd = [cornerVR[0] - 5, cornerVR[1]]

        vLine = Line(vLabelStart[0], vLabelStart[1], vLabelEnd[0], vLabelEnd[1])
        vLabel = Text(dimLabelB, vLabelEnd[0] - 30, (vLabelStart[1] + vLabelEnd[1])/2)
        vLine.set_style(lineStyle.getStyle())
        vLabel.set_style(labelStyle.getStyle())
        labels.addElement(hLine)
        labels.addElement(hLabel)
        labels.addElement(vLine)
        labels.addElement(vLabel)

        #center = [self.gridCoord[0] + self.dimA*SCALING_FACTOR/2, self.gridCoord[1] + self.dimB*SCALING_FACTOR + LABEL_SHIFT]
        #dimLabel = str(self.dimA) + 'nm x ' +str(self.dimB) + 'nm'
        #labels = Text(dimLabel, center[0], center[1])
        #labels.set_style(labelStyle.getStyle())
        return labels
def num(txt, color):
    txt = str(txt)
    elems = []
    r = rect(0, 0, 16, 16)
    s = StyleBuilder()
    s.setFilling(color)
    r.set_style(s.getStyle())
    elems.append(r)
    if txt:
        style2 = StyleBuilder()
        #style2.setFontFamily('envy code r')
        style2.setFontFamily('arial')
        style2.setFontWeight('bold')
        style2.setFilling(ALUM_1)
        # shift text left and up by a bit
        if len(txt) == 1:
            x = 5
        elif len(txt) == 2:
            x = 1.5
        t = text(txt, x, 12.5)
        t.set_style(style2.getStyle())
        elems.append(t)
    return elems
def command(num_txt, cmd, explanation, color):
    x = 0
    y = 0
    elems = [scale(num(num_txt, color), 2)]
    cmd_txt = text(cmd, x+40, y+12)
    s = StyleBuilder()
    s.setFontWeight('bold')
    s.setFontFamily('Bitstream Vera Sans Mono')
    cmd_txt.set_style(s.getStyle())
    elems.append(cmd_txt)

    exp_txt = text(explanation, x+45, y+27)
    s = StyleBuilder()
    #s.setFontWeight('bold')
    s.setFontFamily('Bitstream Vera Serif')
    s.setFontSize('10px')
    exp_txt.set_style(s.getStyle())
    elems.append(exp_txt)
    return elems
Esempio n. 31
0
if config['pagewidth'] != None:
	actual_page_width = config['pagewidth']
	total_label_width = 0
	for r in races:
		total_label_width += r['wmax_label'] * config['label_font_width']
	while total_label_width > actual_page_width:
		actual_page_width += config['pagewidth']
	gap_count = len(races) - 1
	scale_label_width = ((7 * config['scale_font_width']) + 5 if config['scalebars'] else 0)
	free_space = actual_page_width - total_label_width - scale_label_width - (gap_count * 2 * config['gutter'])
	calc_linespan = free_space / gap_count
	config['linespan'] = calc_linespan

# SVG styles

s_label = StyleBuilder(config['label_style'])
s_label.setFontSize(str(config['label_font_height']) + 'px')

# SVG Groups

g_label = G()
g_label.set_style(s_label.getStyle())
g_label.setAttribute('xml:space', 'preserve')
g_linkline = G()
g_linkline.set_style(StyleBuilder(config['linkline_style']).getStyle())
g_weaklink = G()
g_weaklink.set_style(StyleBuilder(config['weaklink_style']).getStyle())
g_underline = G()
g_underline.set_style(StyleBuilder(config['underline_style']).getStyle())

for r in range(0, len(races)):
Esempio n. 32
0
def drawSideFacePair(topCorners, bottomCorners, color):
    pointList = []
    pointList2 = []
    output = G()
    XYStyle1 = StyleBuilder()
    #XYStyle1.setStroke('black')
    #XYStyle1.setStrokeWidth(1.5)
    XYStyle1.setFilling(color)
    #XYStyle1.setFillOpacity(0.8)
    XYStyle2 = StyleBuilder()
    XYStyle2.setStroke(color)
    XYStyle2.setStrokeWidth(0.5)
    XYStyle2.setFilling(color)
    pointList.append(strPathStart(topCorners[2]))
    pointList.append(strPathPoint(topCorners[3]))
    pointList.append(strPathPoint(bottomCorners[3]))
    pointList.append(strPathPoint(bottomCorners[2]))
    svgCode1 = pGram(pointList)
    pointList2.append(strPathStart(topCorners[0]))
    pointList2.append(strPathPoint(topCorners[1]))
    pointList2.append(strPathPoint(bottomCorners[1]))
    pointList2.append(strPathPoint(bottomCorners[0]))
    svgCode2 = pGram(pointList2)
    rightFace = Path(svgCode1)
    rightFace.set_style(XYStyle1.getStyle())
    leftFace = Path(svgCode2)
    leftFace.set_style(XYStyle2.getStyle())
    output.addElement(leftFace)
    output.addElement(rightFace)

    return output
Esempio n. 33
0
 def __init__(self, x, y, width, height, text, style=None):
     Container.__init__(self, x, y, width, height)
     self.has_content = True
     self.text = text
     if style != None:
         self.style = StyleBuilder(style)
Esempio n. 34
0
class Container(object):
    """
    A container is an empty box. Subclasses can specify the content by overriding
    the draw_*() methods.
    """
    def __init__(self, x, y, width, height):
        self.needs_clipping = False
        self.has_background = False
        self.has_content = False
        self.has_labels = False
        self.has_contour = False
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.sb = ShapeBuilder()
        # Create a default background style
        self.bg_style = StyleBuilder({
            'fill': 'none', 'stroke-width': 0, 'stroke': 'none'
        })
        # Create a default contour style
        self.contour_style = StyleBuilder({
            'fill': 'none', 'stroke-width': 0, 'stroke': 'none'
        })
    
    def draw_background(self, elem):
        """
        Draws the background of the container.
        elem is a SVG element, and we should add our content to this element.
        The method doesn't return anything.
        """
        bg_rect = rect(
            x = mm_to_px(self.x), 
            y = mm_to_px(self.y),
            width = mm_to_px(self.width),
            height = mm_to_px(self.height)
        )
        bg_rect.set_style(self.bg_style.getStyle())
        elem.addElement(bg_rect)
    
    def draw_content(self, elem):
        """
        Draws the content of the container.
        elem is a SVG element, and we should add our content to this element.
        The method doesn't return anything.
        """
        pass
    
    def draw_labels(self, elem):
        """
        Draws the labels of the container.
        elem is a SVG element, and we should add our content to this element.
        The method doesn't return anything.
        """
        pass
    
    def draw_contour(self, elem):
        """
        Draws a contour around the container.
        """
        contour_rect = rect(
            x = mm_to_px(self.x), 
            y = mm_to_px(self.y),
            width = mm_to_px(self.width),
            height = mm_to_px(self.height)
        )
        contour_rect.set_style(self.contour_style.getStyle())
        elem.addElement(contour_rect)
Esempio n. 35
0
def drawFrontFacePair(topCorners, bottomCorners, color):
    pointList = []
    pointList2 = []
    output = G()
    YZStyle1 = StyleBuilder()
    #YZStyle1.setStroke('black')
    #YZStyle1.setStrokeWidth(1.5)
    YZStyle1.setFilling(color)
    YZStyle1.setFillOpacity(0.75)
    YZStyle2 = StyleBuilder()
    YZStyle2.setStroke('black')
    YZStyle2.setStrokeWidth(0.5)
    YZStyle2.setFillOpacity(0.75)
    YZStyle2.setFilling('#ffffff')
    pointList.append(strPathStart(topCorners[1]))
    pointList.append(strPathPoint(topCorners[2]))
    pointList.append(strPathPoint(bottomCorners[2]))
    pointList.append(strPathPoint(bottomCorners[1]))
    svgCode1 = pGram(pointList)
    pointList2.append(strPathStart(topCorners[0]))
    pointList2.append(strPathPoint(topCorners[3]))
    pointList2.append(strPathPoint(bottomCorners[3]))
    pointList2.append(strPathPoint(bottomCorners[0]))
    svgCode2 = pGram(pointList2)
    frontFace = Path(svgCode1)
    frontFace.set_style(YZStyle1.getStyle())
    backFace = Path(svgCode2)
    backFace.set_style(YZStyle2.getStyle())
    output.addElement(backFace)
    output.addElement(frontFace)

    return output
def draw_tree():
    if (dc.nameFontSize < 16):
        scale = dc.nameFontSize / 16.0
        nameCapsHgt = dc.nameCapsHgt * scale
        nameDescHgt = dc.nameDescHgt * scale
        nameFontLineHgt = dc.nameFontLineHgt * scale

    nameStyle = StyleBuilder()
    nameStyle.setFontFamily(fontfamily=dc.nameFont)
    nameStyle.setFontSize("%spt" % dc.nameFontSize)
    nameStyle.setTextAnchor("left")
    nameStyle = nameStyle.getStyle()

    svg = Svg()

    # draw nodes

    for depth in depthToNames:
        for name in depthToNames[depth]:
            node = nameToNode[name]
            isLeaf = (node.left == None)

            yLine = node.y + nameCapsHgt + 1

            ob = SvgRect(node.x,
                         node.y,
                         dc.nodeWidth,
                         dc.nodeHeight,
                         id="%s_box" % name)
            ob.set_stroke(dc.lineColor)
            ob.set_stroke_width(dc.lineThickness)
            if (isLeaf): ob.set_fill(dc.leafFillColor)
            else: ob.set_fill(dc.nodeFillColor)
            svg.addElement(ob)

            ob = SvgText("%s" % name, node.x + 1, yLine, id="%s_name" % node)
            ob.set_style(nameStyle)
            svg.addElement(ob)
            yLine += nameFontLineHgt

            if (hasattr(node, "bitsUnion")):
                ob = SvgText("U:" +
                             bits_to_string(node.numBits, node.bitsUnion),
                             node.x + 1,
                             yLine,
                             id="%s_Bunion" % node)
                ob.set_style(nameStyle)
                svg.addElement(ob)
            yLine += nameFontLineHgt

            if (hasattr(node, "bitsIntersection")):
                ob = SvgText(
                    "I:" + bits_to_string(node.numBits, node.bitsIntersection),
                    node.x + 1,
                    yLine,
                    id="%s_Bintersection" % node)
                ob.set_style(nameStyle)
                svg.addElement(ob)
            yLine += nameFontLineHgt

            if (hasattr(node, "bitsAll")):
                ob = SvgText("A:" + bits_to_string(node.numBits, node.bitsAll),
                             node.x + 1,
                             yLine,
                             id="%s_Ball" % node)
                ob.set_style(nameStyle)
                svg.addElement(ob)
            yLine += nameFontLineHgt

            if (hasattr(node, "bitsSome")):
                ob = SvgText("S:" +
                             bits_to_string(node.numBits, node.bitsSome),
                             node.x + 1,
                             yLine,
                             id="%s_Bsome" % node)
                ob.set_style(nameStyle)
                svg.addElement(ob)
            yLine += nameFontLineHgt

    # draw branches

    for depth in depthToNames:
        for name in depthToNames[depth]:
            node = nameToNode[name]
            if (node.left == None): continue

            (leftStartX, leftStartY) = (node.x + 0.4 * dc.nodeWidth,
                                        node.y + dc.nodeHeight)
            (rightStartX, rightStartY) = (node.x + 0.6 * dc.nodeWidth,
                                          node.y + dc.nodeHeight)
            (leftEndX, leftEndY) = (node.left.x + 0.5 * dc.nodeWidth,
                                    node.right.y)
            (rightEndX, rightEndY) = (node.right.x + 0.5 * dc.nodeWidth,
                                      node.right.y)

            draw_branch(svg, "%s_left_branch" % node, leftStartX, leftStartY,
                        leftEndX, leftEndY)
            draw_branch(svg, "%s_right_branch" % node, rightStartX,
                        rightStartY, rightEndX, rightEndY)

    return svg
Esempio n. 37
0
def num(txt, color):
    txt = str(txt)
    elems = []
    r = rect(0, 0, 16, 16)
    s = StyleBuilder()
    s.setFilling(color)
    r.set_style(s.getStyle())
    elems.append(r)
    if txt:
        style2 = StyleBuilder()
        #style2.setFontFamily('envy code r')
        style2.setFontFamily('arial')
        style2.setFontWeight('bold')
        style2.setFilling(ALUM_1)
        # shift text left and up by a bit
        if len(txt) == 1:
            x = 5
        elif len(txt) == 2:
            x = 1.5
        t = text(txt, x, 12.5)
        t.set_style(style2.getStyle())
        elems.append(t)
    return elems
Esempio n. 38
0
    def genLabels(self):

        labels = G()
        labelStyle = StyleBuilder()
        labelStyle.setTextAnchor('middle')
        labelStyle.setFontSize(10)
        lineStyle = StyleBuilder()
        lineStyle.setStroke('#a9a9a9')
        dimLabelA = str(self.x/SCALING_FACTOR) + ' nm'
        dimLabelB = str(self.z/SCALING_FACTOR) + ' nm'
        # horizontal label
        cornerHL = self.hCSlice.getTopLeft()
        cornerHR = self.hCSlice.getTopRight()

        hLabelStart = [cornerHL[0], cornerHL[1] + 5]
        hLabelEnd = [cornerHR[0], cornerHR[1] + 5]

        hLine = Line(hLabelStart[0], hLabelStart[1], hLabelEnd[0], hLabelEnd[1])
        hLabel = Text(dimLabelA, (hLabelStart[0] + hLabelEnd[0])/2, hLabelEnd[1] + 20)
        hLine.set_style(lineStyle.getStyle())
        hLabel.set_style(labelStyle.getStyle())

        cornerVL = self.hCSlice.getTopLeft()
        cornerVR = self.hCSlice.getBottomLeft()

        vLabelStart = [cornerVL[0] - 5, cornerVL[1]]
        vLabelEnd = [cornerVR[0] - 5, cornerVR[1]]

        vLine = Line(vLabelStart[0], vLabelStart[1], vLabelEnd[0], vLabelEnd[1])
        vLabel = Text(dimLabelB, vLabelEnd[0] - 30, (vLabelStart[1] + vLabelEnd[1])/2)
        vLine.set_style(lineStyle.getStyle())
        vLabel.set_style(labelStyle.getStyle())
        labels.addElement(hLine)
        labels.addElement(hLabel)
        labels.addElement(vLine)
        labels.addElement(vLabel)
        return labels
Esempio n. 39
0
    def draw(self):
        faceStyle = StyleBuilder()
        faceStyle.setFilling('blue')
        faceStyle.setStroke('black')
        faceStyle.setFillOpacity(0.5)
        topStyle = StyleBuilder()
        topStyle.setFilling('green')
        topStyle.setStroke('black')
        topStyle.setStrokeWidth(2)
        topStyle.setFillOpacity(0.5)
        sideStyle = StyleBuilder()
        sideStyle.setFilling('red')
        sideStyle.setStroke('black')
        sideStyle.setStrokeWidth(2)
        sideStyle.setFillOpacity(0.5)
        frontFace = Rect(self.startCoord[0], self.startCoord[1], self.x, self.z)
        backFace = Rect(self.startCoord[0] + self.y/math.sqrt(2), self.startCoord[1] - self.y/math.sqrt(2), self.x, self.z)
        # draw parallelogram, grab corners
        cornerBack = backFace.getEdgePoints()
        cornerFront = frontFace.getEdgePoints()
        # Top face string
        pointListT = []
        pointListT.append(strPathStart(cornerBack[0]))
        pointListT.append(strPathPoint(cornerBack[1]))
        pointListT.append(strPathPoint(cornerFront[1]))
        pointListT.append(strPathPoint(cornerFront[0]))
        topFaceString = pGram(pointListT)
        # right side face
        pointListR = [strPathStart(cornerBack[1])]
        pointListR.append(strPathPoint(cornerBack[2]))
        pointListR.append(strPathPoint(cornerFront[2]))
        pointListR.append(strPathPoint(cornerFront[1]))
        # bottom face
        pointListB = [strPathStart(cornerBack[2])]
        pointListB.append(strPathPoint(cornerBack[3]))
        pointListB.append(strPathPoint(cornerFront[3]))
        pointListB.append(strPathPoint(cornerFront[2]))
        # left
        pointListL = [strPathStart(cornerBack[0])]
        pointListL.append(strPathPoint(cornerBack[3]))
        pointListL.append(strPathPoint(cornerFront[3]))
        pointListL.append(strPathPoint(cornerFront[0]))
        # make faces
        topFace = Path(pGram(pointListT))
        rightFace = Path(pGram(pointListR))
        leftFace = Path(pGram(pointListL))
        bottomFace = Path(pGram(pointListB))

        topFace.set_style(topStyle.getStyle())
        bottomFace.set_style(topStyle.getStyle())

        rightFace.set_style(sideStyle.getStyle())
        leftFace.set_style(sideStyle.getStyle())

        frontFace.set_style(faceStyle.getStyle())
        backFace.set_style(faceStyle.getStyle())


        self.out.addElement(backFace)
        self.out.addElement(frontFace)

        self.out.addElement(rightFace)
        self.out.addElement(leftFace)

        self.out.addElement(bottomFace)
        self.out.addElement(topFace)

        return self.out
Esempio n. 40
0
class NodeRenderer(object):
    def __init__(self, conf):

        self.__shapeBuilder = ShapeBuilder()

        self.__fontSize = conf['frame']['font']['size'];
        self.__fontFamily = conf['frame']['font']['name'];
        self.__alignment = conf['frame']['font']['align'];

        self.__frameThickness = conf['frame']['thickness'];
        self.__frameWidth = conf['frame']['width'];
        self.__framePadding = conf['frame']['padding'];

        self.__separatorWidth = conf['frame']['separator']['width'];

        self.__textStyle = StyleBuilder()
        self.__textStyle.setFontFamily(self.__fontFamily)
        self.__textStyle.setFontSize(self.__fontSize.__str__() + 'px')

        self.__LINE_SEPARATOR = 5;
        
        self.__resolver = BBCodeResolver();

    def __createLines(self, values):
        result = [];

        for value in values:
            if isinstance(value, basestring):
                lines = self.__resolver.resolveString(value);
                
                if isinstance(lines, list):
                    for line in lines:
                        result.append(line);
            elif isinstance(value, int):
                result.append(value);
            else:
                assert 1 == 2

        return result;

    def __determineLineHeight(self, isSeparator):
        if isSeparator:
            return self.__separatorWidth + self.__LINE_SEPARATOR;
        else:
            return self.__fontSize + self.__LINE_SEPARATOR;

    def __determineContainterHeight(self, lines):
        #TODO wrapping!

        height = 0;

        for line in lines:
            if isinstance(line, int):
                height = height + self.__determineLineHeight(True);
            else:
                height = height + self.__determineLineHeight(False);

        return height + 2 * self.__framePadding;

    def __prepareNodeContainer(self, startX, startY, width, height, isReference):
        nodeGroup = g()
        nodeGroup.set_style(self.__textStyle.getStyle())

        if isReference:
            color = 'gray';
        else:
            color = 'white';

        rect = self.__shapeBuilder.createRect(startX, startY, width, height, strokewidth = self.__frameThickness, stroke='black', fill=color)
        nodeGroup.addElement(rect)

        return nodeGroup;

    def render(self, node, startX, startY, isReference = False):
        if node['type'] != 'node':
            raise Exception("Wrong input object. Expected type: 'node'");

        lines = self.__createLines(node['value']);

        height = self.__determineContainterHeight(lines);

        nodeContainer = self.__prepareNodeContainer(startX, startY, self.__frameWidth, height, isReference)

        y = startY + self.__framePadding;

        for line in lines:
            if isinstance(line, int): # if int, then render horizontal line
                lineHeight = self.__determineLineHeight(True);
                x = startX;

                separatorObj = self.__shapeBuilder.createLine(x, y, x + self.__frameWidth, y, strokewidth = self.__separatorWidth)
                nodeContainer.addElement(separatorObj)

            elif isinstance(line, list): #list, because line is list of bbcoded spans
                lineHeight = self.__determineLineHeight(False);
                x = startX + self.__framePadding;

                txtObj = text(None, x, y + self.__fontSize);

                for txt in line:
                    span = tspan();
                    span.appendTextContent(txt.getText());
                    span.setAttribute("style", txt.getStyle())
                    txtObj.addElement(span)

                nodeContainer.addElement(txtObj)
            else:
                raise Exception("unsupported value type")

            y = y + lineHeight;

        return nodeContainer;

    #pseudo static method
    def getNodeHeight(self, node):
        lines = self.__createLines(node['value']);
        return self.__determineContainterHeight(lines);
Esempio n. 41
0
class QuantileSurfaceStyle(SimpleSurfaceStyle):
    """
    Chooses a discrete color for a feature based on the quantiles.
    For n colors, we need to have n-1 quantile limits.
    """
    def __init__(self, attr, colors, quantiles, default_color=Color((220,220,220)), style=None):
        # Store the attributes
        self.attr = attr
        self.colors = colors
        self.quantiles = np.array(quantiles)
        self.quantiles.sort()
        self.mark_style = {'fill': 'none', 'stroke-width': 0.25, 'stroke': 'black'}
        self.mark_length = 1
        self.ndecimals = 4
        # Provide a default style if none is specified
        if style == None:
            style = {
                'fill-opacity': 0.7,
                'stroke': 'black',
                'stroke-width': 0.3,
            }
        style['fill'] = default_color.hex
        self.default_style = StyleBuilder(deepcopy(style))
        self.styles = []
        for c in self.colors.colors:
            style['fill'] = c.hex
            self.styles.append(StyleBuilder(deepcopy(style)))
    
    def style_feature(self, feature, elem):
        """
        Styles the provided feature.
        """
        v = feature['properties'][self.attr]
        if v == None:
            elem.set_style(self.default_style.getStyle())
            return
        for i in range(len(self.limits)):
            l = self.limits[i]
            if v < l:
                elem.set_style(self.styles[i].getStyle())
                return
        elem.set_style(self.styles[i+1].getStyle())
    
    def needs_statistics(self):
        return True
    
    def init_statistics(self):
        self.values = []
    
    def update_statistics(self, feat):
        if feat['properties'][self.attr] != None:
            self.values.append(feat['properties'][self.attr])
    
    def finalize_statistics(self):
        self.values = np.array(self.values, dtype=np.float32)
        self.limits = [np.percentile(self.values, q*100) for q in self.quantiles]
        self.limits.sort()
    
    def legend(self, elem, x, y, width, height, label_style):
        n = len(self.colors.colors)
        box_height = int(np.floor(float(height) / (n+2)))
        box_width = min(8, width/2)
        mark_style = StyleBuilder(self.mark_style)
        textsize = int(re.findall('([0-9]+)',
            label_style.get('font-size', "8")
        )[0])
        label_x = x + box_width + self.mark_length + 1
        for i in range(n):
            box = rect(
                x = mm_to_px(x), 
                y = mm_to_px(y + (n-i-1)*box_height),
                width = mm_to_px(box_width),
                height = mm_to_px(box_height)
            )
            s = deepcopy(self.styles[i].style_dict)
            s['stroke'] = 'black'
            box.set_style(StyleBuilder(s).getStyle())
            elem.addElement(box)
            
            if i < (n-1):
                mark = line(
                    X1=mm_to_px(x+box_width), 
                    Y1=mm_to_px(y+(n-i-1)*box_height),
                    X2=mm_to_px(x+box_width+self.mark_length),
                    Y2=mm_to_px(y+(n-i-1)*box_height)
                )
                mark.set_style(mark_style.getStyle())
                elem.addElement(mark)
                label = text(
                    content="%0.*f" % (self.ndecimals, self.limits[i]), 
                    x=mm_to_px(label_x), y=mm_to_px(y+(n-i-1)*box_height)+(textsize/2)
                )
                label.set_style(StyleBuilder(label_style).getStyle())
                elem.addElement(label)
         
        label = text(
            content="Min: %0.*f" % (self.ndecimals, np.min(self.values)), 
            x=mm_to_px(label_x), y=mm_to_px(y+n*box_height)+(textsize/2)
        )
        label.set_style(StyleBuilder(label_style).getStyle())
        elem.addElement(label)
        
        label = text(
            content="Max: %0.*f" % (self.ndecimals, np.max(self.values)), 
            x=mm_to_px(label_x), y=mm_to_px(y+0*box_height)+(textsize/2)
        )
        label.set_style(StyleBuilder(label_style).getStyle())
        elem.addElement(label)