Exemplo n.º 1
0
    def getTalkRect(self, startTime, duration, trackId, text):
        "Return shapes for a specific talk"
        g = Group()
        y_bottom = self.scaleTime(startTime + duration)
        y_top = self.scaleTime(startTime)
        y_height = y_top - y_bottom

        if trackId is None:
            #spans all columns
            x = self._colLeftEdges[1]
            width = self.width - self._colWidths[0]
        else:
            #trackId is 1-based and these arrays have the margin info in column
            #zero, so no need to add 1
            x = self._colLeftEdges[trackId]
            width = self._colWidths[trackId]

        lab = Label()
        lab.setText(text)
        lab.setOrigin(x + 0.5*width, y_bottom+0.5*y_height)
        lab.boxAnchor = 'c'
        lab.width = width
        lab.height = y_height
        lab.fontSize = 6

        r = Rect(x, y_bottom, width, y_height, fillColor=colors.cyan)
        g.add(r)
        g.add(lab)

        #now for a label
        # would expect to color-code and add text
        return g
Exemplo n.º 2
0
def addScale(drawing, xmap, y, start, end, tickLen=10, dx=3, dy=6,
  textAnchor='middle', boxAnchor='s', fontSize=12,
  strokeWidth=1, strokeColor=colors.black, scale=1.0, format='%ibp'):
    x1 = xmap(start)
    x2 = xmap(end)
    line = Line(x1+dx,y,x2-dx,y,
        strokeWidth=strokeWidth, strokeColor=strokeColor)
    drawing.add(line)
    
    leftTick = Line(x1+dx,y-0.5*tickLen,x1+dx,y+0.5*tickLen,
        strokeWidth=strokeWidth, strokeColor=strokeColor)
    drawing.add(leftTick)
    
    rightTick = Line(x2-dx,y-0.5*tickLen,x2-dx,y+0.5*tickLen,
        strokeWidth=strokeWidth, strokeColor=strokeColor)
    drawing.add(rightTick)
    
    label = Label()
    label.setOrigin(0.5*(x1+x2), y+dy)
    
    distance = float(end-start)/scale
    label.setText(format % (distance/scale))
    label.fontSize = fontSize
    label.textAnchor = textAnchor
    label.boxAnchor = boxAnchor
    drawing.add(label)
Exemplo n.º 3
0
 def draw(self):
     # general widget bits
     w = float(self.length)
     h = float(self.height)
     g = shapes.Group()
     
     body = shapes.Polygon(
         [self.x-0.5*w, self.y-0.5*w,
          self.x-0.5*w, self.y+0.5*w,
          self.x+0.5*w, self.y],
         fillColor=self.fillColor,
         strokeColor=self.strokeColor,
         strokeWidth=self.strokeWidth)
     g.add(body)
     
     if self.label:
         b = g.getBounds()
         s = Label()
         s.setText(self.label)
         s.setOrigin(self.x+0.5*w, self.y-h/2+b[3]-b[1]+4)
         s.boxAnchor = self.boxAnchor
         s.textAnchor = self.textAnchor
         s.fontName = 'Helvetica'
         s.fontSize = self.fontSize
         s.angle = self.labelAngle
         g.add(s)
     
     return g
Exemplo n.º 4
0
def addChromosomes(drawing, chrNames, chrSizes, xmap, ymap, w=0.1*DPI, fillColor=colors.skyblue, strokeColor=colors.skyblue):
    for i,chrom in enumerate(chrNames):
        x = xmap(i+1)
        y = ymap(chrSizes[chrom])
        h = ymap(1)-ymap(chrSizes[chrom])
        
        chromosome = Rect(x,y,w,h, strokeColor=strokeColor, fillColor=fillColor)
        drawing.add(chromosome)
        
        topCap = Wedge(x+0.5*w, y+h, 0.5*w, 0, 180, strokeColor=strokeColor, fillColor=fillColor)
        bottomCap = Wedge(x+0.5*w, y, 0.5*w, 180, 0, strokeColor=strokeColor, fillColor=fillColor)
        drawing.add(topCap)
        drawing.add(bottomCap)
        
        label = Label()
        label.setOrigin(xmap(i+1)+w/2, ymap(0))
        label.boxAnchor = 's'
        label.textAnchor = 'middle'
        label.dx = 0
        label.dy = DPI/10
        label.setText(chrom)
        label.fontSize = 36
        label.fontName = 'Helvetica'
        drawing.add(label)
        
        chrLength = Label()
        chrLength.setOrigin(xmap(i+1)+w/2, ymap(chrSizes[chrom]))
        chrLength.boxAnchor = 'n'
        chrLength.textAnchor = 'middle'
        chrLength.dx = 0
        chrLength.dy = -DPI/10
        chrLength.setText('%iMb' % int(chrSizes[chrom]/1e6))
        chrLength.fontSize = 24
        chrLength.fontName = 'Helvetica'
        drawing.add(chrLength)
Exemplo n.º 5
0
def graphout_stackedBar(data, labels, X, Y):
	drawing = Drawing(X*inch, Y*inch)
	bar = VerticalBarChart()
	bar.x = 50
	bar.y = 50
	bar.width = (X-2)*inch
	bar.height = (Y-1)*inch
	bar.data = data
	bar.bars.strokeWidth = 0
	bar.categoryAxis.style='stacked'
	bar.categoryAxis.labels.boxAnchor = 'ne'
	bar.categoryAxis.labels.dx = -2
	bar.categoryAxis.labels.dy = -2
	bar.categoryAxis.labels.angle = 45
	bar.categoryAxis.categoryNames = labels

	# ensure bar chart and legend coloring matches
	for i in range(len(data)):
		bar.bars[i].fillColor = colorList[i]
	
	# Create a title for the y-axis
	yLabel = Label()
	yLabel.setOrigin(0, 50) # for reference, the graph origin is (50, 50)
	yLabel.boxAnchor = 'c'
	yLabel.angle = 90
	yLabel.setText('Data Storage [GB]')
	yLabel.fontSize=16
	yLabel.dy = 1.25*inch
	drawing.add(yLabel)
	drawing.add(bar)
	return drawing
Exemplo n.º 6
0
def getHumPlot():
    drawing = Drawing(400, 200)
    humedad = [getHumedad()]
    lp = LinePlot()
    lp.x = 50
    lp.y = 50
    lp.height = 125
    lp.width = 300
    lp.data = humedad

    ydlabel = Label()
    ydlabel.setText("Humedad (%)")
    ydlabel.angle = 90
    ydlabel.setOrigin(20, 120)

    lp.joinedLines = 2
    lp.lines[0].symbol = makeMarker('Circle')
    lp.lines[0].strokeColor = colors.blue
    lp.xValueAxis.valueMin = 0
    lp.xValueAxis.valueMax = 30
    lp.yValueAxis.valueMin = 0
    lp.yValueAxis.valueMax = 100
    #lp.xValueAxis.visible=False
    #lp.yValueAxis.visible=False #Hide 2nd plot its Yaxis
    drawing.add(lp)
    drawing.add(ydlabel)
    drawing.add(String(130, 200, "Gráfico de humedad", fontSize=16))

    return drawing
Exemplo n.º 7
0
    def getTalkRect(self, startTime, duration, trackId, text):
        "Return shapes for a specific talk"
        g = Group()
        y_bottom = self.scaleTime(startTime + duration)
        y_top = self.scaleTime(startTime)
        y_height = y_top - y_bottom

        if trackId is None:
            #spans all columns
            x = self._colLeftEdges[1]
            width = self.width - self._colWidths[0]
        else:
            #trackId is 1-based and these arrays have the margin info in column
            #zero, so no need to add 1
            x = self._colLeftEdges[trackId]
            width = self._colWidths[trackId]

        lab = Label()
        lab.setText(text)
        lab.setOrigin(x + 0.5 * width, y_bottom + 0.5 * y_height)
        lab.boxAnchor = 'c'
        lab.width = width
        lab.height = y_height
        lab.fontSize = 6

        r = Rect(x, y_bottom, width, y_height, fillColor=colors.cyan)
        g.add(r)
        g.add(lab)

        #now for a label
        # would expect to color-code and add text
        return g
Exemplo n.º 8
0
    def draw_travels(self):
        for p in self.world.packets:
            if self.detailed:
                txt = p.command()
            else:
                txt = "(%d) %s" % (p.number, p.description)
            last_action = (0,0)
            for ts in p.trip:
                action = self.packet_actions[ts.action]
                if ts.actor not in self.verticals:
                    self.verticals[ts.actor] = self.verticals[ts.actor.node]
                x2,y2 = self.verticals[ts.actor], -ts.time*self.yzoom
                if action.sprite:
                    self.sequence_diagram.add(shapes.Circle(x2, y2, 
                    action.size,  fillColor=action.color, strokeWidth=1 ))

                if action.travel:
                    if action.travel_desc:
                        # self.sequence_diagram.add(shapes.String((last_action[0] + x)/2,(last_action[1]+y)/2, label, fill=colors.black, textAnchor = 'middle'))
                        x1, y1 = last_action[0], last_action[1]
                        l = Label()
                        l.setText(txt) 
                        l.angle = atan2((y2-y1)/2, (x2-x1))*360.0/pi
                        l.dy = 10
                        l.setOrigin((x1 + x2)/2,(y1+y2)/2)
                        self.sequence_diagram.add(l)
                        
                        #anchor = Paragraph('<a name="diagram%d"/>' %p.number, styles['Normal'])
                    self.sequence_diagram.add(shapes.Line(last_action[0],last_action[1],x2,y2, strokeColor=colors.black, strokeWidth=1))
                    self.max_y = min(y2, self.max_y, last_action[1])
                last_action = (x2,y2)
Exemplo n.º 9
0
def addChromosomes(drawing,
                   chrNames,
                   chrSizes,
                   xmap,
                   ymap,
                   w=0.1 * DPI,
                   fillColor=colors.skyblue,
                   strokeColor=colors.skyblue):
    for i, chrom in enumerate(chrNames):
        x = xmap(i + 1)
        y = ymap(chrSizes[chrom])
        h = ymap(1) - ymap(chrSizes[chrom])

        chromosome = Rect(x,
                          y,
                          w,
                          h,
                          strokeColor=strokeColor,
                          fillColor=fillColor)
        drawing.add(chromosome)

        topCap = Wedge(x + 0.5 * w,
                       y + h,
                       0.5 * w,
                       0,
                       180,
                       strokeColor=strokeColor,
                       fillColor=fillColor)
        bottomCap = Wedge(x + 0.5 * w,
                          y,
                          0.5 * w,
                          180,
                          0,
                          strokeColor=strokeColor,
                          fillColor=fillColor)
        drawing.add(topCap)
        drawing.add(bottomCap)

        label = Label()
        label.setOrigin(xmap(i + 1) + w / 2, ymap(0))
        label.boxAnchor = 's'
        label.textAnchor = 'middle'
        label.dx = 0
        label.dy = DPI / 10
        label.setText(chrom)
        label.fontSize = 36
        label.fontName = 'Helvetica'
        drawing.add(label)

        chrLength = Label()
        chrLength.setOrigin(xmap(i + 1) + w / 2, ymap(chrSizes[chrom]))
        chrLength.boxAnchor = 'n'
        chrLength.textAnchor = 'middle'
        chrLength.dx = 0
        chrLength.dy = -DPI / 10
        chrLength.setText('%iMb' % int(chrSizes[chrom] / 1e6))
        chrLength.fontSize = 24
        chrLength.fontName = 'Helvetica'
        drawing.add(chrLength)
Exemplo n.º 10
0
def write_label(label, width, height, person):
    text = "\n".join((person['name'], person['addresses'][0]))
    lab = Label()
    lab.setOrigin(8, height - 5)
    lab.fontSize = 14
    lab.setText(text)
    lab.boxAnchor = 'nw'
    label.add(lab)
