示例#1
0
	def drawBranch(self, counter, childrenDice, lastX, lastY, winner = None, numerateur=1, denumerateur=1, progressiveChildCount=1):
		childrenCounter = self.startCounter(counter, childrenDice)
		die = childrenDice.pop()

		progressiveChildCount *= len(die.faces)
		denumerateur *= die.numberSides()

		for face in die.faces:
			

			childrenNumerateur = numerateur*die.faces[face]
			x1, y1, x2, y2 = lastX, lastY, self.x(childrenCounter, die, childrenDice), self.y(childrenCounter, die, childrenDice, progressiveChildCount)
			self.s.addElement(line(x1, y1, x2, y2, style="stroke:rgb(0,0,0);stroke-width:2"))

			sProbability = text(die.probabilitySide(face), (x1+x2)/2.-15, (y1+y2)/2. + 10, style="font-size:40;font-family:arial;fill:"+die.stringColor()+";stroke:rgb(0,0,0);stroke-width:0.5")
			self.s.addElement(sProbability)

			sFace = die.drawFace(face)
			sFace.set_transform("translate("+str(x2 + self.space)+","+str(y2-die.r())+")")
			self.s.addElement(sFace)

			x, y = x2 + die.size + 2*self.space, y2

			if winner:
				winnerDie = dict(winner)
			else:
				winnerDie = {}

			if not winnerDie:
				winnerDie = {}
			if not winnerDie or die not in winnerDie:
				winnerDie[die] = face
			else:
				winnerDie[die] += face
		
			if len(childrenDice) > 0:
				self.drawBranch(childrenCounter, list(childrenDice), x, y, winnerDie, childrenNumerateur, denumerateur, progressiveChildCount)
			else:
				y += die.r()-7
				
				maxFace = 0
				winningDie = None
				for key in winnerDie:
					if winnerDie[key] > maxFace:
						maxFace = winnerDie[key]
						winningDie = key

				prob = childrenNumerateur
				self.addWin(winningDie, prob)

				if self.percent:
					winningProbability = (prob/float(denumerateur))*100
					winningProbability = "{0:.2f} %".format(round(winningProbability,2))
				else:
					winningProbability = str(childrenNumerateur)+"/"+str(denumerateur)
				
				self.s.addElement(text("=", x, y, style="font-size:50;font-family:arial;"))
				self.s.addElement(text(str(winningProbability), x+40, y-5, style="fill:"+winningDie.stringColor()+";font-size:40;font-family:arial;"))

			childrenCounter += 1
    def _svg_clipped_text(self, myString, rectTuple, myStyle):
        myString = self._encode_text(myString)
        # Put text,clipping into a SVG group
        group = g()
        rx, ry, width, height = rectTuple
        text_x = rx + INNER_PADDING
        text_y = ry + height - INNER_PADDING
        # TODO: in SVG, negative value should be OK, but they
        # are not drawn in Firefox. So add a special handling here
        # however the root cause is the layout function for the recs
        # which should be fixed not to have values < 0
        if text_x < INNER_PADDING:
            width = width - (INNER_PADDING - text_x)
            text_x = INNER_PADDING
        pathId = "path%d_%d" % (text_x, text_y)
        p = path(pathData= "M %d %d H %d V %d H %d" % \
                               (rx, ry + height,
                                text_x+width-INNER_PADDING,
                                ry, rx))
        clip = clipPath()
        clip.addElement(p)
        clip.set_id(pathId)
        d = defs()
        d.addElement(clip)
        self.svg.addElement(d)
        myText = text(myString, text_x, text_y)
        myText.set_style(myStyle.getStyle())
        myText.set_textLength(width - 2 * INNER_PADDING)
        myText.set_lengthAdjust("spacingAndGlyphs")
        group.set_clip_path("url(#%s)" % pathId)

        group.addElement(myText)
        return group
示例#3
0
def create_svg_image(tags, filename, size=(800, 600), background=(255, 255, 255), vertical=True, crop=True, fontname='Arial', fontzoom=2, rectangular=False):
    """
    Create data structures to be used for SVG tag clouds.
    """
    image_surface = Surface(size, 0, 32)
    image_surface.fill((255, 255, 255))
    tag_store = _draw_cloud(tags, image_surface, False, fontname=fontname, fontzoom=fontzoom, rectangular=rectangular)

    svg_out = svg(0,0,width='100%',height='100%')

    #tag_store = sorted(tag_store, key=lambda tag: tag.tag['size'])
    #tag_store.reverse()
    for stag in tag_store:
        group = g()
        xx = stag.rect.left - stag.fontoffset[0]
        yy = stag.rect.top - stag.fontoffset[1]

        t = text(stag.tag['tag'], x=xx, y=yy)
        t.set_font_family('Arial')
        t.set_font_size(str(stag.tag['size']))
        t.set_font_stretch('normal')
        t.set_font_style('normal')
        t.set_font_variant('normal')
        t.set_font_weight('normal')

        group.addElement(t)
    	svg_out.addElement(group)

    svg_out.save(filename)
示例#4
0
文件: tree.py 项目: shokoohi/website
    def drawFinalProb(self):
        numDice = len(self.wins)
        x = self.x(0, self.dice[0], []) + self.finalOffset
        i = 1
        for die in sorted(self.wins, key=self.wins.get, reverse=True):
            y = (i * self.height) / (numDice + 1) + self.offset[1]
            if self.percent:
                winningProbability = (self.wins[die] /
                                      float(self.maxDenum())) * 100
                winningProbability = "{0:.2f} %".format(
                    round(winningProbability, 2))
            else:
                winningProbability = str(int(self.wins[die])) + "/" + str(
                    self.maxDenum())

            if i == 1: bonus = ";text-decoration:underline"
            else: bonus = ""

            self.s.addElement(
                text(str(winningProbability),
                     x + 40,
                     y - 5,
                     style="fill:" + die.stringColor() +
                     ";font-size:40;font-family:arial" + bonus))

            i += 1
