コード例 #1
0
ファイル: testcreator.py プロジェクト: KsMomOf2/TestCreator
 def generate_header(self,
                     output="Exam",
                     instructor="Vaccaro",
                     section="English",
                     test_name="Final Exam",
                     version=1):
     header = PageStyle("header")
     with header.create(Head("C")):
         header.append(instructor)
         header.append(LineBreak())
     with header.create(Head("L")):
         header.append(section)
         header.append(LineBreak())
         header.append(test_name +
                       str(version) if output != 'key' else test_name)
     with header.create(Head("R")):
         if (output == "exam"):
             header.append("Student: _____________")
         elif (output == "answers"):
             header.append("Answers v" + str(version))
         else:
             header.append("Key")
     with header.create(Foot("R")):
         header.append(simple_page_number())
     return header
コード例 #2
0
ファイル: ba_report.py プロジェクト: abconley/pima
    def add_header(self):

        header_text = 'Analysis of ' + self.analysis.analysis_name

        header = PageStyle('header')
        with header.create(Head('L')):
            header.append(header_text)
            header.append(LineBreak())

        with header.create(Foot('R')):
            header.append(simple_page_number())

        self.doc.preamble.append(header)
        self.doc.change_document_style('header')
コード例 #3
0
ファイル: export.py プロジェクト: reaper47/musicavis
    def _export_pdf(self, fname: str):
        geometry_options = {"margin": "1in"}
        doc = pylatex.Document(geometry_options=geometry_options)
        header = pylatex.PageStyle("header")

        with doc.create(pylatex.MiniPage(align="c")):
            doc.append(
                pylatex.HugeText(pylatex.utils.bold("Practice Sessions")))
            doc.append(pylatex.LineBreak())

        with header.create(pylatex.Foot("L")):
            header.append("@2019 Musicavis")

        with header.create(pylatex.Foot("R")):
            header.append(pylatex.simple_page_number())

        doc.preamble.append(header)
        doc.change_document_style("header")

        for practice in self.practices:
            with doc.create(
                    pylatex.Section(
                        f"{practice.instrument.name.title()} ({practice.date:%a, %B %m %Y})"
                    )):
                self._add_list_itemize_latex(doc, "Goals",
                                             practice.goals.all())

                with doc.create(pylatex.Subsection("Exercises")):
                    with doc.create(pylatex.Itemize()) as itemize:
                        for x in practice.exercises.all():
                            itemize.add_item(
                                f"{x.name} at {x.bpm_start}-{x.bpm_end}bpm for {x.minutes}m"
                            )

                self._add_list_itemize_latex(doc, "Improvements",
                                             practice.improvements.all())
                self._add_list_itemize_latex(doc, "Positives",
                                             practice.positives.all())

            with doc.create(pylatex.Subsection("Notes:")):
                if practice.notes:
                    for note in practice.notes.split("\r\n"):
                        doc.append(note) if note else doc.append(
                            pylatex.NewLine())

        doc.generate_pdf(fname.split(".pdf")[0], clean=True)
コード例 #4
0
    def dumps(self):
        # Clear the old data
        self.clear()
        assessment = self.assessment

        if hasattr(self.assessment, 'course'):
            course = self.assessment.course
        else:
            course = None

        if course:
            # Create left header
            with self.create(Head('L')):
                self.append(course.name)
                self.append(LineBreak())
                self.append(SmallText(course.kind))
                self.append(self.padding)
        # Create center header
        with self.create(Head('C')):
            self.append(NoEscape(r'\ifbool{instructorKey}{'))
            self.append(SmallText(bold('FOR INSTRUCTORS ONLY')))
            self.append(LineBreak())
            self.append(SmallText(bold(f'(Max. of {assessment.maxpoints} points)')))
            self.append(NoEscape(r'}{}'))
            self.append(self.padding)
        # Create right header
        with self.create(Head('R')):
            self.append(f'{assessment.kind} {assessment.number}.{assessment.version} - {assessment.fullpoints} Points')
            self.append(LineBreak())
            self.append(SmallText(f'Assessing Period: {assessment.period}'))
            self.append(self.padding)
        if course:
            # Create left footer
            with self.create(Foot('L')):
                self.append(course.term)
        # Create center footer
        with self.create(Foot('C')):
            now = datetime.now().strftime('%Y%m%d%H%M')
            self.append(FootnoteText(now))
        # Create right footer
        with self.create(Foot('R')):
            self.append(simple_page_number())

        return super().dumps()
コード例 #5
0
 def gera_cabecalho(self, json_ppra):
     header = PageStyle("header")
     # Create left header
     with header.create(Head("L")) as header_left:
         logo_file = os.path.join(os.path.dirname(__file__), 'logo.png')
         header_left.append(
             StandAloneGraphic(image_options="width=3cm",
                               filename=logo_file))
     # Create center header
     with header.create(Head("C")) as header_center:
         header_center.append("PPRA 2018")
         header_center.append(LineBreak())
         header_center.append(json_ppra['nomeEmpresa'])
         header_center.append(LineBreak())
         header_center.append(json_ppra['nomeFilial'])
     # Create right header
     with header.create(Head("R")) as header_right:
         header_right.append(simple_page_number())
         header_right.append(LineBreak())
         header_right.append("Novembro/2018")
     self.preamble.append(header)
コード例 #6
0
    def write_header(self, doc):
        # def write_header(self):

        # Add document header
        header = PageStyle("header")
        # Create left header
        with header.create(Head("L")):
            header.append(
                "Center for Reflected Text Analytics (CRETA)\nUniversity of Stuttgart"
            )
            # header.append(LineBreak())
            # header.append("R3")
        ## Create center header
        # with header.create(Head("C")):
        #    header.append("Company")
        # Create right header
        with header.create(Head("R")):
            header.append(NoEscape(r'\today'))
        ## Create left footer
        # with header.create(Foot("L")):
        #    header.append("Left Footer")
        ## Create center footer
        with header.create(Foot("C")):
            header.append(simple_page_number())
        ## Create right footer
        # with header.create(Foot("R")):
        #    header.append("Right Footer")

        doc.preamble.append(header)
        doc.change_document_style("header")

        # Add Heading
        with doc.create(MiniPage(align='c')):
            doc.append(LargeText(bold("rCAT v0.1")))
            doc.append(LineBreak())
            doc.append(MediumText(bold("Relational Character Analysis Tool")))

        return doc
コード例 #7
0
def generate_header():
    geometry_options = {"margin": "0.7in"}
    doc = Document(geometry_options=geometry_options)
    # Add document header
    header = PageStyle("header")
    # Create left header
    with header.create(Head("L")):
        header.append("__")
        header.append(LineBreak())
        header.append("_")
    # Create center header
    with header.create(Head("C")):
        header.append("____")
    # Create right header
    with header.create(Head("R")):
        header.append(simple_page_number())
    # Create left footer
    with header.create(Foot("L")):
        header.append("Left Footer")
    # Create center footer
    with header.create(Foot("C")):
        header.append("Center Footer")
    # Create right footer
    with header.create(Foot("R")):
        header.append("Right Footer")

    doc.preamble.append(header)
    doc.change_document_style("header")

    # Add Heading
    with doc.create(MiniPage(align='l')):
        doc.append(LargeText(bold("INVESTMENT PROPERTY - BUY & HOLD")))
        doc.append(LineBreak())
        doc.append(MediumText(bold(" ")))
    doc.generate_pdf("header", clean_tex=False)

    return print('nice')
コード例 #8
0
ファイル: header.py プロジェクト: vovchikthebest/PyLaTeX-fork
def generate_header():
    geometry_options = {"margin": "0.7in"}
    doc = Document(geometry_options=geometry_options)
    # Add document header
    header = PageStyle("header")
    # Create left header
    with header.create(Head("L")):
        header.append("Page date: ")
        header.append(LineBreak())
        header.append("R3")
    # Create center header
    with header.create(Head("C")):
        header.append("Company")
    # Create right header
    with header.create(Head("R")):
        header.append(simple_page_number())
    # Create left footer
    with header.create(Foot("L")):
        header.append("Left Footer")
    # Create center footer
    with header.create(Foot("C")):
        header.append("Center Footer")
    # Create right footer
    with header.create(Foot("R")):
        header.append("Right Footer")

    doc.preamble.append(header)
    doc.change_document_style("header")

    # Add Heading
    with doc.create(MiniPage(align='c')):
        doc.append(LargeText(bold("Title")))
        doc.append(LineBreak())
        doc.append(MediumText(bold("As at:")))

    doc.generate_pdf("header", clean_tex=False)
コード例 #9
0
ファイル: header.py プロジェクト: JelteF/PyLaTeX
def generate_header():
    geometry_options = {"margin": "0.7in"}
    doc = Document(geometry_options=geometry_options)
    # Add document header
    header = PageStyle("header")
    # Create left header
    with header.create(Head("L")):
        header.append("Page date: ")
        header.append(LineBreak())
        header.append("R3")
    # Create center header
    with header.create(Head("C")):
        header.append("Company")
    # Create right header
    with header.create(Head("R")):
        header.append(simple_page_number())
    # Create left footer
    with header.create(Foot("L")):
        header.append("Left Footer")
    # Create center footer
    with header.create(Foot("C")):
        header.append("Center Footer")
    # Create right footer
    with header.create(Foot("R")):
        header.append("Right Footer")

    doc.preamble.append(header)
    doc.change_document_style("header")

    # Add Heading
    with doc.create(MiniPage(align='c')):
        doc.append(LargeText(bold("Title")))
        doc.append(LineBreak())
        doc.append(MediumText(bold("As at:")))

    doc.generate_pdf("header", clean_tex=False)
