Ejemplo n.º 1
0
    def story(self):
        story = list()
        # iterate over qobjects
        keeptogether_list = []
        for qobject in self.obj.qobjects:
            new, keeptogether = qobject.report.story()
            new = list(new)

            if len(new) == 0:
                continue

            if keeptogether:
                keeptogether_list.extend(new)
            else:
                if len(keeptogether_list):
                    add = new.pop(0)
                    if isinstance(add, platypus.KeepTogether):
                        keeptogether_list.extend(add._content)
                    else:
                        keeptogether_list.append(add)

                    story.append(platypus.KeepTogether(keeptogether_list))
                    keeptogether_list = []

                story.extend(new)

        story.extend(keeptogether_list)
        return story
Ejemplo n.º 2
0
def header(txt, style=HeaderStyleList[0], klass=platypus.Paragraph, sep=0.3):
    """Low-level interface func to ReportLab headers."""
    s = platypus.Spacer(0.2 * inch, sep * inch)
    para = klass(txt, style)
    sect = [s, para]
    result = platypus.KeepTogether(sect)
    return result
Ejemplo n.º 3
0
    def story(self):
        story, tmp = Question.story(self)
        if self.obj.calculate.range_count:
            story.append(answers.Range(
                self.obj.calculate.range_min,
                self.obj.calculate.range_max,
                self.obj.calculate.range_values,
                self.obj.answers,
                self.obj.calculate.mean,
                self.obj.calculate.standard_deviation,
                self.obj.calculate.count,
                self.obj.calculate.significant))

        if self.obj.calculate.count > 0 and self.obj.calculate.values:
            for box in self.obj.boxes:
                if box.value in self.obj.calculate.values:
                    story.append(
                        answers.Choice(
                            box.text,
                            self.obj.calculate.values[box.value],
                            False
                        )
                    )

        story = [platypus.KeepTogether(story)]
        return story, False
Ejemplo n.º 4
0
 def story(self):
     story, tmp = Question.story(self)
     if len(self.text) > 0:
         story.append(self.text[0])
         story = [platypus.KeepTogether(story)]
     if len(self.text) > 1:
         story.extend(self.text[1:])
     return story, False
Ejemplo n.º 5
0
 def story(self):
     story, tmp = Question.story(self)
     if self.obj.calculate.count:
         for i in range(len(self.obj.calculate.values)):
             story.append(
                 answers.Choice(self.obj.answers[i],
                                self.obj.calculate.values[i],
                                self.obj.calculate.significant[i]))
         story = [platypus.KeepTogether(story)]
     return story, False
Ejemplo n.º 6
0
 def story(self):
     story, tmp = Question.story(self)
     if self.obj.calculate.count:
         story.append(
             answers.Mark(self.obj.calculate.values.values(),
                          self.obj.answers, self.obj.calculate.mean,
                          self.obj.calculate.standard_deviation,
                          self.obj.calculate.count,
                          self.obj.calculate.significant))
         story = [platypus.KeepTogether(story)]
     return story, False
Ejemplo n.º 7
0
 def story(self):
     story, tmp = Question.story(self)
     if self.obj.calculate.count:
         for box in self.obj.boxes:
             story.append(
                 answers.Choice(box.text,
                                self.obj.calculate.values[box.value],
                                self.obj.calculate.significant[box.value]))
         story = [platypus.KeepTogether(story)]
         if len(self.text) > 0:
             story.append(platypus.Spacer(0, 3 * mm))
             story.extend(self.text)
     return story, False
Ejemplo n.º 8
0
 def write_ingfoot(self):
     # Ugly -- we know that heads comprise two elements -- a
     # condbreak and a head...
     ings = self.txt[2:]
     if len(ings) > 4:
         half = (len(ings) / 2)
         first_half = ings[:-half]
         second_half = ings[-half:]
         t = platypus.Table([[first_half, second_half]])
         t.hAlign = 'LEFT'
         t.setStyle(
             platypus.TableStyle([
                 ('VALIGN', (0, 0), (1, 0), 'TOP'),
             ]))
         self.txt = self.txt[:2] + [t]
     self.txt = self.save_txt + [platypus.KeepTogether(self.txt)]