Exemplo n.º 11
0
 def draw(self):
     # general widget bits
     w = float(self.length)
     h = float(self.height)
     # print self.label,w,h
     
     # Set minimum size
     if abs(w)<self.wmin:
         xmid = self.x+0.5*w
         w = w/abs(w) * self.wmin
         self.x = xmid-0.5*w
     
     g = shapes.Group()
     if abs(w)>self.wNoTail:
         # arrow specific bits
         body = shapes.Rect(x=self.x, y=self.y-self.aspectRatio*h/2,
             width=2*(w/3),
             height=self.aspectRatio*h,
             fillColor=self.fillColor,
             strokeColor=self.strokeColor,
             strokeWidth=self.strokeWidth)
         g.add(body)
         
         head = shapes.Polygon(
             points=[self.x+w, self.y,
                 self.x+2*(w/3), self.y+h/2,
                 self.x+2*(w/3), self.y-h/2,
                 self.x+w, self.y],
             fillColor=self.fillColor,
             strokeColor=self.strokeColor,
             strokeWidth=self.strokeWidth)
         g.add(head)
     else:
         head = shapes.Polygon(
             points=[self.x+w, self.y,
                 self.x, self.y+h/2,
                 self.x, self.y-h/2,
                 self.x+w, self.y],
             fillColor=self.fillColor,
             strokeColor=self.strokeColor,
             strokeWidth=self.strokeWidth)
         g.add(head)
     
     if self.label:
         b = g.getBounds()
         s = Label()
         s.setText(self.label)
         s.setOrigin(self.x+0.5*w+self.labeldx, self.y-h/2+b[3]-b[1]+self.labeldy)
         s.boxAnchor = self.boxAnchor
         s.textAnchor = self.textAnchor
         s.fontName = 'Helvetica'
         s.fontSize = self.fontSize
         s.angle = self.labelAngle
         g.add(s)
     
     return g
Exemplo n.º 12
0
def addLabel(drawing, x, y, text, fontName='Helvetica', fontSize=11, dy=0,
             angle=0, boxAnchor='sw', textAnchor='start'):
    """Add a label to the drawing. 
    This interface here is inconsistent in that it requires pixel coords. FIX
    This just sets convenient defaults for Label."""
    label = Label()
    label.setText(text)
    label.setOrigin(x, y)
    label.fontName = fontName
    label.fontSize = fontSize
    label.boxAnchor = boxAnchor
    label.textAnchor = textAnchor
    label.dy = dy
    label.angle = angle
    drawing.add(label)
Exemplo n.º 13
0
def addPointyCompoundFeature(drawing, xmap, y, gene, 
  strokeColor=None, fillColor=colors.blue, intronColor=colors.blue,
  glyph=PointyBlock, height=12, utrHeight=6, rise=8, 
  labeldy=10, fontSize=10, textAnchor='middle', boxAnchor='s'):
    """Adds a pointy compound feature to the drawing. This is typically
    several exons joined by zig-zag lines with an arrow showing strand."""
    if gene.strand=='+':
        x1,x2 = xmap(gene.start), xmap(gene.end)
    else:
        x2,x1 = xmap(gene.start), xmap(gene.end)
    y = y+height/2
    y1 = y
    line = Line(x1,y1,x2,y1,strokeColor=intronColor)
    drawing.add(line)
    
    for exon in gene:
        if exon.strand=='+':
            x1,x2 = xmap(exon.start), xmap(exon.end)
        else:
            x2,x1 = xmap(exon.start), xmap(exon.end)
        
        g = glyph()
        g.x = x1
        g.y = y
        if exon.kind.lower()=='utr':
            g.height = utrHeight
        else:
            g.height = height
        g.length = x2-x1
        g.fillColor = fillColor
        if strokeColor:
            g.strokeColor = strokeColor
        else:
            g.strokeColor = fillColor
        g.fontSize = fontSize
        drawing.add(g)
    
    label = Label()
    label.setText(gene.name)
    x = 0.5*(gene.start+gene.end)
    label.setOrigin(x,y)
    label.dy = labeldy
    label.textAnchor = textAnchor
    label.boxAnchor = boxAnchor
    drawing.add(label)
Exemplo n.º 14
0
def genLayers2(ls):
    #ls =(titre, taille)
    c = ['#ffeea0', '#ff88ff', '#bbd5e8']
    length = 4 * cm
    #    ls = np.asarray(ls)
    l = []
    for i in range(len(ls)):
        l.append((ls[i][0], ls[i][1]))
    ls = np.asarray(l, dtype=np.str)
    d = Drawing(4 * cm, 100)
    xpos = 0
    ls[:, 1] = layersize2(ls[:, 1])
    tickness = ls[:, 1].astype(np.float32)
    for i in range(len(ls)):
        lab = Label()
        lab.textAnchor = 'middle'
        color = c[0]
        labelTxt = str(ls[:, 0][i])
        if '+' in labelTxt:
            color = c[1]
        elif '-' in labelTxt:
            color = c[2]
        lab.setText(ls[:, 0][i])
        if i > 0:
            d.add(
                Rect(xpos,
                     np.cumsum(tickness)[i - 1],
                     length,
                     tickness[i],
                     fillColor=colors.HexColor(color)))
            lab.setOrigin(xpos + 2 * cm,
                          np.cumsum(tickness)[i - 1] + tickness[i] / 2)
        else:
            d.add(
                Rect(xpos,
                     0,
                     length,
                     tickness[i],
                     fillColor=colors.HexColor(color)))
            lab.setOrigin(xpos + 2 * cm, tickness[i] / 2)
        d.add(lab)

    return d
Exemplo n.º 15
0
def addAxis(drawing, xmap, y, strokeWidth=1, minorStrokeWidth=0.5, 
  tickDir='down', autoTicks=False, nTicks=20, tickLen=5, fontSize=10, nMinorTicks=80, 
  minorTickLen=2, angle=0, dx=0, dy=-2, textAnchor='middle', boxAnchor=None, 
  scale=1.0, format='%i'):
    """Add a horizontal axis to the drawing.
    
    To do: Round tick positions
    """
    line = Line(xmap.x0, y, xmap.x1, y, strokeWidth=strokeWidth)
    drawing.add(line)
    
    if not boxAnchor:
        if tickDir=='down':
            boxAnchor = 'n'
        else:
            boxAnchor = 's'
    signum = {'up': -1, 'down': 1}[tickDir]
    
    if nTicks>0:
        ticks = tick_generator(xmap.start, xmap.end, n=nTicks, convert=int)
    
    for p in ticks:
        x = xmap(p)
        line = Line(x, y, x, y-signum*tickLen, strokeWidth=strokeWidth)
        drawing.add(line)
        s = Label()
        s.setOrigin(x, y-signum*tickLen)
        s.setText(format % (p/scale))
        s.dx = dx
        s.dy = signum*dy
        s.fontName = 'Helvetica'
        s.fontSize = fontSize
        s.textAnchor = textAnchor
        s.boxAnchor = boxAnchor
        s.angle = angle
        drawing.add(s)
    
    minorticks = tick_generator(xmap.start, xmap.end, n=nMinorTicks, convert=int)
    for p in minorticks:
        x = xmap(p)
        line = Line(x, y, x, y-signum*minorTickLen, strokeWidth=minorStrokeWidth)
        drawing.add(line)
Exemplo n.º 16
0
def simple_label():
    drawing = shapes.Drawing(width=400, height=200)

    drawing.add(shapes.Rect(200, 100, 10, 10, fillColor=colors.red))

    x = 50
    angle = 0
    for item in range(3):
        label = Label()
        label.setOrigin(200, 100)
        label.boxAnchor = 'se'
        label.angle = angle
        #label.boxStrokeColor = colors.black
        label.setText('ReportLab label')
        drawing.add(label)

        x += 25
        angle += 45

    renderPDF.drawToFile(drawing, 'simple_label.pdf')
Exemplo n.º 17
0
def border():
    draw = Drawing(1, 1)
    rect = Polygon(points=[
        -12, cm / 6, (PAGE_WIDTH - (RIGHT_MARGIN + LEFT_MARGIN)), cm / 6,
        PAGE_WIDTH - (RIGHT_MARGIN + LEFT_MARGIN),
        -1 * (PAGE_HEIGHT - (TOP_MARGIN + BOTTOM_MARGIN + cm / 2)), -12,
        -1 * (PAGE_HEIGHT - (TOP_MARGIN + BOTTOM_MARGIN + cm / 2))
    ],
                   strokeColor=Color(*charts.BG_COLOR))
    rect.fillColor = Color(*charts.BG_COLOR, 0.1)
    draw.add(rect)
    draw.add(Circle(100, 90, 5, fillColor=colors.green))
    lab = Label()
    lab.setOrigin(350, -50)
    lab.boxAnchor = 'ne'
    lab.fillColor = Color(*charts.BG_COLOR, 0.15)
    lab.fontSize = 72
    lab.angle = 60
    lab.dx = 0
    lab.dy = 0
    lab.setText('Wisdom Tests')
    draw.add(lab)
    return draw
Exemplo n.º 18
0
def barras(datos):
    alto = datos["alto"]
    ancho = datos["ancho"]
    data = datos["data"]
    labels = datos["labels"]
    colores = datos["colores"]

    grafico = VerticalBarChart()
    grafico.x = 30
    grafico.y = 0
    grafico.height = alto
    grafico.width = ancho
    grafico.data = data
    grafico.barSpacing = 1.25
    for i in range(len(colores)):
        color = colors.HexColor(colores[i])
        grafico.bars[i].strokeColor = color
        grafico.bars[i].fillColor = color
    grafico.valueAxis.labels.fontName = "Helvetica"
    grafico.valueAxis.labels.fontSize = FONTSIZE
    grafico.valueAxis.valueMin = 0
    grafico.valueAxis.valueMax = 100
    grafico.valueAxis.valueStep = 10
    grafico.categoryAxis.categoryNames = labels
    grafico.categoryAxis.labels.fontName = "Helvetica"
    grafico.categoryAxis.labels.fontSize = FONTSIZE
    grafico.categoryAxis.labels.dy = -FONTSIZE
    grafico.categoryAxis.labels.boxAnchor = 'c'
    grafico.categoryAxis.labels.angle = 0
    retorno = crearDrawing(grafico)
    etiqueta = Label()
    etiqueta.setOrigin(0, alto)
    etiqueta.fontSize = FONTSIZE
    etiqueta.fontName = "Helvetica"
    etiqueta.setText("(%)")
    retorno.add(etiqueta)
    return retorno
Exemplo n.º 19
0
def addAxis(drawing, xmap, y, fontSize=8, tickLen=4, minorTickLen=2, 
 nTicks=20, strokeWidth=1, minorStrokeWidth=0.5):
    line = Line(xmap.x0, y, xmap.x1, y, strokeWidth=strokeWidth)
    drawing.add(line)

    ticks = tick_generator(xmap.start, xmap.end, n=nTicks, convert=int)
    for p in ticks:
        x = xmap(p)
        line = Line(x, y, x, y-tickLen, strokeWidth=strokeWidth)
        drawing.add(line)
        s = Label()
        s.setOrigin(x, y-tickLen)
        s.setText(str(p))
        s.fontName = 'Helvetica'
        s.fontSize = fontSize
        s.textAnchor = 'middle'
        s.boxAnchor = 'n'
        drawing.add(s)

    minorticks = tick_generator(xmap.start, xmap.end, n=50, convert=int)
    for p in minorticks:
        x = xmap(p)
        line = Line(x, y, x, y-minorTickLen, strokeWidth=minorStrokeWidth)
        drawing.add(line)