コード例 #10
0
def generate_unique():
    geometry_options = {
        "head": "40pt",
        "margin": "0.5in",
        "bottom": "0.6in",
        "includeheadfoot": True
    }
    doc = Document(geometry_options=geometry_options)

    # Generating first page style
    first_page = PageStyle("firstpage")

    # Header image
    with first_page.create(Head("L")) as header_left:
        with header_left.create(MiniPage(width=NoEscape(r"0.49\textwidth"),
                                         pos='c')) as logo_wrapper:
            logo_file = os.path.join(os.path.dirname(__file__),
                                     'sample-logo.png')
            logo_wrapper.append(StandAloneGraphic(image_options="width=120px",
                                filename=logo_file))

    # Add document title
    with first_page.create(Head("R")) as right_header:
        with right_header.create(MiniPage(width=NoEscape(r"0.49\textwidth"),
                                 pos='c', align='r')) as title_wrapper:
            title_wrapper.append(LargeText(bold("Bank Account Statement")))
            title_wrapper.append(LineBreak())
            title_wrapper.append(MediumText(bold("Date")))

    # Add footer
    with first_page.create(Foot("C")) as footer:
        message = "Important message please read"
        with footer.create(Tabularx(
                           "X X X X",
                           arguments=NoEscape(r"\textwidth"))) as footer_table:

            footer_table.add_row(
                [MultiColumn(4, align='l', data=TextColor("blue", message))])
            footer_table.add_hline(color="blue")
            footer_table.add_empty_row()

            branch_address = MiniPage(
                width=NoEscape(r"0.25\textwidth"),
                pos='t')
            branch_address.append("960 - 22nd street east")
            branch_address.append("\n")
            branch_address.append("Saskatoon, SK")

            document_details = MiniPage(width=NoEscape(r"0.25\textwidth"),
                                        pos='t', align='r')
            document_details.append("1000")
            document_details.append(LineBreak())
            document_details.append(simple_page_number())

            footer_table.add_row([branch_address, branch_address,
                                  branch_address, document_details])

    doc.preamble.append(first_page)
    # End first page style

    # Add customer information
    with doc.create(Tabu("X[l] X[r]")) as first_page_table:
        customer = MiniPage(width=NoEscape(r"0.49\textwidth"), pos='h')
        customer.append("Verna Volcano")
        customer.append("\n")
        customer.append("For some Person")
        customer.append("\n")
        customer.append("Address1")
        customer.append("\n")
        customer.append("Address2")
        customer.append("\n")
        customer.append("Address3")

        # Add branch information
        branch = MiniPage(width=NoEscape(r"0.49\textwidth"), pos='t!',
                          align='r')
        branch.append("Branch no.")
        branch.append(LineBreak())
        branch.append(bold("1181..."))
        branch.append(LineBreak())
        branch.append(bold("TIB Cheque"))

        first_page_table.add_row([customer, branch])
        first_page_table.add_empty_row()

    doc.change_document_style("firstpage")
    doc.add_color(name="lightgray", model="gray", description="0.80")

    # Add statement table
    with doc.create(LongTabu("X[l] X[2l] X[r] X[r] X[r]",
                             row_height=1.5)) as data_table:
        data_table.add_row(["date",
                            "description",
                            "debits($)",
                            "credits($)",
                            "balance($)"],
                           mapper=bold,
                           color="lightgray")
        data_table.add_empty_row()
        data_table.add_hline()
        row = ["2016-JUN-01", "Test", "$100", "$1000", "-$900"]
        for i in range(30):
            if (i % 2) == 0:
                data_table.add_row(row, color="lightgray")
            else:
                data_table.add_row(row)

    doc.append(NewPage())

    # Add cheque images
    with doc.create(LongTabu("X[c] X[c]")) as cheque_table:
        cheque_file = os.path.join(os.path.dirname(__file__),
                                   'chequeexample.png')
        cheque = StandAloneGraphic(cheque_file, image_options="width=200px")
        for i in range(0, 20):
            cheque_table.add_row([cheque, cheque])

    doc.generate_pdf("complex_report", clean_tex=False)
コード例 #11
0
def details():
    if __name__ == '__main__':


        image_filename = os.path.join(os.path.dirname(__file__), 'kitten.jpg')
        logo_file = os.path.join(os.path.dirname(__file__),'sample-logo.png')

        geometry_options = {"tmargin": "1cm", "lmargin": "3cm"}
        doc = Document(geometry_options=geometry_options)
        header = PageStyle("header")
        with header.create(Head("R")):
            header.append(simple_page_number())
        with header.create(Foot("C")):
            header.append("Center Footer")
        first_page = PageStyle("firstpage")
        with first_page.create(Head("L")) as header_left:
        with header_left.create(MiniPage(width=NoEscape(r"0.49\textwidth"),pos='c')) as logo_wrapper

        with doc.create(MiniPage(align='l')):
            doc.append(LargeText(bold("INVESTMENT PROPERTY - BUY & HOLD")))
            doc.append(LineBreak())
            doc.append(MediumText(bold(" ")))
        logo_wrapper.append(StandAloneGraphic(image_options="width=120px",
                                              filename=logo_file))
        with doc.create(Section('Home Adress')):
            doc.append('Some regular text and some')
            doc.append(italic('italic text. '))
            doc.append('\nAlso some crazy characters: $&#{}')
            with doc.create(Subsection('Math that is incorrect')):
                doc.append(Math(data=['2*3', '=', 9]))

            with doc.create(Subsection('Table of something')):
                with doc.create(Tabular('rc|cl')) as table:
                    table.add_hline()
                    table.add_row((1, 2, 3, 4))
                    table.add_hline(1, 2)
                    table.add_empty_row()
                    table.add_row((4, 5, 6, 7))

        a = np.array([[100, 10, 20]]).T
        M = np.matrix([[2, 3, 4],
                       [0, 0, 1],
                       [0, 0, 2]])

        with doc.create(Section('The fancy stuff')):
            with doc.create(Subsection('Correct matrix equations')):
                doc.append(Math(data=[Matrix(M), Matrix(a), '=', Matrix(M * a)]))

            with doc.create(Subsection('Alignat math environment')):
                with doc.create(Alignat(numbering=False, escape=False)) as agn:
                    agn.append(r'\frac{a}{b} &= 0 \\')
                    agn.extend([Matrix(M), Matrix(a), '&=', Matrix(M * a)])

            with doc.create(Subsection('Beautiful graphs')):
                with doc.create(TikZ()):
                    plot_options = 'height=4cm, width=6cm, grid=major'
                    with doc.create(Axis(options=plot_options)) as plot:
                        plot.append(Plot(name='model', func='-x^5 - 242'))

                        coordinates = [
                            (-4.77778, 2027.60977),
                            (-3.55556, 347.84069),
                            (-2.33333, 22.58953),
                            (-1.11111, -493.50066),
                            (0.11111, 46.66082),
                            (1.33333, -205.56286),
                            (2.55556, -341.40638),
                            (3.77778, -1169.24780),
                            (5.00000, -3269.56775),
                        ]

                        plot.append(Plot(name='estimate', coordinates=coordinates))

            with doc.create(Subsection('Cute kitten pictures')):
                with doc.create(Figure(position='h!')) as kitten_pic:
                    kitten_pic.add_image(image_filename, width='120px')
                    kitten_pic.add_caption('Look it\'s on its back')

        doc.generate_pdf('full', clean_tex=False)
