Пример #1
0
        def myBarChart(data):
            drawing = Drawing(400, 200)

            bc = VerticalBarChart()
            bc.x = 50
            bc.y = 50
            bc.height = 125
            bc.width = 300
            bc.data = data
            bc.barWidth = .3 * inch
            bc.groupSpacing = .2 * inch

            bc.strokeColor = colors.black

            bc.valueAxis.valueMin = 0
            bc.valueAxis.valueMax = 100
            bc.valueAxis.valueStep = 10

            bc.categoryAxis.labels.boxAnchor = 'ne'
            bc.categoryAxis.labels.dx = 8
            bc.categoryAxis.labels.dy = -2

            catNames = ('Trial1 Trial2 Trial3 Trial4 Trial5').split()
            bc.categoryAxis.categoryNames = catNames

            bc.bars[0].fillColor = colors.red
            bc.bars[1].fillColor = colors.lightblue

            drawing.add(bc)

            return drawing
Пример #2
0
def generateversionchart((versionpickle, picklehash, imagedir, pickledir)):
	datapickle = open(os.path.join(pickledir, versionpickle), 'rb')
	data = cPickle.load(datapickle)
	datapickle.close()

	## calculate the possible widths and heights of chart, bars, labels and so on
	maxversionstring = max(map(lambda x: len(x[0]), data))

	barwidth = 15
	chartwidth = len(data) * barwidth + 10 * len(data)

	maxvalue = max(map(lambda x: x[1], data))
	step = int(math.log(maxvalue,10))
	valueStep = pow(10,step)

	## calculate a possible good value for startx and starty so labels are not cut off
	startx = max(10 + step * 10, 30)

	## TODO: fiddle with values to create nicer looking graphs
	starty = maxversionstring * 10 + 20

	drawheight = 225 + starty
	drawwidth = chartwidth + startx + 10

	## create the drawing
	drawing = Drawing(drawwidth, drawheight)
	bc = VerticalBarChart()
	bc.x = startx
	bc.y = starty
	bc.height = 200
	bc.width = chartwidth
	bc.data = [tuple(map(lambda x: x[1], data))]
	bc.strokeColor = colors.white
	bc.valueAxis.valueMin = 0
	bc.valueAxis.labels.fontSize = 16
	bc.valueAxis.valueMax = maxvalue
	bc.valueAxis.valueStep = valueStep
	bc.categoryAxis.labels.boxAnchor = 'w'
	bc.categoryAxis.labels.dx = 0
	bc.categoryAxis.labels.dy = -2
	bc.categoryAxis.labels.angle = -90
	bc.categoryAxis.labels.fontSize = 16
	bc.categoryAxis.categoryNames = map(lambda x: x[0], data)
	bc.barWidth = barwidth

	drawing.add(bc)
	outname = os.path.join(imagedir, picklehash)

	renderPM.drawToFile(drawing, outname, fmt='PNG')
	return picklehash
Пример #3
0
def generateversionchart((versionpickle, picklehash, imagedir, pickledir)):
    datapickle = open(os.path.join(pickledir, versionpickle), 'rb')
    data = cPickle.load(datapickle)
    datapickle.close()

    ## calculate the possible widths and heights of chart, bars, labels and so on
    maxversionstring = max(map(lambda x: len(x[0]), data))

    barwidth = 15
    chartwidth = len(data) * barwidth + 10 * len(data)

    maxvalue = max(map(lambda x: x[1], data))
    step = int(math.log(maxvalue, 10))
    valueStep = pow(10, step)

    ## calculate a possible good value for startx and starty so labels are not cut off
    startx = max(10 + step * 10, 30)

    ## TODO: fiddle with values to create nicer looking graphs
    starty = maxversionstring * 10 + 20

    drawheight = 225 + starty
    drawwidth = chartwidth + startx + 10

    ## create the drawing
    drawing = Drawing(drawwidth, drawheight)
    bc = VerticalBarChart()
    bc.x = startx
    bc.y = starty
    bc.height = 200
    bc.width = chartwidth
    bc.data = [tuple(map(lambda x: x[1], data))]
    bc.strokeColor = colors.white
    bc.valueAxis.valueMin = 0
    bc.valueAxis.labels.fontSize = 16
    bc.valueAxis.valueMax = maxvalue
    bc.valueAxis.valueStep = valueStep
    bc.categoryAxis.labels.boxAnchor = 'w'
    bc.categoryAxis.labels.dx = 0
    bc.categoryAxis.labels.dy = -2
    bc.categoryAxis.labels.angle = -90
    bc.categoryAxis.labels.fontSize = 16
    bc.categoryAxis.categoryNames = map(lambda x: x[0], data)
    bc.barWidth = barwidth

    drawing.add(bc)
    outname = os.path.join(imagedir, picklehash)

    renderPM.drawToFile(drawing, outname, fmt='PNG')
    return picklehash