示例#5
0
    def drawParts(self, svgObj, nbrWorkers):
        i = 0
        oh = ShapeBuilder()
        myStyle = StyleBuilder()
        myStyle.setFontFamily(fontfamily="Verdana")
        myStyle.setFontWeight('bold')
        myStyle.setFontSize('14pt')
        txt = text("Parallelisable?", 5, 20)
        txt.set_style(myStyle.getStyle())
        svgObj.addElement(txt)

        while i < len(self.timeBlocks):
            if self.timeBlocks[i] > nbrWorkers:
                beginRect = i
                while i < len(
                        self.timeBlocks) and self.timeBlocks[i] > nbrWorkers:
                    i += 1
                endRect = i
                svgObj.addElement(
                    oh.createRect(
                        OFFSET_LEFT +
                        beginRect * RESOLUTION_TASK_DISCOVER * PIX_BY_SEC + 2,
                        5, (endRect - beginRect) * RESOLUTION_TASK_DISCOVER *
                        PIX_BY_SEC + 2,
                        18,
                        strokewidth=2,
                        fill='orange',
                        stroke='white'))
            else:
                i += 1
示例#6
0
    def _svg_clipped_text(self, myString, rectTuple, myStyle):
        myString = self._encode_text(myString)
        # Put text,clipping into a SVG group
        group=g()
        rx, ry, width, height = rectTuple
        text_x = rx + INNER_PADDING
        text_y = ry + height - INNER_PADDING
        # TODO: in SVG, negative value should be OK, but they
        # are not drawn in Firefox. So add a special handling here
        # however the root cause is the layout function for the recs
        # which should be fixed not to have values < 0
        if text_x < INNER_PADDING:
            width = width - (INNER_PADDING-text_x)
            text_x = INNER_PADDING
        pathId = "path%d_%d" % (text_x, text_y)
        p = path(pathData= "M %d %d H %d V %d H %d" % \
                               (rx, ry + height,
                                text_x+width-INNER_PADDING,
                                ry, rx))
        clip = clipPath()
        clip.addElement(p)
        clip.set_id(pathId)
        d=defs()
        d.addElement(clip)
        self.svg.addElement(d)
        myText = text( myString, text_x, text_y )
        myText.set_style(myStyle.getStyle())
        myText.set_textLength(width-2*INNER_PADDING)
        myText.set_lengthAdjust("spacingAndGlyphs")
        group.set_clip_path("url(#%s)" % pathId)
 
        group.addElement(myText)
        return group
示例#7
0
  def plotNode(self, node):
    """Adds a single node to the plot, incl. connection to parent."""
    # Compute node position
    pos_y = node.depth * NODE_DIST_Y
    pos_y += NODE_DIST_Y * 0.5
    pos_x = self.indent * NODE_DIST_X
    pos_x += node.width * NODE_DIST_X * 0.5
    node.pos_x = pos_x
    node.pos_y = pos_y

    # Actual node (circle)
    circle = self.builder.createCircle(pos_x, pos_y, NODE_RADIUS)
    circle.set_style(self.style_node.getStyle())
    self.plot.addElement(circle)

    # Node label
    T = text(node.label, pos_x, pos_y)
    T.set_style(self.style_text.getStyle())
    self.plot.addElement(T)

    # Connection to parent (if any)
    if node.parent:
      # Can use parent.pos_x/y since we're going depth-first.
      L = line(node.parent.pos_x, node.parent.pos_y + NODE_RADIUS,
               pos_x, pos_y - NODE_RADIUS)
      L.set_style(self.style_line.getStyle())
      self.plot.addElement(L)
def KWARGS():
    s = svg() 
    kw = {}
    kw['style'] = 'font-size:20em; font-family:Verdana; fill:blue; '
    t1 = text("KWARGS Text", 0, 300, **kw)
    s.addElement(t1)
    print s.getXML()
    s.save('./testoutput/KWARGS.svg')
示例#9
0
文件: utils.py 项目: doriath/sdgen
 def render(self, svg, x, y):
     t = text(self.content, x, y + self.height * 3 / 4)
     t.set_font_size(self.font.size)
     t.set_font_family(self.font.family)
     t.set_font_style(self.font.style)
     t.set_font_weight(self.font.weight)
     t.set_fill(self.color)
     svg.addElement(t)
示例#10
0
def printFuncNames(svgO, offset):
    global funcAssignDict
    myStyle = StyleBuilder()
    myStyle.setFontFamily(fontfamily="Verdana")
    myStyle.setFontWeight('bold')
    myStyle.setFontSize('20pt') #no need for the keywords all the time
    tmpOff = offset
    txt = text("Functions color map :", 10, tmpOff)
    txt.set_style(myStyle.getStyle())
    svgO.addElement(txt)
    tmpOff += 35
    for key in funcAssignDict:
        myStyle.setFilling(funcAssignDict[key])
        txt = text(str(key), 30, tmpOff)
        txt.set_style(myStyle.getStyle())
        svgO.addElement(txt)
        tmpOff += 30
示例#11
0
def printFuncNames(svgO, offset):
    global funcAssignDict
    myStyle = StyleBuilder()
    myStyle.setFontFamily(fontfamily="Verdana")
    myStyle.setFontWeight('bold')
    myStyle.setFontSize('20pt')  #no need for the keywords all the time
    tmpOff = offset
    txt = text("Functions color map :", 10, tmpOff)
    txt.set_style(myStyle.getStyle())
    svgO.addElement(txt)
    tmpOff += 35
    for key in funcAssignDict:
        myStyle.setFilling(funcAssignDict[key])
        txt = text(str(key), 30, tmpOff)
        txt.set_style(myStyle.getStyle())
        svgO.addElement(txt)
        tmpOff += 30