コード例 #12
0
def get_document(document_title='Report',
                 author='Entail AS',
                 fig_ext=u'.pdf',
                 header_logofilename='entail.pdf',
                 logo_image_option_header="width=250px",
                 workflow_ID=0):
    global _fig_ext
    _fig_ext = fig_ext

    geometry_options = {
        "head": "70pt",
        "margin": "1.5cm",
        "bottom": "1.5cm",
        "includeheadfoot": True
    }
    document_options = ['a4paper']
    doc = Document(geometry_options=geometry_options,
                   document_options=document_options)

    # packages
    doc.packages.append(Package('booktabs'))
    doc.packages.append(Package('chngcntr'))
    doc.packages.append(Package('longtable'))
    doc.packages.append(Package('titlepic'))
    doc.packages.append(Package('float'))
    # page style
    first_page = PageStyle("firstpage")

    # Header image
    with first_page.create(Head("L")) as header_left:
        with header_left.create(
                MiniPage(width=NoEscape(r"0.25\textwidth"),
                         pos='c')) as logo_wrapper:
            logo_file = os.path.join(
                os.path.dirname(os.path.abspath(__file__)),
                header_logofilename).replace('\\', '/')
            logo_wrapper.append(
                StandAloneGraphic(image_options="width=80px",
                                  filename=logo_file))

    # Add document title
    with first_page.create(Head("R")) as right_header:
        with right_header.create(
                MiniPage(width=NoEscape(r"0.75\textwidth"), pos='c',
                         align='r')) as title_wrapper:
            title_wrapper.append(LargeText(bold(document_title)))
            title_wrapper.append(LineBreak())
            title_wrapper.append(MediumText(bold(NoEscape(r'\today'))))

    # Add footer
    with first_page.create(Foot("C")) as center_footer:
        center_footer.append(simple_page_number())
    with first_page.create(Foot("R")) as right_footer:
        with right_footer.create(
                MiniPage(width=NoEscape(r"0.15\textwidth"),
                         pos='r')) as logo_wrapper:
            logo_file = os.path.join(
                os.path.dirname(os.path.abspath(__file__)),
                'tailor.png').replace('\\', '/')
            logo_wrapper.append(
                StandAloneGraphic(image_options="width=50px",
                                  filename=logo_file))

    doc.preamble.append(first_page)
    doc.change_document_style("firstpage")
    doc.preamble.append(Command('title', document_title))
    logo_file = os.path.join(os.path.dirname(os.path.abspath(__file__)),
                             header_logofilename).replace('\\', '/')
    doc.preamble.append(
        Command(
            'titlepic',
            StandAloneGraphic(image_options=logo_image_option_header,
                              filename=logo_file)))
    # doc.preamble.append(Command('author', author))
    doc.preamble.append(Command('date', NoEscape(r'\today')))
    doc.preamble.append(
        Command(
            'hypersetup',
            arguments=
            'colorlinks, citecolor=black, filecolor=black, linkcolor=black, urlcolor=black',
            packages=[Package('hyperref')]))
    doc.preamble.append(NoEscape(r'\counterwithin{figure}{section}'))
    doc.append(NoEscape(r'\maketitle'))

    # Add disclaimer
    doc.append(NewPage())
    doc.append(NoEscape(r'\textbf{Disclaimer}'))
    doc.append(NoEscape(r'\newline'))
    doc.append(NoEscape(r'\vspace{0.2in}'))

    temptext = f'This is in automatically generated report. '
    if workflow_ID == 0:
        temptext += f'The report was generated '
    else:
        temptext += f'The results are extracted from Workflow ID {workflow_ID} '
    temptext += f'on the {datetime.datetime.now().strftime("%m/%d/%Y at %H:%M:%S")}. '
    temptext += f'Errors may occur and it is the user’s responsibility to interpret the reported data '
    temptext += f'with sound engineering judgement.'
    doc.append(temptext)

    doc.append(NewPage())
    doc.append(Command('tableofcontents'))
    doc.append(NewPage())

    return doc
コード例 #13
0
def generate_unique():
    geometry_options = {
        "head": "40pt",
        "margin": "0.5in",
        "bottom": "0.6in",
        "includeheadfoot": True
    }
    doc = Document(geometry_options=geometry_options)

    # Generating first page style
    first_page = PageStyle("firstpage")
    # Header image
    with first_page.create(Head("C")) as header_center:
        with header_center.create(
                MiniPage(width=NoEscape(r"0.50\textwidth"),
                         pos='c')) as logo_wrapper:
            logo_file = os.path.join(os.path.dirname(__file__),
                                     'sample-logo.png')
            logo_wrapper.append(
                StandAloneGraphic(image_options="width=300px",
                                  filename=logo_file))

    # Add document title
    # Add footer
    with first_page.create(Foot("C")) as footer:
        message = "Important message please read"
        with footer.create(
                Tabularx(
                    "X X X X",
                    width_argument=NoEscape(r"\textwidth"))) as footer_table:
            branch_address = MiniPage(width=NoEscape(r"0.25\textwidth"),
                                      pos='t')

            document_details = MiniPage(width=NoEscape(r"0.25\textwidth"),
                                        pos='t',
                                        align='r')
            document_details.append(LineBreak())
            document_details.append(simple_page_number())

            footer_table.add_row([
                branch_address, branch_address, branch_address,
                document_details
            ])

    doc.preamble.append(first_page)
    # End first page style

    # Add customer information
    with doc.create(Tabu("X[l] X[r]")) as first_page_table:
        customer = MiniPage(width=NoEscape(r"0.49\textwidth"), pos='h')

        # Add branch information
        branch = MiniPage(width=NoEscape(r"0.49\textwidth"),
                          pos='t!',
                          align='r')

        first_page_table.add_row([customer, branch])
        first_page_table.add_empty_row()

    doc.change_document_style("firstpage")
    doc.add_color(name="lightgray", model="gray", description="0.80")
    print("Enter the Region")
    R = input(str)

    with doc.create(MiniPage(align='c')):
        doc.append(LargeText(bold("\n\n\n\n\n\n" + R)))
        doc.append(LineBreak())
    print("Enter the adress of home ")
    A = input(str)
    image_filename = os.path.join(os.path.dirname(__file__), 'home.jpg')
    with doc.create(Section('Example : ' + A)):
        with doc.create(Figure(position='h!')) as home_pic:
            home_pic.add_image(image_filename, width='490px')
    with doc.create(Section('Property information :')):
        with doc.create(Itemize()) as itemize:
            print("enter property type")
            x = input(str)
            itemize.add_item(bold("Property type : " + x))
            print("How many bedrooms ?")
            y = input(int)
            itemize.add_item(bold("Bedroom : " + y))
            print("How many bathrooms?")
            z = input(float)
            itemize.add_item(bold("Bathroom : " + z))
            print('Enter the year of built please:')
            a = input(int)
            itemize.add_item(bold("Year built : " + a))
            print('Enter the finished sqft :')
            b = input(int)
            itemize.add_item(bold("Finished sqft : " + b))
            print("Enter the estimate price")
            p1 = input(float)
            print('enter the estimate rent')
            p2 = input(float)
            doc.append(LineBreak())
            table1 = Tabular('|c|c|')
            table1.add_hline()
            table1.add_row(('Estimate price', 'Estimate rent'))
            table1.add_hline()
            table1.add_row((p1 + '$', p2 + '$'))
            table1.add_hline()

        doc.append(table1)
    with doc.create(Section('Financing')):
        with doc.create(Itemize()) as itemize:
            print('Enter type of loan')
            lo = input(str)
            itemize.add_item(bold("Loan Type: " + lo))
            print("Enter loan amount")
            la = input(float)
            itemize.add_item(bold("Loan Amount: " + la))
            print("enter the interest rate with %")
            IR = input(float)
            itemize.add_item(bold("Interest Rate: " + IR + "%"))
            print("enter LTV")
            LTV = input(float)
            itemize.add_item(bold("Loan to Value (LTV): " + LTV + "%"))
            print("enter loan term")
            LT = input(int)
            itemize.add_item(bold("Loan Term: " + LT + "years"))
            print("enter loan payment monthly")
            LPM = input(int)
            print("enter loan payment yearly")
            LPY = input(int)
            itemize.add_item(
                bold("Loan Payment: " + LPM + "(monthly), " + LPY +
                     "(yearly)"))

    with doc.create(Section('Assumptions')):
        with doc.create(Itemize()) as itemize:
            print("enter vacancy rate")
            vr = input(float)
            itemize.add_item(bold('Vacancy Rate' + vr))
            print("property managment")
            pr = input(float)
            itemize.add_item(bold('Property Managment' + pr))
            print("yearly expense")
            yex = input(float)
            itemize.add_item(bold('Yearly Expense incr' + yex))
            print("yearly rent")
            yr = input(float)
            itemize.add_item(bold('Yearly Rent incr' + yr))
            print("yearly equity")
            ye = input(float)
            itemize.add_item(bold('Yearly Equity incr' + ye))
            print("land value")
            lv = input(float)
            itemize.add_item(bold('Land Value' + lv))

        section = Section('Financial projection and expences analysis')
        test1 = Subsection(bold('Financial Projection'))
        test2 = Subsection(bold('Expences'))

        table2 = Tabular('|c|c|c|c|c|c|c|c|c|c|')
        table2.add_hline()
        table2.add_row(("Type", "Year 1", "Year 2", "Year 3", "Year 4",
                        "Year 5", "Year 10", "Year 15", "Year 20", "Year 30"))
        table2.add_hline()
        table2.add_row(("Total Annuel Income", 6, 7, 8, 8, 8, 8, 8, 8, 8))
        table2.add_hline()
        table2.add_row(("Total Annuel Expenses", 6, 7, 8, 8, 8, 8, 8, 8, 8))
        table2.add_hline()
        table2.add_row(
            ("Total Annuel Operating Expenses", 6, 7, 8, 8, 8, 8, 8, 8, 8))
        table2.add_hline()
        table2.add_row(("Total Annual Cash Flow", 6, 7, 8, 8, 8, 8, 8, 8, 8))
        table2.add_hline()
        table2.add_row(("Property Value", 6, 7, 8, 8, 8, 8, 8, 8, 8))
        table2.add_hline()
        table2.add_row(("Cash on Cash ROI", 6, 7, 8, 8, 8, 8, 8, 8, 8))
        table2.add_hline()
        table2.add_row(("Loan Balance", 6, 7, 8, 8, 8, 8, 8, 8, 8))
        table2.add_hline()
        table2.add_row(("Cumulative Cash Flow", 6, 7, 8, 8, 8, 8, 8, 8, 8))
        table2.add_hline()
        table2.add_row(("Equity", 6, 7, 8, 8, 8, 8, 8, 8, 8))
        table2.add_hline()

        table3 = Tabular('|c|c|c|')
        table3.add_hline()
        table3.add_row(("   ", "Monthly", "Annually"))
        table3.add_hline()
        table3.add_row(("Repair Cost", 6, 7))
        table3.add_hline()
        table3.add_row(("Vacancy", 6, 7))
        table3.add_hline()
        table3.add_row(("Insurance", 6, 7))
        table3.add_hline()
        table3.add_row(("Taxes", 6, 7))
        table3.add_hline()
        table3.add_row(("hoe", 6, 7))
        table3.add_hline()
        table3.add_row(("Capital Expenditures", 6, 7))
        table3.add_hline()
        table3.add_row(("Property Managment", 6, 7))
        table3.add_hline()
        table3.add_row(("Other Expences", 6, 7))
        table3.add_hline()
        table3.add_row((LargeText(bold("Total")), 6, 7))
        table3.add_hline()

        test1.append(table2)
        test2.append(table3)
        section.append(test1)
        section.append(test2)
        doc.append(section)
        doc.append(LineBreak)
        print('Cap Rate')
        cap = input()
        print('Cash on Cash Return')
        cac = input()
        print('Retur on investment')
        roi = input()

    doc.append(
        LargeText(
            bold('Cap Rate :' + cap + '\n\n' + "Cash on Cash Return" + cac +
                 "\n\n" + "Return on Investment" + roi)))
    doc.generate_pdf("complex_report", clean_tex=False)