Exemplo n.º 20
0
def genLayers(l0=["substrate", 30], l1=["p++", 20], l2=["p--", 50]):
    c = ['#ffeea0', '#ff88ff', '#bbd5e8']
    length = 4 * cm
    d = Drawing(4 * cm, 100)
    xpos = 0  #*(width-length-4*cm)/2
    #        layer0 = 40
    #        l1[1] = 40
    #        l2[1]= 100-layer0-l1[1]
    l0[1], l1[1], l2[1] = layersize(l0[1], l1[1], l2[1])

    d.add(Rect(xpos, 0, length, l0[1], fillColor=colors.HexColor(c[0])))
    lab = Label()
    lab.textAnchor = 'middle'
    lab.setText(l0[0])
    lab.setOrigin(xpos + 2 * cm, l0[1] / 2)
    d.add(lab)

    d.add(Rect(xpos, l0[1], length, l1[1], fillColor=colors.HexColor(c[1])))
    lab = Label()
    lab.textAnchor = 'middle'
    lab.setText(l1[0])
    lab.setOrigin(xpos + 2 * cm, l0[1] + l1[1] / 2)
    d.add(lab)

    d.add(
        Rect(xpos,
             l0[1] + l1[1],
             length,
             l2[1],
             fillColor=colors.HexColor(c[2])))
    lab = Label()
    lab.textAnchor = 'middle'
    lab.setText(l2[0])
    lab.setOrigin(xpos + 2 * cm, l0[1] + l1[1] + l2[1] / 2)
    d.add(lab)

    return d
Exemplo n.º 21
0
lab.setText('Some\nMulti-Line\nLabel')

d.add(lab)
""")


from reportlab.graphics import shapes
from reportlab.graphics.charts.textlabels import Label

d = Drawing(200, 100)

# mark the origin of the label
d.add(Circle(100,90, 5, fillColor=colors.green))

lab = Label()
lab.setOrigin(100,90)
lab.boxAnchor = 'ne'
lab.angle = 45
lab.dx = 0
lab.dy = -20
lab.boxStrokeColor = colors.green
lab.setText('Some\nMulti-Line\nLabel')

d.add(lab)

draw(d, 'Label example')



disc("""
In the drawing above, the label is defined relative to the green blob.
print lp.data

lp.joinedLines = 1
lp.lines.symbol = makeMarker('Circle')
lp.lineLabelFormat = '%2.2f'
lp.strokeColor = colors.black
lp.xValueAxis.valueMin = 0
lp.xValueAxis.valueMax = 2100
lp.xValueAxis.labelTextFormat = '%2.0f'
lp.yValueAxis.valueMin = 0
lp.yValueAxis.valueMax = 100
lp.yValueAxis.valueStep = 10

xlbl = Label()
xlbl.setText("No. of Genes")
xlbl.setOrigin(310, 72)

ylbl = Label()
ylbl.setText("Percentage\n      (%)")
ylbl.setOrigin(28, 260)

lp.lines[0].strokeColor = colors.darkgreen
lp.lineLabels[0].strokeColor = colors.darkgreen
lp.lines[1].strokeColor = colors.tomato
lp.lineLabels[1].strokeColor = colors.tomato
lp.lines[2].strokeColor = colors.aquamarine
lp.lineLabels[2].strokeColor = colors.aquamarine
lp.lines[3].strokeColor = colors.purple
lp.lineLabels[3].strokeColor = colors.purple

lgnd = Legend()
Exemplo n.º 23
0
class BaseHorizontalBarChart(object):
    pdfmetrics.registerFont(TTFont('simsun', 'simsun.ttc'))

    def __init__(
        self,
        width=A4[0],
        height=A4[1] * 0.25,
        leftMargin=inch,
        rightMargin=inch,
        axis_font_size=10,
        axis_font_name='simsun',
    ):
        self.axis_font_name = axis_font_name
        self.axis_font_size = axis_font_size
        self.width = width
        self.height = height
        self.chart_width = self.width - leftMargin - rightMargin
        self.chart_height = self.height

        self.chart = HorizontalBarChart()
        self.chart.x = 0
        self.chart.y = 0

        self.chart.width = self.chart_width
        self.chart.height = self.chart_height
        self.chart.bars.strokeColor = None
        # 设置柱状图的柱子颜色
        self.chart.bars[0].fillColor = deepskyblue

        # 设置在柱状图后增加该坐标的值
        self.chart.barLabelFormat = '%0.2f'
        self.chart.barLabels.boxAnchor = 'w'  # 锚点,用不好..
        self.chart.barLabels.dx = 0.1 * cm  # 柱状图的值向右偏移0.1CM

        # 设置柱状图的柱宽
        self.chart.barWidth = height * 0.05

        self.title = Label()
        self.x_unit = Label()
        self.y_unit = Label()

        self.title.setText('')
        self.x_unit.setText('')
        self.y_unit.setText('')

        self.x_unit.fontName = self.axis_font_name
        self.y_unit.fontName = self.axis_font_name

    def add_title(self,
                  title='',
                  title_font_size=18,
                  title_font_name='simsun'):
        if title:
            self.title.setText(title)
            self.title.setOrigin(0, 0)
            self.title.dx = 0.5 * self.chart_width
            self.title.dy = self.chart.height + title_font_size
            self.title.fontName = title_font_name
            self.title.fontSize = title_font_size
        else:
            self.title.fontSize = 0

    def add_category_axis(self, category_names=None, axis_unit=None):
        # 设置纵坐标轴
        self.chart.categoryAxis.labels.fontName = self.axis_font_name
        self.chart.categoryAxis.labels.fontSize = self.axis_font_size
        self.chart.categoryAxis.categoryNames = category_names
        if category_names:
            self.chart.height = len(category_names) * self.axis_font_size * 2
            self.chart_height = self.chart.height
            # print(self.chart_height)
            self.height = self.chart.height + getattr(self.title, 'fontSize')

        if axis_unit:
            # 纵坐标轴单位
            self.y_unit.setText(axis_unit)
            self.y_unit.setOrigin(0, 0)
            self.y_unit.dy = self.chart.height + self.axis_font_size
            self.y_unit.dx = -1 * self.axis_font_size * math.floor(
                len(axis_unit) / 2)

    def add_values(self, values, axis_unit=None):

        min_value = 0
        max_value = max(values)
        if max_value >= 50:
            step = 10
        else:
            step = 5

        # 设置横坐标轴
        self.chart.valueAxis.labels.fontName = self.axis_font_name
        self.chart.valueAxis.labels.fontSize = self.axis_font_size
        self.chart.valueAxis.valueMin = min_value
        self.chart.valueAxis.valueMax = min(
            divmod(max_value, step)[0] * step + step, 100)
        self.chart.valueAxis.valueStep = step

        if values:
            self.chart.data = [values]
        else:
            self.data = [
                0 for _ in range(len(self.chart.categoryAxis.categoryNames))
            ]
        # self.chart.data = values

        if axis_unit:
            self.x_unit.setText(axis_unit)
            self.x_unit.setOrigin(0, 0)
            if len(axis_unit) == 1:
                self.x_unit.dx = self.chart_width + self.axis_font_size
            else:
                self.x_unit.dx = self.chart_width + self.axis_font_size * math.floor(
                    len(axis_unit) / 2)

    def show(self):
        ret = list()
        print(self.width, self.height)
        print(self.chart_width, self.chart_height)
        print(self.chart.width, self.chart.height)
        draw = Drawing(self.width, self.height)
        draw.add(self.title)
        draw.add(self.chart)
        draw.add(self.x_unit)
        draw.add(self.y_unit)
        spacer = Spacer(
            self.chart_width,
            getattr(self.title, 'fontSize') * 2 + self.axis_font_size)
        ret.append(spacer)
        ret.append(draw)
        # Spacer(chart_width, title_font_size * 2 + axis_font_size), d)
        return self.ret
Exemplo n.º 24
0
def addCompoundFeature(drawing, xmap, y, gene, 
  strokeColor=None, fillColor=colors.blue, 
  intronColor=colors.blue, intronWidth=0.5,
  glyph=Block, height=12, utrHeight=6,
  labeldy=10, fontSize=10, textAnchor='middle', boxAnchor='s'):
    """Adds a compund feature to the drawing.
    A compound feature is typically several exons joined by zig-zag lines."""
    rise = height + utrHeight
    
    intronStarts = [None]
    intronEnds = []
    heights = []
    for exon in gene:
        x1,x2 = xmap(exon.start), xmap(exon.end)
        
        kind = exon.kind.lower()
        if kind in ['exon', 'utr']:
            intronStarts.append(exon.end)
            intronEnds.append(exon.start)
        
        g = glyph()
        g.x = x1
        g.y = y+height/2
        if exon.kind.lower()=='exon':
            g.height = height
            heights.append(height)
        else:
            g.height = utrHeight
            heights.append(utrHeight)
        
        g.length = x2-x1
        g.fillColor = fillColor
        if strokeColor:
            g.strokeColor = strokeColor
        else:
            g.strokeColor = fillColor
        g.fontSize = fontSize
        drawing.add(g)
    
    for i,(intronStart,intronEnd) in enumerate(zip(intronStarts[1:], intronEnds[1:])):
        x1 = xmap(intronStart)
        x2 = xmap(0.5*(intronStart+intronEnd))
        x3 = xmap(intronEnd)
        # if abs(x3-x1)<3: continue
        # print intronStart,intronEnd,heights[i],heights[i+1]
        
        y1 = y+heights[i]/2+height/2
        y2 = y+rise
        y3 = y+heights[i+1]/2+height/2
        
        line1 = Line(x1,y1,x2,y2,strokeColor=intronColor,strokeWidth=intronWidth)
        line2 = Line(x2,y2,x3,y3,strokeColor=intronColor,strokeWidth=intronWidth)
        drawing.add(line1)
        drawing.add(line2)
    
    # Draw arrows
    if xmap.flipped:
        signum = -1
    else:
        signum = 1
    
    if gene.strand=='+':
        x1 = xmap(gene.end)
        x2 = x1 + signum*15
        x3 = x1 + signum*10
        y1 = y + 0.5*height
        y2 = y + 0.75*height
        y3 = y + 0.25*height
        line1 = Line(x1,y1,x2,y1,strokeColor=intronColor,strokeWidth=intronWidth)
        line2 = Line(x2,y1,x3,y2,strokeColor=intronColor,strokeWidth=intronWidth)
        line3 = Line(x2,y1,x3,y3,strokeColor=intronColor,strokeWidth=intronWidth)
        drawing.add(line1)
        drawing.add(line2)
        drawing.add(line3)
    else:
        x1 = xmap(gene.start)
        x2 = x1 - signum*15
        x3 = x1 - signum*10
        y1 = y + 0.5*height
        y2 = y + 0.75*height
        y3 = y + 0.25*height
        line1 = Line(x1,y1,x2,y1,strokeColor=intronColor,strokeWidth=intronWidth)
        line2 = Line(x2,y1,x3,y2,strokeColor=intronColor,strokeWidth=intronWidth)
        line3 = Line(x2,y1,x3,y3,strokeColor=intronColor,strokeWidth=intronWidth)
        drawing.add(line1)
        drawing.add(line2)
        drawing.add(line3)
    
    # if gene has attribute name...
    label = Label()
    label.setText(gene.name)
    pos = 0.5*(gene.start+gene.end)
    x = xmap(pos)
    label.setOrigin(x,y)
    label.dy = labeldy
    label.textAnchor = textAnchor
    label.boxAnchor = boxAnchor
    drawing.add(label)