Ejemplo n.º 9
0
 def getPreEl(self, txt):
     s = platypus.Spacer(0.1 * inch, 0.1 * inch)
     p = platypus.Preformatted(txt, PreStyle)
     precomps = [s, p]
     result = platypus.KeepTogether(precomps)
     return result
Ejemplo n.º 10
0
def create_posts(url):
    browser.get(url)

    inp = input("Is the loading complete?")

    src = browser.page_source
    soup = BeautifulSoup(src, 'html.parser')
    y = soup.findAll("mark")

    cl1 = y[0].get("class")
    cl2 = y[-1].get("class")

    dont_look = ""

    if cl1 != cl2:
        dont_look = cl1

    header = soup.select('h1')[0].text
    header = '<link href="' + url + '">' + header + '</link>'

    items = []
    mainHeadline = platypus.Paragraph(header, mainHeadlineStyle)
    items.append(mainHeadline)
    posts.append(mainHeadline)
    for m in y:
        if (m.get("class") == dont_look):
            continue

        body = m.text
        parent = m.parent
        if parent.name == 'h1':
            item = platypus.KeepTogether(items)
            items = []
            headline = platypus.Paragraph(parent.text, headlineStyle)
            posts.append(headline)
            items.append(headline)
        else:
            sib = parent.previous_sibling
            t = False
            if not sib:
                t = True
            else:

                while sib.name != 'h1':

                    if not sib.previous_sibling:
                        sib = sib.parent
                    else:
                        sib = sib.previous_sibling

                    if not sib:
                        t = True
                        break

            if (t):
                para = platypus.Paragraph(body, paraStyle)
                posts.append(para)
            else:
                if (sib.text == items[0].text):
                    para = platypus.Paragraph(body, paraStyle)
                    items.append(para)
                    posts.append(para)
                else:
                    item = platypus.KeepTogether(items)
                    items = []
                    headline = platypus.Paragraph(sib.text, headlineStyle)
                    items.append(headline)
                    posts.append(headline)
                    para = platypus.Paragraph(body, paraStyle)
                    items.append(para)
                    posts.append(para)
def create_report(inbam1, invcf1, inbam2, invcf2, infasta, snpMatrix,
	quantityWantSites, rows, output):
	# Attempt to auto-detect sample names (experimental)
	S1Name = (get_prefix(inbam1, invcf1)).rstrip('.fastq-reference')
	S2Name = (get_prefix(inbam2, invcf2)).rstrip('.fastq-reference')

	pairwiseSNPs = get_pairwiseSNPlist(snpMatrix, S1Name, S2Name)
	pairwiseSNPpositions = pairwiseSNPs.keys()

	if quantityWantSites > len(pairwiseSNPpositions):
		print 'Selecting all {} putative SNP sites to print...'.format(len(pairwiseSNPpositions))
		quantityWantSites = len(pairwiseSNPpositions)
	randSitesUnsorted = random.sample(pairwiseSNPpositions, quantityWantSites)  #randomly selected sites to investigate
	randSitesUnsortedInts = [int(i) for i in randSitesUnsorted]  #convert strings to integers
	listWantSitesVCF = sorted(randSitesUnsortedInts, reverse=True)  #for pileup report building
	randSites = sorted(randSitesUnsortedInts)

	vcfData1, vcfData2 = get_vcf_data(randSites, invcf1, invcf2)

	if len(vcfData1) != len(vcfData2):
		print 'ERROR: unequal number of SNPs identified between {} and {}'.format(S1Name, S2Name)
		sys.exit('ERROR in VCF parsing')
	numSites = len(vcfData1)

	# Calculate page and frames
	doc = Platypus.BaseDocTemplate(output, topMargin=0, bottomMargin=0, leftMargin=10, rightMargin=0)
	doc.pagesize = landscape(A4) #ISO Code A4
	# A4 Dimensions: 297 mm x 210 mm ; 11.69 in x 8.27 in ; 842 pt x 595 pt

	frameCount = 2  #(numsites + (-numsites%6)) // 6
	frameWidth = doc.height / frameCount
	frameHeight = doc.width - .05 * inch
	frames = []

	# Construct a frame for each column
	for frame in range(frameCount):
		leftMargin = doc.leftMargin + frame * frameWidth
		column = Platypus.Frame(leftMargin, doc.bottomMargin, frameWidth, frameHeight)
		frames.append(column)
	template = Platypus.PageTemplate(frames=frames)
	doc.addPageTemplates(template)

	PAGE_HEIGHT = defaultPageSize[0] #size in points
	PAGE_WIDTH  = defaultPageSize[1]
	styles = getSampleStyleSheet()
	style  = styles['Normal']
	style.fontName = 'Courier'
	style.fontSize = 6.5

	Title = ('Report containing {} of {} putative SNPs for {} and {}'.format(
		str(quantityWantSites), str(len(pairwiseSNPpositions)),
		os.path.basename(invcf1), os.path.basename(invcf2)))
	report = [Paragraph(Title, styles['Heading2'])]

	while numSites > 0:
		# handle SNP sites at beginning of Chrom (<50 bases in)
		posMinusFitty = (listWantSitesVCF[numSites - 1] - 50)
		centeredPos = str(max(posMinusFitty, 0))

		pos = str(vcfData1[numSites-1][0])
		gap = Platypus.Spacer(0.25, 0.05*inch)

		# vcfData lists are ordered: [pos, chrom, qual, DP, MQ, alt]
		for sample in [[vcfData1, inbam1, S1Name], [vcfData2, inbam2, S2Name]]:
			pileup = Platypus.Preformatted(get_ttview(sample[1], infasta,
								(sample[0][1][1]), centeredPos, rows), style)

			qual = sample[0][numSites-1][2]
			DP   = sample[0][numSites-1][3]
			MQ   = sample[0][numSites-1][4]
			SNP  = str(sample[0][numSites-1][5])
			
			header = Paragraph('{} at position {} for {} with a QUAL of {}, MQ of {}, and raw read depth (DP) of {}'.format(
				SNP, pos, sample[2], qual, MQ, DP), styles['Heading6'])
			report.append(Platypus.KeepTogether([gap, header, pileup]))

		numSites -= 1

	doc.build(report)