コード例 #14
0
def generate_unique(sectors_notirradiated, hv_notirradiated, spark_notirradiated, irradatgif):
	geometry_options = {
		"head": "40pt",
		"margin": "0.5in",
		"bottom": "1.0in",
		"includeheadfoot": True
	}
	doc = Document(indent=False,geometry_options=geometry_options)

	# Generating first page style
	first_page = PageStyle("firstpage")

	# Header image
	with first_page.create(Head("L")) as header_left:
		with header_left.create(MiniPage(width=NoEscape(r"0.49\textwidth"),
										 pos='c')) as logo_wrapper:
			logo_file = os.path.join(os.path.dirname(__file__),
									 '../cernlogo.png')
			logo_wrapper.append(StandAloneGraphic(image_options="width=80px",
								filename=logo_file))

	# Add document title
	with first_page.create(Head("R")) as right_header:
		with right_header.create(MiniPage(width=NoEscape(r"0.49\textwidth"),
								 pos='c', align='r')) as title_wrapper:
			title_wrapper.append(LargeText(bold("ATLAS New Small Wheel")))
			title_wrapper.append(LineBreak())
			title_wrapper.append(bold("Integration Tests"))
			title_wrapper.append(LineBreak())
			title_wrapper.append(bold(now.strftime("%d-%m-%Y")))
			title_wrapper.append(LineBreak())
			title_wrapper.append("\n")
			title_wrapper.append(LargeText(bold("Chamber: "+str(chambername))))
			title_wrapper.append(LineBreak())
			title_wrapper.append("ID: "+str(ID))
			title_wrapper.append(LineBreak())

	# Add footer
	with first_page.create(Foot("C")) as footer:

		with footer.create(Tabularx(
				"X X X ",
				width_argument=NoEscape(r"\textwidth"))) as footer_table:

			footer_table.add_empty_row()

			footer_table.add_hline(color="blue")

			branch_address1 = MiniPage(
				width=NoEscape(r"0.25\textwidth"),
				pos='t')
			branch_address1.append("Lorenzo Pezzotti")
			branch_address1.append("\n")
			branch_address1.append("*****@*****.**")

			branch_address2 = MiniPage(
				width=NoEscape(r"0.25\textwidth"),
				pos='t')
			branch_address2.append("Alan Peyaud")
			branch_address2.append("\n")
			branch_address2.append("*****@*****.**")

			branch_address3 = MiniPage(
				width=NoEscape(r"0.25\textwidth"),
				pos='t')
			branch_address3.append("Ivan Gnesi")
			branch_address3.append("\n")
			branch_address3.append("*****@*****.**")

			document_details = MiniPage(width=NoEscape(r"0.2\textwidth"),
										pos='t', align='r')
			document_details.append(" ")
			document_details.append(LineBreak())
			document_details.append(simple_page_number())

			footer_table.add_row([branch_address1, branch_address2,
								  branch_address3])

	doc.append(first_page)
	# End first page style
	redcircle = glob.glob("redcircle.png")
	redcircle = StandAloneGraphic(redcircle, image_options="width=220px")

	# Add customer information
	with doc.create(Tabu("X[r]")) as first_page_table:
		'''
		# Add branch information
		branch = MiniPage(width=NoEscape(r"0.49\textwidth"), pos='t!',
						  align='r')
		branch.append("Chamber name: ")
		branch.append(LineBreak())
		branch.append("ID: ")
		branch.append(LineBreak())

		first_page_table.add_row([branch])
		'''
		first_page_table.add_empty_row()

	doc.change_document_style("firstpage")
	doc.add_color(name="lightgray", model="gray", description="0.85")
	doc.add_color(name="lightgray2", model="gray", description="0.6")

	if irradatgif == "y":
		title = "HV irradiated"
	else:
		title = "HV not irradiated"
	with doc.create(Section(title, numbering=False)):
	   # Add statement table
		doc.append("\n")
		doc.append(timeslot)
		doc.append(LineBreak())
		doc.append(str(deltatime/60)+str("_min"))
		doc.append(LineBreak())
		doc.append("Spike_treshold_0.2_uA")
		doc.append(LineBreak())

		with doc.create(LongTabu("|X[l]|X[r]|X[r]|X[r]|X[r]|",
								 row_height=1.5)) as data_table:
			data_table.add_hline()
			data_table.add_row(["Sector",
								"HV",
								"spark/min",
								"Efficiency",
								"Flag"],
							   mapper=bold,
							   color="lightgray2")
			data_table.add_hline()
			data_table.end_table_header()
			data_table.add_hline()
			row = ["sector", "hv","spark", "efficiency", "0 or 1"]
			acceptedlist = []
			not_acc_counter = 0
			pscolor = "blue"
			for i in range(len(hv_notirradiated)):
				if (i % 2) == 0:
					'''
					if int(hv_notirradiated[i]) > 567.9 and spark_notirradiated[i]<1.0:
						accepted = 1
						acceptedlist.append(accepted)

					else:
						accepted = 0
						acceptedlist.append(accepted)
					'''
					if int(hv_notirradiated[i]) > 567.9:
						hvcolor = "black"

					if 548.0 < int(hv_notirradiated[i]) < 567.9:
						hvcolor = "orange"

					if int(hv_notirradiated[i])< 548.0:
						hvcolor = "red"

					if spark_notirradiated[i] > 6.0:
						sparkcolor = "red"

					if spark_notirradiated[i] == 6.0:
						sparkcolor = "orange"

					if spark_notirradiated[i] < 6.0:
						sparkcolor = "black"

					if efficiency[i] < 80.0:
						effcolor = "red"

					if efficiency[i] > 80.0:
						effcolor = "black"

					if efficiency == 80.0:
						effcolor = "orange"

					if sparkcolor == "red" or hvcolor == "red" or effcolor == "red":
						acceptedcolor = "red"
						accepted = 0
						acceptedlist.append(accepted)
						not_acc_counter = not_acc_counter+1

					else:
						acceptedcolor = "black"
						accepted = 1
						acceptedlist.append(accepted)


					data_table.add_row([str(sectors_notirradiated[i]), TextColor(hvcolor,str(int(hv_notirradiated[i]))),
					TextColor(sparkcolor, str(round(spark_notirradiated[i],2))), TextColor(effcolor, str(round(efficiency[i],1))),
					TextColor(acceptedcolor, "V")])
					data_table.add_hline()
				else:
					'''
					if int(hv_notirradiated[i]) > 567.9 and spark_notirradiated[i]<1.0:
						accepted = 1
						acceptedlist.append(accepted)
					else:
						accepted = 0
						acceptedlist.append(accepted)
					'''
					if int(hv_notirradiated[i]) > 567.9:
						hvcolor = "black"

					if 548.0 < int(hv_notirradiated[i]) < 567.9:
						hvcolor = "orange"

					if int(hv_notirradiated[i])< 548.0:
						hvcolor = "red"

					if spark_notirradiated[i] > 6.0:
						sparkcolor = "red"

					if spark_notirradiated[i] == 6.0:
						sparkcolor = "orange"

					if spark_notirradiated[i] < 6.0:
						sparkcolor = "black"

					if efficiency[i] < 80.0:
						effcolor = "red"

					if efficiency[i] > 80.0:
						effcolor = "black"

					if efficiency == 80.0:
						effcolor = "orange"

					if sparkcolor == "red" or hvcolor == "red" or effcolor == "red":
						acceptedcolor = "red"
						accepted = 0
						acceptedlist.append(accepted)
						not_acc_counter = not_acc_counter+1

					else:
						acceptedcolor = "black"
						accepted = 1
						acceptedlist.append(accepted)


					data_table.add_row([str(sectors_notirradiated[i]), TextColor(hvcolor,str(int(hv_notirradiated[i]))),
					TextColor(sparkcolor, str(round(spark_notirradiated[i],2))), TextColor(effcolor, str(round(efficiency[i],1))),
					TextColor(acceptedcolor, "V")], color="lightgray")
					data_table.add_hline()

			data_table.add_hline()
			data_table.add_row("Out of spec", str(len([x for x in hv_notirradiated if x < 548.0])), str(len([x for x in spark_notirradiated if x > 6.0])), str(len([x for x in efficiency if x < 80.0])), str(not_acc_counter))

			data_table.add_empty_row()
			data_table.add_hline()
			data_table.add_row("Chamber efficiency", "","", "", str(round(total_efficiency)))
			data_table.add_hline()
			if "LM2" in chambername:
				newefficiency = efficiency
				newefficiency.pop(4)
				newefficiency.pop(4)
				newefficiency.pop(8)
				newefficiency.pop(8)
				data_table.add_row("Efficiency no LE8", "","", "", str(round(np.mean(newefficiency))))
				data_table.add_hline()

	doc.append(NoEscape('\\clearpage'))
	with doc.create(Section('Summary', numbering=False)):
		piecart.create_pie([acceptedlist.count(1), acceptedlist.count(0)], "piechart.pdf")


		 # Add cheque images
		with doc.create(LongTabu("X[c]")) as summary1_table:
			pie = glob.iglob("piechart.pdf")
			#png_list = [StandAloneGraphic(x, image_options="width=120px") for x in png_list]
			pienew = [StandAloneGraphic(x, image_options="width=220px") for x in pie]
			summary1_table.add_row([pienew[0]])

		#here I have sectors_notirradiated, hv_notirradiated, spark_notirradiated, acceptedlist
		SM1channels = ["L1","R1","L2","R2","L3","R3","L4","R4","L5","R5"]
		SM2channels = ["L6","R6","L7","R7","L8","R8"]

		badresultsall = []
		badresultseta = []
		badresultsstereo = []

		if chambername[0:3] == "SM1":
		   channels = SM1channels
		if chambername[0:3] == "SM2":
		   channels = SM2channels
		if chambername[0:3] == "LM1":
			channels = SM1channels
		if chambername[0:3] == "LM2":
			channels = SM2channels

		for channel in channels:
		   cntall = sum(1 for x, sector in enumerate(sectors_notirradiated) if sector[2:4] == channel and acceptedlist[x] == 1)
		   cnteta = sum(1 for x, sector in enumerate(sectors_notirradiated) if sector[2:4] == channel and (sector[1:2] == "1" or sector[1:2] == "2") and acceptedlist[x] == 1)
		   cntstereo = sum(1 for x, sector in enumerate(sectors_notirradiated) if sector[2:4] == channel and (sector[1:2] == "3" or sector[1:2] == "4") and acceptedlist[x] == 1)
		   badresultsall.append(4-int(cntall))
		   badresultseta.append(2-int(cnteta))
		   badresultsstereo.append(2-int(cntstereo))

		#doc.append(NewPage())

		with doc.create(LongTabu("X[l] X[r] X[r] X[r]",
								 row_height=1.5)) as data_table2:
			data_table2.add_row(["Sector overimposed (from eta side)",
								"Eta",
								"Stereo",
								"Eta+Stereo"],
								mapper=bold,
								color="lightgray2")
			data_table2.add_empty_row()
			data_table2.add_hline()
			row = ["Sector (all layers)", "Out of spec (Eta)", "Out of spec (Stereo)", "Out of spec (E+S)"]

			for i in range(len(channels)):
				if (i % 2) == 0:
					data_table2.add_row([str(channels[i]), str(int(badresultseta[i])), str(badresultsstereo[i]), badresultsall[i]], color="lightgray")
				else:
					data_table2.add_row([str(channels[i]), str(int(badresultseta[i])), str(badresultsstereo[i]), badresultsall[i]])

		with doc.create(LongTabu("X[l] X[r]",
								 row_height=1.5)) as data_table3:
			data_table3.add_row(["Layer",
								"Mean Efficiency"],
								mapper=bold,
								color="lightgray2")
			data_table3.add_empty_row()
			data_table3.add_hline()
			row = ["layers", "efficiency"]
			channelsT3 = ["L1", "L2", "L3", "L4"]
			for i in range(len(layers_efficiency)):
				if (i % 2) == 0:
					data_table3.add_row([str(channelsT3[i]), str(round(layers_efficiency[i],1))], color="lightgray")
				else:
					data_table3.add_row([str(channelsT3[i]), str(round(layers_efficiency[i],1))])

	doc.append(NewPage())

	if irradatgif == "y":
		title = "Current with irradiation"
	else:
		title = "Current with no irradiation"
	with doc.create(Section(title, numbering=False)):

	# Add cheque images
		with doc.create(LongTabu("X[c] X[c] X[c] X[c]")) as cheque_table:
			png_list = glob.glob('BB5-i*.pdf')
			png_list.sort(key=os.path.getmtime)
			png_list = [StandAloneGraphic(x, image_options="width=120px") for x in png_list]
			print len(png_list)
			row_image = []
			i = 0
			for image in png_list:
				row_image.append(image)
				i = i +1
				if i==4:
					cheque_table.add_row([row_image[0], row_image[1], row_image[2], row_image[3]])
					row_image = []
					i=0

	png_list = []
	doc.generate_pdf("complex_report", clean_tex=False, compiler='pdflatex')