Exemplo n.º 25
0
class BasePie(object):
    pdfmetrics.registerFont(TTFont('simsun', 'simsun.ttc'))

    def __init__(self,
                 width=A4[0],
                 height=A4[0] / 2,
                 left_margin=0,
                 right_margin=0,
                 top_margin=0,
                 bottom_margin=0,
                 label_font_size=10,
                 label_font_name='simsun'):

        self.label_font_size = label_font_size
        self.label_font_name = label_font_name

        self.width = width
        self.height = height

        # self.chart_width = self.width
        # self.chart_height = self.height
        self.chart_width = self.chart_height = min(
            self.width - left_margin - right_margin,
            self.height - top_margin - bottom_margin)
        self.chart = Pie()
        # self.chart.x = 0
        # self.chart.y = 0
        self.chart.x = (self.width - self.chart_width) / 2
        self.chart.y = (self.height - self.chart_height) / 2
        self.chart.width = self.chart_width
        self.chart.height = self.chart_height

        self.title = Label()

    def add_values(self, values):
        self.chart.data = values

    def add_labels(self, labels, unit=None):
        self.chart.labels = labels

    def add_title(self,
                  title='',
                  title_font_name='simsun',
                  title_font_size=18):
        if title:
            self.title.setText(title)
            self.title.setOrigin(0, 0)
            self.title.dx = self.width / 2
            # self.title.dy = self.height - (self.height - self.chart_height)/2
            self.title.dy = self.height + title_font_size * 2
            self.title.fontName = title_font_name
            self.title.fontSize = title_font_size
        else:
            self.title.fontSize = 0

    def show(self):
        ret = list()
        draw = Drawing(self.width, self.height)
        draw.add(self.title)
        draw.add(self.chart)
        # spacer = Spacer(self.chart_width, getattr(self.title, 'fontSize') * 2 + self.label_font_size)
        spacer = Spacer(self.chart_width, getattr(self.title, 'fontSize') * 4)
        ret.append(spacer)
        ret.append(draw)
        return ret
print lp.data

lp.joinedLines = 1
lp.lines.symbol = makeMarker('Circle')
lp.lineLabelFormat = '%2.2f'
lp.strokeColor = colors.black
lp.xValueAxis.valueMin = 0
lp.xValueAxis.valueMax = 5
lp.xValueAxis.labelTextFormat = '%2.0f'
lp.yValueAxis.valueMin = 0
lp.yValueAxis.valueMax = 104
lp.yValueAxis.valueStep = 10

xlbl = Label()
xlbl.setText("No. of Clusters")
xlbl.setOrigin(310, 53)

xlbl1 = Label()
xlbl1.setText("No. Of Clusters Vs Accuracy")
xlbl1.setOrigin(310, 25)

ylbl = Label()
ylbl.setText("Accuracy\n      (%)")
ylbl.setOrigin(28, 260)

lp.lines[0].strokeColor = colors.purple
lp.lineLabels[0].strokeColor = colors.purple

d.add(lp)
d.add(xlbl)
d.add(xlbl1)
Exemplo n.º 27
0
def makeSummary(self, stype):
    logger.debug('StartQT4::makeSummary(%s)' % stype)
    pinfo = self.imageViews[-1].getSummaryDemographics()
    if pinfo is None:
        return

    reportname = self.imageViews[-1].getReportName() + '.pdf'
    filename = QtGui.QFileDialog.getSaveFileName(
        self,
        directory=reportname,
        filter='PDF Files *.pdf(*.pdf);;All Files *(*)')
    #filename = QtGui.QFileDialog.getSaveFileName(self, filter='PDF Files *.pdf(*.pdf);;All Files *(*)')
    if len(filename) == 0:
        return
    doc = SimpleDocTemplate(str(filename),
                            pagesize=A4,
                            rightMargin=1.5 * cm,
                            leftMargin=2 * cm,
                            topMargin=2 * cm,
                            bottomMargin=3 * cm)
    elements = []
    #data = pinfo.items()

    for iv in self.imageViews:
        vt = iv.getVelocityText()
        if stype == 'BOTH' or stype == iv.getViewShortName():
            pinfo.append(vt)
    t = Table(pinfo, rowHeights=12)
    t.setStyle(
        TableStyle([('BACKGROUND', (1, 1), (-2, -2), colors.green),
                    ('TEXTCOLOR', (0, 0), (1, -1), colors.black),
                    ('ALIGNMENT', (0, 0), (0, -1), 'RIGHT')]))

    elements.append(t)
    for iv in self.imageViews:
        if stype == 'BOTH' or stype == iv.getViewShortName():
            drawing = Drawing(400, 280)
            cd = iv.getDataPointer()
            vt = iv.getVelocityText()
            pinfo.append(vt)
            #ydata = cd.getCOMYScaled(False, 'mm').tolist()
            ydata = cd.getCOMYScaled(True, 'mm').tolist()
            xPlaneFit = cd.getYPlaneFit(units='mm', bothAxes=True).tolist()
            vdata = cd.getVelocitySlopeScaled(units='mm', bothAxes=True)
            gdata = [ydata, xPlaneFit]
            if vdata is not None:
                gdata.append(vdata.tolist())
            title = Label()
            title.setOrigin(150, 240)
            title.setText(iv.getViewName())
            ylabel = Label()
            ylabel.setOrigin(0, 100)
            ylabel.angle = 90
            ylabel.setText("Millimeters")
            xlabel = Label()
            xlabel.setOrigin(70, 0)
            xlabel.setText("Seconds")
            lp = LinePlot()
            lp.height = 230
            lp.width = 400
            lp.data = gdata
            lp.lines[0].strokeColor = colors.blue
            lp.lines[1].strokeColor = colors.red
            lp.lines[2].strokeColor = colors.green
            #lp.xValueAxis.xLabel = "Seconds"
            drawing.add(title)
            drawing.add(ylabel)
            drawing.add(xlabel)
            drawing.add(lp)
            elements.append(drawing)

    doc.build(elements,
              onFirstPage=self.pdfHeaderFooter,
              onLaterPages=self.pdfHeaderFooter)
    def results_chart(self, control_mean, match_mean, treated_mean, att):
        """
        Specify layout of the results chart and generate
        flowable object that can be added to the pdf
        """
        drawing = Drawing()
        vbc = VerticalBarChart()

        # Offset chart from border and text
        vbc.x = self.chart_offset_x
        vbc.y = self.chart_offset_y

        # Set figure size
        vbc.height = self.chart_height
        vbc.width = self.chart_width

        # Specify chart -- list of lists -- list of series with enteries
        vbc.data = [[control_mean, match_mean, treated_mean, att]]

        #Set Y-Axis ranges
        #axis_range = self._calculate_y_axis(vbc.data)
        #vbc.valueAxis.valueMin = axis_range['min']
        #vbc.valueAxis.valueMax = axis_range['max']
        #vbc.valueAxis.valueStep = axis_range['step']

        #Grid formatting
        vbc.valueAxis.visibleGrid = 1
        vbc.valueAxis.gridStrokeColor = colors.lightgrey

        # Set bar characteristics
        vbc.bars[(0, 0)].fillColor = colors.blue
        vbc.bars[(0, 1)].fillColor = colors.yellow
        vbc.bars[(0, 2)].fillColor = colors.red
        vbc.bars[(0, 3)].fillColor = colors.green
        vbc.bars.strokeColor = None
        vbc.barSpacing = 2

        # Create callout labels
        #vbc.barLabels.fontName = "Helvetica"
        vbc.barLabels.fontSize = 8
        vbc.barLabels.fillColor = colors.black
        vbc.barLabelFormat = '%.2f'
        vbc.barLabels.nudge = 5

        # X-axis labels
        #vbc.categoryAxis.labels.dy = -60
        #vbc.valueAxis.labels.fontName = 'Helvetica'
        vbc.categoryAxis.categoryNames = [
            'Control Mean', 'Matched Control Mean', 'Treatment mean', 'ATT'
        ]

        lab = Label()
        lab.setOrigin(10, 155)
        lab.boxAnchor = 'ne'
        lab.angle = 90
        lab.dx = 0
        lab.dy = -15

        #lab.boxStrokeColor = colors.green
        lab.setText('Result Values')
        drawing.add(lab)

        drawing.add(vbc)
        self.elements.append(drawing)