示例#12
0
def TextFeatures():
  s = svg("test")
  myStyle = StyleBuilder()
  myStyle.setFontFamily(fontfamily="Verdana")
  myStyle.setFontSize('5em')
  myStyle.setFilling(fill="blue")
  t1 = text("Verdana, blue, 5em", 0, 100)
  t1.set_style(myStyle.getStyle())
  t2 = text("pySVG simple", 0, 200)
  s.addElement(t1)
  s.addElement(t2)
  
  r = rect(350, 250, 100, 100)
  r.set_fill("green")
  s.addElement(r)
  
  myStyle = StyleBuilder()
  myStyle.setFontFamily(fontfamily="Times")
  myStyle.setFontSize('2em')
  myStyle.setFontStyle('italic')
  myStyle.setFontWeight('bold')
  myStyle.setFilling(fill="red")
  myStyle.setFillOpacity('0.5')
  myStyle.setFillRule('evenodd')
  
  t3 = text("Times, italic, 2em, bold, opacity=0.5, fillrule=evenodd", 0, 300)
  t3.set_style(myStyle.getStyle())
  s.addElement(t3)

  myStyle = StyleBuilder()
  myStyle.setFontFamily(fontfamily="Times")
  myStyle.setFontSize('2em')
  myStyle.setFontStyle('italic')
  myStyle.setFilling(fill="red")
  myStyle.setFillOpacity('0.5')
  #myStyle.fill="blue"
  t4 = text("Times, italic, 2em, non bold, opacity=0.5", 0, 400)
  t4.set_style(myStyle.getStyle())
  s.addElement(t4)

  
  print s.getXML()
  s.save('./testoutput/3_TextFeatures.svg')
示例#13
0
def HelloWorld2():
  s = svg() 
  myStyle = StyleBuilder()
  myStyle.setFontFamily(fontfamily="Verdana")
  myStyle.setFontSize('5em') #no need for the keywords all the time
  myStyle.setFilling("blue")
  t1 = text("Hello World", 0, 100)
  t1.set_style(myStyle.getStyle())
  s.addElement(t1)
  print s.getXML()
  s.save('./testoutput/2_HelloWorld2.svg')
示例#14
0
def getText(intext, posx, posy, fontsize=12):
    esctext = xml.sax.saxutils.escape(intext)
    t = text(esctext,
             x="%fin" % (posx * mils2inch),
             y="%fin" % (posy * mils2inch))
    #~ t.set_stroke_width('1px')
    #~ t.set_stroke('#00C')
    #~ t.set_fill('none')
    #~ t.set_font_size("36")
    t.set_font_size("%fin" % (fontsize * mils2inch))
    return t
示例#15
0
def traceTimeline(svgO, offset, upTo):
    oh = ShapeBuilder()

    svgO.addElement(oh.createRect(OFFSET_LEFT - 10, offset + 5, OFFSET_LEFT + (upTo + 1) * PIX_BY_SEC + 10, HEIGHT_BY_WORKER / 2))

    for i in range(int(upTo) + 2):
        svgO.addElement(text(str(i), OFFSET_LEFT + i * PIX_BY_SEC - 5 * len(str(i)), offset + 40))

    for i in range((int(upTo) + 2) * 10):
        if i % 10 == 0:
            svgO.addElement(oh.createLine(OFFSET_LEFT + i * PIX_BY_SEC / 10, offset + 5, OFFSET_LEFT + i * PIX_BY_SEC / 10, offset + 20, stroke='red', strokewidth=2))
        else:
            svgO.addElement(oh.createLine(OFFSET_LEFT + i * PIX_BY_SEC / 10, offset + 5, OFFSET_LEFT + i * PIX_BY_SEC / 10, offset + 20, stroke='black', strokewidth=2))
    myStyle = StyleBuilder()
    myStyle.setFontFamily(fontfamily="Verdana")
    myStyle.setFontStyle('italic')
    myStyle.setFontSize('12pt') #no need for the keywords all the time
    txt = text("Time (seconds)", OFFSET_LEFT + 10, offset + 55)
    txt.set_style(myStyle.getStyle())
    svgO.addElement(txt)
    return
示例#16
0
def traceTimeline(svgO, offset, upTo):
    oh = ShapeBuilder()

    svgO.addElement(
        oh.createRect(OFFSET_LEFT - 10, offset + 5,
                      OFFSET_LEFT + (upTo + 1) * PIX_BY_SEC + 10,
                      HEIGHT_BY_WORKER / 2))

    for i in range(int(upTo) + 2):
        svgO.addElement(
            text(str(i), OFFSET_LEFT + i * PIX_BY_SEC - 5 * len(str(i)),
                 offset + 40))

    for i in range((int(upTo) + 2) * 10):
        if i % 10 == 0:
            svgO.addElement(
                oh.createLine(OFFSET_LEFT + i * PIX_BY_SEC / 10,
                              offset + 5,
                              OFFSET_LEFT + i * PIX_BY_SEC / 10,
                              offset + 20,
                              stroke='red',
                              strokewidth=2))
        else:
            svgO.addElement(
                oh.createLine(OFFSET_LEFT + i * PIX_BY_SEC / 10,
                              offset + 5,
                              OFFSET_LEFT + i * PIX_BY_SEC / 10,
                              offset + 20,
                              stroke='black',
                              strokewidth=2))
    myStyle = StyleBuilder()
    myStyle.setFontFamily(fontfamily="Verdana")
    myStyle.setFontStyle('italic')
    myStyle.setFontSize('12pt')  #no need for the keywords all the time
    txt = text("Time (seconds)", OFFSET_LEFT + 10, offset + 55)
    txt.set_style(myStyle.getStyle())
    svgO.addElement(txt)
    return