コード例 #15
0
def report(context, json_report, json_varreport, rulegraph_img):

    config = json_report
    sample_config = json.load(open(json_report))
    var_config = json.load(open(get_config(json_varreport)))

    tex_path = os.path.abspath(
        os.path.join(sample_config["analysis"]["analysis_dir"],
                     "delivery_report"))

    if not rulegraph_img:
        rulegraph_img = sample_config['analysis']['dag']

    os.makedirs(tex_path, exist_ok=True)

    geometry_options = {
        "head": "40pt",
        "headheight": "130pt",
        "headsep": "1cm",
        "margin": "1.5cm",
        "bottom": "1.5cm",
        "includeheadfoot": True
    }
    doc = Document(geometry_options=geometry_options)

    doc.packages.append(Package('lscape'))
    doc.packages.append(Package('longtable'))
    doc.packages.append(Package('float'))
    doc.packages.append(Package('caption', options='labelfont=bf'))
    doc.append(
        NoEscape(
            r'\captionsetup[table]{labelsep=space, justification=raggedright, singlelinecheck=off}'
        ))

    #Add first page style
    first_page = PageStyle("header", header_thickness=1)

    #Add Header
    with first_page.create(Head("C")) as mid_header:

        with mid_header.create(
                MiniPage(width=NoEscape(r"0.2\textwidth"),
                         pos='c')) as logo_wrapper:
            logo_file = os.path.join(os.path.dirname(__file__), '..',
                                     'assests/cg.png')
            logo_wrapper.append(
                StandAloneGraphic(image_options="width=50px",
                                  filename=logo_file))

        with mid_header.create(
                Tabularx(
                    "p{3cm} p{2cm} X X p{4cm} p{3cm}",
                    width_argument=NoEscape(r"0.8\textwidth"))) as mid_table:
            mid_table.add_row(
                [MultiColumn(6, align='r', data=simple_page_number())])
            mid_table.add_row([
                MultiColumn(6,
                            align='c',
                            data=MediumText("Molecular report on"))
            ])
            mid_table.add_row([
                MultiColumn(6,
                            align='c',
                            data=MediumText(get_sample_name(config)))
            ])
            mid_table.add_empty_row()
            mid_table.add_row([
                'gender', "NA", " ", " ", 'Sample recieved:',
                sample_config['analysis']['date']['sample_received']
            ])
            mid_table.add_row([
                'tumor type', "NA", " ", " ", 'Analysis completion:',
                sample_config['analysis']['date']['analysis_finish']
            ])
            mid_table.add_row([
                'analysis type', "NA", " ", " ", 'PDF Report date:',
                datetime.now().strftime("%Y-%m-%d %H:%M")
            ])
            mid_table.add_row(
                ['sample type', "NA", " ", " ", 'Delivery date', "NA"])
            mid_table.add_row([
                'sample origin', "NA", " ", " ", 'Analysis:',
                r'BALSAMIC v' + sample_config['analysis']['BALSAMIC']
            ])

    doc.preamble.append(first_page)

    #End First page

    #    doc.preamble.append(
    #        Command(
    #            'title',
    #            NoEscape(r'BALSAMIC v' + sample_config["analysis"]["BALSAMIC"] +
    #                     r'\\ \large Developer Report')))
    #    doc.preamble.append(
    #        Command('author', 'Patient ID: ' + get_sample_name(config)))
    #    doc.preamble.append(Command('date', NoEscape(r'\today')))
    #    doc.append(NoEscape(r'\maketitle'))
    doc.change_document_style("header")

    with doc.create(Section(title='Analysis report', numbering=True)):

        with doc.create(
                Subsection('Summary of variants and variant callers',
                           numbering=True)):
            doc.append(
                "Placeholder for text about BAM alignment metrics and variant callers. Here comes the info on reads, "
                +
                "QC metrics, align metrics, and general sample information. preferabily in table format."
            )
            doc.append("\n")

            summary_tables = ["TMB", "VarClass", "VarCaller", "VarCallerClass"]
            for i in summary_tables:

                shellcmd = [
                    os.path.join(os.path.dirname(os.path.abspath(__file__)),
                                 "..", "..", "scripts/VariantReport.R")
                ]
                shellcmd.extend([
                    "--infile", sample_config["vcf"]["merged"]["SNV"],
                    "--genomeSize", sample_config["bed"]["genome_size"],
                    "--type", "latex", "--mode", i, "--outfile",
                    os.path.join(tex_path,
                                 sample_config['analysis']['sample_id'])
                ])
                print(" ".join(shellcmd))

                outTab = subprocess.check_output(shellcmd)
                doc.append(
                    NoEscape(
                        outTab.decode('utf-8').replace("\\centering",
                                                       "\\small")))
            doc.append(NoEscape(r'\normalsize'))
            doc.append(NewPage())

        with doc.create(Subsection("Summary of MVL report", numbering=True)):
            doc.append(
                "Placeholder for general description of MVL settings. A mention to summary "
                +
                "pipeline, summary of MVL settings. Gene coverage for identified genes should go here. Figures!"
            )
            outCov = dict()

            cmd_param = defaultdict(list)
            J = defaultdict(list)
            for i in var_config["filters"]:
                cmd_param["TUMOR_DP"].append(
                    var_config["filters"][i]["TUMOR"]["DP"])
                cmd_param["TUMOR_AD"].append(
                    var_config["filters"][i]["TUMOR"]["AD"])
                cmd_param["TUMOR_AFmax"].append(
                    var_config["filters"][i]["TUMOR"]["AF_max"])
                cmd_param["TUMOR_AFmin"].append(
                    var_config["filters"][i]["TUMOR"]["AF_min"])
                cmd_param["TUMOR_inMVL"].append(
                    var_config["filters"][i]["in_mvl"])
                cmd_param["var_type"].append(",".join(
                    ["SNP", "INDEL", "MNP", "OTHER"]))
                cmd_param["varcaller"].append(",".join(
                    var_config["filters"][i]["variantcaller"]))
                cmd_param["ann"].append(
                    ",".join(var_config["filters"][i]["annotation"]["SNV"]) +
                    "," +
                    ",".join(var_config["filters"][i]["annotation"]["INDEL"]))
                cmd_param["name"].append(i.replace("_", "\_"))
                cmd_param["outfile_tex"].append(tex_path + "/" + i + ".tex")
                cmd_param["outfile_gene"].append(tex_path + "/" + i +
                                                 ".genelist")

            for i in cmd_param:
                J[i] = ";".join(cmd_param[i])

            shellcmd = [
                os.path.join(os.path.dirname(os.path.abspath(__file__)), "..",
                             "..", "scripts/VariantReport.R")
            ]
            shellcmd.extend([
                "--infile", "'" + sample_config["vcf"]["merged"]["SNV"] + "'",
                "--dp", "'" + J["TUMOR_DP"] + "'", "--tumorad",
                "'" + J["TUMOR_AD"] + "'", "--afmax",
                "'" + J["TUMOR_AFmax"] + "'", "--afmin",
                "'" + J["TUMOR_AFmin"] + "'", "--inMVL",
                "'" + J["TUMOR_inMVL"] + "'", "--exclusiveSets", "TRUE",
                "--vartype", "'" + J["var_type"] + "'", "--varcaller",
                "'" + J["varcaller"] + "'", "--ann", "'" + J["ann"] + "'",
                "--name", "'" + J["name"] + "'", "--type", "latex"
            ])

            subprocess.check_output(
                " ".join(shellcmd +
                         ["--outfile", "'" + J["outfile_tex"] + "'"]),
                shell=True)

            print(" ".join(shellcmd +
                           ["--outfile", "'" + J["outfile_tex"] + "'"]))
            subprocess.check_output(" ".join(shellcmd + [
                "--outfile", "'" + J["outfile_gene"] + "'", "--exportGene", "T"
            ]),
                                    shell=True)

            for c, i in enumerate(var_config["filters"]):
                with doc.create(
                        Subsubsection(var_config["filters"][i]["name"],
                                      numbering=True)):
                    print(cmd_param["outfile_tex"])
                    fname = cmd_param["outfile_tex"][c]
                    if os.stat(fname).st_size > 10:
                        #get gene list
                        with open(cmd_param["outfile_gene"][c]) as myfile:
                            genes = myfile.read().replace('\n', '')

                        with open(fname, 'r') as myfile:
                            data = myfile.read()  #.replace('\n', '')

                        #doc.append(NoEscape(r'\begin{landscape}'))
                        #longtable instead of tabular makes the table span multiple pages, but the header doesn't span. Occasionally
                        #the alignment also is messed up. There must be a hidden package conflict OR general alignment issues.
                        #doc.append(NoEscape(varreport.replace("{tabular}","{longtable}")))
                        doc.append(
                            NoEscape(
                                data.replace("\\centering", "\\scriptsize")))

                        for s in sample_config["bed"]["exon_cov"]:
                            shellcmd = [
                                os.path.join(
                                    os.path.dirname(os.path.abspath(__file__)),
                                    "..", "scripts/CoverageRep.R")
                            ]
                            shellcmd.extend([
                                "--infile",
                                sample_config["bed"]["exon_cov"][s],
                                "--genename", genes, "--name",
                                s.replace("_", "\_"), "--type", "latex"
                            ])
                            outCov = subprocess.check_output(shellcmd)

                            doc.append(
                                NoEscape(
                                    outCov.decode('utf-8').replace(
                                        "\\centering", "\\scriptsize")))
                        #doc.append(NoEscape(r'\end{landscape}'))
                    else:
                        doc.append("No variants were found for this filter")