def main():
    args = parseArgs()
    inbam = args.bam
    infasta = args.fasta
    invcf = args.vcf
    numsites = args.numsites
    output = args.output
    rows = args.rows

    SNPs, INDELs = get_vcf(invcf)
    vcfSNPs = len(SNPs)
    print 'Identified %s putative SNPs' % vcfSNPs
    #print 'Identified %s putative INDEL bases' % len(INDELs)

    # enable explicitly given positions (e.g., -p '89,3969181,44,123456') to investigate
    if args.positions:
        posList = [int(n) for n in args.positions.split(',')]
        listWantSitesVCF = []
        for i in posList:
            if any(i in x for x in SNPs):
                for SNP in SNPs:
                    if SNP[1] == i:
                        listWantSitesVCF.append(SNP)
            else:
                sys.exit('ERROR: specified position %s not a SNP' % i)
        quantityWantSites = len(listWantSitesVCF)
        listWantSitesVCF.reverse()

    # randomly select SNP sites if positions (-p) unspecified
    else:
        quantityWantSites = int(numsites)
        if quantityWantSites > vcfSNPs:
            print 'Number of requested SNP sites to investigate exceeds number of identified SNPs'
            print 'Selecting all %s putative SNP sites to print...' % vcfSNPs
            quantityWantSites = vcfSNPs

        randSitesUnsorted = random.sample(
            SNPs, quantityWantSites)  #randomly selected sites to investigate
        listWantSitesVCF = sorted(randSitesUnsorted,
                                  key=itemgetter(1),
                                  reverse=True)

    #calculate page and frames
    doc = Platypus.BaseDocTemplate(output,
                                   topMargin=0,
                                   bottomMargin=0,
                                   leftMargin=10,
                                   rightMargin=0)
    doc.pagesize = landscape(A4)  #ISO Code A4
    # A4 Dimensions: 297 mm x 210 mm ; 11.69 in x 8.27 in ; 842 pt x 595 pt

    frameCount = 2  #(numsites + (-numsites%6)) // 6
    frameWidth = doc.height / frameCount
    frameHeight = doc.width - .05 * inch
    frames = []

    #construct a frame for each column
    for frame in range(frameCount):
        leftMargin = doc.leftMargin + frame * frameWidth
        column = Platypus.Frame(leftMargin, doc.bottomMargin, frameWidth,
                                frameHeight)
        frames.append(column)
    template = Platypus.PageTemplate(frames=frames)
    doc.addPageTemplates(template)

    PAGE_HEIGHT = defaultPageSize[0]  #size in points
    PAGE_WIDTH = defaultPageSize[1]
    styles = getSampleStyleSheet()
    style = styles['Normal']
    style.fontName = 'Courier'
    style.fontSize = 6.5

    Title = ('Report containing ' + str(quantityWantSites) + ' of ' +
             str(vcfSNPs) + ' putative SNPs for ' + os.path.basename(invcf))
    report = [Paragraph(Title, styles['Heading2'])]

    while quantityWantSites > 0:
        posMinusFitty = (listWantSitesVCF[quantityWantSites - 1][1] - 50)
        centeredPos = max(
            posMinusFitty,
            0)  #handles SNP sites at beginning of chrom (<50 bases in)

        pileup = Platypus.Preformatted(
            get_ttview(inbam, infasta,
                       listWantSitesVCF[quantityWantSites - 1][0], centeredPos,
                       rows), style)
        pos = str(listWantSitesVCF[quantityWantSites - 1][1])
        QUAL = str(listWantSitesVCF[quantityWantSites - 1][2])
        DP = str(listWantSitesVCF[quantityWantSites - 1][3])
        MQ = str(listWantSitesVCF[quantityWantSites - 1][4])
        SNP = str(listWantSitesVCF[quantityWantSites - 1][5])
        header = Paragraph(
            SNP + ' at position ' + pos + ' with a QUAL of ' + QUAL +
            ', MQ of ' + MQ + ', and raw read depth (DP) of ' + DP,
            styles['Heading6'])
        gap = Platypus.Spacer(0.25, 0.05 * inch)
        report.append(Platypus.KeepTogether([gap, header, pileup]))
        quantityWantSites -= 1
    doc.build(report)