示例#17
0
文件: pySVGLogo.py 项目: J-VARO/linux
def main():
    mySVG=svg(0,0, width="100%", height="100%")
    t=text("pySVG", x=0,y=100)
    group=g()
    group.set_transform("rotate(-30)")
    t.set_stroke_width('1px')
    t.set_stroke('#00C')
    t.set_fill('none')
    t.set_font_size("36")
    group.addElement(t)
  
    mySVG.addElement(group)
  
    print mySVG.getXML()
    mySVG.save('./testoutput/pySVGLogo.svg')
示例#18
0
    def gen(self, svg):
        # outlines
        if self.opt.outline:
            t = Turtle(fill="lightgrey")
            t.moveTo(Vector(self.sx, self.sy))
            t.penDown()
            for i in self.edges:
                p = i.basic(t)
                t.right(90)
            t.finish()

            for i in t.getSVGElements():
                svg.addElement(i)

        ## fill
        # bodge up the insets
        self.edges[0].length = self.edges[0].length - self.edges[
            1].inset - self.edges[3].inset
        self.edges[1].length = self.edges[1].length - self.edges[
            0].inset - self.edges[2].inset
        self.edges[2].length = self.edges[2].length - self.edges[
            3].inset - self.edges[1].inset
        self.edges[3].length = self.edges[3].length - self.edges[
            2].inset - self.edges[0].inset
        #gr = g()
        gr = a()
        #		gr.set_xlink_href('./?face='+self.name)
        #		gr.set_target('_parent')
        t = Turtle()
        t.moveTo(
            Vector(self.sx + self.edges[3].inset,
                   self.sy + self.edges[0].inset))
        t.penDown()
        for i in self.edges:
            p = i.gen(t)
            t.right(90)
        t.penUp()
        t.finish()
        for i in t.getSVGElements():
            gr.addElement(i)
        if self.opt.show_labels:
            te = text(self.name, self.sx + self.width / 2,
                      self.sy + self.length / 2)
            te.setAttribute("text-anchor", "middle")
            gr.addElement(te)
        svg.addElement(gr)
示例#19
0
    def plotNode(self, tree, nid, shape=None):
        """Adds a single node to the plot, incl. connection to parent."""
        # Compute node position

        node = tree[nid]
        pos_y = node.depth * NODE_DIST_Y
        pos_y += NODE_DIST_Y * 0.5
        pos_x = self.indent * NODE_DIST_X
        pos_x += node.width * NODE_DIST_X * 0.5
        node.pos_x = pos_x
        node.pos_y = pos_y

        # Actual node (circle)
        #circle = self.builder.createCircle(pos_x, pos_y, NODE_RADIUS)
        if shape is None:
            circle = self.builder.createCircle(pos_x, pos_y, NODE_RADIUS)
        elif shape == 'rect':
            circle = self.builder.createRect(pos_x, pos_y, NODE_RADIUS,
                                             NODE_RADIUS * 0.5)
        elif shape == 'ellipse':
            circle = self.builder.createEllipse(pos_x, pos_y,
                                                NODE_RADIUS * 0.8,
                                                NODE_RADIUS * 0.4)

        circle.set_style(self.style_node.getStyle())
        self.plot.addElement(circle)

        # Node label
        T = text(node.tag, pos_x, pos_y)
        T.set_style(self.style_text.getStyle())
        self.plot.addElement(T)

        # Connection to parent (if any)
        if node.bpointer:
            father_node = tree[node.bpointer]
            # Can use parent.pos_x/y since we're going depth-first.
            if shape == 'ellipse':
                L = line(father_node.pos_x,
                         father_node.pos_y + NODE_RADIUS * 0.4, pos_x,
                         pos_y - NODE_RADIUS * 0.4)
            else:
                L = line(father_node.pos_x, father_node.pos_y + NODE_RADIUS,
                         pos_x, pos_y - NODE_RADIUS)
            L.set_style(self.style_line.getStyle())
            self.plot.addElement(L)
示例#20
0
	def drawFinalProb(self):
		numDice = len(self.wins)
		x = self.x(0, self.dice[0],[]) + self.finalOffset
		i = 1
		for die in sorted(self.wins, key=self.wins.get, reverse=True):
			y = (i*self.height)/(numDice + 1) + self.offset[1]
			if self.percent:
				winningProbability = (self.wins[die]/float(self.maxDenum()))*100
				winningProbability = "{0:.2f} %".format(round(winningProbability,2))
			else:
				winningProbability = str(int(self.wins[die]))+"/"+str(self.maxDenum())

			if i == 1: bonus = ";text-decoration:underline"
			else: bonus = ""

			self.s.addElement(text(str(winningProbability), x+40, y-5, style="fill:"+die.stringColor()+";font-size:40;font-family:arial"+bonus))

			i += 1