def run(self, include_sub_survey=False, dimensions=[]):

    # Build data set
    averages = []
    category_names = []
    
    for dimension in self.getDimensions():
        averages.append(self.get_average_score_for_dimension(
            include_sub_survey=include_sub_survey,
            dimension=dimension))
        category_names.append(dimension)
        
    drawing = Drawing(600, 300)
    
    bc = VerticalBarChart()         
    bc.x = 20
    bc.y = 20  
    bc.height = 260
    bc.width = 580
    bc.data = [averages]
    bc.categoryAxis.categoryNames = category_names
    bc.categoryAxis.labels.fontName = 'Helvetica'
    bc.categoryAxis.labels.fontSize = 10
    bc.categoryAxis.labels.textAnchor = 'middle'
    bc.categoryAxis.visibleTicks = 0
    bc.valueAxis.valueMax = 100.0
    bc.valueAxis.valueMin = min(averages, 0)
    bc.valueAxis.labels.fontName = 'Helvetica'
    bc.valueAxis.labels.fontSize = 10
    bc.valueAxis.labels.textAnchor = 'middle'
    bc.barLabelFormat = '%.0f'
    bc.barLabels.dy = 8
    bc.barLabels.fontName = 'Helvetica'
    bc.barLabels.fontSize = 10
    bc.barWidth = len(averages)
    bc.fillColor = None

    drawing.add(bc)
    
    # Write out
    data = drawing.asString('png')
    request = self.REQUEST
    response = request.RESPONSE
    response.setHeader('Content-Type', 'image/png')
    response.setHeader('Content-Disposition','inline; filename=%s.png' % self.getId())
    response.setHeader('Content-Length', len(data))           
    response.setHeader('Cache-Control', 's-maxage=0')
    
    return data
Пример #5
0
def letrasGrafico(data):
    "Make a slightly pathologic bar chart with only TWO data items."
    drawing = Drawing(800, 300)
    bc = VerticalBarChart()
    bc.x = 50
    bc.y = -10
    bc.height = 300
    bc.width = 300
    bc.barWidth = 15
    bc.Title = "Frencuencias en "
    bc.data = data
    #bc.strokeColor = colors.black
    bc.valueAxis.valueMin = 0
    bc.valueAxis.valueMax = 7000
    bc.valueAxis.valueStep = 500
    bc.categoryAxis.labels.boxAnchor = 'e'
    bc.categoryAxis.labels.angle = 0
    abc = "abcdefghijklmnopqrstuvwxyz"
    bc.categoryAxis.categoryNames = list(abc)
    drawing.add(bc)
    return drawing
Пример #6
0
def getVetricalBarChart(taxes_int):
    values = []
    years = []
    font = 'Arial'
    for year in taxes_int:
        years.append(year)
        values.append(taxes_int[year])

    data = [values]
    chart = VerticalBarChart()
    chart.height = 180
    chart.width = 450
    chart.data = data

    chart.valueAxis.valueMin = 0
    chart.barWidth = 20
    chart.groupSpacing = 5
    chart.barLabels.fontName = font
    chart.barLabels.fontSize = 8
    chart.bars[0].fillColor = colors.cornflowerblue
    chart.barLabelFormat = '%d тг'
    chart.barLabels.nudge = 7

    chart.categoryAxis.labels.fontName = font
    chart.categoryAxis.labels.fontSize = 8
    chart.categoryAxis.categoryNames = years

    chart.valueAxis.labels.fontName = font
    chart.valueAxis.labels.fontSize = 8
    # chart.valueAxis.gridStrokeDashArray = strokeDashArray
    # chart.valueAxis.gridStrokeWidth = strokeWidth
    # chart.valueAxis.strokeDashArray = strokeDashArray
    # chart.valueAxis.strokeWidth = strokeWidth


    drawing = Drawing(300)
    drawing.add(chart)
    return drawing
Пример #7
0
def myBarChart(data):
    drawing = Drawing(400, 200)
    bc = VerticalBarChart()
    bc.x = 50
    bc.y = 50
    bc.height = 125
    bc.width = 300
    bc.data = data
    bc.barWidth = .3*inch
    bc.groupSpacing = .2 * inch
    bc.strokeColor = colors.black
    bc.valueAxis.valueMin = 0
    bc.valueAxis.valueMax = 100
    bc.valueAxis.valueStep = 10
    bc.categoryAxis.labels.boxAnchor = 'ne'
    bc.categoryAxis.labels.dx = 8
    bc.categoryAxis.labels.dy = -2
    catNames = string.split('Trial1 Trial2 Trial3 Trial4 Trial5')
    bc.categoryAxis.categoryNames = catNames
    bc.bars[0].fillColor = colors.blue
    bc.bars[1].fillColor = colors.lightblue
    drawing.add(bc)
    return drawing