#                doc.append(NoEscape(r'\normalsize'))

            doc.append(NewPage())

        with doc.create(Subsection('Coverage report')):
            for s in sample_config["bed"]["target_cov"]:
                with doc.create(Figure(position='h!')) as cov_img:
                    covplot = ".".join(
                        [os.path.join(tex_path, s), "Coverage.pdf"])
                    shellcmd = [
                        os.path.join(
                            os.path.dirname(os.path.abspath(__file__)), "..",
                            "..", "scripts/CoveragePlot.R")
                    ]
                    shellcmd.extend([
                        "--infile", sample_config["bed"]["target_cov"][s],
                        "--outfile", covplot, "--title",
                        s.replace("_", "\_")
                    ])
                    subprocess.check_output(shellcmd)
                    cov_img.add_image(covplot, width='450px')
                    cov_img.add_caption('Coverage report for sample ' +
                                        s.replace("_", "\_"))

            doc.append(NewPage())
        with doc.create(Subsection('Analysis pipeline')):
            with doc.create(Figure(position='h!')) as pipeline_img:
                pipeline_img.add_image(rulegraph_img, width='450px')
                pipeline_img.add_caption('BALSAMIC pipeline')
            doc.append(NewPage())

    with doc.create(Section(title="Appendix", numbering=True)):
        with doc.create(Subsection("MVL settings", numbering=True)):
            fmt = "p{3cm}" * (len(var_config["filters"]) + 1)
            with doc.create(Tabular(fmt)) as data_table:
                header_row1 = [""]
                for i in var_config["filters"]:
                    header_row1.append(var_config["filters"][i]["name"])
                data_table.add_hline()
                data_table.add_row(header_row1,
                                   mapper=[bold],
                                   color="lightgray")
                data_table.add_hline()
                data_table.add_empty_row()
                column = list(var_config["filters"][next(
                    iter(var_config["filters"]))]["TUMOR"].keys())
                for i in column:
                    row = [i]
                    for j in var_config["filters"]:
                        row.append(var_config["filters"][j]["TUMOR"][i])
                    data_table.add_row(row)

                row = ["MVL"]
                for i in var_config["filters"]:
                    row.append(var_config["filters"][i]["in_mvl"])

                row = ["Variantcallers"]
                for i in var_config["filters"]:
                    row.append("\n".join(
                        var_config["filters"][i]["variantcaller"]))
                data_table.add_row(row)
                data_table.add_hline()

        with doc.create(
                Subsection("Bioinformatic tool in pipeline", numbering=True)):
            doc.append(
                "The following Bioinformatic tools were used in the analysis:\n\n"
            )
            with doc.create(Tabular("p{4cm}p{4cm}")) as data_table:
                data_table.add_hline()
                conda_env = glob.glob(
                    os.path.join(os.path.dirname(os.path.abspath(__file__)),
                                 "..", "..", "conda_yaml/*.yaml"))

                pkgs = get_package_split(conda_env)

                data_table.add_row(["Package", "Version"], color="lightgray")
                data_table.add_hline()
                data_table.add_row(
                    ["BALSAMIC", sample_config['analysis']['BALSAMIC']])

                for k, v in pkgs.items():
                    data_table.add_row([k, v])
            doc.append(NewPage())

    print(tex_path)
    doc.generate_tex(os.path.join(tex_path, get_sample_name(config)))
    #    doc.generate_pdf(
    #        os.path.join(tex_path, get_sample_name(config)), clean_tex=False)
    shellcmd = [
        "pdflatex", "-output-directory=" + tex_path,
        os.path.join(tex_path, get_sample_name(config)) + ".tex", "1>",
        "/dev/null"
    ]
    #generate_pdf doesn't run AUX files properly and ends up with incorrect total page numbers. So subprocess for
    #pdflatex is called twice instead.

    print(" ".join(shellcmd))
    subprocess.run(" ".join(shellcmd), shell=True)
    subprocess.run(" ".join(shellcmd), shell=True)