示例#21
0
    def plotNode(self, tree, nid, shape=None):
        """Adds a single node to the plot, incl. connection to parent."""
        # Compute node position

        node = tree[nid]
        pos_y = node.depth * NODE_DIST_Y
        pos_y += NODE_DIST_Y * 0.5
        pos_x = self.indent * NODE_DIST_X
        pos_x += node.width * NODE_DIST_X * 0.5
        node.pos_x = pos_x
        node.pos_y = pos_y

        # Actual node (circle)
        #circle = self.builder.createCircle(pos_x, pos_y, NODE_RADIUS)
        if shape is None:
            circle = self.builder.createCircle(pos_x, pos_y, NODE_RADIUS)
        elif shape == 'rect':
            circle = self.builder.createRect(pos_x, pos_y, NODE_RADIUS,
                                             NODE_RADIUS * 0.5)
        elif shape == 'ellipse':
            circle = self.builder.createEllipse(pos_x, pos_y, NODE_RADIUS * 0.8,
                                                NODE_RADIUS * 0.4)

        circle.set_style(self.style_node.getStyle())
        self.plot.addElement(circle)

        # Node label
        T = text(node.tag, pos_x, pos_y)
        T.set_style(self.style_text.getStyle())
        self.plot.addElement(T)

        # Connection to parent (if any)
        if node.bpointer:
            father_node = tree[node.bpointer]
            # Can use parent.pos_x/y since we're going depth-first.
            if shape == 'ellipse':
                L = line(father_node.pos_x, father_node.pos_y + NODE_RADIUS * 0.4,
                         pos_x, pos_y - NODE_RADIUS * 0.4)
            else:
                L = line(father_node.pos_x, father_node.pos_y + NODE_RADIUS,
                        pos_x, pos_y - NODE_RADIUS)
            L.set_style(self.style_line.getStyle())
            self.plot.addElement(L)
示例#22
0
    def drawParts(self, svgObj, nbrWorkers):
        i = 0
        oh = ShapeBuilder()
        myStyle = StyleBuilder()
        myStyle.setFontFamily(fontfamily="Verdana")
        myStyle.setFontWeight('bold')
        myStyle.setFontSize('14pt')
        txt = text("Parallelisable?", 5, 20)
        txt.set_style(myStyle.getStyle())
        svgObj.addElement(txt)

        while i < len(self.timeBlocks):
            if self.timeBlocks[i] > nbrWorkers:
                beginRect = i
                while i < len(self.timeBlocks) and self.timeBlocks[i] > nbrWorkers:
                    i += 1
                endRect = i
                svgObj.addElement(oh.createRect(OFFSET_LEFT + beginRect * RESOLUTION_TASK_DISCOVER * PIX_BY_SEC + 2, 5, (endRect - beginRect) * RESOLUTION_TASK_DISCOVER * PIX_BY_SEC + 2, 18, strokewidth=2, fill='orange', stroke='white'))
            else:
                i += 1
示例#23
0
	def gen(self,svg):
		# outlines 
		if self.opt.outline:
			t = Turtle(fill="lightgrey") 
			t.moveTo(Vector(self.sx,self.sy))
			t.penDown()
			for i in self.edges:
				p = i.basic(t)
				t.right(90)	
			t.finish()
			
			for i in t.getSVGElements():
				svg.addElement(i)

		## fill
		# bodge up the insets 
		self.edges[0].length = self.edges[0].length - self.edges[1].inset -  self.edges[3].inset
		self.edges[1].length = self.edges[1].length - self.edges[0].inset -  self.edges[2].inset
		self.edges[2].length = self.edges[2].length - self.edges[3].inset -  self.edges[1].inset
		self.edges[3].length = self.edges[3].length - self.edges[2].inset -  self.edges[0].inset
		#gr = g()
		gr = a()
#		gr.set_xlink_href('./?face='+self.name)
#		gr.set_target('_parent')
		t = Turtle()
		t.moveTo(Vector(self.sx+self.edges[3].inset,self.sy+self.edges[0].inset))
		t.penDown()
		for i in self.edges:
			p = i.gen(t)
			t.right(90)
		t.penUp()
		t.finish()
		for i in t.getSVGElements():
			gr.addElement(i)
		if self.opt.show_labels:
			te = text(self.name,self.sx+self.width/2,self.sy+self.length/2)
			te.setAttribute("text-anchor","middle")
			gr.addElement(te)
		svg.addElement(gr)
示例#24
0
    def saveSVG(self, path):
        """docstring for saveSVG"""
        NODE_RADIUS = 14
        dcSource = wx.PaintDC(self)
        
        import pysvg
        s = pysvg.svg()
        
        sb = pysvg.ShapeBuilder()
        
        for line in self.lines:
            element = sb.createLine(line[0].X, 
                                    line[0].Y, 
                                    line[1].X, 
                                    line[1].Y,
                                    strokewidth=2,
                                    stroke="black")
            s.addElement(element)
        
        h_step = self._font_size
        font_style = pysvg.StyleBuilder()
        font_style.setFontFamily(fontfamily="Verdana")
        font_style.setFontSize("{0}".format(self._font_size))
        font_style.setFilling("black")
        
        for node in self.nodes:
            s.addElement(sb.createCircle(node.X, node.Y, NODE_RADIUS,
                            strokewidth=2, fill='#436EEA'))
            if len(node._t_labels) != 0:
                # TODO:
                _t_labels = node._t_labels

                rect_width = 0
                for i in range(len(_t_labels)):
                    lwidth, lheight, ldescent, el = \
                                    dcSource.GetFullTextExtent(_t_labels[i])
                    if lwidth > rect_width:
                        rect_width = lwidth * self._font_size / self._base_size
                
                horizontal_offset = rect_width / 2
                    
                # element = sb.createRect(node.X - rect_width / 2 - 3, 
                #                         node.Y - h_step * len(_t_labels) - NODE_RADIUS, 
                #                         rect_width + 6, 
                #                         h_step * len(_t_labels) + 2,
                #                         strokewidth=1,
                #                         stroke="black",
                #                         fill="white")
                # s.addElement(element)
 
                for i in range(len(_t_labels)):
                    t = pysvg.text(_t_labels[i], node.X - horizontal_offset,
                            node.Y - NODE_RADIUS - h_step * i - 5)
                    t.set_style(font_style.getStyle())
                    s.addElement(t)

            if len(node._b_labels) != 0:
                # TODO:
                _b_labels = node._b_labels        

                rect_width = 0
                for i in range(len(_b_labels)):
                    lwidth, lheight, ldescent, el = \
                                        dcSource.GetFullTextExtent(_b_labels[i])
                    if lwidth > rect_width:
                        rect_width = lwidth * self._font_size / self._base_size
                
                horizontal_offset = rect_width / 2

                # element = sb.createRect(node.X - rect_width / 2 - 3, 
                #                         node.Y + NODE_RADIUS - 2, 
                #                         rect_width + 6, 
                #                         h_step * len(_b_labels) + 2,
                #                         strokewidth=1,
                #                         stroke="black",
                #                         fill="white")
                # s.addElement(element)

                for i in range(len(_b_labels)):
                    t = pysvg.text(unicode(_b_labels[i]), node.X - horizontal_offset,
                            node.Y + NODE_RADIUS + h_step * (i + 0.8) + 5)
                    t.set_style(font_style.getStyle())
                    s.addElement(t)          
                            
        s.save(path)