Пример #8
0
def main(argv):
    parser = argparse.ArgumentParser()

    # the following options are provided on the commandline
    parser.add_argument("-f", "--file", action="store", dest="cleanupfile",
                        help="path to cleanup result file", metavar="FILE")
    parser.add_argument("-o", "--output", action="store", dest="outputfile",
                        help="path to output file", metavar="FILE")
    args = parser.parse_args()

    # path of the gzip compressed releases file
    if args.cleanupfile is None:
        parser.error("cleanup file missing")

    if args.outputfile is None:
        parser.error("output file missing")

    if os.path.isdir(args.outputfile):
        print("outputfile %s is a directory, cannot overwrite" % args.outputfile, file=sys.stderr)
        sys.exit(1)

    if not os.path.exists(args.cleanupfile):
        print("result file missing", file=sys.stderr)
        sys.exit(1)

    unique_releases = set()
    cleanupfile = open(args.cleanupfile, 'r')

    # store the number of the last release found with a small in the
    # dataset. This is to ensure that the right amount of columns will
    # be generated in the end through an ugly hack
    max_release_number = 0

    # store the release number for releases with a smell
    for l in cleanupfile:
        if 'https://www.discogs.com/release/' in l and ' -- ' in l:
            #release_number = int(l.rsplit('/', 1)[1])
            release_number = int(l.rsplit('/', 1)[1].split()[0])
            max_release_number = max(max_release_number, release_number)
            unique_releases.add(release_number)
        else:
            print(l)
    cleanupfile.close()

    # count the number of releases, with a smell
    statistics = collections.Counter()
    statistics.update(map(lambda x: x//1000000, unique_releases))

    last_index = max_release_number//1000000

    bardata = (sorted(statistics.items()))
    barwidth = 20

    # sometimes some dummy data need to be inserted to
    # ensure that empty bars are generated if needed
    if len(bardata) != last_index:
        for i in range(0, last_index):
            if bardata[i][0] != i:
                for d in range(0, bardata[i][0] - i):
                    bardata.append((i, 0))
                    bardata.sort()

    print("Unique releases:", len(unique_releases))
    print(bardata)

    maximumvalue = max(map(lambda x: x[1], bardata))
    step = int(math.log(maximumvalue, 10))
    valueStep = pow(10, step)

    # calculate a possible good value for startx so labels are not cut off
    startx = max(10 + step * 10, 30)

    # make sure that the chart is large enough
    chartwidth = len(bardata) * barwidth + 10 * len(bardata)
    drawheight = 225
    drawwidth = chartwidth + startx + 20

    # create the drawing that the barchart will be added to
    drawing = Drawing(drawwidth, drawheight)
    barchart = VerticalBarChart()
    barchart.x = startx
    barchart.y = 20
    barchart.height = 200
    barchart.width = chartwidth
    barchart.data = [tuple(map(lambda x: x[1], bardata))]
    barchart.strokeColor = colors.white
    barchart.valueAxis.valueMin = 0
    barchart.valueAxis.labels.fontSize = 16
    barchart.valueAxis.valueMax = maximumvalue
    barchart.valueAxis.valueStep = valueStep
    barchart.categoryAxis.labels.boxAnchor = 'w'
    barchart.categoryAxis.labels.dx = 0
    barchart.categoryAxis.labels.dy = -10
    #barchart.categoryAxis.labels.angle = -90
    barchart.categoryAxis.labels.fontSize = 16
    barchart.categoryAxis.categoryNames = list(map(lambda x: str(x[0]), bardata))
    barchart.barWidth = barwidth

    drawing.add(barchart)
    renderPM.drawToFile(drawing, args.outputfile, fmt='PNG')
Пример #9
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)
Пример #10
0
def genChart(width, height):

    chart = VerticalBarChart()
    chart.data = [(12, 11, 9, 6, 2, 22, 7)]

    # Vertical axis - Y axis
    chart.valueAxis.valueMin = 0
    chart.valueAxis.valueMax = 25
    chart.valueAxis.visible = 0  # hide

    # Horizontal axis - X axis
    chart.categoryAxis.categoryNames = [
        'Asia', 'Africa', 'North America', 'South America', 'Antarctica',
        'Europe', 'Australia'
    ]
    # We could hide X axis like we did with Y axis:
    #   example: chart.categoryAxis.visible = 0
    # Hidding the X axis will hide all the elements of X axis
    # and we want to see the labels!
    #   example: chart.categoryAxis.labels.visible = 1 # by default they are visible
    # So we just hide what we don't want to see!
    chart.categoryAxis.visibleAxis = 0  # hide line
    chart.categoryAxis.visibleTicks = 0  # hide line ticks
    chart.categoryAxis.labels.angle = 90  # rotate labels
    chart.categoryAxis.labels.dx = -30  # adjust labels position at x
    chart.categoryAxis.labels.dy = 30  # adjust labels position at y

    # Numbers above each bar
    chart.barLabelFormat = '%s'  # contains the provived string
    chart.barLabels.nudge = 15  # space between the bar and the text
    chart.barLabels.angle = -20  # rotate the text
    chart.barLabels.fontName = 'barText'  # registered font at report.py line 91
    chart.barLabels.fontSize = 20
    chart.barLabels.fillColor = colors.red

    chart.barWidth = 5
    chart.barSpacing = 8  # space between each bar
    # NOTE: bar list doesn't work like we could expect,
    # the first element apparently sets the configuration for all!
    chart.bars[0].fillColor = colors.toColor('hsl(240, 100%, 20%)')
    chart.bars[0].strokeColor = colors.white

    chart.x = width * 5 / 100  # starts at 5% of width space
    chart.y = height * 5 / 100  # starts at 5% of height space
    chart.width = width * 90 / 100  # uses 90% of width
    chart.height = height * 80 / 100  # uses 80% of height

    titleShadow = String(
        19,
        height * 60 / 100 - 1,  # x and y start point
        'Average JC attacks by continent',
        fontSize=20,
        fontName='chartTitle',  # registered font at report.py line 94
        fillColor=colors.red)

    title = String(
        20,
        height * 60 / 100,  # x and y start point
        'Average JC attacks by continent',
        fontSize=20,
        fontName='chartTitle',  # registered font at report.py line 94
        fillColor=colors.orange)

    bounds = title.getBounds()  # returns a tuple with (x1,y1,x2,y2)

    rectangle = Rect(
        bounds[0] - 3,
        bounds[1],  # x1 and y1
        bounds[2] - bounds[0] + 3,
        20  # x2 and y2
    )
    rectangle.fillColor = colors.black

    drawing = Drawing()
    drawing.add(rectangle)
    drawing.add(titleShadow)
    drawing.add(title)
    drawing.add(chart)

    # Bars bottom 'labels'
    # For a better understand of this coordinates please
    # see code guide
    charWidth = utils.getStringWidth('A')
    dataLen = len(chart.data[0])  # 7 elements

    startPoint = chart.getBounds()[0]
    barAndLabelWidth = chart.width / dataLen  # total width / 7 elements
    center = barAndLabelWidth / 2 - charWidth / 2

    yPos = chart.y - 10

    # Example:
    # drawing.add(String(startPoint + barAndLabelWidth * 0 + center, chart.y - 10, 'A'))
    # drawing.add(String(startPoint + barAndLabelWidth * 1 + center, chart.y - 10, 'B'))
    # ...
    # drawing.add(String(startPoint + barAndLabelWidth * 6 + center, chart.y - 10, 'G'))
    for index, char in enumerate('ABCDEFG', start=0):
        xPos = startPoint + barAndLabelWidth * index + center

        drawing.add(String(xPos, yPos, char))

    return drawing
Пример #11
0
    def print_sensor_data(self, report_instance):
        buffer = self.buffer
        doc = SimpleDocTemplate(buffer,
                                rightMargin=50,
                                leftMargin=50,
                                topMargin=20,
                                bottomMargin=50,
                                pagesize=self.pagesize)

        # A large collection of style sheets pre-made for us
        styles = getSampleStyleSheet()
        styles.add(ParagraphStyle(name='centered', alignment=TA_CENTER))

        style_Normal = styles["Normal"]
        style_Normal.textColor = colors.black

        style_Alerta = styles["Normal"]
        style_Alerta.textColor = colors.black

        style_Title = styles["Heading1"]
        style_Title.alignment = TA_LEFT

        style_Title_Center = styles["Heading1"]
        style_Title_Center.alignment = TA_CENTER

        # Our container for 'Flowable' objects
        elements = []

        # Saltos de linea
        saltosDeLineax1 = Paragraph("<br/>", style_Title)
        saltosDeLineax2 = Paragraph("<br/><br/>", style_Title)
        saltosDeLineax3 = Paragraph("<br/><br/><br/>", style_Title)

        # ps = ParagraphStyle('title', fontSize=20, leading=24)
        #  p1 = "here is some paragraph to see in large font"
        # Paragraph(p1, ps),

        # Tabla con reporte de incidencias y LOGOS.
        titulo_data = []
        titulo_table = []
        logo_cliente = Paragraph(
            '' + report_instance.sensor.arduino.project.enterprise.name,
            style_Normal)
        titulo_ciente = Paragraph(
            'Reporte de incidencias<br/>Sensor ' +
            report_instance.sensor.description, style_Title_Center)

        img_sensait = Image("arduino/static/sensait/logos/Sensait_logo.png")
        img_sensait.drawHeight = 8 * mm
        img_sensait.drawWidth = 20 * mm

        titulo_data.append((logo_cliente, titulo_ciente, img_sensait))

        titulo_table = Table(titulo_data,
                             colWidths=(50 * mm, 100 * mm, 50 * mm))
        titulo_table.setStyle(
            TableStyle([('INNERGRID', (0, 0), (-1, -1), 0.25, colors.white),
                        ('BOX', (0, 0), (-1, -1), 0.25, colors.white)]))
        elements.append(titulo_table)

        elements.append(saltosDeLineax2)

        resumen_data = []
        resumen_table = []

        resumen_laboratorio = Paragraph(
            '<b>Laboratorio:</b><br/>' +
            report_instance.sensor.arduino.project.name, style_Normal)
        resumen_equipo = Paragraph(
            '<b>Equipo:</b><br/>' + report_instance.sensor.arduino.name,
            style_Normal)
        resumen_serie = Paragraph(
            '<b>Modelo:</b><br/>' +
            report_instance.sensor.arduino.modelo_transmisor, style_Normal)

        resumen_data.append(
            (resumen_laboratorio, resumen_equipo, resumen_serie))

        resumen_periodo = Paragraph(
            '<b>Periodo:</b><br/>' + datetime.fromtimestamp(
                report_instance.fecha_inicial).strftime('%d/%m/%Y %H:%M:%S') +
            " al <br/>" + datetime.fromtimestamp(
                report_instance.fecha_final).strftime('%d/%m/%Y %H:%M:%S'),
            style_Normal)

        # Cantidad de Dias del reporte seleccionado.
        difEpochDias = (report_instance.fecha_final -
                        report_instance.fecha_inicial) / 86400
        periodoReporte = "Dia"

        if difEpochDias == 30:
            periodoReporte = "Mensual"
        elif difEpochDias == 15 or difEpochDias == 14:
            periodoReporte = "Quincenal"
        elif difEpochDias == 7 or difEpochDias == 6:
            periodoReporte = "Semanal"
        elif difEpochDias != 1:
            periodoReporte = str(difEpochDias) + " dias"
        else:
            periodoReporte = str(difEpochDias) + " Dia"

        resumen_rangodias = Paragraph(
            '<b>Periodo Generado:</b><br/>' + str(periodoReporte),
            style_Normal)
        resumen_void = Paragraph(" ", style_Normal)

        resumen_data.append((resumen_periodo, resumen_rangodias, resumen_void))

        # resumen_proyecto = Paragraph('<b>Proyecto:</b><br/>' + report_instance.sensor.arduino.project.name, style_Normal)
        # resumen_transmisor = Paragraph('<b>Transmisor:</b><br/>' + report_instance.sensor.arduino.name, style_Normal)
        # resumen_void = Paragraph(" ", style_Normal)

        # resumen_data.append((resumen_proyecto, resumen_transmisor, resumen_void))

        resumen_sensor = Paragraph(
            '<b>Sensor:</b><br/>' + report_instance.sensor.description,
            style_Normal)
        resumen_valmin = Paragraph(
            '<b>Valor Minimo:</b><br/>' +
            "%.2f" % report_instance.sensor.min_value, style_Normal)
        resumen_valmax = Paragraph(
            '<b>Valor Maximo:</b><br/>' +
            "%.2f" % report_instance.sensor.max_value, style_Normal)

        resumen_data.append((resumen_sensor, resumen_valmin, resumen_valmax))

        # VALORES MINIMOS Y MAXIMOS CALCULO.
        min_value = report_instance.sensor.min_value
        max_value = report_instance.sensor.max_value

        totalAlertas = 0
        promedioRegistros = 0.0
        totalRegistros = 0

        valmax = 0
        valmin = 0

        # Tabla de ejemplo
        main_table = []
        dataTable_L = []
        dataTable_R = []
        table_data = []

        all_alerts = []
        alert_list = []

        dataTable_L.append(
            ("Fecha y Hora", "Lectura", "Estado", "Numero incidencia"))
        sensorStatus = "Correcto"

        for num, data in enumerate(report_instance.sensor_data(), start=0):
            if str(data.data) != str("-127.00"):
                totalRegistros = num
                promedioRegistros += float(data.data)
                if num == 0:
                    valmin = float(data.data)
                if float(data.data) > float(max_value) or float(
                        min_value) > float(data.data):
                    sensorStatus = "Fuera de Rango"
                    alert_list.append(data)
                    totalAlertas += 1
                else:
                    sensorStatus = "Correcto"
                    if len(alert_list) > 0:
                        # print "New List " + str(len(all_alerts))
                        all_alerts.append(list(alert_list))
                        alert_list = []

                if float(data.data) > float(valmax):
                    valmax = float(data.data)
                if float(valmin) > float(data.data):
                    valmin = float(data.data)

                if len(alert_list) > 0:
                    alerta_code = "Alerta # " + str(len(all_alerts))
                else:
                    alerta_code = " "

                dataTable_L.append((datetime.fromtimestamp(
                    data.epoch).strftime('%d/%m/%Y %H:%M:%S'), data.data,
                                    sensorStatus, alerta_code))

        table_L = Table(dataTable_L, colWidths=[(doc.width) / 4.0] * 4)
        table_L.setStyle(
            TableStyle([('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
                        ('BOX', (0, 0), (-1, -1), 0.25, colors.black)]))

        print promedioRegistros
        print totalRegistros
        if float(promedioRegistros) == 0 and float(promedioRegistros) == 0:
            val_promedio = 0
        else:
            val_promedio = float(promedioRegistros) / float(totalRegistros)

        resumen_promedio = Paragraph(
            '<b>Temperatura Promedio:</b><br/>' + "%.2f" % val_promedio,
            style_Normal)
        resumen_minima = Paragraph(
            '<b>Temperatura Minimo Registrada:</b><br/>' + "%.2f" % valmin,
            style_Normal)
        resumen_maxima = Paragraph(
            '<b>Temperatura Maxima Registrada:</b><br/>' + "%.2f" % valmax,
            style_Normal)

        resumen_data.append((resumen_promedio, resumen_minima, resumen_maxima))

        resumen_totalregistros = Paragraph(
            '<b>Total de Registros:</b><br/>' + "%.2f" % totalRegistros,
            style_Normal)
        resumen_totalfuera = Paragraph(
            '<b>Resumen Registros:</b><br/>' + "X %.2f" % totalAlertas +
            "<br/> + %.2f" % (totalRegistros - totalAlertas), style_Normal)
        resumen_alertasregistradas = Paragraph(
            '<b>Total alertas registradas:</b><br/>' + str(len(all_alerts)),
            style_Normal)
        resumen_void = Paragraph(" ", style_Normal)

        resumen_data.append((resumen_totalregistros, resumen_totalfuera,
                             resumen_alertasregistradas))

        resumen_table = Table(resumen_data,
                              colWidths=[(doc.width) / 3.0] * 3,
                              rowHeights=(16 * mm))
        resumen_table.setStyle(
            TableStyle([('INNERGRID', (0, 0), (-1, -1), 0.25, colors.white),
                        ('BOX', (0, 0), (-1, -1), 0.25, colors.white),
                        ('VALIGN', (0, 0), (-1, -1), 'TOP')]))
        elements.append(resumen_table)

        # Informacion del reporte digamos LEGAL.
        # elements.append(Paragraph('La informacion que se despliega a continuacion son propiedad de la empresa que contrata el servicio de SENSAIT. La informacion que se despliega a continuacion son propiedad de la empresa que contrata el servicio de SENSAIT. ', styles['Normal']))

        elements.append(saltosDeLineax3)

        valores_Correctos = int(totalRegistros - totalAlertas)
        drawing = Drawing(400, 200)
        data = [(valores_Correctos, int(totalAlertas))]
        bc = VerticalBarChart()
        bc.x = 50
        bc.y = 50
        bc.height = 200
        bc.width = 400
        bc.data = data
        bc.barSpacing = 2.5
        bc.barWidth = 5
        bc.strokeColor = colors.black
        bc.valueAxis.valueMin = 0
        bc.valueAxis.valueMax = int(totalRegistros)
        bc.valueAxis.valueStep = 50
        bc.categoryAxis.labels.boxAnchor = 'ne'
        bc.categoryAxis.labels.dx = 8
        bc.categoryAxis.labels.dy = -2
        # bc.categoryAxis.labels.angle = 30
        bc.categoryAxis.categoryNames = [
            'Correctos = ' + str(valores_Correctos),
            'Fuera de Rango = ' + str(totalAlertas)
        ]
        bc.bars[(0, 0)].fillColor = colors.green
        bc.bars[(0, 1)].fillColor = colors.red
        drawing.add(bc)
        elements.append(drawing)

        elements.append(
            Paragraph(
                'Responsable ' +
                report_instance.sensor.arduino.project.nombre_encargado,
                style_Title))

        elements.append(PageBreak())

        # table_R = Table(dataTable_R, colWidths=[(doc.width) / 3.0] * 3)
        # table_R.setStyle(TableStyle([('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black), ('BOX', (0, 0), (-1, -1), 0.25, colors.black)]))

        # dataTable_Main = [table_L]  table_R
        # table_Main = Table(table_L, colWidths=[doc.width])
        # table_Main.setStyle(TableStyle([('INNERGRID', (0, 0), (-1, -1), 0.25, colors.red), ('BOX', (0, 0), (-1, -1), 0.25, colors.red)]))

        # Tabla con todos los registros...
        elements.append(
            Paragraph(
                str(len(all_alerts)) + ' ALERTAS REGISTRADAS',
                style_Title_Center))

        # Tablas POR ALERTA...
        alert_data_tables = []
        alerts_tables = []
        alert_content = []

        alerts_onedata_data = []
        alerts_onedata_table = []
        # print "all_alerts.len()"
        # print len(all_alerts)

        alerts_onedata_data.append(
            ("Fecha Alerta", "# Registros en alerta ", "Valor"))
        alert_max_value = float(report_instance.sensor.max_value)
        alert_min_value = float(report_instance.sensor.min_value)

        for num, alertlist in enumerate(all_alerts, start=0):
            print str(len(alertlist))
            # Esto genera la tabla para un rango de registros NO LO QUITARE jeje
            if len(alertlist) > 200:
                one_fecha = str(
                    datetime.fromtimestamp(
                        alertlist[len(alertlist) -
                                  1].epoch).strftime('%d/%m/%Y %H:%M:%S'))
                one_registros = len(alertlist)
                one_value = str(alertlist[len(alertlist) - 1].data)
                alerts_onedata_data.append(
                    (one_fecha, one_registros, one_value))
                # alerts_onedata_data.append( alertlist[num] , drawing))
            else:
                titulo = Paragraph('<b>Alerta # ' + str(num) + ' </b>',
                                   style_Normal)

                alert_data_tables = []
                alert_content = []
                alert_graph = []
                alert_limit = []
                alert_graph_dates = []

                alerta_primer_registro = Paragraph(
                    '<b>Fecha inicio alerta:</b><br/>' + str(
                        datetime.fromtimestamp(alertlist[0].epoch).strftime(
                            '%d/%m/%Y %H:%M:%S') + "<br/><br/>"), style_Normal)
                alerta_ultima_registro = Paragraph(
                    '<b>Fecha final alerta:</b><br/>' + str(
                        datetime.fromtimestamp(alertlist[len(alertlist) -
                                                         1].epoch).
                        strftime('%d/%m/%Y %H:%M:%S') + "<br/><br/>"),
                    style_Normal)
                tiempoAlerta = alertlist[0].epoch - alertlist[len(alertlist) -
                                                              1].epoch

                print "difEpoch: " + str(alertlist[len(alertlist) - 1].epoch)
                print "difEpochR: " + str(tiempoAlerta)
                print "difEpoch: " + str(alertlist[0].epoch)

                alerta_duracion = Paragraph(
                    '<b>Duracion alerta:</b><br/>' + str(
                        datetime.fromtimestamp(tiempoAlerta).strftime('%M:%S')
                        + "<br/><br/>"), style_Normal)
                alerta_total_registros = Paragraph(
                    '<b>Registros fuera de rango:</b><br/>' +
                    str(len(alertlist)) + "<br/><br/>", style_Normal)
                rango_maximo = Paragraph(
                    '<b>Valor Maximo:</b><br/>' +
                    "%.2f" % report_instance.sensor.max_value + "<br/><br/>",
                    style_Normal)
                rango_minimo = Paragraph(
                    '<b>Valor Maximo:</b><br/>' +
                    "%.2f" % report_instance.sensor.min_value + "<br/><br/>",
                    style_Normal)
                alerta_comentarios = Paragraph(
                    "<b>Comentarios:</b><br/>__________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________<br/>",
                    style_Normal)
                alerta_accioncorrectiva = Paragraph(
                    "<b>Accion correctiva:</b><br/>__________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________<br/>",
                    style_Normal)

                alerta_data = []
                alerta_table = []

                alerta_data.append((titulo, " "))
                alerta_data.append(
                    (alerta_primer_registro, alerta_ultima_registro))
                alerta_data.append((alerta_duracion, alerta_total_registros))
                alerta_data.append((rango_maximo, rango_minimo))
                alerta_data.append((" ", saltosDeLineax2))
                # alerta_data.append((alerta_comentarios))

                alerta_table = Table(alerta_data, colWidths=(50 * mm, 50 * mm))
                alerta_table.setStyle(
                    TableStyle([
                        ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.white),
                        ('BOX', (0, 0), (-1, -1), 0.25, colors.white)
                    ]))

                # alert_content.append(alerta_primer_registro)
                # alert_content.append(alerta_ultima_registro)
                # alert_content.append(alerta_duracion)
                # alert_content.append(alerta_total_registros)
                # alert_content.append(rango_maximo)
                # alert_content.append(rango_minimo)
                # alert_content.append(alerta_comentarios)
                # alert_content.append(saltosDeLineax2)
                valMax = 0
                valMin = 0
                valTmp = 0

                for ids, alert in enumerate(alertlist, start=0):
                    # print alert.data
                    # datos = Paragraph(str(alert.data), style_Normal)
                    valTmp = float(alert.data)
                    # print "tmp: " + str(valTmp)
                    # print "max: " + str(valMax)
                    # print "min: " + str(valMin)
                    if float(valTmp >= 0):
                        if float(valTmp) > float(valMax):
                            valMax = valTmp
                            if valMin == 0:
                                valMin = float(valTmp)

                        if float(valMin) > float(valTmp):
                            valMin = float(valTmp)

                    else:
                        if float(valTmp) < float(valMax):
                            valMax = valTmp
                            if valMin == 0:
                                valMin = float(valTmp)

                        if float(valTmp) > float(valMin):
                            valMin = float(valTmp)

                    valueData = float(alert.data)

                    alert_graph.append(valueData)
                    alert_limit.append(alert_max_value)
                    alert_graph_dates.append(
                        str(
                            datetime.fromtimestamp(
                                alert.epoch).strftime('%H:%M:%S')))
                # END FOR
                print "tmp: " + str(valTmp)
                print "max: " + str(valMax)
                print "min: " + str(valMin)

                # CALCULAR BIEN LOS LIMITES DE LA GRAFICA
                if float(valMin) >= 0:
                    lim_min = float(valMin - 1)

                elif float(valMax) >= 0:
                    lim_max = float(valMax + 2)

                elif float(valMax) < 0:
                    lim_max = float(valMax - 2)

                elif float(valMin) < 0:
                    lim_min = float(valMin - 1)
                # END CALCULAR LIMITES

                lim_min = valMin
                lim_max = valMax

                print "lim_min: " + str(lim_min)
                print "lim_max: " + str(lim_max)

                drawing = Drawing(200, 220)
                data = [alert_graph, alert_limit]
                lc = HorizontalLineChart()
                lc.x = 10
                lc.y = 30
                lc.height = 150
                lc.width = 220
                lc.data = data
                # lc.strokeColor = colors.black
                catNames = alert_graph_dates
                lc.categoryAxis.categoryNames = catNames
                lc.categoryAxis.labels.dx = 0
                lc.categoryAxis.labels.dy = -15
                lc.categoryAxis.labels.angle = 75
                lc.categoryAxis.labels.boxAnchor = 'n'
                lc.joinedLines = 1
                lc.lines[0].symbol = makeMarker('FilledCircle')
                # lc.lineLabelFormat = '%2.0f'
                # lc.strokeColor = colors.black
                lc.valueAxis.valueMin = lim_min
                lc.valueAxis.valueMax = lim_max
                lc.valueAxis.valueStep = 1
                lc.lines[0].strokeWidth = 2
                # lc.lines[1].strokeWidth = 1.5
                drawing.add(lc)

                # print "endFor"

                alert_data_tables.append((drawing, alerta_table))
                alert_data_tables.append(
                    (alerta_comentarios, alerta_accioncorrectiva))

                alerts_tables = Table(alert_data_tables,
                                      colWidths=[(doc.width) / 2.0] * 2)
                alerts_tables.setStyle(
                    TableStyle([
                        ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.white),
                        ('BOX', (0, 0), (-1, -1), 0.25, colors.white)
                    ]))
                elements.append(alerts_tables)

                # elements.append(PageBreak())

        if len(alerts_onedata_data) > 1:

            elements.append(
                Paragraph('ALERTAS CON 5 REGISTROS O MENOS',
                          style_Title_Center))
            elements.append(saltosDeLineax1)
            alerts_onedata_table = Table(alerts_onedata_data,
                                         colWidths=[(doc.width) / 3.0] * 3)
            alerts_onedata_table.setStyle(
                TableStyle([('INNERGRID', (0, 0), (-1, -1), 0.25,
                             colors.black),
                            ('BOX', (0, 0), (-1, -1), 0.25, colors.black)]))
            elements.append(alerts_onedata_table)
            # elements.append(PageBreak())

        elements.append(PageBreak())
        elements.append(Paragraph('DETALLE DE REGISTROS', style_Title_Center))
        elements.append(table_L)
        # elements.append(table_R)

        # Se agrega el llamado del header y footer
        doc.build(elements,
                  onFirstPage=self._header_footer,
                  onLaterPages=self._header_footer,
                  canvasmaker=NumberedCanvas)
    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)