コード例 #16
0
def generate_unique():
    geometry_options = {
        "head": "40pt",
        "margin": "0.5in",
        "bottom": "0.6in",
        "includeheadfoot": True
    }
    doc = Document(geometry_options=geometry_options)

    # Generating first page style
    first_page = PageStyle("firstpage")

    # Header image
    with first_page.create(Head("L")) as header_left:
        with header_left.create(
                MiniPage(width=NoEscape(r"0.49\textwidth"),
                         pos='c')) as logo_wrapper:
            logo_file = os.path.join(os.path.dirname(__file__),
                                     'sample-logo.png')
            logo_wrapper.append(
                StandAloneGraphic(image_options="width=120px",
                                  filename=logo_file))

    # Add document title
    with first_page.create(Head("R")) as right_header:
        with right_header.create(
                MiniPage(width=NoEscape(r"0.49\textwidth"), pos='c',
                         align='r')) as title_wrapper:
            title_wrapper.append(LargeText(bold("Bank Account Statement")))
            title_wrapper.append(LineBreak())
            title_wrapper.append(MediumText(bold("Date")))

    # Add footer
    with first_page.create(Foot("C")) as footer:
        message = "Important message please read"
        with footer.create(
                Tabularx(
                    "X X X X",
                    width_argument=NoEscape(r"\textwidth"))) as footer_table:

            footer_table.add_row(
                [MultiColumn(4, align='l', data=TextColor("blue", message))])
            footer_table.add_hline(color="blue")
            footer_table.add_empty_row()

            branch_address = MiniPage(width=NoEscape(r"0.25\textwidth"),
                                      pos='t')
            branch_address.append("960 - 22nd street east")
            branch_address.append("\n")
            branch_address.append("Saskatoon, SK")

            document_details = MiniPage(width=NoEscape(r"0.25\textwidth"),
                                        pos='t',
                                        align='r')
            document_details.append("1000")
            document_details.append(LineBreak())
            document_details.append(simple_page_number())

            footer_table.add_row([
                branch_address, branch_address, branch_address,
                document_details
            ])

    doc.preamble.append(first_page)
    # End first page style

    # Add customer information
    with doc.create(Tabu("X[l] X[r]")) as first_page_table:
        customer = MiniPage(width=NoEscape(r"0.49\textwidth"), pos='h')
        customer.append("Verna Volcano")
        customer.append("\n")
        customer.append("For some Person")
        customer.append("\n")
        customer.append("Address1")
        customer.append("\n")
        customer.append("Address2")
        customer.append("\n")
        customer.append("Address3")

        # Add branch information
        branch = MiniPage(width=NoEscape(r"0.49\textwidth"),
                          pos='t!',
                          align='r')
        branch.append("Branch no.")
        branch.append(LineBreak())
        branch.append(bold("1181..."))
        branch.append(LineBreak())
        branch.append(bold("TIB Cheque"))

        first_page_table.add_row([customer, branch])
        first_page_table.add_empty_row()

    doc.change_document_style("firstpage")
    doc.add_color(name="lightgray", model="gray", description="0.80")

    # Add statement table
    with doc.create(LongTabu("X[l] X[2l] X[r] X[r] X[r]",
                             row_height=1.5)) as data_table:
        data_table.add_row(
            ["date", "description", "debits($)", "credits($)", "balance($)"],
            mapper=bold,
            color="lightgray")
        data_table.add_empty_row()
        data_table.add_hline()
        row = ["2016-JUN-01", "Test", "$100", "$1000", "-$900"]
        for i in range(30):
            if (i % 2) == 0:
                data_table.add_row(row, color="lightgray")
            else:
                data_table.add_row(row)

    doc.append(NewPage())

    # Add cheque images
    with doc.create(LongTabu("X[c] X[c]")) as cheque_table:
        cheque_file = os.path.join(os.path.dirname(__file__),
                                   'chequeexample.png')
        cheque = StandAloneGraphic(cheque_file, image_options="width=200px")
        for i in range(0, 20):
            cheque_table.add_row([cheque, cheque])

    doc.generate_pdf("complex_report", clean_tex=False)