示例#25
0
def HelloWorld1():
    s = svg()
    t = text("Hello World", 0, 100)
    s.addElement(t)
    print s.getXML()
    s.save("./testoutput/1_HelloWorld1.svg", encoding="UTF-8")
示例#26
0
def traceWorker(svgO, workerFile, offset, decalageTemps=0.):
    global funcAssignDict
    global taskDict
    oh = ShapeBuilder()
    xmlTree = etree.parse(workerFile)
    print("ADD WORKER ", workerFile)

    assert xmlTree.getroot().tag == 'dtm'

    wbt = float(xmlTree.getroot().get('timeBegin'))

    myStyle = StyleBuilder()
    myStyle.setFontFamily(fontfamily="Verdana")
    myStyle.setFontWeight('bold')
    myStyle.setFontSize('14pt')
    myStyle.setFilling('blue')
    txt = text("Worker " + str(xmlTree.getroot().get('workerId')), 5,
               offset + HEIGHT_BY_WORKER / 2)
    txt.set_style(myStyle.getStyle())
    svgO.addElement(txt)

    maxEndTime = 0.
    dataTask = ""
    taskTarget = ""
    for taskTag in xmlTree.getroot()[0]:
        beginTimes = []
        endTimes = []
        for taskInfo in taskTag:
            if taskInfo.tag == 'event' and taskInfo.get(
                    'type') == "begin" or taskInfo.get('type') == 'wakeUp':
                #print(taskInfo.get('time'))
                beginTimes.append(
                    float(taskInfo.get('time')) - wbt + decalageTemps)
            elif taskInfo.tag == 'event' and taskInfo.get(
                    'type') == "end" or taskInfo.get('type') == 'sleep':
                assert len(endTimes) < len(beginTimes)
                endTimes.append(
                    float(taskInfo.get('time')) - wbt + decalageTemps)
                if maxEndTime < endTimes[-1]:
                    maxEndTime = endTimes[-1]
            elif taskInfo.tag == 'target':
                if not taskInfo.get('name') in funcAssignDict:
                    print("Choose color " + colorsList[len(funcAssignDict)])
                    funcAssignDict[taskInfo.get('name')] = colorsList[len(
                        funcAssignDict)]
                dataTask = taskInfo.get('name') + " : "
                taskTarget = taskInfo.get('name')
                indexArg = 0
                while not (taskInfo.get('arg' + str(indexArg)) is None):
                    dataTask += taskInfo.get('arg' + str(indexArg)) + ", "
                    indexArg += 1
        taskDict[taskTag.get('id')] = (float(taskTag.get('creationTime')) -
                                       wbt + decalageTemps, beginTimes,
                                       endTimes)

        #print(beginTimes, endTimes)
        for i in xrange(len(beginTimes)):
            if endTimes[i] - beginTimes[i] < 5. / PIX_BY_SEC:
                #endTimes[i] += 4. / PIX_BY_SEC
                svgO.addElement(
                    oh.createLine(OFFSET_LEFT + decalageTemps * PIX_BY_SEC +
                                  beginTimes[i] * PIX_BY_SEC + 1,
                                  offset,
                                  OFFSET_LEFT + decalageTemps * PIX_BY_SEC +
                                  beginTimes[i] * PIX_BY_SEC + 1,
                                  offset + HEIGHT_BY_WORKER,
                                  strokewidth=3,
                                  stroke=funcAssignDict[taskTarget]))
            else:
                svgO.addElement(
                    oh.createRect(OFFSET_LEFT + decalageTemps * PIX_BY_SEC +
                                  beginTimes[i] * PIX_BY_SEC + 2,
                                  offset,
                                  endTimes[i] * PIX_BY_SEC - 2 -
                                  (beginTimes[i] * PIX_BY_SEC + 2),
                                  HEIGHT_BY_WORKER,
                                  strokewidth=3,
                                  stroke=funcAssignDict[taskTarget]))
        #svgO.addElement(text(dataTask, beginTime * PIX_BY_SEC + 25, offset + HEIGHT_BY_WORKER / 2))

    loadsList = []
    timesList = []
    for loadTag in xmlTree.getroot()[1]:
        tmpLoad = []
        for workerState in loadTag:
            if workerState.tag != "workerKnownState":
                continue
            loadWorker = [float(i) for i in workerState.get('load').split(",")]
            tmpLoad.append(
                loadWorker[0] + loadWorker[1] + loadWorker[2]
            )  # En cours, en attente de demarrage et en attente de redemarrage
        loadsList.append(tmpLoad)
        timesList.append(float(loadTag.get('time')))

    timesList = [t - wbt + decalageTemps for t in timesList]
    plt.figure()
    if len(sys.argv) > 3 and sys.argv[3] == "log":
        plt.yscale('log', nonposy='clip')
    count = 0
    for line in zip(*loadsList):
        plt.plot(timesList, line, label='Worker ' + str(count))
        count += 1

    plt.legend()
    plt.xlabel('Temps normalise')
    plt.ylabel('Load estime')
    plt.savefig(sys.argv[2] + 'loads_' +
                str(xmlTree.getroot().get('workerId')) + '.png')

    return maxEndTime
}
entries = []
proteins = []