Exemplo n.º 29
0
def get_pdf_results(task_id):

    # Flask response
    response = Response()
    response.status_code = 200

    task = data.get_task_result(task_id)
    #Saving file to a in-memory file
    output_file = StringIO.StringIO()

    def header_footer(canvas, doc):

        canvas.saveState()

        background = 'static/img/pdf_bg.png'
        canvas.drawImage(background,
                         1 * inch,
                         5.75 * inch,
                         width=8 * inch,
                         height=6 * inch,
                         mask='auto')

        # Header
        logo = Image('static/img/logo/logo.png')
        logo.drawHeight = 0.5 * inch
        logo.drawWidth = 1.75 * inch
        date = datetime.now().strftime("%y-%m-%d %H:%M")
        headerData = [[logo, '', date]]
        headerTable = Table(headerData,
                            colWidths=[2 * inch, 3.58 * inch, 1.2 * inch],
                            style=[('LINEBELOW', (0, 0), (2, 0), 1,
                                    colors.HexColor(0xcccccc)),
                                   ('TEXTCOLOR', (0, 0), (2, 0),
                                    colors.HexColor(0x807F83)),
                                   ('VALIGN', (1, 0), (1, 0), 'MIDDLE'),
                                   ('VALIGN', (2, 0), (2, 0), 'MIDDLE')])
        headerTable.wrapOn(canvas, doc.width, doc.topMargin)
        headerTable.drawOn(canvas, doc.leftMargin, doc.height + doc.topMargin)

        pageNum = "Page %d" % doc.page
        footerData = [[
            'KAPSARC Building Energy Assessment Tool (BEAT)', pageNum
        ]]
        footerTable = Table(footerData,
                            colWidths=[5.76 * inch, 1 * inch],
                            style=[('LINEABOVE', (0, 0), (1, 0), 2,
                                    colors.HexColor(0xcccccc)),
                                   ('TEXTCOLOR', (0, 0), (1, 0),
                                    colors.HexColor(0x807F83)),
                                   ('ALIGN', (1, 0), (1, 0), 'RIGHT')])
        footerTable.wrapOn(canvas, doc.width, doc.bottomMargin)
        footerTable.drawOn(canvas, doc.leftMargin, 0.5 * inch)

        canvas.restoreState()

    pdfmetrics.registerFont(TTFont('Vera', 'Vera.ttf'))
    pdfmetrics.registerFont(TTFont('VeraBd', 'VeraBd.ttf'))
    pdfmetrics.registerFont(TTFont('VeraIt', 'VeraIt.ttf'))
    pdfmetrics.registerFont(TTFont('VeraBI', 'VeraBI.ttf'))
    styles = getSampleStyleSheet()
    # Title
    styles.add(
        ParagraphStyle(name='styleTitle',
                       alignment=TA_CENTER,
                       fontSize=16,
                       fontName='Vera',
                       textColor=colors.HexColor(0x61a659),
                       leading=30,
                       spaceBefore=35,
                       spaceAfter=10))
    # Headings
    styles.add(
        ParagraphStyle(name='styleHeading',
                       parent=styles['Heading2'],
                       fontSize=14,
                       textColor=colors.HexColor(0x807F83),
                       leading=20,
                       spaceBefore=10,
                       underlineProportion=1.1,
                       spaceAfter=10))
    styles.add(
        ParagraphStyle(name='styleHeading2',
                       parent=styles['Heading2'],
                       fontSize=14,
                       textColor=colors.HexColor(0x61a659),
                       leading=20,
                       spaceBefore=20,
                       underlineProportion=1.1,
                       spaceAfter=20))
    styles.add(
        ParagraphStyle(
            name='styleHeading3',
            #alignment= TA_CENTER,
            fontSize=12,
            fontName='Vera',
            textColor=colors.HexColor(0x61a659),
            leading=20,
            spaceBefore=10,
            spaceAfter=5))
    # Body text
    styles.add(
        ParagraphStyle(name='styleBodyText',
                       parent=styles['Normal'],
                       fontSize=9,
                       textColor=colors.HexColor(0x666666),
                       spaceBefore=5,
                       spaceAfter=15))

    styleTitle = styles['styleTitle']
    styleHeading = styles['styleHeading']
    styleHeading2 = styles['styleHeading2']
    styleHeading3 = styles['styleHeading3']
    styleBodyText = styles['styleBodyText']
    pdf_chart_colors = [
        "#3D6531",
        "#61a24f",
        "#89B97B",
        "#B0D1A7",
        "#cde5c7",
        "#7e7f82",
        "#9E9FA1",
        "#BFBFC1",
        "#DFDFE0",
        "#ffd200",
        "#FFE360",
        "#FFEE9F",
    ]

    Elements = []
    doc = BaseDocTemplate(output_file,
                          showBoundary=0,
                          pagesize=A4,
                          title='KASPSARC BEAT Report',
                          author="KAPSARC",
                          leftMargin=0.75 * inch,
                          rightMargin=0.75 * inch,
                          topMargin=inch,
                          bottomMargin=inch)

    frame = Frame(doc.leftMargin,
                  doc.topMargin,
                  doc.width,
                  doc.height,
                  topPadding=0.3 * inch,
                  showBoundary=0)
    template = PageTemplate(id='template',
                            frames=[frame],
                            onPage=header_footer)
    doc.addPageTemplates([template])

    ## PAGE 1
    #add some flowables
    Elements.append(
        Paragraph("KAPSARC Building Energy Assessment Tool (BEAT)",
                  styleTitle))
    Elements.append(Paragraph("Your Building Description", styleHeading))
    rowHeights = 0.3 * inch
    calibrationData = task['calibrationData']
    Elements.append(Paragraph("General Information:", styleHeading3))
    infoTableData = [
        [
            Paragraph('<b>- Name: </b>' + calibrationData['txtBldgName'],
                      styleBodyText),
            Paragraph('<b>- Address: </b>' + calibrationData['txtBldgAddress'],
                      styleBodyText),
            Paragraph('<b>- Type: </b>' + calibrationData['cmbBldgType'],
                      styleBodyText)
        ],
        [
            Paragraph(
                '<b>- Location: </b>' + calibrationData['cmbBldgLocation'],
                styleBodyText),
            Paragraph('<b>- Shape: </b>' + calibrationData['cmbBldgShape'],
                      styleBodyText),
            Paragraph(
                '<b>- Floor Area (m' + u"\u00b2" + '): </b>' +
                str(calibrationData['txtFloorArea']), styleBodyText)
        ]
    ]
    infoTable = Table(infoTableData,
                      colWidths=[160, 165, 150],
                      rowHeights=rowHeights)
    Elements.append(infoTable)

    Elements.append(Paragraph('<br />', styleBodyText))
    Elements.append(Paragraph("Envelope Construction Details:", styleHeading3))
    envTableData = [
        [
            Paragraph(
                '<b>- South Wall: </b>' + calibrationData['cmbSouthWall'],
                styleBodyText),
            Paragraph('<b>- West Wall: </b>' + calibrationData['cmbWestWall'],
                      styleBodyText)
        ],
        [
            Paragraph(
                '<b>- North Wall: </b>' + calibrationData['cmbNorthWall'],
                styleBodyText),
            Paragraph('<b>- East Wall: </b>' + calibrationData['cmbEastWall'],
                      styleBodyText)
        ],
        [
            Paragraph('<b>- Roof: </b>' + calibrationData['cmbRoof'],
                      styleBodyText),
            Paragraph(
                '<b>- Floor: </b>' + calibrationData['cmbFirstFloorContact'],
                styleBodyText)
        ],
        [
            Paragraph('<b>- Windows Type: </b>' + calibrationData['glasstype'],
                      styleBodyText),
            Paragraph(
                '<b>- Overhang Depth (m): </b>' +
                str(calibrationData['txtWinSouthOverhang']), styleBodyText)
        ]
    ]
    envTable = Table(envTableData, colWidths=[240, 235], rowHeights=rowHeights)
    Elements.append(envTable)

    Elements.append(Paragraph('<br />', styleBodyText))
    Elements.append(Paragraph("Air Conditioning Systems", styleHeading3))
    hvacTableData = [[
        Paragraph(
            '<b>- HVAC  System Type: </b>' + calibrationData['cmbBldgSystem'],
            styleBodyText),
        Paragraph(
            '<b>- Cooling Temperature Setting (' + u"\u00b0" + 'C): </b>' +
            str(calibrationData['txtCoolSetTemp']), styleBodyText)
    ],
                     [
                         Paragraph(
                             '<b>- Energy Efficiency Ratio (EER): </b>' +
                             str(calibrationData['eir']), styleBodyText),
                         Paragraph(
                             '<b>- Heating Temperature Setting (' + u"\u00b0" +
                             'C): </b>' +
                             str(calibrationData['txtHeatSetTemp']),
                             styleBodyText)
                     ]]
    hvacTable = Table(hvacTableData,
                      colWidths=[240, 235],
                      rowHeights=rowHeights)
    Elements.append(hvacTable)

    Elements.append(Paragraph('<br />', styleBodyText))
    Elements.append(Paragraph("Overall Assessment", styleHeading))
    Elements.append(
        Paragraph(
            "Based on your description and current SASO requirements, the tool provides the following assessments:",
            styleBodyText))

    if task['compliant']:
        compliant = "<strong><font color=green>meets</font></strong>"
    else:
        compliant = "<strong><font color=red>does not meet</font></strong>"
    if (task['ngEnergyDiff'] < 0):
        energyDiff = "<strong><font color=green>" + str(
            task['energyDiff']) + " kWh/year, less</font></strong>"
    else:
        energyDiff = "<strong><font color=red>" + str(
            task['energyDiff']) + " kWh/year, more</font></strong>"

    Elements.append(
        Paragraph(
            "- Your building " + compliant +
            " SASO requirements for all building envelope", styleBodyText))
    Elements.append(
        Paragraph(
            "- Your building consumed " + energyDiff +
            " than the SASO Baseline", styleBodyText))

    if task['compliant']:
        Elements.append(
            Paragraph(
                "- You may reduce even more your energy consumption in your building by using LED lamps and high efficient appliances and air conditioning system",
                styleBodyText))
    else:
        Elements.append(
            Paragraph(
                " - You need to add more insulation to the walls and/or roof, or use more efficient window glazing to comply with SASO requirements",
                styleBodyText))
    if not task['compliant'] and (task['ngEnergyDiff'] >= 0):
        Elements.append(
            Paragraph(
                " - You may also consider using LED lamps and energy efficient appliances and air conditioning system",
                styleBodyText))

    Elements.append(PageBreak())
    Elements.append(
        Paragraph("How electricity is used in your building?", styleHeading3))
    Elements.append(
        Paragraph(
            "Your building needs electricity to operate several types of equipment including: air-conditioning, lighting, appliances and domestic hot water.",
            styleBodyText))

    #add image
    Elements.append(
        Image('static/img/results-intro.png',
              width=4 * inch,
              height=1.2 * inch))
    #add text
    Elements.append(
        Paragraph(
            "Based on the description you provided as well as typical lighting and appliances used in households, here how your building consumes electricity on annual basis:",
            styleBodyText))

    bepuPieData = task['bepuPieData']
    bepuTableData = [[0 for i in xrange(len(bepuPieData[0]))]
                     for i in xrange(len(bepuPieData) + 1)]
    bepuChartLabel = [0 for i in xrange(len(bepuPieData))]
    bepuChartData = [0 for i in xrange(len(bepuPieData))]
    bepuTableData[0][0] = 'End-Use'
    bepuTableData[0][1] = 'Annual Electricity Use'
    for i, result in enumerate(bepuPieData):
        # write body cells
        bepuTableData[i + 1][0] = str(result['label'])
        bepuTableData[i + 1][1] = int(result['value'])
        bepuChartLabel[i] = str(result['label'])
        bepuChartData[i] = result['value']

    #add chart
    bepuChart = Drawing(400, 200)
    pc = Pie()
    pc.data = bepuChartData
    labelc = [0 for i in xrange(len(bepuChartData))]
    for i, r in enumerate(bepuChartData):
        labelc[i] = str(round(r / sum(bepuChartData) * 100, 1)) + "%"
    pc.labels = labelc
    pc._seriesCount = len(bepuChartLabel)
    pc.slices.strokeColor = colors.HexColor(0xffffff)
    pc.slices.strokeWidth = 0.5
    bepu_chart_colors = ['#FFC43E', '#A4A4A4', '#F67A40', '#5894D0', '#98cd99']
    for i, r in enumerate(bepuChartLabel):
        pc.slices[i].fillColor = colors.HexColor(bepu_chart_colors[i])

    pc.width = pc.height = 120
    pc.x = 40
    pc.y = 30
    # add_legend(d, pc)
    legend = Legend()
    legend.alignment = 'right'
    legend.x = pc.width + pc.x + 80
    legend.y = pc.height - 10
    legend.dx = 8
    legend.dy = 8
    legend.fontName = 'Helvetica'
    legend.fillColor = colors.HexColor(0x807F83)
    legend.fontSize = 10
    legend.boxAnchor = 'nw'
    legend.columnMaximum = 8
    legend.strokeWidth = 0.5
    legend.strokeColor = colors.HexColor(0xffffff)
    legend.deltax = 75
    legend.deltay = 10
    legend.autoXPadding = 10
    legend.yGap = 0
    legend.dxTextSpace = 5
    legend.dividerLines = 1 | 2 | 4
    legend.dividerOffsY = 6
    legend.subCols.rpad = 70
    legend.dividerColor = colors.HexColor(0xdedede)
    legend.colorNamePairs = [(pc.slices[i].fillColor,
                              (bepuChartLabel[i][0:20],
                               '  %s ' % "{:,}".format(int(pc.data[i]))))
                             for i in xrange(len(pc.data))]
    legendHeader = Legend()
    legendHeader.colorNamePairs = [
        ('', ('End-Use', 'Annual Electricity Use\n(kWh/year)'))
    ]
    legendHeader.alignment = 'right'
    legendHeader.x = legend.x - 20
    legendHeader.y = legend.y + 30
    legendHeader.fontName = 'Helvetica'
    legendHeader.fillColor = colors.HexColor(0x807F83)
    legendHeader.fontSize = 10
    legendHeader.boxAnchor = 'nw'
    legendHeader.subCols.rpad = 80
    legendFooter = Legend()
    legendFooter.colorNamePairs = [
        ('', ('Total', str("{:,}".format(int(sum(bepuChartData)))) + ''))
    ]
    legendFooter.alignment = 'right'
    legendFooter.x = legendHeader.x + 5
    legendFooter.y = legend.y - (len(bepuChartLabel) + 1) * 10
    legendFooter.fontName = 'Helvetica-Bold'
    legendFooter.fillColor = colors.HexColor(0x807F83)
    legendFooter.fontSize = 10
    legendFooter.boxAnchor = 'nw'
    legendFooter.subCols.rpad = 145
    bepuChart.add(legend)
    bepuChart.add(legendHeader)
    bepuChart.add(legendFooter)
    pc.slices.fontColor = colors.HexColor(0x807F83)
    n = len(pc.data)
    bepuChart.add(pc, '')
    Elements.append(bepuChart)

    ## PAGE 2
    Elements.append(
        Paragraph("When electricity is consumed in your building?",
                  styleHeading3))
    Elements.append(
        Paragraph(
            "Based on the weather of your location as well as typical lighting and appliances used in households, your building consumes electricity as noted in the following monthly profile:",
            styleBodyText))
    #add chart
    pseBarData = task['pseBarData']

    pseTableData = [[0 for i in xrange(len(pseBarData[0]['values']) + 1)]
                    for i in xrange(len(pseBarData) + 1)]
    pseChartData = [[0 for i in xrange(len(pseBarData[0]['values']))]
                    for i in xrange(len(pseBarData))]
    pseChartLegend = [0 for i in xrange(len(pseBarData))]
    pseTableData[0][0] = 'Key'
    month = [
        'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct',
        'Nov', 'Dec'
    ]
    for i, m in enumerate(month):
        pseTableData[0][i + 1] = str(month[i])
    for i, result in enumerate(pseBarData):
        # write body cells
        pseTableData[i + 1][0] = str(result['key'])
        pseChartLegend[i] = str(result['key'])
        for j, value in enumerate(result['values']):
            pseTableData[i + 1][j + 1] = int(result['values'][j]['y'])
            pseChartData[i][j] = int(result['values'][j]['y'])

    pseChart = Drawing(400, 200)
    bc = VerticalBarChart()
    bc.x = 70
    bc.y = 0
    bc.height = 200
    bc.width = 300
    bc.data = pseChartData
    bc.strokeColor = colors.black
    bc.valueAxis.valueMin = 0
    bc.strokeWidth = 0
    bc.valueAxis.valueMin = 0
    bc.categoryAxis.style = 'stacked'
    bc.categoryAxis.labels.boxAnchor = 'ne'
    bc.categoryAxis.labels.dx = 10
    bc.categoryAxis.labels.dy = -2
    bc.valueAxis.labels.fontName = 'Helvetica'
    bc.valueAxis.labels.fontSize = 10
    bc.valueAxis.strokeWidth = 0.5
    bc.valueAxis.strokeColor = colors.HexColor(0x807F83)
    bc.categoryAxis.strokeWidth = 0.5
    bc.categoryAxis.strokeColor = colors.HexColor(0x807F83)
    bc.valueAxis.labels.fillColor = colors.HexColor(0x807F83)
    bc.categoryAxis.labels.fontName = 'Helvetica'
    bc.categoryAxis.labels.fontSize = 10
    bc.categoryAxis.labels.fillColor = colors.HexColor(0x807F83)
    bc.categoryAxis.categoryNames = month
    # create a list and add the elements of our document (image, paragraphs, table, chart) to it
    #add our barchart and legend
    bc.barWidth = .3 * inch
    bc.groupSpacing = .2 * inch

    bc.bars.strokeColor = colors.HexColor(0xffffff)
    bc.bars.strokeWidth = 0.
    pse_chart_colors = ['#FFC43E', '#A4A4A4', '#F67A40', '#5894D0']
    for i, r in enumerate(pseChartLegend):
        bc.bars[i].fillColor = colors.HexColor(pse_chart_colors[i])
    #  = colors.blue
    legend = Legend()
    legend.alignment = 'right'
    legend.x = bc.width + bc.x + 5
    legend.y = bc.height + bc.y
    legend.deltax = 40
    legend.dxTextSpace = 5
    legend.dx = 8
    legend.dy = 8
    legend.fontName = 'Helvetica'
    legend.fillColor = colors.HexColor(0x807F83)
    legend.fontSize = 10
    legend.boxAnchor = 'nw'
    legend.columnMaximum = (len(bc.data) + 1) / 2
    legend.strokeWidth = 0.5
    legend.strokeColor = colors.HexColor(0xffffff)
    legend.deltax = 75
    legend.deltay = 12
    legend.dividerColor = colors.HexColor(0xdedede)
    legend.columnMaximum = len(pseChartLegend)
    legend.colorNamePairs = [(bc.bars[i].fillColor, pseChartLegend[i])
                             for i in xrange(len(bc.data))]
    #pseChart.hAlign = 'RIGHT'

    label = Label()
    label.setOrigin(10, bc.height / 2)
    #label.boxAnchor = 'sw'
    label.angle = 90
    label.fillColor = colors.HexColor(0x807F83)
    label.setText('Electricity Consumption (kWh)')
    label.fontName = 'Helvetica'

    pseChart.add(legend, 'legend')
    pseChart.add(bc)
    pseChart.add(label)
    Elements.append(pseChart)

    Elements.append(PageBreak())

    ## PAGE 3
    Elements.append(
        Paragraph(
            "Does your building meet SASO Thermal Performance Requirements?",
            styleHeading3))
    Elements.append(
        Paragraph(
            "Based on your description, the thermal transmittance properties of the walls, roof and glazing are calculated, and compared with SASO thermal building performance requirements:",
            styleBodyText))

    #add chart
    lvdData = task['lvdData']
    lvdChartData = [[0 for i in xrange(len(lvdData[0]['values']))]
                    for i in xrange(len(lvdData))]
    lvdChartCategoryNames = [0 for i in xrange(len(lvdData[0]['values']))]
    lvdComparedObjKey = [0 for i in xrange(len(lvdData))]
    for i, result in enumerate(lvdData):
        # write body cells
        lvdComparedObjKey[i] = str(lvdData[i]['key'])
        for j, value in enumerate(result['values']):
            lvdChartCategoryNames[j] = value['label']
            lvdChartData[i][j] = value['value']

    lvdChart = Drawing(400, 200)
    bc = VerticalBarChart()
    bc.x = 70
    bc.y = 0
    bc.height = 200
    bc.width = 300
    bc.data = lvdChartData
    bc.strokeColor = colors.black
    # bc.fillColor=colors.blue
    bc.valueAxis.valueMin = 0
    bc.strokeWidth = 0
    bc.valueAxis.valueMin = 0
    bc.categoryAxis.labels.boxAnchor = 'n'
    bc.categoryAxis.labels.dx = 0
    bc.categoryAxis.labels.dy = -2
    # bc.categoryAxis.labels.angle = 20
    bc.valueAxis.labels.fontName = 'Helvetica'
    bc.valueAxis.labels.fontSize = 10
    bc.valueAxis.strokeWidth = 0.5
    bc.valueAxis.strokeColor = colors.HexColor(0x807F83)
    bc.categoryAxis.strokeWidth = 0.5
    bc.categoryAxis.strokeColor = colors.HexColor(0x807F83)
    bc.valueAxis.labels.fillColor = colors.HexColor(0x807F83)
    bc.categoryAxis.labels.fontName = 'Helvetica'
    bc.categoryAxis.labels.fontSize = 8
    bc.categoryAxis.labels.fillColor = colors.HexColor(0x807F83)
    bc.categoryAxis.categoryNames = lvdChartCategoryNames
    bc.categoryAxis.labels.angle = 0
    # create a list and add the elements of our document (image, paragraphs, table, chart) to it
    #add our barchart and legend
    bc.barWidth = .3 * inch
    bc.groupSpacing = .2 * inch

    bc.bars.strokeColor = colors.HexColor(0xffffff)
    bc.bars.strokeWidth = 0.5
    lvd_chart_colors = ['#5894D0', '#F67A40']
    for i, r in enumerate(lvdComparedObjKey):
        bc.bars[i].fillColor = colors.HexColor(lvd_chart_colors[i])

    #  = colors.blue
    legend = Legend()
    legend.alignment = 'right'
    legend.x = bc.width + bc.x + 5
    legend.y = bc.height + bc.y
    legend.deltax = 40
    legend.dxTextSpace = 5
    legend.dx = 8
    legend.dy = 8
    legend.fontName = 'Helvetica'
    legend.fillColor = colors.HexColor(0x807F83)
    legend.fontSize = 10
    legend.boxAnchor = 'nw'
    legend.columnMaximum = (len(bc.data) + 1) / 2
    legend.strokeWidth = 0.5
    legend.strokeColor = colors.HexColor(0xffffff)
    legend.deltax = 75
    legend.deltay = 12
    legend.dividerColor = colors.HexColor(0xdedede)
    legend.columnMaximum = len(lvdComparedObjKey)
    legend.colorNamePairs = [(bc.bars[i].fillColor, lvdComparedObjKey[i])
                             for i in xrange(len(bc.data))]
    #pseChart.hAlign = 'RIGHT'

    label = Label()
    label.setOrigin(10, bc.height / 2)
    #label.boxAnchor = 'sw'
    label.angle = 90
    label.fillColor = colors.HexColor(0x807F83)
    label.setText('Envelope U-value (W/m' + u'\u00b2' + '.k)')
    label.fontName = 'Helvetica'

    lvdChart.add(label)
    lvdChart.add(legend, 'legend')
    lvdChart.add(bc)
    Elements.append(lvdChart)

    #Elements.append(PageBreak())
    Elements.append(Paragraph('<br /><br />', styleBodyText))
    ## PAGE 4
    Elements.append(
        Paragraph("How energy efficient is your building?", styleHeading3))
    Elements.append(
        Paragraph(
            "Using your input specifications, the annual electricity consumption is calculated and compared with a similar building that meets SASO requirements:",
            styleBodyText))

    #add chart
    bepuComparisonData = task['bepuComparisonData']

    bepuComparisonChartData = [[
        0 for i in xrange(len(bepuComparisonData[0]['values']))
    ] for i in xrange(len(bepuComparisonData))]
    bepuChartCategoryNames = [
        0 for i in xrange(len(bepuComparisonData[0]['values']))
    ]
    bepuComparedObjKey = [0 for i in xrange(len(bepuComparisonData))]
    for i, result in enumerate(bepuComparisonData):
        # write body cells
        bepuComparedObjKey[i] = str(bepuComparisonData[i]['key'])
        for j, value in enumerate(result['values']):
            bepuChartCategoryNames[j] = value['label']
            bepuComparisonChartData[i][j] = value['value']

    bepuComparisonChart = Drawing(400, 200)
    bc = VerticalBarChart()
    bc.x = 70
    bc.y = 0
    bc.height = 200
    bc.width = 300
    bc.data = bepuComparisonChartData
    bc.strokeColor = colors.black
    # bc.fillColor=colors.blue
    bc.valueAxis.valueMin = 0
    bc.strokeWidth = 0
    bc.valueAxis.valueMin = 0
    bc.categoryAxis.labels.boxAnchor = 'ne'
    bc.categoryAxis.labels.dx = 10
    bc.categoryAxis.labels.dy = -2
    # bc.categoryAxis.labels.angle = 20
    bc.valueAxis.labels.fontName = 'Helvetica'
    bc.valueAxis.labels.fontSize = 10
    bc.valueAxis.strokeWidth = 0.5
    bc.valueAxis.strokeColor = colors.HexColor(0x807F83)
    bc.categoryAxis.strokeWidth = 0.5
    bc.categoryAxis.strokeColor = colors.HexColor(0x807F83)
    bc.valueAxis.labels.fillColor = colors.HexColor(0x807F83)
    bc.categoryAxis.labels.fontName = 'Helvetica'
    bc.categoryAxis.labels.fontSize = 10
    bc.categoryAxis.labels.fillColor = colors.HexColor(0x807F83)
    bc.categoryAxis.categoryNames = bepuChartCategoryNames
    bc.categoryAxis.labels.angle = 30
    # create a list and add the elements of our document (image, paragraphs, table, chart) to it
    #add our barchart and legend
    bc.barWidth = .3 * inch
    bc.groupSpacing = .2 * inch

    bc.bars.strokeColor = colors.HexColor(0xffffff)
    bc.bars.strokeWidth = 0.5
    bepu_chart_colors = ['#5894D0', '#F67A40']
    for i, r in enumerate(bepuComparedObjKey):
        bc.bars[i].fillColor = colors.HexColor(bepu_chart_colors[i])
    #  = colors.blue
    # bc.bars[1].fillColor = colors.lightblue
    legend = Legend()
    legend.alignment = 'right'
    legend.x = bc.width + bc.x + 5
    legend.y = bc.height + bc.y
    legend.deltax = 40
    legend.dxTextSpace = 5
    legend.dx = 8
    legend.dy = 8
    legend.fontName = 'Helvetica'
    legend.fillColor = colors.HexColor(0x807F83)
    legend.fontSize = 10
    legend.boxAnchor = 'nw'
    legend.columnMaximum = (len(bc.data) + 1) / 2
    legend.strokeWidth = 0.5
    legend.strokeColor = colors.HexColor(0xffffff)
    legend.deltax = 75
    legend.deltay = 12
    legend.dividerColor = colors.HexColor(0xdedede)
    legend.columnMaximum = len(bepuComparedObjKey)
    legend.colorNamePairs = [(bc.bars[i].fillColor, bepuComparedObjKey[i])
                             for i in xrange(len(bc.data))]
    #pseChart.hAlign = 'RIGHT'

    label = Label()
    label.setOrigin(10, bc.height / 2)
    #label.boxAnchor = 'sw'
    label.angle = 90
    label.fillColor = colors.HexColor(0x807F83)
    label.setText('Annual Energy Use (kWh/year)')
    label.fontName = 'Helvetica'

    bepuComparisonChart.add(label)
    bepuComparisonChart.add(legend, 'legend')
    bepuComparisonChart.add(bc)
    Elements.append(bepuComparisonChart)

    Elements.append(PageBreak())

    doc.build(Elements)

    output_file.seek(0)

    # Set filname and mimetype
    file_name = 'K-BEAT_export_{}.pdf'.format(
        datetime.now().strftime("%Y-%m-%d %H:%M:%S"))

    #Returning the file from memory
    return send_file(output_file,
                     attachment_filename=file_name,
                     as_attachment=True)