コード例 #17
0
def generate_unique_dw(final_hvs1, final_hvs2, hl1_ch1, hl2_ch1, hl1_ch2,
                       hl2_ch2, sectors):
    geometry_options = {
        "head": "40pt",
        "margin": "0.5in",
        "bottom": "1.0in",
        "includeheadfoot": True
    }
    doc = Document(indent=False, geometry_options=geometry_options)

    # Generating first page style
    first_page = PageStyle("firstpage")

    # Header image
    with first_page.create(Head("L")) as header_left:
        with header_left.create(
                MiniPage(width=NoEscape(r"0.49\textwidth"),
                         pos='c')) as logo_wrapper:
            logo_file = os.path.join(os.path.dirname(__file__),
                                     '../cernlogo.png')
            logo_wrapper.append(
                StandAloneGraphic(image_options="width=80px",
                                  filename=logo_file))

    # Add document title
    with first_page.create(Head("R")) as right_header:
        with right_header.create(
                MiniPage(width=NoEscape(r"0.49\textwidth"), pos='c',
                         align='r')) as title_wrapper:
            title_wrapper.append(LargeText(bold("ATLAS New Small Wheel")))
            title_wrapper.append(LineBreak())
            title_wrapper.append(bold("Integration Tests"))
            title_wrapper.append(LineBreak())
            title_wrapper.append(bold(now.strftime("%d-%m-%Y")))
            title_wrapper.append(LineBreak())
            title_wrapper.append("\n")
            title_wrapper.append(
                LargeText(bold("Double Wedge: " + str(DW_name))))
            title_wrapper.append(LineBreak())

    # Add footer
    with first_page.create(Foot("C")) as footer:

        with footer.create(
                Tabularx(
                    "X X X ",
                    width_argument=NoEscape(r"\textwidth"))) as footer_table:

            footer_table.add_empty_row()

            footer_table.add_hline(color="blue")

            branch_address1 = MiniPage(width=NoEscape(r"0.25\textwidth"),
                                       pos='t')
            branch_address1.append("Lorenzo Pezzotti")
            branch_address1.append("\n")
            branch_address1.append("*****@*****.**")

            branch_address2 = MiniPage(width=NoEscape(r"0.25\textwidth"),
                                       pos='t')
            branch_address2.append("Alan Peyaud")
            branch_address2.append("\n")
            branch_address2.append("*****@*****.**")

            branch_address3 = MiniPage(width=NoEscape(r"0.25\textwidth"),
                                       pos='t')
            branch_address3.append("Ivan Gnesi")
            branch_address3.append("\n")
            branch_address3.append("*****@*****.**")

            document_details = MiniPage(width=NoEscape(r"0.2\textwidth"),
                                        pos='t',
                                        align='r')
            document_details.append(" ")
            document_details.append(LineBreak())
            document_details.append(simple_page_number())

            footer_table.add_row(
                [branch_address1, branch_address2, branch_address3])

    doc.append(first_page)
    # End first page style
    redcircle = glob.glob("redcircle.png")
    redcircle = StandAloneGraphic(redcircle, image_options="width=220px")

    # Add customer information
    with doc.create(Tabu("X[r]")) as first_page_table:
        first_page_table.add_empty_row()

    doc.change_document_style("firstpage")
    doc.add_color(name="lightgray", model="gray", description="0.80")

    doc.append("\n")
    doc.append(timeslot)
    doc.append(LineBreak())

    # IP
    with doc.create(Section('IP SIDE', numbering=False)):
        # first chamber
        # Verify if its SM1, LM1, SM1 or LM2
        if chambername1IP[0:3] == "SM1" or chambername2HO[0:3] == "LM1":
            limit = 10
        else:
            limit = 6

        with doc.create(
                Subsection("Chambers: " + chambername1IP + " + " +
                           chambername2IP,
                           numbering=False)):
            with doc.create(Subsection(chambername1IP, numbering=False)):
                with doc.create(
                        LongTabu("|X[l]|X[r]|X[r]|X[r]|X[r]|X[r]|X[r]|",
                                 row_height=1.5)) as data_table:
                    data_table.add_hline()
                    data_table.add_row(
                        ["Sector", "L1", "L2", "L3", "L4", "HL1", "HL2"],
                        mapper=bold,
                        color="lightgray")
                    data_table.add_hline()
                    row = ["blank", "l1", "l2", "l3", "l4", "hl1", "hl2"]
                    for i, hv in enumerate(final_hvs1[0]):
                        hl1_str = ""
                        hl2_str = ""
                        l1 = ""
                        l2 = ""
                        l3 = ""
                        l4 = ""
                        # assign each sector to a line
                        if hv == hl1_ch1:
                            hl1_str = str(hl1_ch1)
                        elif hv == hl2_ch1:
                            hl2_str = str(hl2_ch1)
                        elif i > limit - 1 + limit * 2:
                            l4 = "570"
                        elif i > limit - 1 + limit:
                            l3 = "570"
                        elif i > limit - 1:
                            l2 = "570"
                        else:
                            l1 = "570"
                        if (i % 2) == 0:
                            data_table.add_row([
                                str(sectors[0][i]), l1, l2, l3, l4, hl1_str,
                                hl2_str
                            ])
                        else:
                            data_table.add_row([
                                str(sectors[0][i]), l1, l2, l3, l4, hl1_str,
                                hl2_str
                            ],
                                               color="lightgray")
                    data_table.add_hline()

            # second chamber
            if chambername2IP[0:3] == "SM1" or chambername2HO[0:3] == "LM1":
                limit = 10
            else:
                limit = 6
            with doc.create(Subsection(chambername2IP, numbering=False)):
                with doc.create(
                        LongTabu("|X[l]|X[r]|X[r]|X[r]|X[r]|X[r]|X[r]|",
                                 row_height=1.5)) as data_table2:
                    data_table2.add_hline()
                    data_table2.add_row(
                        ["Sector", "L1", "L2", "L3", "L4", "HL1", "HL2"],
                        mapper=bold,
                        color="lightgray")
                    data_table2.add_hline()
                    row = ["blank", "l1", "l2", "l3", "l4", "hl1", "hl2"]
                    for i, hv in enumerate(final_hvs1[1]):
                        hl1_str = ""
                        hl2_str = ""
                        l1 = ""
                        l2 = ""
                        l3 = ""
                        l4 = ""
                        # assign each sector to a line
                        if hv == hl1_ch1:
                            hl1_str = str(hl1_ch1)
                        elif hv == hl2_ch1:
                            hl2_str = str(hl2_ch1)
                        elif i > limit - 1 + limit * 2:
                            l4 = "570"
                        elif i > limit - 1 + limit:
                            l3 = "570"
                        elif i > limit - 1:
                            l2 = "570"
                        else:
                            l1 = "570"

                        if (i % 2) == 0:
                            data_table2.add_row([
                                str(sectors[1][i]), l1, l2, l3, l4, hl1_str,
                                hl2_str
                            ])
                        else:
                            data_table2.add_row([
                                str(sectors[1][i]), l1, l2, l3, l4, hl1_str,
                                hl2_str
                            ],
                                                color="lightgray")
                    data_table2.add_hline()
    # HO
    # Swap R an L
    final_hvs2[0] = swap(final_hvs2[0])
    final_hvs2[1] = swap(final_hvs2[1])
    if chambername1HO[0:3] == "SM1" or chambername2HO[0:3] == "LM1":
        limit = 10
    else:
        limit = 6
    doc.append(NewPage())
    with doc.create(Section('HO SIDE', numbering=False)):
        # first chamber
        with doc.create(
                Subsection("Chambers: " + chambername1HO + " + " +
                           chambername2HO,
                           numbering=False)):
            with doc.create(Subsection(chambername1HO, numbering=False)):
                with doc.create(
                        LongTabu("|X[l]|X[r]|X[r]|X[r]|X[r]|X[r]|X[r]|",
                                 row_height=1.5)) as data_table3:
                    data_table3.add_hline()
                    data_table3.add_row(
                        ["Sector", "L1", "L2", "L3", "L4", "HL1", "HL2"],
                        mapper=bold,
                        color="lightgray")
                    data_table3.add_hline()
                    row = ["blank", "l1", "l2", "l3", "l4", "hl1", "hl2"]
                    for i, hv in enumerate(final_hvs2[0]):
                        hl1_str = ""
                        hl2_str = ""
                        l1 = ""
                        l2 = ""
                        l3 = ""
                        l4 = ""
                        # assign each sector to a line
                        if hv == hl1_ch2:
                            hl1_str = str(hl1_ch2)
                        elif hv == hl2_ch2:
                            hl2_str = str(hl2_ch2)
                        elif i > limit - 1 + limit * 2:
                            l4 = "570"
                        elif i > limit - 1 + limit:
                            l3 = "570"
                        elif i > limit - 1:
                            l2 = "570"
                        else:
                            l1 = "570"
                        if (i % 2) == 0:
                            data_table3.add_row([
                                str(sectors[2][i]), l1, l2, l3, l4, hl1_str,
                                hl2_str
                            ])
                        else:
                            data_table3.add_row([
                                str(sectors[2][i]), l1, l2, l3, l4, hl1_str,
                                hl2_str
                            ],
                                                color="lightgray")
                    data_table3.add_hline()

            # second chamber
            if chambername2HO[0:3] == "SM1" or chambername2HO[0:3] == "LM1":
                limit = 10
            else:
                limit = 6
            with doc.create(Subsection(chambername2HO, numbering=False)):
                with doc.create(
                        LongTabu("|X[l]|X[r]|X[r]|X[r]|X[r]|X[r]|X[r]|",
                                 row_height=1.5)) as data_table4:
                    data_table4.add_hline()
                    data_table4.add_row(
                        ["Sector", "L1", "L2", "L3", "L4", "HL1", "HL2"],
                        mapper=bold,
                        color="lightgray")
                    data_table4.add_hline()
                    row = ["blank", "l1", "l2", "l3", "l4", "hl1", "hl2"]
                    for i, hv in enumerate(final_hvs2[1]):
                        hl1_str = ""
                        hl2_str = ""
                        l1 = ""
                        l2 = ""
                        l3 = ""
                        l4 = ""
                        # assign each sector to a line
                        if hv == hl1_ch2:
                            hl1_str = str(hl1_ch2)
                        elif hv == hl2_ch2:
                            hl2_str = str(hl2_ch2)
                        elif i > limit - 1 + limit * 2:
                            l4 = "570"
                        elif i > limit - 1 + limit:
                            l3 = "570"
                        elif i > limit - 1:
                            l2 = "570"
                        else:
                            l1 = "570"

                        if (i % 2) == 0:
                            data_table4.add_row([
                                str(sectors[3][i]), l1, l2, l3, l4, hl1_str,
                                hl2_str
                            ])
                        else:
                            data_table4.add_row([
                                str(sectors[3][i]), l1, l2, l3, l4, hl1_str,
                                hl2_str
                            ],
                                                color="lightgray")
                    data_table4.add_hline()
    doc.generate_pdf("complex_report_DW", clean_tex=False, compiler='pdflatex')
コード例 #18
0
def generate_report(main_title, name, title, email, payroll):

    # For saving the report in the Desktop folder
    dir_output=os.path.join(
        '~',
        'Desktop',
        'absconbest_payroll',
        'output'
    )
    dir_output=os.path.expanduser(dir_output)
    geometry_options = {
        "head": "40pt",
        "margin": "0.5in",
        "bottom": "0.6in",
        "includeheadfoot": True
    }
    doc = Document(geometry_options=geometry_options)

    # Generating
    # first page style
    first_page = PageStyle("firstpage")

    # Header image
    with first_page.create(Head("L")) as header_left:
        with header_left.create(
            MiniPage(width=NoEscape(r"0.49\textwidth"), pos='c')
        ) as logo_wrapper:
            logo_file = 'logo.png'
            logo_wrapper.append(
                StandAloneGraphic(
                    image_options="width=120px",
                    filename=logo_file
                )
            )

    # Add document title
    with first_page.create(Head("R")) as right_header:
        with right_header.create(MiniPage(
            width=NoEscape(r"0.49\textwidth"),
            pos='c',
            align='r')
        ) as title_wrapper:
            title_wrapper.append(LargeText(bold('Payroll Report')))
            title_wrapper.append(LineBreak())
            title_wrapper.append(MediumText(bold(main_title)))

    # Add footer
    with first_page.create(Foot("C")):
        first_page.append(simple_page_number())

    doc.preamble.append(first_page)

    #Add employee information
    with doc.create(Tabu("X[l] X[r]")) as first_page_table:
        employee = MiniPage(width=NoEscape(r"0.49\textwidth"), pos='h')
        employee.append(name)
        employee.append("\n")
        employee.append(title)
        employee.append("\n")
        employee.append(email)

        #Dummy table
        branch = MiniPage(width=NoEscape(r"0.49\textwidth"), pos='t!',
                          align='r')
        # branch.append(bold("1181..."))
        # branch.append(LineBreak())
        # branch.append(bold("TIB Cheque"))

        first_page_table.add_row([employee, branch])
        first_page_table.add_empty_row()

    doc.change_document_style("firstpage")
    doc.add_color(name="lightgray", model="gray", description="0.80")

    #Add payroll table
    with doc.create(LongTabu("X[l] X[c] X[c] X[c] X[r]",
                             row_height=1.5)) as data_table:
        data_table.add_row(['Work',
                            'Rate Per Hour ($)',
                            'Time in Minutes',
                            'Time in Hours',
                            'Wage ($)'],
                           mapper=bold,
                           color="lightgray")
        data_table.add_empty_row()
        data_table.add_hline()

        #Following Pandas' API
        payroll=payroll.reset_index()
        for i in range(len(payroll.index)):
            try:
                row = [payroll['Work'][i],
                       round(payroll['Rate Per Hour'][i],0),
                       round(payroll['TIM'][i],0),
                       round(payroll['TIH'][i],3),
                       round(payroll['Wage'][i],1)]
            except TypeError:
                row = [payroll['Work'][i],
                       'n/a',
                       round(payroll['TIM'][i],0),
                       round(payroll['TIH'][i],3),
                       round(payroll['Wage'][i],1)]
            if (i%2)==0:
                data_table.add_row(row, color="lightgray")
            else:
                data_table.add_row(row)
        # data_table.add_row([payroll['Work'][l_p],
        #                     round(payroll['TIM'][l_p],0),
        #                     round(payroll['TIH'][l_p],3),
        #                     '',
        #                     round(payroll['Wage'][l_p],1)]
        # )

    doc.append(NewPage())

    doc.generate_pdf(
        filepath=os.path.join(
dir_output,
            main_title.lower().replace(" ","_").replace(",",""),
        ),
        clean_tex=True,
        clean=True,
    )