proteins = infile.readline().strip().split('\t')
for line in infile.readlines():
    items = line.strip().split('\t')
    entries.append(items[1:])

x = 10
y = 10
s = svg()
oh = ShapeBuilder()
style = StyleBuilder()
style.setFontSize('1em')  #no need for the keywords all the time
t1 = text(sys.argv[1] + " ", x - 10, y)
t1.set_style(style.getStyle())
s.addElement(t1)
y += 10
x = 20
for entry in entries:
    k = 0
    for e in entry:
        #if e == "1":
        #s.addElement(oh.createCircle(x-10, y, 2,  fill=colors[k]))
        #	 s.addElement(oh.createCircle(x-10, y, 2,  fill=('grey', 'green')[k%2]))
        t1 = text(e, x - 10, y)
        style.setFilling(colors[int(e)])
        t1.set_style(style.getStyle())
        s.addElement(t1)
        k += 1
示例#28
0
def traceWorker(svgO, workerFile, offset, decalageTemps=0.):
    global funcAssignDict
    global taskDict
    oh = ShapeBuilder()
    xmlTree = etree.parse(workerFile)
    print("ADD WORKER ", workerFile)

    assert xmlTree.getroot().tag == 'dtm'

    wbt = float(xmlTree.getroot().get('timeBegin'))

    myStyle = StyleBuilder()
    myStyle.setFontFamily(fontfamily="Verdana")
    myStyle.setFontWeight('bold')
    myStyle.setFontSize('14pt')
    myStyle.setFilling('blue')
    txt = text("Worker " + str(xmlTree.getroot().get('workerId')), 5, offset + HEIGHT_BY_WORKER / 2)
    txt.set_style(myStyle.getStyle())
    svgO.addElement(txt)

    maxEndTime = 0.
    dataTask = ""
    taskTarget = ""
    for taskTag in xmlTree.getroot()[0]:
        beginTimes = []
        endTimes = []
        for taskInfo in taskTag:
            if taskInfo.tag == 'event' and taskInfo.get('type') == "begin" or taskInfo.get('type') == 'wakeUp':
                #print(taskInfo.get('time'))
                beginTimes.append(float(taskInfo.get('time')) - wbt + decalageTemps)
            elif taskInfo.tag == 'event' and taskInfo.get('type') == "end" or taskInfo.get('type') == 'sleep':
                assert len(endTimes) < len(beginTimes)
                endTimes.append(float(taskInfo.get('time')) - wbt + decalageTemps)
                if maxEndTime < endTimes[-1]:
                    maxEndTime = endTimes[-1]
            elif taskInfo.tag == 'target':
                if not taskInfo.get('name') in funcAssignDict:
                    print("Choose color " + colorsList[len(funcAssignDict)])
                    funcAssignDict[taskInfo.get('name')] = colorsList[len(funcAssignDict)]
                dataTask = taskInfo.get('name') + " : "
                taskTarget = taskInfo.get('name')
                indexArg = 0
                while not (taskInfo.get('arg' + str(indexArg)) is None):
                    dataTask += taskInfo.get('arg' + str(indexArg)) + ", "
                    indexArg += 1
        taskDict[taskTag.get('id')] = (float(taskTag.get('creationTime')) - wbt + decalageTemps, beginTimes, endTimes)

        #print(beginTimes, endTimes)
        for i in xrange(len(beginTimes)):
            if endTimes[i] - beginTimes[i] < 5. / PIX_BY_SEC:
                #endTimes[i] += 4. / PIX_BY_SEC
                svgO.addElement(oh.createLine(OFFSET_LEFT + decalageTemps * PIX_BY_SEC + beginTimes[i] * PIX_BY_SEC + 1, offset, OFFSET_LEFT + decalageTemps * PIX_BY_SEC + beginTimes[i] * PIX_BY_SEC + 1, offset + HEIGHT_BY_WORKER, strokewidth=3, stroke=funcAssignDict[taskTarget]))
            else:
                svgO.addElement(oh.createRect(OFFSET_LEFT + decalageTemps * PIX_BY_SEC + beginTimes[i] * PIX_BY_SEC + 2, offset, endTimes[i] * PIX_BY_SEC - 2 - (beginTimes[i] * PIX_BY_SEC + 2), HEIGHT_BY_WORKER, strokewidth=3, stroke=funcAssignDict[taskTarget]))
        #svgO.addElement(text(dataTask, beginTime * PIX_BY_SEC + 25, offset + HEIGHT_BY_WORKER / 2))

    loadsList = []
    timesList = []
    for loadTag in xmlTree.getroot()[1]:
        tmpLoad = []
        for workerState in loadTag:
            if workerState.tag != "workerKnownState":
                continue
            loadWorker = [float(i) for i in workerState.get('load').split(",")]
            tmpLoad.append(loadWorker[0]+loadWorker[1]+loadWorker[2])       # En cours, en attente de demarrage et en attente de redemarrage
        loadsList.append(tmpLoad)
        timesList.append(float(loadTag.get('time')))

    timesList = [t-wbt+decalageTemps for t in timesList]
    plt.figure()
    if len(sys.argv) > 3 and sys.argv[3] == "log":
        plt.yscale('log', nonposy='clip')
    count = 0
    for line in zip(*loadsList):
        plt.plot(timesList, line, label='Worker '+str(count))
        count += 1

    plt.legend()
    plt.xlabel('Temps normalise')
    plt.ylabel('Load estime')
    plt.savefig(sys.argv[2] + 'loads_'+str(xmlTree.getroot().get('workerId'))+'.png')

    return maxEndTime