Exemplo n.º 30
0
def getPlot():
    drawing = Drawing(400, 200)
    #temps = [((0.5,7), (1.5,1), (2.5,2), (3.5,1), (4.5,3), (5.5,5), (6.5, 10), (7.5,6))]
    temps = [getTemps()]
    bc = LinePlot()
    bc.x = 50
    bc.y = 50
    bc.height = 125
    bc.width = 300
    bc.data = temps
    #labels
    yilabel = Label()
    yilabel.setText("Temperatura (°C)")
    yilabel.angle = 90
    yilabel.setOrigin(20,120)
    xlabel = Label()
    xlabel.setText("Días")
    xlabel.setOrigin(200,20)

    labelT = Label()
    labelT.setText("Temperatura")
    labelT.setOrigin(210,185)

    labelH = Label()
    labelH.setText("Humedad")
    labelH.setOrigin(285,185)


    bc.xValueAxis.valueMin = 0
    bc.xValueAxis.valueMax = 20
    bc.xValueAxis.valueSteps = [x for x in range(1,bc.xValueAxis.valueMax)]
    #bc.xValueAxis.labelTextFormat = '%2.1f'
    bc.yValueAxis.valueMin = 0
    bc.yValueAxis.valueMax = 60
    bc.yValueAxis.valueSteps = [0, 10, 20, 30, 40, 50, 60]
    drawing.add(bc)
    drawing.add(yilabel)
    drawing.add(xlabel)
    drawing.add(Line(170,185,185,185, strokeColor=colors.red))
    drawing.add(Line(250,185,265,185, strokeColor=colors.blue))
    drawing.add(labelT)
    drawing.add(labelH)

    #humedad=[[(0.5, 4), (1.5, 3), (2.5, 4), (3.5, 6), (4.5, 4), (5.5, 2), (6.5, 5), (7.5, 6)]]
    humedad = [getHumedad()]
    lp = LinePlot()
    lp.x = bc.x
    lp.y = bc.y
    lp.height = bc.height
    lp.width = bc.width
    lp.data = humedad

    ydlabel = Label()
    ydlabel.setText("Humedad (%)")
    ydlabel.angle = -90
    ydlabel.setOrigin(lp.x+lp.width+30,lp.y+70)

    lp.joinedLines = 1
    lp.lines[0].symbol = makeMarker('Circle')
    lp.lines[0].strokeColor=colors.blue
    lp.lineLabelFormat = '%2.0f'
    lp.xValueAxis.valueMin = 0
    lp.xValueAxis.valueMax = bc.xValueAxis.valueMax
    lp.yValueAxis.valueMin = 0
    lp.yValueAxis.valueMax = 100
    lp.xValueAxis.visible=False
    lp.yValueAxis.visible=False #Hide 2nd plot its Yaxis
    drawing.add(lp)
    drawing.add(ydlabel)

    y2Axis = YValueAxis()#Replicate 2nd plot Yaxis in the right
    y2Axis.setProperties(lp.yValueAxis.getProperties())
    y2Axis.setPosition(lp.x+lp.width,lp.y,lp.height)
    y2Axis.tickRight=5
    y2Axis.tickLeft=0
    y2Axis.labels.dx = 20
    y2Axis.configure(humedad)
    y2Axis.visible=True
    drawing.add(y2Axis)

    return drawing