Ejemplo n.º 13
0
    def _create(self):
        """
        Does the final creation of the Platypus Image object.
        Including a correct numeration for the Figures list.

        Typically this Method will be called by the _PreBuild-Method of
        the Story class.

        :return: story with all final objects for pdf rendering
        :rtype: list of platypus objects ready for rendering.
        """
        story = []

        # Check if image is stored on disk
        if isinstance(self._image, basestring) and (os.path.isfile(
                self._image)):
            # Create a Platypus Image from the given image path
            img = utils.ImageReader(self._image)
            imgw, imgh = img.getSize()
            aspect = imgh / float(imgw)

            lazy_value = 1
            img_path = self._image
            if self._mem_reduction is True:
                # value 2 means "open the image when required then shut it"
                lazy_value = 2
                # the image is converted to JPEG only if it is a PNG
                if what_image_type(self._image) is "png":
                    base_file_name_without_ext = os.path.splitext(
                        os.path.basename(self._image))[0]
                    full_dir_path = os.path.dirname(self._image)
                    img_path_jpeg = os.path.join(
                        full_dir_path,
                        base_file_name_without_ext + "." + "jpeg")
                    jpeg_image = pil_image.open(self._image)
                    jpeg_image.save(img_path_jpeg, "JPEG")
                    img_path = img_path_jpeg

            img = plat.Image(img_path,
                             width=self._width,
                             height=(self._width * aspect),
                             lazy=lazy_value)
        elif hasattr(self._image, 'wrapOn'):
            img = self._image
        else:
            # unknown image or image with unsupported type
            print(
                "pdf build warning: unknown image type for image with caption: %s"
                % self._name)
            img = plat.Paragraph("unknown image type", NORMAL_STYLE)
            self._halign = None

        # align horizontally TO 'LEFT', 'CENTER' (default) or
        # 'RIGHT' as supported by plat.Flowable
        # use already set value if no change requested
        if self._halign:
            img.hAlign = self._halign

        # Add Image
        flowables = [plat.Spacer(1, 1 * cm), img]

        # Add Title
        if self._name is not None:
            flowables.append(
                plat.Paragraph(
                    "<b>%s %s</b>: %s" %
                    (self.FIGURE_CAPTION, self._build_figure_number_string(),
                     replace_html_chars(self._name)), self.STYLE))
            flowables.append(plat.Spacer(1, 1 * cm))

        # Add everything to story
        story.append(plat.KeepTogether(flowables))

        return story