示例#29
0
 def _text(self, the_text, x, y):
     encoded_text = self._encode_text(the_text)
     return text(encoded_text, x, y)
示例#30
0
def HelloWorld1():
  s = svg()
  t = text("Hello World", 0, 100)
  s.addElement(t)
  print s.getXML()
  s.save('./testoutput/1_HelloWorld1.svg')
示例#31
0
        colors_k += 1
    if not entries.has_key(species):
        entries[species] = []
    entries[species].append((domain, start, end, e_value))
    if not lengths.has_key(species):
        lengths[species] = length

y = 10
for line in orderfile:
    pass
for species in lengths.keys():
    # species = line.strip()
    s.addElement(oh.createLine(0, y + 3, lengths[
                 species], y + 3, strokewidth=1, stroke="black"))
    for (domain, start, end, e_value) in entries[species]:
        s.addElement(oh.createRect(start, y, end - start, 6, 1, 1,
                     strokewidth=1, stroke='black', fill=domain_color[domain]))
    y += 10
s.save('HRP1_domains.svg')

s = svg()
oh = ShapeBuilder()
y = 10
for domain, color in domain_color.items():
    s.addElement(oh.createRect(10, y, 100, 20, 5, 5,
                 strokewidth=1, stroke='black', fill=domain_color[domain]))
    t = text(domain, 120, y + 15)
    s.addElement(t)
    y += 40
s.save('legend.svg')
示例#32
0
文件: tree.py 项目: shokoohi/website
    def drawBranch(self,
                   counter,
                   childrenDice,
                   lastX,
                   lastY,
                   winner=None,
                   numerateur=1,
                   denumerateur=1,
                   progressiveChildCount=1):
        childrenCounter = self.startCounter(counter, childrenDice)
        die = childrenDice.pop()

        progressiveChildCount *= len(die.faces)
        denumerateur *= die.numberSides()

        for face in die.faces:

            childrenNumerateur = numerateur * die.faces[face]
            x1, y1, x2, y2 = lastX, lastY, self.x(childrenCounter, die,
                                                  childrenDice), self.y(
                                                      childrenCounter, die,
                                                      childrenDice,
                                                      progressiveChildCount)
            self.s.addElement(
                line(x1, y1, x2, y2, style="stroke:rgb(0,0,0);stroke-width:2"))

            sProbability = text(die.probabilitySide(face), (x1 + x2) / 2. - 15,
                                (y1 + y2) / 2. + 10,
                                style="font-size:40;font-family:arial;fill:" +
                                die.stringColor() +
                                ";stroke:rgb(0,0,0);stroke-width:0.5")
            self.s.addElement(sProbability)

            sFace = die.drawFace(face)
            sFace.set_transform("translate(" + str(x2 + self.space) + "," +
                                str(y2 - die.r()) + ")")
            self.s.addElement(sFace)

            x, y = x2 + die.size + 2 * self.space, y2

            if winner:
                winnerDie = dict(winner)
            else:
                winnerDie = {}

            if not winnerDie:
                winnerDie = {}
            if not winnerDie or die not in winnerDie:
                winnerDie[die] = face
            else:
                winnerDie[die] += face

            if len(childrenDice) > 0:
                self.drawBranch(childrenCounter, list(childrenDice), x, y,
                                winnerDie, childrenNumerateur, denumerateur,
                                progressiveChildCount)
            else:
                y += die.r() - 7

                maxFace = 0
                winningDie = None
                for key in winnerDie:
                    if winnerDie[key] > maxFace:
                        maxFace = winnerDie[key]
                        winningDie = key

                prob = childrenNumerateur
                self.addWin(winningDie, prob)

                if self.percent:
                    winningProbability = (prob / float(denumerateur)) * 100
                    winningProbability = "{0:.2f} %".format(
                        round(winningProbability, 2))
                else:
                    winningProbability = str(childrenNumerateur) + "/" + str(
                        denumerateur)

                self.s.addElement(
                    text("=", x, y, style="font-size:50;font-family:arial;"))
                self.s.addElement(
                    text(str(winningProbability),
                         x + 40,
                         y - 5,
                         style="fill:" + winningDie.stringColor() +
                         ";font-size:40;font-family:arial;"))

            childrenCounter += 1
示例#33
0
    entries[species].append((domain, start, end))
    if not lengths.has_key(species):
        lengths[species] = length

homologs = {}
for line in homofile:
    sp, ln = line.strip().split("\t")
    homologs[sp] = int(ln)

order = []
for line in orderfile:
    order.append(line.strip())

style = StyleBuilder()
style.setFontSize('3em')  #no need for the keywords all the time
t1 = text(name, 0, 30)
t1.set_style(style.getStyle())
s.addElement(t1)

x = 300
y = 70
for species in order:
    s.addElement(text(species, 0, y))
    if species in homologs:
        s.addElement(
            oh.createLine(x,
                          y,
                          x + homologs[species],
                          y,
                          strokewidth=1,
                          stroke="black"))
 def _text(self, the_text, x, y):
     encoded_text = self._encode_text(the_text)
     return text(encoded_text, x, y)