Exemplo n.º 31
0
def scatter_plot_2(final_dis_clock, xname, yname):
    drawing = Drawing(400, 300)

    chart = ScatterPlot()

    chart.width = 450
    chart.height = 350

    chart.x = 32
    chart.y = 26

    chart.data = [final_dis_clock]

    chart.joinedLines = 0
    chart.fillColor = color03
    chart.lineLabelFormat = None
    chart.lineLabels.fontName = 'Helvetica'

    lab = Label()
    lab.setOrigin(130, 260)

    chart.xValueAxis.avoidBoundFrac = 1
    chart.xValueAxis.visibleGrid = 1
    chart.xValueAxis.tickDown = 2
    chart.xValueAxis.labels.fontName = 'Helvetica'
    chart.xValueAxis.labels.fontSize = 10
    chart.xValueAxis.labelTextFormat = '%d'
    chart.leftPadding = -32

    chart.xLabel = xname
    chart.xValueAxis.forceZero = 1

    chart.yValueAxis.avoidBoundFrac = 1
    chart.yValueAxis.visibleGrid = 1
    chart.yValueAxis.tickLeft = 2
    chart.yValueAxis.labels.fontName = 'Helvetica'
    chart.yValueAxis.labels.fontSize = 10
    chart.yValueAxis.labelTextFormat = '%s'

    chart.yValueAxis.valueMin = 0.0
    chart.yValueAxis.valueStep = 3.0
    chart.yValueAxis.valueMax = 9.0

    chart.yLabel = yname
    chart.yLabel.center(10)
    chart.yValueAxis.forceZero = 0

    # Title = Label()
    # Title.fontName = 'Helvetica-Bold'
    # Title.fontSize = 10
    # Title.x = 100
    # Title.y = 550
    # Title._text = 'This is just a test chart'
    # Title.maxWidth = 20
    # Title.height = 100
    # Title.textAnchor = 'middle'

    # legend = Legend()
    # legend.colorNamePairs = [(color01, 'Widgets'), (color02, 'Sprockets')]
    # legend.fontName = 'Helvetica'
    # legend.fontSize = 8
    # legend.x = 470
    # legend.y = 470
    # legend.dxTextSpace = 4
    # legend.dy = 7
    # legend.dx = 7
    # legend.deltay = 4
    # legend.alignment = 'right'

    drawing.add(chart)
    return drawing
Exemplo n.º 32
0
def makeSummary(self, stype):
  logger.debug('StartQT4::makeSummary(%s)' % stype)
  pinfo = self.imageViews[-1].getSummaryDemographics()
  if pinfo is None:
    return

  reportname = self.imageViews[-1].getReportName()+'.pdf'
  filename = QtGui.QFileDialog.getSaveFileName(self, directory=reportname, filter='PDF Files *.pdf(*.pdf);;All Files *(*)')
  #filename = QtGui.QFileDialog.getSaveFileName(self, filter='PDF Files *.pdf(*.pdf);;All Files *(*)')
  if len(filename) == 0:
    return
  doc = SimpleDocTemplate(str(filename), pagesize=A4, rightMargin=1.5*cm, leftMargin=2*cm, topMargin=2*cm, bottomMargin=3*cm)
  elements = []
  #data = pinfo.items()

  for iv in self.imageViews:
    vt = iv.getVelocityText()
    if stype == 'BOTH' or stype == iv.getViewShortName():
      pinfo.append(vt)
  t=Table(pinfo, rowHeights=12)
  t.setStyle(TableStyle([('BACKGROUND',(1,1),(-2,-2),colors.green),
			('TEXTCOLOR',(0,0),(1,-1),colors.black),
			('ALIGNMENT', (0,0),(0,-1), 'RIGHT')]))

  elements.append(t)
  for iv in self.imageViews:
    if stype == 'BOTH' or stype == iv.getViewShortName():
      drawing = Drawing(400, 280)
      cd = iv.getDataPointer()
      vt = iv.getVelocityText()
      pinfo.append(vt)
      #ydata = cd.getCOMYScaled(False, 'mm').tolist()
      ydata = cd.getCOMYScaled(True, 'mm').tolist()
      xPlaneFit = cd.getYPlaneFit(units='mm', bothAxes=True).tolist()
      vdata = cd.getVelocitySlopeScaled(units='mm', bothAxes=True)
      gdata = [ydata, xPlaneFit]
      if vdata is not None:
	gdata.append(vdata.tolist())
      title = Label()
      title.setOrigin(150, 240)
      title.setText(iv.getViewName())
      ylabel = Label()
      ylabel.setOrigin(0, 100)
      ylabel.angle = 90
      ylabel.setText("Millimeters")
      xlabel = Label()
      xlabel.setOrigin(70, 0)
      xlabel.setText("Seconds")
      lp = LinePlot()
      lp.height = 230
      lp.width = 400
      lp.data = gdata
      lp.lines[0].strokeColor = colors.blue
      lp.lines[1].strokeColor = colors.red
      lp.lines[2].strokeColor = colors.green
      #lp.xValueAxis.xLabel = "Seconds"
      drawing.add(title)
      drawing.add(ylabel)
      drawing.add(xlabel)
      drawing.add(lp)
      elements.append(drawing)

  doc.build(elements, onFirstPage=self.pdfHeaderFooter, onLaterPages=self.pdfHeaderFooter)
Exemplo n.º 33
0
def half_year(title,city, year, startmon):
    '''startmon is the 1-indexed month to start the page on'''
    reqd, mons = get_months(year, startmon)

    LEFTMARGIN  = 5
    DAYCOLWIDTH = 50
    CELLWIDTH   = 80
    CELLHEIGHT  = 19
    TOPROWHEIGHT = 18
    WIDTH = LEFTMARGIN + DAYCOLWIDTH + CELLWIDTH*6
    HEIGHT = reqd * CELLHEIGHT + TOPROWHEIGHT

    d = shapes.Drawing(WIDTH, HEIGHT)

    lab = Label()
    lab.setOrigin(LEFTMARGIN,HEIGHT)
    lab.boxAnchor = 'nw'
    lab.setText(title)
    lab.fontName = 'Times-Bold'
    d.add(lab)

    # Month headings
    for i in range(6):
        x = LEFTMARGIN + i*CELLWIDTH + DAYCOLWIDTH + CELLWIDTH/2
        month_name = calendar.month_abbr[i + startmon]
        d.add(shapes.String(x, HEIGHT-14, month_name,
            fontSize=14, fontName='Times-Bold', textAnchor='middle'))

    # Day row headings
    for i in range(reqd):
        y = HEIGHT - i*CELLHEIGHT - TOPROWHEIGHT
        weekday_name = calendar.day_abbr[i%7]
        d.add(shapes.String(LEFTMARGIN + 10, y-14, weekday_name,
            fontSize=14))

    # Draw the day cells, for each month
    for j in range(6):
      x = LEFTMARGIN + j*CELLWIDTH + DAYCOLWIDTH
      # for each day
      for i in range(reqd):
        if i >= len(mons[j]) or not mons[j][i]:
          continue
        y = HEIGHT - i*CELLHEIGHT - TOPROWHEIGHT
        # cells for each day, light grey background if weekend
        weekend = i%7 > 4
        lightgrey = colors.HexColor(0xD0B090)
        color = weekend and lightgrey or colors.white

        # Now we have (x, y, color) for (year, month=j+startmon, day=mons[j][i])
        # Get the ephemerides for the date
        date = datetime.datetime(year, j+startmon, mons[j][i])
        (sunrise, sunset, moon_phase, moon_fm) = ephem3.ephem_one_day(city, date)

        # Insert the date cell at x, y
        d.add(shapes.Rect(x, y, CELLWIDTH, -CELLHEIGHT, fillColor=color))
        d.add(shapes.String(x+1, y-10, str(mons[j][i]), fontSize=10))
        green = colors.HexColor(0x207020)

        # Insert the moon phase
        if moon_fm:
          d.add(shapes.String(x+15, y-10, moon_fm, fontSize=8, fillColor=green))
      # for each day
    # for each month
    return d
    def balance_statistics_chart(self, control_vars, match_vars, var_names):
        """
        Specify layout of the balance statistics chart and generate
        flowable object that can be added to the pdf
        """
        drawing = Drawing()
        vbc = VerticalBarChart()

        # Chart position in document
        vbc.x = self.chart_offset_x
        vbc.y = self.chart_offset_y
        vbc.height = self.chart_height
        vbc.width = self.chart_width

        # Specify data
        # [[control_var1, control_var2], [match_var1, match_var2]]
        vbc.data = [control_vars, match_vars]

        #Set Y-Axis ranges
        #axis_range = self._calculate_y_axis(vbc.data)
        #vbc.valueAxis.valueMin = axis_range['min']
        #vbc.valueAxis.valueMax = axis_range['max']
        #vbc.valueAxis.valueStep = axis_range['step']

        #Grid formatting
        vbc.valueAxis.visibleGrid = 1
        vbc.valueAxis.gridStrokeColor = colors.lightgrey

        #Bar formatting
        vbc.bars[0].fillColor = colors.blue
        vbc.bars[1].fillColor = colors.yellow
        vbc.bars.strokeColor = None
        vbc.groupSpacing = 1
        vbc.barWidth = 5

        # Callout label formatting (numbers above bar)
        #vbc.barLabels.fontName = "Arial"
        vbc.barLabels.fontSize = 8
        vbc.barLabels.fillColor = colors.black
        vbc.barLabelFormat = '%.2f'
        vbc.barLabels.nudge = 5

        # Central axis
        vbc.categoryAxis.visibleTicks = 1

        # X-axis labels
        #vbc.categoryAxis.labels.dy = -60
        vbc.valueAxis.labels.fontName = 'Helvetica'
        vbc.categoryAxis.categoryNames = var_names

        lab = Label()
        lab.setOrigin(10, 155)
        lab.boxAnchor = 'ne'
        lab.angle = 90
        lab.dx = 0
        lab.dy = -15

        #lab.boxStrokeColor = colors.green
        lab.setText('Percent Bias')
        drawing.add(lab)
        drawing.add(vbc)
        self.elements.append(drawing)