Пример #13
0
def MakeHistogram(filename):  #, data):
    '''
	c = canvas.Canvas(filename, pagesize=A2)   # A2 = C size = 17x22 inches
	width, height = A2
	c.rect(36, 36, width-72, height-72, stroke=1, fill=0)   # x, y, width, height, stroke, fill
	'''
    '''
	#framePage(c, 'Color Demo - RGB Space - page %d' % c.getPageNumber())
	miny = 10000000
	maxy = 0
	
	for bin in bins:
		print bin
		if bin > maxy:
			maxy = bin
		if bin < min:
			miny = bin
	#

	minx = 0
	maxx = len(data)
	'''
    '''
	x = 10
	for bin in data:
		c.setFillColor(colors.red)
		c.rect(x, 100, 10, bin, stroke=1, fill=1)   # x, y, width, height, stroke, fill
		x += 20
		
		#all_colors = reportlab.lib.colors.getAllNamedColors().items()
		#all_colors.sort() # alpha order by name
		#c.setFont('Times-Roman', 12)
		#c.drawString(72,730, 'This shows all the named colors in the HTML standard.')
		#y = 700
		#for (name, color) in all_colors:
			#c.setFillColor(colors.black)
			#c.drawString(100, y, name)
			#c.setFillColor(color)
			#c.rect(200, y-10, 300, 30, fill=1)
			#y = y - 40
			#if y < 100:
				#c.showPage()
				#framePage(c, 'Color Demo - RGB Space - page %d' % c.getPageNumber())
				#y = 700
	#
	c.showPage()
	c.save()
	'''

    #------------------------------
    from reportlab.graphics.shapes import Drawing
    from reportlab.graphics.charts.barcharts import VerticalBarChart
    drawing = Drawing(1600, 1200)
    data = \
    [
     (99, 99, 97, 95, 87, 93),
     (56, 48, 59, 50, 56, 52),
     (50, 50, 50, 50, 50, 50)
    ]
    bc = VerticalBarChart()
    bc.x = 250  # Position
    bc.y = 250
    bc.height = 700  # Size
    bc.width = 1000
    #bc.data = [data]    # Expects a list of tuples; one tuple for each series
    bc.data = data  # Expects a list of tuples; one tuple for each series
    bc.strokeColor = colors.black
    bc.valueAxis.valueMin = 0
    #top = (maxy + 100) / 100
    #top = top * 100
    #bc.valueAxis.valueMax = top
    #bc.valueAxis.valueStep = 100
    bc.groupSpacing = 100
    bc.barSpacing = 0
    bc.barWidth = 50
    bc.categoryAxis.labels.boxAnchor = 'ne'
    bc.categoryAxis.labels.dx = 8
    bc.categoryAxis.labels.dy = -2
    bc.categoryAxis.labels.angle = 0
    bc.categoryAxis.labels._value.fontSize = 20
    bc.categoryAxis.categoryNames = [
        'Composite', 'Vocabulary', 'Reading', 'Language', 'Mathematics',
        'Sources'
    ]
    drawing.add(bc)

    from reportlab.graphics import renderPDF
    renderPDF.drawToFile(drawing, filename, 'Test')
    '''