Exemplo n.º 35
0
def getTempPlot():
    drawing = Drawing(400, 200)
    temps = [getTemps()]
    bc = LinePlot()
    bc.x = 50
    bc.y = 50
    bc.height = 125
    bc.width = 300
    bc.data = temps
    bc.lines[0].symbol = makeMarker('Circle')

    #labels
    yilabel = Label()
    yilabel.setText("Temperatura (°C)")
    yilabel.angle = 90
    yilabel.setOrigin(20, 120)
    xlabel = Label()
    xlabel.setText("Días")
    xlabel.setOrigin(200, 20)

    #labelT = Label()
    #labelT.setText("Temperatura")
    #labelT.setOrigin(210,185)

    #labelH = Label()
    #labelH.setText("Humedad")
    #labelH.setOrigin(285,185)

    label55 = Label()
    label55.setText("55°")
    label55.setOrigin(325, 185)

    bc.xValueAxis.valueMin = 0
    bc.xValueAxis.valueMax = 30
    bc.xValueAxis.valueSteps = [x for x in range(0, bc.xValueAxis.valueMax, 5)]
    #bc.xValueAxis.labelTextFormat = '%2.1f'
    bc.yValueAxis.valueMin = 0
    bc.yValueAxis.valueMax = 80
    bc.yValueAxis.valueSteps = [0, 10, 20, 30, 40, 50, 60, 70, 80]
    drawing.add(bc)
    drawing.add(yilabel)
    drawing.add(xlabel)
    #drawing.add(Line(170,185,185,185, strokeColor=colors.red))
    #drawing.add(Line(250,185,265,185, strokeColor=colors.blue))
    drawing.add(
        Line(300,
             185,
             315,
             185,
             strokeColor=colors.black,
             strokeDashArray=[2, 2]))
    drawing.add(
        Line(50,
             135,
             350,
             135,
             strokeColor=colors.black,
             strokeDashArray=[2, 2]))
    #drawing.add(labelT)
    #drawing.add(labelH)
    drawing.add(label55)
    #drawing.add(Grid())
    drawing.add(String(130, 200, "Gráfico de temperaturas", fontSize=16))

    return drawing
Exemplo n.º 36
0
    if not line.isspace() and line[0] not in COMMENT_CHARS:
        data.append([float(n) for n in line.split()])
print(data)
pred = [row[2] for row in data]
high = [row[3] for row in data]
low = [row[4] for row in data]
times = [row[0] + row[1] / 12.0 for row in data]

lp = LinePlot()
lp.x = 50
lp.y = 50
lp.height = 125
lp.width = 300
lp.data = [
    list(zip(times, pred)),
    list(zip(times, high)),
    list(zip(times, low))
]
lp.lines[0].strokeColor = colors.blue
lp.lines[1].strokeColor = colors.red
lp.lines[2].strokeColor = colors.green

lab = Label()
lab.setOrigin(350, 180)
lab.setText('blue line:pred\nred line:high\ngreen line:low')
lab.boxStrokeColor = colors.green
drawing.add(lab)
drawing.add(lp)
drawing.add(String(250, 150, 'Sunspots', fontSize=14, fillColor=colors.red))
renderPDF.drawToFile(drawing, 'report2.pdf', 'Sunspots')
Exemplo n.º 37
0
    def exportMonthlyReport(self, file, month, year):
        """Outputs the monthly report to the specified file location
            Parameters:
                self: the class instance
                file: str - file location and name ending in .pdf
                month: str - required month
                year: int - required year
        """

        # For conversion of month to three letter abbreviation
        months = [
            'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
            'Oct', 'Nov', 'Dec'
        ]

        # Creating a title
        title = Label()
        title.setOrigin(300, 20)
        title.boxAnchor = 'ne'
        title.dx = 0
        title.dy = -5
        title.fontSize = 30
        title.setText("Monthly Report")

        # Adding title to a drawing
        draw_title = Drawing(0, 40)
        draw_title.add(title)

        # Creating a subtitle
        subtitle = Label()
        subtitle.setOrigin(320, 20)
        subtitle.boxAnchor = 'ne'
        subtitle.dx = 0
        subtitle.dy = -10
        subtitle.fontSize = 14

        # Converts month to three letter abbreviation
        str_month = months[int(month) - 1]

        # Setting the subtitle's text
        subtitle.setText("Australia Zoo Wildlife Hospital, " + str_month +
                         " " + str(year))

        # Adding subtitle to a drawing
        draw_subtitle = Drawing(0, 30)
        draw_subtitle.add(subtitle)

        # Creating a label for the first chart
        label_lga = Label()
        label_lga.setOrigin(180, 20)
        label_lga.boxAnchor = 'ne'
        label_lga.dx = 0
        label_lga.dy = -20
        label_lga.setText("Local Government Area Totals")

        # Adding label to a drawing
        draw_label_lga = Drawing(0, 40)
        draw_label_lga.add(label_lga)

        # Creating drawing for the lga chart
        draw_lga = Drawing(0, 270)
        draw_lga.add(self.getSpecificBarChart("LGA", month, year))

        # Creating a label for the second chart
        label_taxons = Label()
        label_taxons.setOrigin(180, 20)
        label_taxons.boxAnchor = 'ne'
        label_taxons.dx = 0
        label_taxons.dy = -20
        label_taxons.setText("Taxon Grouping Totals")

        # Adding label to a drawing
        draw_label_taxons = Drawing(0, 40)
        draw_label_taxons.add(label_taxons)

        # Creating drawing for the taxons chart
        draw_taxons = Drawing(0, 270)
        draw_taxons.add(self.getSpecificBarChart("Taxons", month, year))

        # List of drawings in order of how to place them in the canvas
        drawlist = [
            draw_title, draw_subtitle, draw_label_lga, draw_lga,
            draw_label_taxons, draw_taxons
        ]

        # Creating a canvas (pdf file) and saving it to a location
        canvas = Canvas(file)

        # Creating a frame to add flowables (drawings) to
        frame = Frame(inch, 0, 15.92 * cm, 29.7 * cm)

        # Adding flowables
        frame.addFromList(drawlist, canvas)

        # Saving the pdf
        canvas.save()
Exemplo n.º 38
0
    def draw_hex(self):
        print 'Reporting Hex'
        story = []
        for p in self.world.packets:
            pl,t = p.build_ps()
            XSTART = 0
            XDSTART = 210
            y = 0.0
            XMUL= 100.0
            YMUL = 10.0
            larg = 16
            YDUMP = PAGE_HEIGHT*0.80/YMUL - 10
            YDUMP = 0
            canvas = shapes.Drawing(500, 100)
            # canvas.add(shapes.Rect(0,0, 500, PAGE_HEIGHT, fillColor=colors.yellow))
            backcolor=colgen(0.6, 0.8, 1.0)
            forecolor=colgen(0.2, 0.5, 0.8)
            def hexstr(x):
                s = []
                for c in x:
                    s.append("%02x" % ord(c))
                return " ".join(s)

            my_y = 0
            shift = 0
            last_x = 0
            while t:
                bkcol = backcolor.next()
                proto,fields = t.pop()
                l = Label()
                l.setText(proto.name)
                l.boxAnchor = 'w'
                l.boxStrokeColor = colors.gray
                bc = colors.Color(bkcol[0], bkcol[1], bkcol[2] )
                l.boxFillColor = bc
                l.setOrigin(XSTART, (YDUMP-y)*YMUL)
                canvas.add(l)
                my_y = y
                for fname, fval, fdump in fields:
                    y += 1.5
                    col = forecolor.next()
                    l = Label()
                    l.boxAnchor = 'w'
                    l.setText(fname.name)
                    l.setOrigin(XSTART + (0.1 * XMUL), (YDUMP-y)*YMUL)
                    canvas.add(l)
                    
                    if fval is not None:
                        if len(fval) > 24:
                            fval = fval[:21]+"..."
                    else:
                        fval=""
                    
                    l = Label()
                    l.setText(fval)
                    xlabel, ylabel = XSTART+(1.5*XMUL), (YDUMP-y)*YMUL
                    l.setOrigin(xlabel, ylabel)
                    l.boxStrokeWidth = 2
                    l.boxAnchor = 'e'
                    canvas.add(l)
                    
                    first = True
                    while fdump:
                        dmp, fdump = fdump[:larg-shift],fdump[larg-shift:]
                        l = Label()
                        l.boxAnchor = 'w'
                        l.fontName = 'Courier'
                        l.boxFillColor = colors.Color(bkcol[0], bkcol[1], bkcol[2])
                        l.boxStrokeColor = colors.Color(col[0], col[1], col[2])
                        l.boxStrokeWidth = 2
                        xdump, ydump = XDSTART+ last_x * 0.06*XMUL, (YDUMP-my_y)*YMUL
                        l.setOrigin(xdump, ydump)
                        h = hexstr(dmp)
                        l.setText(h)
                        canvas.add(l)
                        if first:
                            link = shapes.Line(xdump, ydump, xlabel, ylabel, strokeColor=colors.Color(col[0], col[1], col[2]), strokeWidth=1)
                            canvas.add(link)
                            first = False
                        shift += len(dmp)
                        last_x += len(h) +1
                        if shift >= larg:
                            shift = 0
                            last_x = 0
                            my_y += 2
                y += 2
            scale = 0.7
            canvas.shift(0, y * YMUL*scale)
            canvas.height = min(y * YMUL *scale , PAGE_HEIGHT*0.80)
            canvas.scale(scale, scale)
            # para = Paragraph('<a name="hex%d"/>'%p.number + \
            # '<a href="#summary%d">(%d) %s</a>' % (p.number, p.number, p.description), styles['Normal'])
            # story.append([[para, Spacer(1,10), canvas]])
            para = Paragraph('<a href="#summary%d">(%d) %s</a>' % (p.number, p.number, p.description), styles['Normal'])
            story.append([[para, Spacer(1,10), canvas]])

        t = Table(story)
        t.setStyle(TableStyle([
                        ('INNERGRID', (0,0), (-1,-1), 0.1, colors.black), 
                        ('BOX', (0,0), (-1,-1), 0.1, colors.black), 
                        ]))
        return [t]