示例#1
0
def generate_eva_report():

    geometry_options = {
        "head": "40pt",
        "margin": "0.5in",
        "bottom": "0.6in",
        "includeheadfoot": True
    }
    doc = Document(geometry_options=geometry_options)

    reportStyle = PageStyle("reportStyle")

    with reportStyle.create(Head("R")) as left_header:
        with left_header.create(
                MiniPage(width=NoEscape(r"0.49\textwidth"), pos='c',
                         align='l')) as title_wrapper:
            title_wrapper.append(LargeText(bold("RiMEA-Projekt")))
            title_wrapper.append(LineBreak())
            title_wrapper.append(MediumText(bold("Anlyse")))

    doc.preamble.append(reportStyle)

    doc.change_document_style("reportStyle")

    with doc.create(LongTabu("X[c] X[c]", row_height=1.5)) as report_table:
        report_table.add_row(["Test", "evacuation time(s)"], mapper=bold)
        report_table.add_hline()

    for i in range(1, 4):
        report_table.add_row(i, get_evac_time(i)[0])

    doc.append(NewPage())

    doc.generate_pdf("RiMEA-Projekt-Evacution-Analyse", clean_tex=False)
示例#2
0
文件: args.py 项目: cmrfrd/PyLaTeX
def test_document():
    geometry_options = {
        "includeheadfoot": True,
        "headheight": "12pt",
        "headsep": "10pt",
        "landscape": True
    }

    doc = Document(default_filepath='default_filepath',
                   documentclass='article',
                   fontenc='T1',
                   inputenc='utf8',
                   lmodern=True,
                   data=None,
                   page_numbers=True,
                   indent=False,
                   document_options=["a4paper", "12pt"],
                   geometry_options=geometry_options)

    repr(doc)

    doc.append('Some text.')
    doc.change_page_style(style="empty")
    doc.change_document_style(style="plain")
    doc.add_color(name="lightgray", model="gray", description="0.6")
    doc.add_color(name="abitless", model="gray", description="0.8")
    doc.set_variable(name="myVar", value="1234")
    doc.set_variable(name="myVar", value="1234")
    doc.change_length(parameter=r"\headheight", value="0.5in")

    doc.generate_tex(filepath='')
    doc.generate_pdf(filepath='', clean=True)
示例#3
0
def generate_pdf(stroka):
    pdf_path = get_dir('odli_pdf') + '\\' +stroka.Surname +' '+ stroka.Firstname +' '+ stroka.Patronymic
    logo_image = r'miaclogo.png'

    pdf = Document(pdf_path)
    pdf.packages.add(Package('babel',options='russian'))
    pdf.packages.add(Package('pdfx', options= NoEscape('a-1b') ))
    pdf.packages.add(Package('inputenc',options='utf8'))
    pdf.packages.add(Package('fontenc',options='T2A'))
    pdf.packages.add(Package('geometry',options='a5paper'))

    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='l')) as logo_wrapper:
            logo_wrapper.append(StandAloneGraphic(image_options="width=120px",filename=logo_image))
        with header_left.create(MiniPage(width=NoEscape(r"0.49\textwidth"),pos='c')) as logo_wrapper:
            logo_wrapper.append(NoEscape("Сгенерированно в СПб ГБУЗ МИАЦ"))
            logo_wrapper.append(NewLine())
            logo_wrapper.append(NoEscape("В основе данные, предоставленные лабораториями"))
    pdf.preamble.append(first_page)

    pdf.change_document_style("firstpage")
    pdf.add_color(name="lightgray", model="gray", description="0.80")
    pdf.append(HorizontalSpace(size="500px"))
    with pdf.create(Section(NoEscape("Исследование на COVID-19"),numbering=False)):
        pdf.append(NoEscape("Наименование лаборатории: " + stroka.Name_Lab ))
        pdf.append(NewLine())
        pdf.append(NoEscape("Дата исследования: " + stroka.Date_Test))
        pdf.append(NewLine())
        pdf.append(NoEscape("Ответственный за исследование: "))
        pdf.append(NewLine())
        pdf.append(NoEscape(stroka.lab_familia +' '+ stroka.lab_name +' '+ stroka.lab_secondname))
    with pdf.create(Section(NoEscape("Пациент: ") ,numbering=False)):
        pdf.append(LargeText(NoEscape(stroka.Surname +' '+ stroka.Firstname +' '+ stroka.Patronymic)))
        pdf.append(NewLine())
        pdf.append(NewLine())
        pdf.append(NoEscape("Дата рождения: " + stroka.Birthday))
        pdf.append(NewLine())
        pdf.append(NoEscape("Паспорт: " + stroka.Passport))
        pdf.append(NewLine())
        pdf.append(NoEscape("СНИЛС: " + stroka.Snils))
        pdf.append(NewLine())
        pdf.append(NoEscape("ОМС: " + stroka.Policy_OMS))
        pdf.append(NewLine())
        pdf.append(NoEscape("Контактный номер: " + stroka.Phone))
        pdf.append(NewLine())
    with pdf.create(Section(NoEscape("Результат: "),numbering=False)):
        pdf.append(NoEscape("Качественное обнаружение короновируса SARS 2 в различных образцах: "))
        pdf.append(NewLine())
        pdf.append(NewLine())
        if stroka.Result_Test == 'ND':
            pdf.append(TextColor('green',LargeText(NoEscape('Не обнаружено'))))
        if stroka.Result_Test == 'DET':
            pdf.append(TextColor('red',LargeText(NoEscape('Обнаружено'))))

    pdf.generate_pdf(clean_tex=True,compiler='pdflatex')

    with open(pdf_path+'.pdf', "rb") as pdf_file:
        encoded_pdf = base64.b64encode(pdf_file.read()).decode()
    return encoded_pdf
示例#4
0
    def create_document(self):
        geometry = {
            "head": "40pt",
            "margin": "1in",
            "bottom": "1in",
        }

        doc = Document(geometry_options=geometry)
        page = PageStyle("pagestyle")
        with page.create(Head("L")) as header_left:
            with header_left.create(
                    MiniPage(width=NoEscape(r"0.5\textwidth"),
                             pos="c")) as logo_wrapper:
                logo_file = os.path.join(get_current_directory(),
                                         "assets/" + LOGO).replace("\\", "/")
                logo_wrapper.append(
                    StandAloneGraphic(image_options="width=120px",
                                      filename=logo_file))

        with page.create(Head("R")) as right_header:
            with right_header.create(
                    MiniPage(width=NoEscape(r"0.5\textwidth"),
                             pos="c",
                             align="r")) as title_wrapper:
                title_wrapper.append(LargeText(bold("Vindskjerming")))

        doc.preamble.append(page)
        doc.change_document_style("pagestyle")
        return doc
示例#5
0
class PdfFront(AbstractFront):
	FILE_EXTENSION = 'pdf'
	PAGE_GEOMETRY = {
		'margin': '2.0cm'
	}
	PACKAGES = ['amsfonts']

	def __init__(self):
		self._doc = Document(
			geometry_options=PdfFront.PAGE_GEOMETRY,
			page_numbers=False
		)
		for package in PdfFront.PACKAGES:
			self._doc.preamble.append(Command('usepackage', arguments=package))
	
	def _create_header(self, info):
		style_name = NoEscape('header{}'.format(info['run']))
		header = PageStyle(style_name)
		with header.create(Head('L')):
			header.append(info['name'])
			header.append(LineBreak())
			header.append('Date: {}'.format(self._date()))
		with header.create(Head('R')):
			header.append('Seed: {}'.format(info['seed']))
			header.append(LineBreak())
			header.append('Run: {}'.format(info['run']))
		self._doc.preamble.append(header)
		self._doc.change_document_style(style_name)
		
	def _write_questions(self, info):
		self._doc.append(NoEscape(r'\flushleft'))
		i = 1
		for question, answers, options in info['questions']:
			self._doc.append('{}. {}'.format(i, question))
			self._doc.append(LineBreak())
			for image in options['images']:
				with self._doc.create(Figure(position='h!')) as fig:
					fig.add_image(image['src'], width='{}px'.format(image.get('width', 100)))
					if image.get('description'):
						fig.add_caption(image.get('description'))
			i += 1
			if len(answers) == 0:
				for _ in range(options['hints'].get('max_lines', 1)):
					self._doc.append(NewLine())
			else:
				l = options['hints'].get('max_cols', 1)
				table_data = [answers[j:j+l] for j in range(0, len(answers), l)]
				with self._doc.create(Tabular('l'*l)) as table:
					for row in table_data:
						table.add_row(row, mapper = lambda x: NoEscape(r'$\Box~~$') + x, strict=False)
			self._doc.append(LineBreak())
		
	def _save(self, info):
		self._doc.generate_pdf(self._filename(info))
		
	def _add_page_separator(self):
		self._doc.append(NoEscape(r'\clearpage'))
示例#6
0
    def make_doc(self, foirequest):
        doc = Document(
            lmodern=True,
            geometry_options={
                "a4paper": True,
                "margin": "1in",
            },
        )
        # Change font
        doc.packages.append(Package('fontspec,xunicode,array'))
        doc.packages.append(Package('sectsty'))
        doc.preamble.append(NoEscape("\\usepackage{helvet}"))
        doc.preamble.append(
            NoEscape("\\sectionfont{\\fontsize{12}{15}\\selectfont}"))

        # Adjust description list
        doc.packages.append(Package('enumitem'))
        doc.preamble.append(
            NoEscape(
                "\\setlist[description]{labelindent=0cm,style=multiline,leftmargin=1.5cm}"
            ))

        # Hyphenation
        doc.append(NoEscape("\\lefthyphenmin=5"))
        doc.append(NoEscape("\\sloppy"))

        # doc.preamble.append(Command('title', foirequest.title))
        # doc.preamble.append(Command('author', foirequest.get_absolute_domain_short_url()))
        # doc.preamble.append(Command('date', NoEscape('\\today')))
        # doc.append(NoEscape('\\maketitle'))

        # Set up header and footer
        header = PageStyle("header")
        with header.create(Foot("L")):
            header.append(italic(settings.SITE_NAME))
        with header.create(Head("C")):
            header.append(foirequest.title)
        with header.create(Foot("R")):
            header.append(
                str(
                    _('Request #{request_no}').format(
                        request_no=foirequest.pk)))
        with header.create(Foot("C")):
            header.append(
                italic(NoEscape(r'Seite \thepage\ von \pageref{LastPage}')))
        doc.preamble.append(header)
        doc.change_document_style("header")

        for i, message in enumerate(foirequest.messages):
            last = i == len(foirequest.messages) - 1
            add_message_to_doc(doc, message)
            if not last:
                doc.append(NewPage())

        return doc
示例#7
0
def make_doc(file,
             title,
             author,
             geometry_options={"margin": "1.15cm"},
             options=""):
    """ Create and return a formatted Pylatex Document with my data
    
    Parameters
    ----------
    file = Path() (from pathlib) to ifentify the tex and pdf output files
    
    Returns
    ----------
    The document class

    """

    # geometry_options = {"tmargin": "1.5cm", "lmargin": "2.5cm"},

    doc = Document(default_filepath=file.as_posix(),
                   documentclass='article',
                   document_options=['12pt', 'titlepage'] + options,
                   fontenc="T1",
                   inputenc=ENCODING,
                   font_size="normalsize",
                   lmodern=True,
                   page_numbers=False,
                   indent=False,
                   geometry_options=geometry_options)
    doc.change_document_style("empty")
    date = str(datetime.datetime.date(datetime.datetime.now()))
    comment(doc.preamble, "Automatically generated by make on " + date)

    doc.preamble.append(Command("usepackage", "graphicx"))
    doc.preamble.append(Command("usepackage", "enumitem"))
    doc.preamble.append(Command("usepackage", "url"))
    doc.preamble.append(NoEscape("\\setcounter{secnumdepth}{0}"))
    doc.preamble.append(Command("usepackage", "titlesec"))
    doc.preamble.append(NoEscape("\\titlespacing\\section{0pt}{12pt}{12pt}"))
    doc.preamble.append(
        NoEscape("\\titlespacing\\subsection{0pt}{12pt}{12pt}"))
    doc.preamble.append(Command("title", title.title()))
    doc.preamble.append(Command("author", author.title()))
    doc.preamble.append(Command("date", NoEscape(r'\today')))
    doc.append(NoEscape(r'\maketitle'))
    return doc
示例#8
0
def generate_style(schema: PLDSchema, locale: LocaleDictionary,
                   document: Document) -> Document:
    document.preamble.append(
        UnsafeCommand("newcommand",
                      Command("rowWidth"),
                      extra_arguments=NoEscape("\\linewidth-(\\tabcolsep*2)")))
    document.preamble.append(
        Command('renewcommand',
                NoEscape('\\familydefault'),
                extra_arguments=NoEscape('\\sfdefault')))
    document.preamble.append(
        Command("graphicspath", NoEscape("{assets/}{../assets/}")))
    header = PageStyle("header")
    with header.create(Head("L")) as left_header:
        left_header: Head
        left_header.create(
            StandAloneGraphic("primary_logo.pdf", NoEscape("width=30pt")))
    with header.create(Head("R")) as right_header:
        right_header: Head
        right_header.append(LargeText(locale.project_log_document))
    with header.create(Foot("R")) as right_footer:
        right_footer: Foot
        right_footer.append(
            NoEscape(
                f"{locale.page} \\thepage\\ {locale.of} \\pageref{{LastPage}}")
        )
    with header.create(Foot("L")) as left_footer:
        left_footer: Foot
        left_footer.append(
            StandAloneGraphic("secondary_logo.pdf", NoEscape("width=100pt")))
    document.preamble.append(
        Command(
            "title",
            NoEscape(
                StandAloneGraphic("primary_logo.pdf", NoEscape(
                    "width=100pt")).dumps() + "~\\\\[1cm]\n" +
                locale.project_log_document)))
    now = datetime.date.today()
    document.preamble.append(
        Command("date", f"{now.day}/{now.month}/{now.year}"))
    document.preamble.append(
        Command("author", NoEscape("\\and ".join(schema.authors))))
    document.preamble.append(header)
    document.change_document_style("header")

    return document
示例#9
0
def compile_document_week(no):
    "produce a pdf of the weeks workout"

    # input accessory lifts for main lifts
    bench = [('Decline DB Press (4 x 12)'), ('Face pull (4 x 12)'),
             ('Low/High flyes ss/w press (4 x 12)'), ('Press ups (4 x Max)')]
    # squat = [('Leg press (4 x 15)'), ('Leg extension (4 x 12)'),
    #          ('Leg curl (4 x 12)'), ('Roll out (4 x Max)')]
    squat = [('Smith Front/Back (4 x 12)'), ('Calf Raises (4 x 12)'),
             ('Walking Lunges (4 x 12)'), ('Roll out (4 x Max)')]
    dead = [('Pendlay Row (4 x 8-12)'), ('Hip thrust (4 x 8-12)'),
            ('Pull up (4 x Max)'), ('Leg raise (4 x 8-12)')]
    press = [('Landmine press (4 x 8-12)'), ('Lateral/Rear raises (4 x 8-12)'),
             ('DB Curls (4 x 8-12)'), ('Roll outs (4 x Max)')]

    acc = [bench, squat, press, dead]

    # input main lifts and one rep maxes
    # last updated 21/03/2017
    main_lifts = [('Bench', 90), ('Squat', 128), ('Military Press', 63),
                  ('Deadlift', 143)]

    date = t.strftime("%d/%m/%Y")
    doc = Document()
    doc.packages.append(Package('geometry', options=['margin=2cm']))
    doc.packages.append(Package('times'))
    doc.packages.append(Package('float'))
    doc.packages.append(Package('graphicx'))
    header = generate_header()
    doc.preamble.append(header)
    doc.change_document_style("header")

    # Add title
    doc.append(LineBreak())
    doc.append(LargeText(bold("8/6/3 Workout Routine")))
    doc.append(LineBreak())
    doc.append(MediumText(bold("As of: " + date)))
    doc.append(LineBreak())

    # Add workout for a week
    gen_week(doc, main_lifts, no, acc)
    date_1 = t.strftime("%Y%m%d")
    directory = "/home/thomas/Documents/workout_print/workouts"
    filename = (directory + "/workout_routine_week_" + str(no) + "_" + date_1)
    doc.generate_pdf(filename, clean_tex=True)
示例#10
0
def generate_labels():
    geometry_options = {"margin": "0.5in"}
    doc = Document(geometry_options=geometry_options)

    doc.change_document_style("empty")

    for i in range(10):
        with doc.create(MiniPage(width=r"0.5\textwidth")):
            doc.append("Vladimir Gorovikov")
            doc.append("\n")
            doc.append("Company Name")
            doc.append("\n")
            doc.append("Somewhere, City")
            doc.append("\n")
            doc.append("Country")

        if (i % 2) == 1:
            doc.append(VerticalSpace("20pt"))
            doc.append(LineBreak())

    doc.generate_pdf("minipage", clean_tex=False)
示例#11
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')
示例#12
0
def wrap_table_in_latex_document(table: str,
                                 landscape: bool = False,
                                 margin: float = 1.5) -> str:
    """
    Wraps a table inside a proper latex document.

    Uses ``\\longtable`` instead of ``\\tabular`` to fit data on multiple pages.

    Args:
        table: table string to wrap the document around
        landscape: whether to layout the table in landscape mode
        margin: margin around the table in cm

    Returns:
        the resulting latex document as a string
    """
    doc = Document(documentclass="scrbook",
                   document_options="paper=a4",
                   geometry_options={
                       "margin": f"{margin}cm",
                       "landscape": "true" if landscape else "false"
                   })
    # set monospace font
    monospace_comm = UnsafeCommand('renewcommand',
                                   r'\familydefault',
                                   extra_arguments=r'\ttdefault')
    doc.preamble.append(monospace_comm)

    doc.packages.append(Package('longtable'))
    doc.packages.append(Package('booktabs'))

    doc.change_document_style("empty")

    # embed latex table inside document
    doc.append(NoEscape(table))

    return tp.cast(str, doc.dumps())
示例#13
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("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)
示例#14
0
def generate_unique():
    geometry_options = {
        "head": "40pt",
        "margin": "0.5in",
        "bottom": "0.6in",
        "includeheadfoot": True
    }
    doc = Document(geometry_options=geometry_options,
                   document_options="a4paper")

    # 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__), logo_name)
            logo_wrapper.append(
                StandAloneGraphic(image_options="width=50px",
                                  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("Sjain ventures ltd")))
            title_wrapper.append(LineBreak())
            title_wrapper.append(MediumText(bold("C-246, Vallabhnagar")))
            title_wrapper.append(LineBreak())
            # title_wrapper.append(TextColor("gray", MediumText(bold("Raipur, CG"))))
            title_wrapper.append(MediumText(bold("Raipur, CG")))

    # 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])

    # Newly added
    with first_page.create(Foot("L")) as right_footer:
        with right_footer.create(
                MiniPage(width=NoEscape(r"0.49\textwidth"), pos='l',
                         align='l')) as contact_wrapper:
            contact_wrapper.append(MediumText(bold("Alok Kumar Sharma")))
            contact_wrapper.append(LineBreak())
            contact_wrapper.append(MediumText("*****@*****.**"))
            contact_wrapper.append(LineBreak())
            contact_wrapper.append(MediumText("+91 7877681234"))

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

    # Add customer information
    with doc.create(Tabu("X[r]")) as first_page_table:
        # customer = MiniPage(width=NoEscape(r"0.9\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("http://sjainventures.com")
        branch.append(LineBreak())
        branch.append("*****@*****.**")
        # branch.append(LineBreak())
        # branch.append("+91 7877681234")

        first_page_table.add_row([branch])  # [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(25):
    #         if (i % 2) == 0:
    #             data_table.add_row(row, color="lightgray")
    #         else:
    #             data_table.add_row(row)

    with doc.create(Paragraph("Dear Rishikesh,")) as para1:
        para1.append(lorem_ipsum.LOREM_IPSUM_TEXT2)

    # 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__),
    #                                'facebook_logo.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)
示例#15
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
    def save_latex(self,
                   uiObj,
                   Design_Check,
                   reportsummary,
                   filename,
                   rel_path,
                   Disp_2d_image,
                   Disp_3d_image,
                   module=''):
        companyname = str(reportsummary["ProfileSummary"]['CompanyName'])
        companylogo = str(reportsummary["ProfileSummary"]['CompanyLogo'])
        groupteamname = str(reportsummary["ProfileSummary"]['Group/TeamName'])
        designer = str(reportsummary["ProfileSummary"]['Designer'])
        projecttitle = str(reportsummary['ProjectTitle'])
        subtitle = str(reportsummary['Subtitle'])
        jobnumber = str(reportsummary['JobNumber'])
        client = str(reportsummary['Client'])

        does_design_exist = reportsummary['does_design_exist']
        osdagheader = '/ResourceFiles/images/Osdag_header_report.png'
        # Add document header
        geometry_options = {
            "top": "5cm",
            "hmargin": "2cm",
            "headheight": "100pt",
            "footskip": "100pt",
            "bottom": "5cm"
        }
        doc = Document(geometry_options=geometry_options, indent=False)
        doc.packages.append(Package('amsmath'))
        doc.packages.append(Package('graphicx'))
        doc.packages.append(Package('needspace'))
        doc.append(pyl.Command('fontsize', arguments=[8, 12]))
        doc.append(pyl.Command('selectfont'))

        doc.add_color('OsdagGreen', 'RGB', '153,169,36')
        doc.add_color('PassColor', 'RGB', '153,169,36')
        doc.add_color('Red', 'RGB', '255,0,0')
        doc.add_color('Green', 'RGB', '0,200,0')
        doc.add_color('FailColor', 'HTML', '933A16')
        header = PageStyle("header")
        # Create center header
        with header.create(Head("C")):
            with header.create(Tabularx('|l|p{4cm}|l|X|')) as table:
                table.add_hline()
                # MultiColumn(4)
                table.add_row((
                    MultiColumn(
                        2,
                        align='|c|',
                        data=('' if companylogo is '' else StandAloneGraphic(
                            image_options="height=0.95cm",
                            filename=companylogo))),
                    MultiColumn(2,
                                align='|c|',
                                data=[
                                    'Created with',
                                    StandAloneGraphic(
                                        image_options="width=4.0cm,height=1cm",
                                        filename=rel_path + osdagheader)
                                ]),
                ))
                table.add_hline()
                table.add_row(('Company Name', companyname, 'Project Title',
                               projecttitle),
                              color='OsdagGreen')
                table.add_hline()
                table.add_row(
                    ('Group/Team Name', groupteamname, 'Subtitle', subtitle),
                    color='OsdagGreen')
                table.add_hline()
                table.add_row(('Designer', designer, 'Job Number', jobnumber),
                              color='OsdagGreen')
                table.add_hline()
                table.add_row(
                    ('Date', time.strftime("%d /%m /%Y"), 'Client', client),
                    color='OsdagGreen')
                table.add_hline()

        # Create right footer
        with header.create(Foot("R")):
            header.append(NoEscape(r'Page \thepage'))
        #
        # doc.preamble.append(header)
        # doc.change_document_style("header")

        # Add Heading
        # with doc.create(MiniPage(align='c')):

        doc.preamble.append(header)
        doc.change_document_style("header")
        with doc.create(Section('Input Parameters')):
            with doc.create(
                    LongTable('|p{5cm}|p{2.5cm}|p{1.5cm}|p{3cm}|p{3.5cm}|',
                              row_height=1.2)) as table:
                table.add_hline()
                for i in uiObj:
                    # row_cells = ('9', MultiColumn(3, align='|c|', data='Multicolumn not on left'))
                    if i == "Selected Section Details" or i == KEY_DISP_ANGLE_LIST or i == KEY_DISP_TOPANGLE_LIST or i == KEY_DISP_CLEAT_ANGLE_LIST:
                        # if type(uiObj[i]) == list:
                        continue
                    if type(uiObj[i]) == dict:
                        table.add_hline()
                        sectiondetails = uiObj[i]
                        image_name = sectiondetails[KEY_DISP_SEC_PROFILE]

                        Img_path = '/ResourceFiles/images/' + image_name + '.png'
                        if (len(sectiondetails)) % 2 == 0:
                            # merge_rows = int(round_up(len(sectiondetails),2)/2 + 2)
                            merge_rows = int((len(sectiondetails) / 2)) + 2
                        else:
                            merge_rows = round_up((len(sectiondetails) / 2), 2)
                        if (len(sectiondetails)) % 2 == 0:
                            sectiondetails[''] = ''

                        a = list(sectiondetails.keys())
                        # index=0
                        for x in range(1, (merge_rows + 1)):
                            # table.add_row("Col.Det.",i,columndetails[i])
                            if x == 1:
                                table.add_row((
                                    MultiRow(
                                        merge_rows,
                                        data=StandAloneGraphic(
                                            image_options=
                                            "width=5cm,height=5cm",
                                            filename=rel_path + Img_path)),
                                    MultiColumn(2, align='|c|', data=a[x]),
                                    MultiColumn(2,
                                                align='|c|',
                                                data=sectiondetails[a[x]]),
                                ))
                            elif x <= 4:
                                table.add_row((
                                    '',
                                    MultiColumn(2,
                                                align='|c|',
                                                data=NoEscape(a[x])),
                                    MultiColumn(2,
                                                align='|c|',
                                                data=NoEscape(
                                                    sectiondetails[a[x]])),
                                ))
                            else:
                                table.add_row((
                                    '',
                                    NoEscape(a[x]),
                                    sectiondetails[a[x]],
                                    NoEscape(a[merge_rows + x - 4]),
                                    sectiondetails[a[merge_rows + x - 4]],
                                ))
                            table.add_hline(2, 5)
                    elif uiObj[i] == "TITLE":
                        table.add_hline()
                        table.add_row((MultiColumn(
                            5,
                            align='|c|',
                            data=bold(i),
                        ), ))
                        table.add_hline()
                    elif i == 'Section Size*':
                        table.add_hline()
                        table.add_row((
                            MultiColumn(
                                3,
                                align='|c|',
                                data=i,
                            ),
                            MultiColumn(2,
                                        align='|c|',
                                        data="Ref List of Input Section"),
                        ))
                        table.add_hline()
                    elif len(str(uiObj[i])) > 55 and type(
                            uiObj[i]) != pyl.math.Math:
                        str_len = len(str(uiObj[i]))
                        loop_len = round_up((str_len / 55), 1, 1)
                        for j in range(1, loop_len + 1):
                            b = 55 * j + 1
                            if j == 1:
                                table.add_row((
                                    MultiColumn(3,
                                                align='|c|',
                                                data=MultiRow(loop_len,
                                                              data=i)),
                                    MultiColumn(2,
                                                align='|c|',
                                                data=uiObj[i][0:b]),
                                ))
                            else:
                                table.add_row((
                                    MultiColumn(3,
                                                align='|c|',
                                                data=MultiRow(loop_len,
                                                              data="")),
                                    MultiColumn(2,
                                                align='|c|',
                                                data=uiObj[i][b - 55:b]),
                                ))
                        table.add_hline()
                    else:
                        table.add_hline()
                        table.add_row((
                            MultiColumn(3, align='|c|', data=NoEscape(i)),
                            MultiColumn(2, align='|c|', data=uiObj[i]),
                        ))
                        table.add_hline()
            for i in uiObj:
                if i == 'Section Size*' or i == KEY_DISP_ANGLE_LIST or i == KEY_DISP_TOPANGLE_LIST or i == KEY_DISP_CLEAT_ANGLE_LIST:
                    with doc.create(Subsection("List of Input Section")):
                        # with doc.create(LongTable('|p{8cm}|p{8cm}|', row_height=1.2)) as table:
                        with doc.create(Tabularx('|p{4cm}|X|',
                                                 row_height=1.2)) as table:
                            table.add_hline()
                            table.add_row((
                                MultiColumn(
                                    1,
                                    align='|c|',
                                    data=i,
                                ),
                                MultiColumn(1,
                                            align='|X|',
                                            data=uiObj[i].strip("[]")),
                            ))
                            # str_len = len(uiObj[i])
                            # loop_len = round_up((str_len/100),1,1)
                            # table.add_hline()
                            # for j in range(1,loop_len+1):
                            #     b= 100*j+1
                            #     if j ==1:
                            #         table.add_row((MultiColumn(1, align='|c|', data=i, ),
                            #                        MultiColumn(1, align='|X|', data=uiObj[i][0:b]),))
                            #     else:
                            #         table.add_row((MultiColumn(1, align='|c|', data=" ", ),
                            #                        MultiColumn(1, align='|X|', data=uiObj[i][b-100:b]),))
                            table.add_hline()

        doc.append(
            pyl.Command('Needspace', arguments=NoEscape(r'10\baselineskip')))
        doc.append(NewPage())
        count = 0
        with doc.create(Section('Design Checks')):
            with doc.create(
                    Tabularx(
                        r'|>{\centering}p{12.5cm}|>{\centering\arraybackslash}X|',
                        row_height=1.2)) as table:
                table.add_hline()
                # Fail = TextColor("FailColor", bold("Fail"))
                # Pass = TextColor("PassColor", bold("Pass"))

                if does_design_exist != True:
                    table.add_row(bold('Design Status'),
                                  color_cell("Red", bold("Fail")))
                else:
                    table.add_row(bold('Design Status'),
                                  color_cell("OsdagGreen", bold("Pass")))
                table.add_hline()

            for check in Design_Check:

                if check[0] == 'SubSection':
                    if count >= 1:
                        # doc.append(NewPage())
                        doc.append(
                            pyl.Command(
                                'Needspace',
                                arguments=NoEscape(r'10\baselineskip')))
                    with doc.create(Subsection(check[1])):
                        #########################
                        # if uiObj== "WELDImage":
                        #     table.add_hline()
                        #     table.add_row((MultiColumn(5, align='|c|', data=bold(i), ),))
                        #     table.add_hline()
                        # else:
                        #########################
                        with doc.create(LongTable(check[2], row_height=1.2)
                                        ) as table:  # todo anjali remove
                            table.add_hline()
                            table.add_row(
                                ('Check', 'Required', 'Provided', 'Remarks'),
                                color='OsdagGreen')
                            table.add_hline()
                            table.end_table_header()
                            table.add_hline()
                            count = count + 1
                elif check[0] == "Selected":
                    if count >= 1:
                        # doc.append(NewPage())
                        doc.append(
                            pyl.Command(
                                'Needspace',
                                arguments=NoEscape(r'10\baselineskip')))
                    with doc.create(Subsection(check[1])):
                        with doc.create(LongTable(check[2],
                                                  row_height=1.2)) as table:
                            table.add_hline()
                            for i in uiObj:
                                # row_cells = ('9', MultiColumn(3, align='|c|', data='Multicolumn not on left'))

                                print(i)
                                if type(
                                        uiObj[i]
                                ) == dict and i == 'Selected Section Details':
                                    table.add_hline()
                                    sectiondetails = uiObj[i]
                                    image_name = sectiondetails[
                                        KEY_DISP_SEC_PROFILE]
                                    Img_path = '/ResourceFiles/images/' + image_name + '.png'
                                    if (len(sectiondetails)) % 2 == 0:
                                        # merge_rows = int(round_up(len(sectiondetails),2)/2 + 2)
                                        merge_rows = int(
                                            round_up((len(sectiondetails) /
                                                      2), 1, 0) + 2)
                                    else:
                                        merge_rows = int(
                                            round_up((len(sectiondetails) /
                                                      2), 1, 0) + 1)
                                    print('Hi',
                                          len(sectiondetails) / 2,
                                          round_up(len(sectiondetails), 2) / 2,
                                          merge_rows)
                                    if (len(sectiondetails)) % 2 == 0:
                                        sectiondetails[''] = ''
                                    a = list(sectiondetails.keys())
                                    # index=0
                                    for x in range(1, (merge_rows + 1)):
                                        # table.add_row("Col.Det.",i,columndetails[i])
                                        if x == 1:
                                            table.add_row((
                                                MultiRow(
                                                    merge_rows,
                                                    data=StandAloneGraphic(
                                                        image_options=
                                                        "width=5cm,height=5cm",
                                                        filename=rel_path +
                                                        Img_path)),
                                                MultiColumn(2,
                                                            align='|c|',
                                                            data=NoEscape(
                                                                a[x])),
                                                MultiColumn(
                                                    2,
                                                    align='|c|',
                                                    data=NoEscape(
                                                        sectiondetails[a[x]])),
                                            ))
                                        elif x <= 4:
                                            table.add_row((
                                                '',
                                                MultiColumn(2,
                                                            align='|c|',
                                                            data=NoEscape(
                                                                a[x])),
                                                MultiColumn(
                                                    2,
                                                    align='|c|',
                                                    data=sectiondetails[a[x]]),
                                            ))
                                        else:
                                            table.add_row((
                                                '',
                                                NoEscape(a[x]),
                                                sectiondetails[a[x]],
                                                NoEscape(a[merge_rows + x -
                                                           4]),
                                                sectiondetails[a[merge_rows +
                                                                 x - 4]],
                                            ))

                                        table.add_hline(2, 5)
                            table.add_hline()
                        count = count + 1
                else:

                    if check[3] == 'Fail':
                        table.add_row((NoEscape(check[0])), check[1], check[2],
                                      TextColor("Red", bold(check[3])))
                    else:
                        table.add_row((NoEscape(check[0])), check[1], check[2],
                                      TextColor("OsdagGreen", bold(check[3])))
                    table.add_hline()

        # 2D images
        if len(Disp_2d_image) != 0:

            if module == KEY_DISP_BCENDPLATE or module == KEY_DISP_BB_EP_SPLICE:
                if does_design_exist and sys.platform != 'darwin':
                    doc.append(NewPage())
                    weld_details = rel_path + Disp_2d_image[0]
                    detailing_details = rel_path + Disp_2d_image[1]
                    stiffener_details = rel_path + Disp_2d_image[2]

                    with doc.create(Section('2D Drawings (Typical)')):

                        with doc.create(Figure()) as image:
                            image.add_image(weld_details,
                                            width=NoEscape(r'0.7\textwidth'),
                                            placement=NoEscape(r'\centering'))
                            image.add_caption(
                                'Typical Weld Details -- Beam to End Plate Connection'
                            )
                            # doc.append(NewPage())

                        with doc.create(Figure()) as image_2:
                            image_2.add_image(
                                detailing_details,
                                width=NoEscape(r'0.7\textwidth'),
                                placement=NoEscape(r'\centering'))
                            image_2.add_caption('Typical Detailing')
                            # doc.append(NewPage())

                        with doc.create(Figure()) as image_3:
                            image_3.add_image(
                                stiffener_details,
                                width=NoEscape(r'0.9\textwidth'),
                                placement=NoEscape(r'\centering'))
                            image_3.add_caption('Typical Stiffener Details')
                            # doc.append(NewPage())

            elif module == KEY_DISP_BASE_PLATE:
                if does_design_exist and sys.platform != 'darwin':
                    doc.append(NewPage())
                    bp_sketch = rel_path + Disp_2d_image[0]
                    bp_detailing = rel_path + Disp_2d_image[1]
                    bp_weld = rel_path + Disp_2d_image[2]
                    bp_anchor = rel_path + Disp_2d_image[3]
                    bp_key = rel_path + Disp_2d_image[4]

                    with doc.create(Section('2D Drawings (Typical)')):
                        with doc.create(Figure()) as image_1:
                            image_1.add_image(
                                bp_sketch,
                                width=NoEscape(r'1.0\textwidth'),
                                placement=NoEscape(r'\centering'))
                            image_1.add_caption('Typical Base Plate Details')
                            # doc.append(NewPage())

                        with doc.create(Figure()) as image_2:
                            image_2.add_image(
                                bp_detailing,
                                width=NoEscape(r'1.0\textwidth'),
                                placement=NoEscape(r'\centering'))
                            image_2.add_caption('Typical Base Plate Detailing')
                            # doc.append(NewPage())

                        with doc.create(Figure()) as image_3:
                            image_3.add_image(
                                bp_weld,
                                width=NoEscape(r'1.0\textwidth'),
                                placement=NoEscape(r'\centering'))
                            image_3.add_caption('Typical Weld Details')
                            # doc.append(NewPage())

                        with doc.create(Figure()) as image_4:
                            image_4.add_image(
                                bp_anchor,
                                width=NoEscape(r'0.5\textwidth'),
                                placement=NoEscape(r'\centering'))
                            image_4.add_caption('Typical Anchor Bolt Details')
                            # doc.append(NewPage())

                        if len(Disp_2d_image[-1]) > 0:
                            with doc.create(Figure()) as image_5:
                                image_5.add_image(
                                    bp_key,
                                    width=NoEscape(r'0.9\textwidth'),
                                    placement=NoEscape(r'\centering'))
                                image_5.add_caption(
                                    'Typical Shear Key Details')
                                # doc.append(NewPage())

        if does_design_exist and sys.platform != 'darwin':
            doc.append(NewPage())
            Disp_top_image = "/ResourceFiles/images/top.png"
            Disp_side_image = "/ResourceFiles/images/side.png"
            Disp_front_image = "/ResourceFiles/images/front.png"
            view_3dimg_path = rel_path + Disp_3d_image
            view_topimg_path = rel_path + Disp_top_image
            view_sideimg_path = rel_path + Disp_side_image
            view_frontimg_path = rel_path + Disp_front_image
            with doc.create(Section('3D Views')):
                with doc.create(
                        Tabularx(
                            r'|>{\centering}X|>{\centering\arraybackslash}X|',
                            row_height=1.2)) as table:
                    view_3dimg_path = rel_path + Disp_3d_image
                    view_topimg_path = rel_path + Disp_top_image
                    view_sideimg_path = rel_path + Disp_side_image
                    view_frontimg_path = rel_path + Disp_front_image
                    table.add_hline()
                    table.add_row([
                        StandAloneGraphic(image_options="height=4cm",
                                          filename=view_3dimg_path),
                        StandAloneGraphic(image_options="height=4cm",
                                          filename=view_topimg_path)
                    ])
                    table.add_row('(a) 3D View', '(b) Top View')
                    table.add_hline()
                    table.add_row([
                        StandAloneGraphic(image_options="height=4cm",
                                          filename=view_sideimg_path),
                        StandAloneGraphic(image_options="height=4cm",
                                          filename=view_frontimg_path)
                    ])
                    table.add_row('(c) Side View', '(d) Front View')
                    table.add_hline()
                # with doc.create(Figure(position='h!')) as view_3D:
                #     view_3dimg_path = rel_path + Disp_3d_image
                #     # view_3D.add_image(filename=view_3dimg_path, width=NoEscape(r'\linewidth'))
                #
                #     view_3D.add_image(filename=view_3dimg_path,width=NoEscape(r'\linewidth,height=6.5cm'))
                #
                #     view_3D.add_caption('3D View')

        with doc.create(Section('Design Log')):
            doc.append(
                pyl.Command('Needspace',
                            arguments=NoEscape(r'10\baselineskip')))
            logger_msgs = reportsummary['logger_messages'].split('\n')
            for msg in logger_msgs:
                if ('WARNING' in msg):
                    colour = 'blue'
                elif ('INFO' in msg):
                    colour = 'OsdagGreen'
                elif ('ERROR' in msg):
                    colour = 'red'
                else:
                    continue
                doc.append(TextColor(colour, '\n' + msg))
        try:
            doc.generate_pdf(filename, compiler='pdflatex', clean_tex=False)
        except:
            pass
示例#17
0
    def generar(self, Carrera, Asignatura, Curso, listaPreguntas, aleatorio):

        today = str(self.__fecha)

        geometry_options = {
            "head": "48pt",
            "margin": "0.5in",
            "bottom": "0.6in",
            "includeheadfoot": True
        }

        doc = Document(geometry_options=geometry_options)

        header = PageStyle("header")  # DEFINIMOS LA VARIABLE CON ESTILO

        #image_filename = os.path.join(os.path.dirname("__file__"), '../static/zigmap.png') # IMAGEN UNAB

        #data_folder = os.path.join("../", "static/zigmap.png")

        #file_to_open = os.path.join(data_folder, "zigmap.png")

        #image_filename = data_folder
        image_filename = "zigmap.png"

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

        # Header image
        with first_page.create(Head("L")) as header_left:

            with header_left.create(
                    SubFigure(
                        position='L',
                        width=NoEscape(r'0.10\linewidth'))) as logo_wrapper:

                print("IMAGEN")
                #logo_wrapper.add_image('zigmap.png', width=NoEscape(r'\linewidth'))

        # Add document title
        with first_page.create(Head("C")) as center_header:
            with center_header.create(
                    MiniPage(width=NoEscape(r"0.49\textwidth"),
                             pos='c',
                             align='c')) as title_wrapper:
                title_wrapper.append(LargeText(bold(self.__nombre)))

        # 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("Solemne II")))
                #title_wrapper.append(LineBreak())
                title_wrapper.append(MediumText(bold(
                    Asignatura.get_nombreA())))

        # Add footer
        with first_page.create(Foot("C")) as footer:
            message = "Programación II"
            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("black", message))
                ])
                footer_table.add_hline(color="black")
                footer_table.add_empty_row()

                branch_address = MiniPage(width=NoEscape(r"0.45\textwidth"),
                                          pos='t',
                                          align='l')
                branch_address.append(
                    MediumText("Facultad de " + Carrera.get_facultad()))
                branch_address.append("\n")
                branch_address.append("")

                branch_address2 = MiniPage(width=NoEscape(r"0.10\textwidth"),
                                           pos='t')
                branch_address2.append("")
                branch_address2.append("\n")
                branch_address2.append("")

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

                footer_table.add_row([
                    branch_address, branch_address2, branch_address2,
                    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.55\textwidth"), pos='h')
            customer.append("Nombre: ___________________________________")
            customer.append("\n")
            customer.append("    Rut:  _______________")
            customer.append("\n")
            customer.append("Nota: ______________")
            customer.append("\n")
            customer.append("\n")

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

            if self.__unidad == "unidad1":
                branch.append(bold("Unidad: 1"))
            elif self.__unidad == "unidad2":
                branch.append(bold("Unidad: 2"))
            else:
                branch.append(bold("Unidades: 1 & 2"))
            branch.append(LineBreak())

            branch.append(bold("Curso: "))
            branch.append(bold(Curso.get_cod()))
            branch.append(LineBreak())

            branch.append(bold("Ponderación: "))
            branch.append(bold(self.__ponderacion + "%"))
            branch.append(LineBreak())

            first_page_table.add_row([customer, branch])

        doc.append(LargeText(bold("Indicaciones:")))

        # INDICACIONES

        with doc.create(Itemize()) as itemize:
            doc.append(LineBreak())
            itemize.add_item(
                " Lea atentamente los enunciados de cada pregunta antes de contestar."
            )
            itemize.add_item(
                " Conteste su evaluación en silencio, está prohibido conversar o gesticulizar en la sala durante la prueba."
            )
            itemize.add_item(
                " Dispone de 90 minutos para realizar esta evaluación.")
            itemize.add_item(
                " Marque la alternativa con lapiz pasta, no se aceptan marcadas con lapiz grafito."
            )
            itemize.add_item(
                " Utilice solamente sus materiales, está prohibido solicitar materiales a sus compañeros."
            )
            # you can append to existing items
            itemize.append(Command("ldots"))

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

        now = str(datetime.today())

        for p in listaPreguntas:
            with doc.create(Section('Pregunta - ' + p.get_tipo())):

                doc.append(p.get_contenido())

        doc.append(NewPage())

        nombreFile = str(
            self.__nombre) + " - " + self.get_fecha() + " - " + str(aleatorio)

        print(
            "--------------------------ANTES DE DIR------------------------------"
        )

        try:
            # GENERANDO PDF
            doc.generate_pdf(filepath="tests/" + nombreFile,
                             clean_tex=True,
                             clean=True)
            #doc.generate_pdf(dirName + "/" + nombreFile, clean_tex=False)

        except FileNotFoundError as e:
            doc.generate_pdf(filepath="../tests/" + nombreFile,
                             clean_tex=True,
                             clean=True)
示例#18
0
class RelatorioCliente:
    def __init__(self, nomeArquivo, usuario, db=None):
        self.nomeArquivo = nomeArquivo
        self.usuarioModel = UsuarioModel().fromList(usuario)

        self.geometry = {
            'head': '40pt',
            'margin': '1.5cm',
            'tmargin': '1cm',
            'includeheadfoot': True
        }
        self.documento = Document(f'{self.nomeArquivo}',
                                  geometry_options=self.geometry,
                                  page_numbers=False)
        self.firstPage = None

        self.daoClientes = DaoCliente(db=db)

        # Estatísticas
        self.totalClientes = 0
        self.clientesAtivos = 0
        self.clientesInativos = 0
        self.mediaClientesAtivos = 0
        self.clientesList = None
        self.carregarClientes()
        self.contaTotalClientes()

    def constroiCabecalho(self):
        self.firstPage = PageStyle('firstpage')

        with self.firstPage.create(Head("L")) as header_left:
            with header_left.create(
                    MiniPage(width=NoEscape(r"0.3\textwidth"),
                             pos='l')) as logo_wrapper:
                with logo_wrapper.create(
                        Tabularx('X X',
                                 width_argument=NoEscape(
                                     r"0.5\textwidth"))) as logo:
                    logo.add_row([MultiColumn(2, align='c')])
                    logo_file = os.path.join(os.getcwd(), 'Telas', 'Imagens',
                                             'nautilusDash.png')
                    imagem = StandAloneGraphic(image_options="width=36px",
                                               filename=logo_file)
                    textLogo = MiniPage(width=NoEscape(r"0.6\textwidth"),
                                        content_pos='t',
                                        align='l')

                    textLogo.append(LargeText(bold('Nautilus')))
                    textLogo.append(LineBreak())
                    textLogo.append('Navegue sem medo')
                    textLogo.append(LineBreak())
                    textLogo.append('\n')

                    logo.add_row([imagem, textLogo])

        with self.firstPage.create(Head("C")) as headerCenter:
            with headerCenter.create(
                    MiniPage(width=NoEscape(r"0.4\textwidth"),
                             pos='c')) as centro:
                centro.append(LargeText(bold('Relatório geral de clientes')))

        # Add document title
        with self.firstPage.create(Head("R")) as right_header:
            with right_header.create(
                    MiniPage(width=NoEscape(r"0.3\textwidth"),
                             pos='R',
                             align='r')) as title_wrapper:
                title_wrapper.append(
                    LargeText(bold(self.usuarioModel.nomeEmpresa)))
                title_wrapper.append(LineBreak())
                title_wrapper.append(
                    MediumText(mascaraMeses(data=datetime.date.today())))

    def constroiCorpo(self):

        with self.documento.create(Tabu("X[l] X[r]")) as first_page_table:
            customer = MiniPage(width=NoEscape(r"0.49\textwidth"), pos='h')
            customer.append(bold("Nome fantasia: "))
            customer.append(self.usuarioModel.nomeFantasia)
            customer.append("\n")
            customer.append(bold("CNPJ: "))
            customer.append(mascaraCNPJ(self.usuarioModel.cnpj))
            customer.append("\n")
            customer.append(bold("Endereço: "))
            if self.usuarioModel.endereco == 'None':
                customer.append('---')
            else:
                customer.append(self.usuarioModel.endereco)

            # Add branch information
            branch = MiniPage(width=NoEscape(r"0.49\textwidth"),
                              pos='t!',
                              align='r')
            branch.append(f"Total de clientes: {self.totalClientes}")
            branch.append(LineBreak())
            branch.append(f"Total de clientes Ativos: {self.clientesAtivos}")
            branch.append(LineBreak())
            branch.append(
                f"Média de clientes ativos: {round((self.clientesAtivos / self.totalClientes)*100)} % "
            )
            branch.append(LineBreak())

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

        self.documento.change_document_style("firstpage")

        with self.documento.create(
                LongTabu("X[1.5l] X[2l] X[r] X[r] X[r]",
                         row_height=1.5)) as data_table:
            data_table.add_row([
                "Última atualização", "Nome do cliente", "Turma", "credits($)",
                "balance($)"
            ],
                               mapper=bold,
                               color="lightgray")
            data_table.add_empty_row()
            data_table.add_hline()
            for i, cliente in enumerate(self.clientesList):
                clienteRow = list()
                clienteRow.append(mascaraMeses(cliente[13]))
                clienteRow.append(cliente[1] + ' ' + cliente[2])
                clienteRow.append('Teste 1')
                clienteRow.append('Teste 2')
                clienteRow.append('Teste 3')
                if (i % 2) == 0:
                    data_table.add_row(clienteRow, color="lightgray")
                else:
                    data_table.add_row(clienteRow)

    def exportaRelatorio(self, tipo='pdf'):

        # Desenvolvimento
        fileName = QFileDialog.getSaveFileName(
            directory=str(Path.home()),
            options=QFileDialog.DontUseNativeDialog,
            filter="Adobe Pdf (*.pdf);;Excel (*.xlsx)")

        # Produção
        # fileName = QFileDialog.getSaveFileName(directory=str(Path.home()), filter="Adobe Pdf (*.pdf);;Excel (*.xlsx)")
        print(f'\033[33m{fileName}')

        if fileName[0] != '':
            if '*.pdf' in fileName[1]:
                self.constroiCabecalho()
                self.constroiCorpo()
                self.documento.preamble.append(self.firstPage)
                self.documento.generate_pdf(fileName[0], clean_tex=False)
            else:
                self.exportaExcel(fileName[0])

    def contaTotalClientes(self):
        self.totalClientes = self.daoClientes.contaTotal()
        self.clientesAtivos = self.daoClientes.contaTotal(
            where='WHERE ativo = TRUE')
        self.clientesInativos = self.totalClientes - self.clientesAtivos

    def carregarClientes(self):
        self.clientesList = self.daoClientes.findAll(all=True)

    def exportaExcel(self, path):

        colunas = [
            'Inscrição', 'Nome', 'Sobrenome', 'Telefone', 'E-mail', 'CPF',
            'Endereço', 'Complemento', 'CEP', 'Bairro', 'Meio de Pagamento',
            'Usuário ativo', 'Data do Cadastro', 'Última atualização'
        ]

        dataFrameClientes = pd.DataFrame(self.clientesList, columns=colunas)

        excelWriter = pd.ExcelWriter(f'{path}.xlsx', endine='openpyxl')

        dataFrameClientes.to_excel(excel_writer=excelWriter, index=False)
        excelWriter.save()
示例#19
0
class PimaReport:
    def __init__(self, analysis):

        self.analysis = analysis
        self.report = analysis.report
        self.doc = None

    def start_doc(self):

        geometry_options = {"margin": "0.75in"}
        self.doc = Document(geometry_options=geometry_options)
        self.doc.preamble.append(Command('usepackage{float}'))

    def add_header(self):

        header_text = 'Analysis of ' + self.report['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')

    def add_summary(self):

        with self.doc.create(
                Section(self.analysis.summary_title, numbering=False)):

            with self.doc.create(Subsection('Run information',
                                            numbering=False)):
                with self.doc.create(Tabular('lp{6cm}lp{20cm}',
                                             width=2)) as table:
                    table.add_row(('Date', self.analysis.start_time))
                    if self.analysis.ont_fast5:
                        table.add_row(('ONT FAST5', self.analysis.ont_fast5))
                    if self.analysis.ont_raw_fastq:
                        table.add_row(
                            ('ONT FASTQ', self.analysis.ont_raw_fastq))
                    if self.analysis.illumina_fastq:
                        table.add_row(
                            ('Illumina FASTQ',
                             ', '.join(self.analysis.illumina_fastq)))
                    if self.analysis.genome_fasta:
                        table.add_row(('Assembly', self.analysis.genome_fasta))
                    if self.analysis.reference_fasta:
                        table.add_row(
                            ('Reference', self.analysis.reference_fasta))

                self.doc.append(VerticalSpace("10pt"))

            if not (self.analysis.ont_n50 is None):
                with self.doc.create(
                        Subsection('ONT library statistics', numbering=False)):
                    with self.doc.create(Tabular('ll', width=2)) as table:
                        table.add_row(
                            ('ONT N50', '{:,}'.format(self.analysis.ont_n50)))
                        table.add_row(
                            ('ONT reads',
                             '{:,}'.format(self.analysis.ont_read_count)))
                        table.add_row(('ONT bases',
                                       '{:s}'.format(self.analysis.ont_bases)))
                    self.doc.append(VerticalSpace("10pt"))

            if not (self.analysis.illumina_length_mean is None):
                with self.doc.create(
                        Subsection('Illumina library statistics',
                                   numbering=False)):
                    with self.doc.create(Tabular('ll', width=2)) as table:
                        table.add_row(('Illumina mean length', '{:.1f}'.format(
                            self.analysis.illumina_length_mean)))
                        table.add_row(
                            ('Illumina reads',
                             '{:,}'.format(self.analysis.illumina_read_count)))
                        table.add_row(
                            ('Illumina bases',
                             '{:s}'.format(self.analysis.illumina_bases)))
                    self.doc.append(VerticalSpace("10pt"))

            if not (self.analysis.genome is None):
                with self.doc.create(
                        Subsection('Assembly statistics', numbering=False)):
                    with self.doc.create(Tabular('ll', width=2)) as table:
                        table.add_row(('Contigs', len(self.analysis.genome)))

                        genome_size = 0
                        for i in self.analysis.genome:
                            genome_size += len(i.seq)
                        genome_size = si_format(genome_size, precision=1)
                        table.add_row(('Assembly size', genome_size))

                    self.doc.append(VerticalSpace("10pt"))

            if len(self.report[self.analysis.assembly_title]) > 0:
                if len(self.report[self.analysis.assembly_title][
                        self.analysis.assembly_notes_title]) > 0:
                    with self.doc.create(
                            Subsection(self.analysis.assembly_notes_title,
                                       numbering=False)):
                        left = FlushLeft()
                        for note in self.report[self.analysis.assembly_title][
                                self.analysis.assembly_notes_title]:
                            left.append(note)
                            left.append(LineBreak())
                        self.doc.append(left)
                    self.doc.append(VerticalSpace("10pt"))

            if not (self.analysis.contig_info is None):

                for method in ['ONT', 'Illumina']:

                    if not method in self.analysis.contig_info.index:
                        continue

                    with self.doc.create(
                            Subsection('Assembly coverage by ' + method,
                                       numbering=False)):

                        table_format = 'l' * self.analysis.contig_info[
                            method].shape[1]

                        self.doc.append('')

                        with self.doc.create(Tabular(table_format)) as table:
                            table.add_row(
                                ('Contig', 'Length (bp)', 'Coverage (X)'))
                            table.add_hline()
                            formatted = self.analysis.contig_info[method].copy(
                            )
                            formatted.iloc[:, 1] = formatted.iloc[:, 1].apply(
                                lambda x: '{:,}'.format(x))
                            for i in range(self.analysis.contig_info[method].
                                           shape[0]):
                                table.add_row(
                                    formatted.iloc[i, :].values.tolist())

                        self.doc.append(LineBreak())
                        self.doc.append(VerticalSpace("10pt"))

    def add_alignment(self):

        if len(self.report[self.analysis.alignment_title][
                self.analysis.contig_alignment_title]) > 0:
            alignments = self.report[self.analysis.alignment_title][
                self.analysis.contig_alignment_title]
        else:
            return

        self.doc.append(NewPage())

        with self.doc.create(
                Section(self.analysis.alignment_title, numbering=False)):

            with self.doc.create(
                    Subsection(self.analysis.snp_indel_title,
                               numbering=False)):

                with self.doc.create(Tabular('ll', width=2)) as table:
                    table.add_row(
                        ('SNPs',
                         '{:,}'.format(self.analysis.quast_mismatches)))
                    table.add_row(('Small indels',
                                   '{:,}'.format(self.analysis.quast_indels)))
                self.doc.append(LineBreak())

            if len(self.report[self.analysis.alignment_title][
                    self.analysis.alignment_notes_title]) > 0:

                with self.doc.create(
                        Subsection(self.analysis.alignment_notes_title,
                                   numbering=False)):

                    left = FlushLeft()
                    for note in self.report[self.analysis.alignment_title][
                            self.analysis.alignment_notes_title]:
                        left.append(note)
                        left.append(LineBreak())
                    self.doc.append(left)

            for contig in alignments.index.tolist():

                contig_title = 'Alignment to ' + contig
                self.doc.append(
                    Command('graphicspath{{../circos/' + contig + '/}}'))
                image_png = os.path.basename(alignments[contig])

                with self.doc.create(Subsection(contig_title,
                                                numbering=False)):
                    with self.doc.create(Figure(position='H')) as figure:
                        figure.add_image(image_png, width='5in')

    def add_features(self):

        if len(self.report[self.analysis.feature_title]) == 0:
            return

        self.doc.append(NewPage())

        with self.doc.create(
                Section(self.analysis.feature_title, numbering=False)):
            for feature_name in self.report[
                    self.analysis.feature_title].index.tolist():

                features = self.report[
                    self.analysis.feature_title][feature_name].copy()
                if features.shape[0] == 0:
                    continue
                features.iloc[:, 1] = features.iloc[:, 1].apply(
                    lambda x: '{:,}'.format(x))
                features.iloc[:, 2] = features.iloc[:, 2].apply(
                    lambda x: '{:,}'.format(x))

                table_format = 'l' * (features.shape[1] - 1)

                with self.doc.create(Subsection(feature_name,
                                                numbering=False)):
                    if (features.shape[0] == 0):
                        self.doc.append('None')
                        continue

                    for contig in pandas.unique(features.iloc[:, 0]):

                        self.doc.append(contig)

                        contig_features = features.loc[(
                            features.iloc[:, 0] == contig), :]

                        with self.doc.create(Tabular(table_format)) as table:
                            table.add_row(('Start', 'Stop', 'Feature',
                                           'Identity (%)', 'Strand'))
                            table.add_hline()
                            for i in range(contig_features.shape[0]):
                                feature = contig_features.iloc[i, :].copy(
                                    deep=True)
                                feature[4] = '{:.3f}'.format(feature[4])
                                table.add_row(feature[1:].values.tolist())

                        self.doc.append(LineBreak())
                        self.doc.append(VerticalSpace("10pt"))

    def add_feature_plots(self):

        if len(self.report[self.analysis.feature_plot_title]) == 0:
            return

        self.doc.append(NewPage())

        self.doc.append(Command('graphicspath{{../drawing/}}'))

        with self.doc.create(Section('Feature plots', numbering=False)):

            self.doc.append('Only contigs with features are shown')

            for contig in self.report[
                    self.analysis.feature_plot_title].index.tolist():

                image_png = os.path.basename(
                    self.report[self.analysis.feature_plot_title][contig])

                with self.doc.create(Figure(position='h!')) as figure:
                    figure.add_image(image_png, width='7in')

    def add_mutations(self):

        # Make sure we looked for mutations
        if len(self.report[self.analysis.mutation_title]) == 0:
            return

        mutations = self.report[self.analysis.mutation_title]

        self.doc.append(NewPage())

        table_format = 'l' * 4

        with self.doc.create(
                Section(self.analysis.mutation_title, numbering=False)):

            for region_name in mutations.index.tolist():

                region_mutations = mutations[region_name].copy()

                with self.doc.create(Subsection(region_name, numbering=False)):
                    if (region_mutations.shape[0] == 0):
                        self.doc.append('None')
                        continue

                    region_mutations.iloc[:,
                                          1] = region_mutations.iloc[:, 1].apply(
                                              lambda x: '{:,}'.format(x))

                    with self.doc.create(Tabular(table_format)) as table:
                        table.add_row(('Reference contig', 'Position',
                                       'Reference', 'Alternate'))
                        table.add_hline()
                        for i in range(region_mutations.shape[0]):
                            table.add_row(region_mutations.iloc[
                                i, [0, 1, 3, 4]].values.tolist())

    def add_amr_matrix(self):

        # Make sure that we have an AMR matrix to plot
        amr_matrix = self.report[self.analysis.amr_matrix_title]

        if len(amr_matrix) == 0:
            return

        if amr_matrix is None:
            return

        self.doc.append(NewPage())

        with self.doc.create(
                Section(self.analysis.amr_matrix_title, numbering=False)):

            self.doc.append(
                'AMR genes and mutations with their corresponding drugs.')

            self.doc.append(Command('graphicspath{{../}}'))

            with self.doc.create(Figure(position='h!')) as figure:
                figure.add_image(amr_matrix['png'], width='7in')

    def add_large_indels(self):

        # Make sure we looked for mutations
        if len(self.report[self.analysis.large_indel_title]) == 0:
            return

        large_indels = self.report[self.analysis.large_indel_title]

        if large_indels is None:
            return

        self.doc.append(NewPage())

        with self.doc.create(
                Section(self.analysis.large_indel_title, numbering=False)):

            for genome in ['Reference insertions', 'Query insertions']:

                genome_indels = large_indels[genome].copy()

                with self.doc.create(Subsection(genome, numbering=False)):
                    if (genome_indels.shape[0] == 0):
                        self.doc.append('None')
                        continue

                    genome_indels.iloc[:, 1] = genome_indels.iloc[:, 1].apply(
                        lambda x: '{:,}'.format(x))
                    genome_indels.iloc[:, 2] = genome_indels.iloc[:, 2].apply(
                        lambda x: '{:,}'.format(x))
                    genome_indels.iloc[:, 3] = genome_indels.iloc[:, 3].apply(
                        lambda x: '{:,}'.format(x))

                    table_format = 'l' * genome_indels.shape[1]

                    with self.doc.create(Tabular(table_format)) as table:
                        table.add_row(
                            ('Reference contig', 'Start', 'Stop', 'Size (bp)'))
                        table.add_hline()
                        for i in range(genome_indels.shape[0]):
                            table.add_row(
                                genome_indels.iloc[i, :].values.tolist())

    def add_plasmids(self):

        if len(self.report[self.analysis.plasmid_title]) == 0:
            return

        # Make sure we looked for mutations
        plasmids = self.report[self.analysis.plasmid_title].copy()

        if plasmids is None:
            return

        self.doc.append(NewPage())

        with self.doc.create(
                Section(self.analysis.plasmid_title, numbering=False)):

            if (plasmids.shape[0] == 0):
                self.doc.append('None')
                return

            plasmids.iloc[:, 3] = plasmids.iloc[:, 3].apply(
                lambda x: '{:,}'.format(x))
            plasmids.iloc[:, 4] = plasmids.iloc[:, 4].apply(
                lambda x: '{:,}'.format(x))
            plasmids.iloc[:, 5] = plasmids.iloc[:, 5].apply(
                lambda x: '{:,}'.format(x))

            table_format = 'p{0.15\linewidth}p{0.3\linewidth}p{0.1\linewidth}p{0.08\linewidth}p{0.08\linewidth}p{0.08\linewidth}'

            with self.doc.create(Tabular(table_format)) as table:
                table.add_row(('Genome contig', 'Plasmid hit', 'Plasmid acc.',
                               'Contig size', 'Aliged', 'Plasmid size'))
                table.add_hline()
                for i in range(plasmids.shape[0]):
                    table.add_row(plasmids.iloc[i, 0:6].values.tolist())

    def add_methods(self):

        self.doc.append(NewPage())

        methods = self.report[self.analysis.methods_title]

        with self.doc.create(
                Section(self.analysis.methods_title, numbering=False)):

            for methods_section in methods.index.tolist():

                if len(methods[methods_section]) == 0:
                    continue

                with self.doc.create(
                        Subsection(methods_section, numbering=False)):

                    self.doc.append('  '.join(methods[methods_section]))

    def make_tex(self):

        self.doc.generate_tex(self.analysis.report_prefix)

    def make_report(self):

        self.start_doc()
        self.add_header()
        self.add_summary()
        self.add_alignment()
        self.add_features()
        self.add_feature_plots()
        self.add_mutations()
        self.add_large_indels()
        self.add_plasmids()
        self.add_amr_matrix()
        #self.add_snps()
        self.add_methods()
        self.make_tex()
    def save_latex(self, reportsummary, filename, rel_path, Disp_3d_image):
        companyname = str(reportsummary["ProfileSummary"]['CompanyName'])
        companylogo = str(reportsummary["ProfileSummary"]['CompanyLogo'])
        groupteamname = str(reportsummary["ProfileSummary"]['Group/TeamName'])
        designer = str(reportsummary["ProfileSummary"]['Designer'])
        projecttitle = str(reportsummary['ProjectTitle'])
        subtitle = str(reportsummary['Subtitle'])
        jobnumber = str(reportsummary['JobNumber'])
        client = str(reportsummary['Client'])

        header = PageStyle("header")
        # Create center header
        with header.create(Head("C")):
            with header.create(Tabularx('|l|p{6cm}|l|X|')) as table:
                table.add_hline()
                # MultiColumn(4)
                table.add_row(('Company Name', companyname, 'Project Title',
                               projecttitle),
                              color='OsdagGreen')
                table.add_hline()
                table.add_row(
                    ('Group/Team Name', groupteamname, 'Subtitle', subtitle),
                    color='OsdagGreen')
                table.add_hline()
                table.add_row(('Designer', designer, 'Job Number', jobnumber),
                              color='OsdagGreen')
                table.add_hline()
                table.add_row(
                    ('Date', time.strftime("%d /%m /%Y"), 'Client', client),
                    color='OsdagGreen')
                table.add_hline()
        # Create right footer
        with header.create(Foot("R")):
            header.append(NoEscape(r'Page \thepage'))

        geometry_options = {
            "top": "1.2in",
            "bottom": "1in",
            "left": "0.6in",
            "right": "0.6in",
            "headsep": "0.8in"
        }
        doc = Document(geometry_options=geometry_options, indent=False)
        doc.packages.append(Package('amsmath'))
        doc.packages.append(Package('graphicx'))
        doc.packages.append(Package('needspace'))
        doc.add_color('OsdagGreen', 'HTML', 'D5DF93')
        doc.preamble.append(header)
        doc.change_document_style("header")

        with doc.create(Section('Design Conclusion')):
            with doc.create(Tabularx('|X|X|', row_height=1.2)) as table:
                table.add_hline()
                table.add_row(('Section Designation', 'Remarks'),
                              color='OsdagGreen')
                table.add_hline()
                table.add_row(
                    (reportsummary['Define Section']['Section Designation'],
                     'Pass'))
                table.add_hline()

        with doc.create(Section('Section Details')):
            with doc.create(Tabularx('|X|X|', row_height=1.2)) as table:
                table.add_hline()
                table.add_row(
                    (bold('Section Type'),
                     reportsummary['Define Section']['Section Type']))
                table.add_hline()
                table.add_row(
                    (bold('Section Template'),
                     reportsummary['Define Section']['Section Template']))
                table.add_hline()

        with doc.create(Section('Section Parameters')):
            with doc.create(Tabularx('|X|X|', row_height=1.2)) as table:
                for parameter in reportsummary['Define Section'][
                        'Section Parameters']:
                    para = reportsummary['Define Section'][
                        'Section Parameters'][parameter]
                    table.add_hline()
                    table.add_row((bold(para[0]), para[1]))
                table.add_hline()

        labels = [
            'Area, a(cm²)',
            'Moment of Inertia',
            'I_zz(cm4)',
            'I_yy(cm4)',
            'Radius of Gyration',
            'r_zz(cm)',
            'r_yy(cm)',
            'Centriod',
            'c_z(cm)',
            'c_y(cm)',
            'Plastic Section modulus',
            'Z_pz(cm³)',
            'Z_py(cm³)',
            'Elastic Section modulus',
            'Z_zz(cm³)',
            'Z_yy(cm³)',
        ]
        values = list(reportsummary['Section Properties'].values())
        Properties = [
            (labels[0], values[0]),
            (labels[1], ""),
            (labels[2], values[1]),
            (labels[3], values[2]),
            (labels[4], ""),
            (labels[5], values[3]),
            (labels[6], values[4]),
            (labels[7], ""),
            (labels[8], values[5]),
            (labels[9], values[6]),
            (labels[10], ""),
            (labels[11], values[7]),
            (labels[12], values[8]),
            (labels[13], ""),
            (labels[14], values[9]),
            (labels[15], values[10]),
        ]

        with doc.create(Section('Section Properties')):
            with doc.create(Tabularx('|X|X|', row_height=1.2)) as table:
                for ppty in Properties:
                    table.add_hline()
                    table.add_row((bold(ppty[0]), ppty[1]))
                table.add_hline()
        doc.append(NewPage())

        if (not 'TRAVIS' in os.environ):
            with doc.create(Section('3D View')):
                with doc.create(Figure(position='h!')) as view_3D:
                    view_3dimg_path = rel_path + Disp_3d_image
                    # view_3D.add_image(filename=view_3dimg_path, width=NoEscape(r'\linewidth'))
                    view_3D.add_image(filename=view_3dimg_path)

                    view_3D.add_caption('3D View')
        try:
            doc.generate_pdf(filename, compiler='pdflatex', clean_tex=False)
        except:
            pass
示例#21
0
def generate_unique(cpm):
    geometry_options = {
        "head": "60pt",
        "margin": "0.5in",
        "bottom": "0.6in",
        "includeheadfoot": True
    }
    doc = Document(geometry_options=geometry_options)

    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',
                         align='L')) as logo_wrapper:
            logo_file = os.path.join(current_app.root_path,
                                     "static/logo/sf.png")
            logo_wrapper.append(
                StandAloneGraphic(image_options="width=120px",
                                  filename=logo_file))

    with first_page.create(Head("R")) as header_right:
        with header_right.create(
                MiniPage(width=NoEscape(r'0.49\textwidth'), pos='c',
                         align='r')) as wrapper_right:
            wrapper_right.append(LargeText(bold('SOCIALFISH')))
            wrapper_right.append(LineBreak())
            wrapper_right.append(MediumText(bold('UNDEADSEC')))
            wrapper_right.append(LineBreak())
            wrapper_right.append(NoEscape(r'\today'))

    with first_page.create(Head('C')) as header_center:
        header_center.append('CAPTURE REPORT')

    with first_page.create(Foot("C")) as footer:
        message = "Important message please read"

    doc.preamble.append(first_page)

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

        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")

    with doc.create(LongTabu("X[15l]", row_height=1.8)) as data_table:
        data_table.add_row(["Organization\nCapture IP\nBrowser\nLog\n"],
                           mapper=bold,
                           color="lightgray")
        data_table.add_empty_row()
        data_table.add_hline()

        result_query, result_count = generate_report(cpm)
        x = 0

        for i in range(result_count):

            url = result_query[1 + x].split('//')[1]
            ip = result_query[7 + x]
            log_dict = literal_eval(result_query[2 + x])

            if 'skstamp' in log_dict.keys():
                rm_trash = log_dict.pop('skstamp')
            elif 'utf8' in log_dict.keys():
                rm_trash = log_dict.pop('utf8')

            browser = result_query[4 + x] + ' v' + result_query[5 + x]
            x = 8 * (i + 1)

            row_tex = [
                url + '\n' + ip + '\n' + browser + '\n' + str(log_dict) + '\n'
            ]

            if (i % 2) == 0:
                data_table.add_row(row_tex, color="lightgray")
            else:
                data_table.add_row(row_tex)

    doc.append(NewPage())
    pdf_name = 'Report{}'.format(strftime('-%y%m'))
    doc.generate_pdf(pdf_name, clean_tex=False)
    open_new(os.getcwd() + '/' + pdf_name + '.pdf')
示例#22
0
class TestCreator:
    def __init__(self, questions):
        self.all_qs = questions.all_questions
        self.headers = questions.headings
        self.folder = questions.folder
        self.filename, self.extension = os.path.splitext(
            os.path.basename(questions.wordfile))
        self.doc = None
        self.convert()

    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

    def mcExamOptions(self,
                      output='concept',
                      versions=4,
                      version=1,
                      randomq='true',
                      randoma='true'):
        #output=concept, exam, key, answers, analysis
        options = 'output=' + output + ', '
        options += 'numberofversions=' + str(versions) + ', '
        options += 'version=' + str(version) + ', '
        options += 'seed=' + str(7) + ', '
        options += 'randomizequestions=' + randomq + ', '
        options += 'randomizeanswers=' + randoma + ', '
        options += 'writeRfile=' + 'false'
        return options

    def keep_qandas_together(self):
        # Code to keep the questions and answers on the same page
        # Returns an Arguments type
        linewidthCmd = Command(command='linewidth')
        labelWidthCmd = Command(command='labelwidth')
        beginMiniPgCmd = Command(
            command='begin',
            arguments='minipage',
            options='t',
            extra_arguments=NoEscape(linewidthCmd.dumps() + '-' +
                                     labelWidthCmd.dumps()))
        endMiniPgCmd = Command(command='end', arguments='minipage')
        parCmd = Command(command='par')
        arg2 = NoEscape(beginMiniPgCmd.dumps())
        arg3 = NoEscape(endMiniPgCmd.dumps() + parCmd.dumps())
        return Arguments('setmcquestion', arg2, arg3)

    def addAnswerList(self, question):
        self.doc.append(Command('begin', arguments='mcanswerslist'))

        if question.alloftheabove and question.noneoftheabove:
            self.doc.append(NoEscape("[permutenone]"))
        elif question.alloftheabove or question.noneoftheabove:
            self.doc.append(NoEscape("[fixlast]"))

        for index in range(0, len(question.choices)):
            if str(index + 1) == question.answer:
                opt = 'correct'
            else:
                opt = ''

            self.doc.append(Command('answer', options=opt))
            self.strip_tags(question.choices[index])

        self.doc.append(Command('end', 'mcanswerslist'))

    def addQuestion(self, question):
        if question.instructions != None:
            self.doc.append(Command('begin', 'mcquestioninstruction'))
            self.doc.append(question.instructions)
            self.doc.append(Command('end', 'mcquestioninstruction'))

        self.doc.append(Command('question'))
        self.strip_tags(question.question)

        self.addAnswerList(question)

    def add_allQs(self):
        for quest in self.all_qs:
            self.addQuestion(quest)

    def strip_tags(self, string):
        while '\\' in string:
            # Find slash, grab the text before the slash (left), find the other locations
            # that are key - the braces - and grab the key and the emphaszied text, then
            # send the rest of the rest of the string back through the while loop in case
            # there are other tags that need to be stripped
            # TODO: what happens if text is both italicized and underlined?

            slashLocation = string.find('\\')
            left = string[:slashLocation]
            textStart = string.find('{')
            tag = string[slashLocation + 1:textStart]
            tagEnd = string.find('}')
            emphasizedText = string[textStart + 1:tagEnd]
            #            if '\\' in emphasizedText:
            # so ... with a double tag ... you have to
            # update where the tagEnd is, put the left stuff in the document
            # put the first tag in and the first part of the emphasized text in
            # then the strip the tags from the new emphasized text
            # and what do you do with the right side ... hmmmm
            #                self.strip_tags(emphasizedText)

            # Append the text as appropriate
            self.doc.append(left)
            if tag == 'underline':
                self.doc.append(Command('underline', emphasizedText))
            elif tag == 'textit':
                self.doc.append(italic(emphasizedText))
            elif tag == 'textbf':
                self.doc.append(bold(emphasizedText))
            else:
                self.doc.append(emphasizedText)
            if string[tagEnd + 1:tagEnd + 2] == ' ':  # Force a space
                self.doc.append(bold(' '))
            string = string[
                tagEnd +
                1:]  # remove what was added to the doc already from the string


#   After the while loop is done, if there is any string left, append it (it is not emphasized)
        self.doc.append(string)

    def add_instructions(self, instructions):
        # Leaving this in its own method in case we want to add different formatting for the instructions
        self.strip_tags(instructions)

    def add_mcexam_package(self,
                           output='exam',
                           version=1,
                           versions=4,
                           randomq='true',
                           randoma='true'):
        return Package(
            'mcexam',
            self.mcExamOptions(
                output=output,  #concept, exam, key, answers, analysis
                versions=versions,
                version=version,
                randomq=randomq,
                randoma=randoma))

    def add_packages(self,
                     output,
                     version,
                     versions=4,
                     randomq='true',
                     randoma='true'):
        #        self.doc.packages.append(Package('mcexam', self.mcExamOptions('concept', 4, 1, 'true', 'true')))
        self.doc.packages.append(
            self.add_mcexam_package(output, version, versions, randomq,
                                    randoma))
        self.doc.packages.append(Package('calc'))
        self.doc.packages.append(Package('geometry', options='margin=0.75in'))

    def convert(self, versions=4, randomq='true', randoma='true'):
        #create_qs()
        newfolder = self.folder + '/' + self.filename
        if not os.path.exists(newfolder):
            os.mkdir(newfolder)

        output = 'exam'  # output needs to run through a list to get all versions
        for output in {'exam', 'answers', 'key'}:
            for version in range(1, versions + 1):
                if output == 'key' and version > 1:  # Only create 1 key document with all versions
                    break

                self.doc = Document(document_options="letter")
                self.add_packages(output, version, versions, randomq, randoma)

                self.doc.preamble.append(
                    Command(command='renewenvironment',
                            arguments=self.keep_qandas_together()))
                self.doc.preamble.append(
                    self.generate_header(output, Teacher.NAME,
                                         self.headers.section,
                                         self.headers.test_name, version))
                self.doc.change_document_style("header")

                self.add_instructions(self.headers.instructions)
                self.doc.append(Command('begin', 'mcquestions'))
                self.add_allQs()
                self.doc.append(Command('end', 'mcquestions'))

                #        self.doc.generate_pdf('basic_maketitle2', clean_tex=False, compiler='pdflatex')
                if (output == 'key'):
                    newfilename = newfolder + '/' + self.filename + '_' + output
                else:
                    newfilename = newfolder + '/' + self.filename + '_' + output + '_v' + str(
                        version)
                self.doc.generate_pdf(newfilename,
                                      clean_tex=False,
                                      compiler='pdflatex')
                print("." + " " + newfilename)
示例#23
0
class PimaReport:
    def __init__(self, analysis):

        self.analysis = analysis
        self.doc = None

        self.summary_title = 'Summary'
        self.basecalling_title = 'Basecalling'
        self.assembly_notes_title = 'Assembly notes'
        self.alignment_title = 'Comparison with reference'
        self.alignment_notes_title = 'Alignment notes'
        self.contig_alignment_title = 'Alignment vs. reference contigs'
        self.large_indel_title = 'Large insertions & deletions'
        self.snp_indel_title = 'SNPs and small indels'
        self.feature_title = 'Features found in the assembly'
        self.feature_plot_title = 'Feature annotation plots'
        self.mutation_title = 'Mutations found in the sample'
        self.amr_matrix_title = 'AMR matrix'

        self.methods = pd.Series(dtype='float64')
        self.methods_title = 'Methods'
        self.basecalling_methods_title = 'Basecalling'
        self.contamination_methods_title = 'Contamination check'
        self.methods[self.contamination_methods_title] = pd.Series(
            dtype='float64')
        self.assembly_methods_title = 'Assembly'
        self.methods[self.assembly_methods_title] = pd.Series(dtype='float64')
        self.reference_methods_title = 'Reference comparison'
        self.methods[self.reference_methods_title] = pd.Series(dtype='float64')
        self.mutation_methods_title = 'Mutation screening'
        self.methods[self.mutation_methods_title] = pd.Series(dtype='float64')
        self.feature_methods_title = 'Feature annotation'
        self.methods[self.feature_methods_title] = pd.Series(dtype='float64')
        self.plasmid_methods_title = 'Plasmid annotation'
        self.methods[self.plasmid_methods_title] = pd.Series(dtype='float64')

    def start_doc(self):

        geometry_options = {"margin": "0.75in"}
        self.doc = Document(geometry_options=geometry_options)
        self.doc.preamble.append(Command('usepackage{float}'))

    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')

    def add_summary(self):

        with self.doc.create(Section(self.summary_title, numbering=False)):

            with self.doc.create(Subsection('CDC Advisory',
                                            numbering=False)) as subsection:
                self.doc.append(cdc_advisory)

            self.add_run_information()

            self.add_ont_library_information()

            methods = []
            if self.analysis.did_guppy_ont_fast5:
                methods += [
                    'ONT reads were basecalled using guppy (v ' +
                    self.analysis.versions['guppy'] + ').'
                ]
            if self.analysis.did_qcat_ont_fastq:
                methods += [
                    'ONT reads were demultiplexed and trimmed using qcat (v ' +
                    self.analysis.versions['qcat'] + ').'
                ]
            self.methods[self.basecalling_methods_title] = pd.Series(methods)

            self.add_illumina_library_information()
            self.add_assembly_information()
            self.add_contig_info()
            self.add_assembly_notes()

            if self.analysis.did_flye_ont_fastq:
                method = 'ONT reads were assembled using Flye (v ' + self.analysis.versions[
                    'flye'] + ').'
                self.methods[self.assembly_methods_title] = self.methods[
                    self.assembly_methods_title].append(pd.Series(method))
            if self.analysis.did_medaka_ont_assembly:
                method = 'The genome assembly was polished using ONT reads and Medaka (v ' +\
                    self.analysis.versions['medaka'] + ').'
                self.methods[self.assembly_methods_title] = self.methods[
                    self.assembly_methods_title].append(pd.Series(method))

    def add_run_information(self):

        with self.doc.create(Subsection('Run information', numbering=False)):
            with self.doc.create(
                    Tabular('p{0.15\linewidth}p{0.65\linewidth}',
                            width=2)) as table:
                table.add_row(('Date', self.analysis.start_time))
                if self.analysis.ont_fast5:
                    table.add_row(('ONT FAST5', self.analysis.ont_fast5))
                if self.analysis.ont_raw_fastq:
                    table.add_row(('ONT FASTQ', self.analysis.ont_raw_fastq))
                if self.analysis.illumina_fastq:
                    table.add_row(('Illumina FASTQ',
                                   ', '.join(self.analysis.illumina_fastq)))
                if self.analysis.genome_fasta:
                    table.add_row(('Assembly', self.analysis.genome_fasta))
                if self.analysis.reference_fasta:
                    table.add_row(('Reference', self.analysis.reference_fasta))

            self.doc.append(VerticalSpace("10pt"))

    def add_ont_library_information(self):

        if self.analysis.ont_n50 is None:
            return

        with self.doc.create(
                Subsection('ONT library statistics', numbering=False)):
            with self.doc.create(Tabular('ll', width=2)) as table:
                table.add_row(
                    ('ONT N50', '{:,}'.format(self.analysis.ont_n50)))
                table.add_row(
                    ('ONT reads', '{:,}'.format(self.analysis.ont_read_count)))
                table.add_row(
                    ('ONT bases', '{:s}'.format(self.analysis.ont_bases)))
            self.doc.append(VerticalSpace("10pt"))

    def add_illumina_library_information(self):
        if self.analysis.illumina_length_mean is None:
            return

        with self.doc.create(
                Subsection('Illumina library statistics', numbering=False)):
            with self.doc.create(Tabular('ll', width=2)) as table:
                table.add_row(
                    ('Illumina mean length',
                     '{:.1f}'.format(self.analysis.illumina_length_mean)))
                table.add_row(
                    ('Illumina reads',
                     '{:,}'.format(self.analysis.illumina_read_count)))
                table.add_row(('Illumina bases',
                               '{:s}'.format(self.analysis.illumina_bases)))
            self.doc.append(VerticalSpace("10pt"))

    def add_assembly_information(self):

        if self.analysis.genome is None:
            return

        with self.doc.create(Subsection('Assembly statistics',
                                        numbering=False)):
            with self.doc.create(Tabular('ll', width=2)) as table:
                table.add_row(('Contigs', len(self.analysis.genome)))

                genome_size = 0
                for i in self.analysis.genome:
                    genome_size += len(i.seq)
                genome_size = si_format(genome_size, precision=1)
                table.add_row(('Assembly size', genome_size))

            self.doc.append(VerticalSpace("10pt"))

    def add_contig_info(self):

        if self.analysis.contig_info is None:
            return

        for method in ['ONT', 'Illumina']:

            if not method in self.analysis.contig_info.index:
                continue

            with self.doc.create(
                    Subsection('Assembly coverage by ' + method,
                               numbering=False)):

                table_format = 'l' * self.analysis.contig_info[method].shape[1]

                self.doc.append('')

                with self.doc.create(Tabular(table_format)) as table:
                    table.add_row(('Contig', 'Length (bp)', 'Coverage (X)'))
                    table.add_hline()
                    formatted = self.analysis.contig_info[method].copy()
                    formatted.iloc[:, 1] = formatted.iloc[:, 1].apply(
                        lambda x: '{:,}'.format(x))
                    for i in range(self.analysis.contig_info[method].shape[0]):
                        table.add_row(formatted.iloc[i, :].values.tolist())
                self.doc.append(LineBreak())
                self.doc.append(VerticalSpace("10pt"))

    def add_assembly_notes(self):

        if len(self.analysis.assembly_notes) == 0:
            return

        with self.doc.create(
                Subsection(self.assembly_notes_title, numbering=False)):
            left = FlushLeft()
            for _, note in self.analysis.assembly_notes.iteritems():
                left.append(note)
                left.append(LineBreak())
                self.doc.append(left)
            self.doc.append(VerticalSpace("10pt"))

    def add_contamination(self):

        if len(self.analysis.kraken_fracs) == 0:
            return

        self.doc.append(NewPage())

        with self.doc.create(Section('Contamination check', numbering=False)):

            for read_type, kraken_fracs in self.analysis.kraken_fracs.iteritems(
            ):

                left = FlushLeft()
                left.append(read_type + ' classifications')
                left.append(VerticalSpace('5pt'))
                self.doc.append(left)

                with self.doc.create(
                        Tabular(''.join(['l'] * kraken_fracs.shape[1]),
                                width=kraken_fracs.shape[1])) as table:
                    table.add_row(
                        ('Percent of reads', 'Reads', 'Level', 'Label'))
                    table.add_hline()
                    for index, row in kraken_fracs.iterrows():
                        table.add_row(row.tolist())

                self.doc.append(LineBreak())
                self.doc.append(VerticalSpace('5pt'))

                if not self.contamination_methods_title in self.methods:
                    self.methods[self.contamination_methods_title] = ''

        method = 'Kraken2 (' + self.analysis.versions[
            'kraken2'] + ') was used to assign the raw reads into taxa.'
        self.methods[self.contamination_methods_title] = self.methods[
            self.contamination_methods_title].append(pd.Series(method))

    def add_alignment(self):

        if len(self.analysis.contig_alignment) > 0:
            alignments = self.analysis.contig_alignment
        else:
            return

        self.doc.append(NewPage())

        with self.doc.create(Section(self.alignment_title, numbering=False)):

            with self.doc.create(
                    Subsection(self.snp_indel_title, numbering=False)):

                with self.doc.create(Tabular('ll', width=2)) as table:
                    table.add_row(
                        ('SNPs',
                         '{:,}'.format(self.analysis.quast_mismatches)))
                    table.add_row(('Small indels',
                                   '{:,}'.format(self.analysis.quast_indels)))
                self.doc.append(LineBreak())

            if len(self.analysis.alignment_notes) > 0:

                with self.doc.create(
                        Subsection(self.alignment_notes_title,
                                   numbering=False)):

                    left = FlushLeft()
                    for note in self.analysis.alignment_notes:
                        left.append(note)
                        left.append(LineBreak())
                    self.doc.append(left)

            for contig in alignments.index.tolist():

                contig_title = 'Alignment to ' + contig
                self.doc.append(
                    Command('graphicspath{{../circos/' + contig + '/}}'))
                image_png = os.path.basename(alignments[contig])

                with self.doc.create(Subsection(contig_title,
                                                numbering=False)):
                    with self.doc.create(Figure(position='H')) as figure:
                        figure.add_image(image_png, width='5in')


        method = 'The genome assembly was aligned against the reference sequencing using dnadiff (v ' \
            + self.analysis.versions['dnadiff'] + ').'
        self.methods[self.reference_methods_title] = self.methods[
            self.reference_methods_title].append(pd.Series(method))

    def add_features(self):

        if len(self.analysis.feature_hits) == 0:
            return

        self.doc.append(NewPage())

        with self.doc.create(Section(self.feature_title, numbering=False)):
            for feature_name in self.analysis.feature_hits.index.tolist():

                features = self.analysis.feature_hits[feature_name].copy()
                if features.shape[0] == 0:
                    continue

                features.iloc[:, 1] = features.iloc[:, 1].apply(
                    lambda x: '{:,}'.format(x))
                features.iloc[:, 2] = features.iloc[:, 2].apply(
                    lambda x: '{:,}'.format(x))

                table_format = 'l' * (features.shape[1] - 1)

                with self.doc.create(Subsection(feature_name,
                                                numbering=False)):
                    if (features.shape[0] == 0):
                        self.doc.append('None')
                        continue

                    for contig in pd.unique(features.iloc[:, 0]):

                        self.doc.append(contig)

                        contig_features = features.loc[(
                            features.iloc[:, 0] == contig), :]

                        with self.doc.create(Tabular(table_format)) as table:
                            table.add_row(('Start', 'Stop', 'Feature',
                                           'Identity (%)', 'Strand'))
                            table.add_hline()
                            for i in range(contig_features.shape[0]):
                                feature = contig_features.iloc[i, :].copy(
                                    deep=True)
                                feature[4] = '{:.3f}'.format(feature[4])
                                table.add_row(feature[1:].values.tolist())

                        self.doc.append(LineBreak())
                        self.doc.append(VerticalSpace("10pt"))

        method = 'The genome assembly was queried for features using blastn (v ' + self.analysis.versions['blastn'] + ').  ' + \
            'Feature hits were clustered using bedtools (v ' + self.analysis.versions['bedtools'] + ') ' + \
            'and the highest scoring hit for each cluster was reported.'
        self.methods[self.feature_methods_title] = self.methods[
            self.feature_methods_title].append(pd.Series(method))

    def add_feature_plots(self):

        if len(self.analysis.feature_plots) == 0:
            return

        self.doc.append(NewPage())

        self.doc.append(Command('graphicspath{{../drawing/}}'))

        with self.doc.create(Section('Feature plots', numbering=False)):

            self.doc.append('Only contigs with features are shown')

            for contig in self.analysis.feature_plots.index.tolist():

                image_png = os.path.basename(
                    self.analysis.feature_plots[contig])

                with self.doc.create(Figure(position='h!')) as figure:
                    figure.add_image(image_png, width='7in')

    def add_mutations(self):

        # Make sure we looked for mutations
        if not getattr(self.analysis, 'did_call_amr_mutations', False):
            return

        mutations = self.analysis.amr_mutations

        self.doc.append(NewPage())

        table_format = 'p{0.1\linewidth}p{0.1\linewidth}p{0.12\linewidth}p{0.12\linewidth}p{0.12\linewidth}p{0.34\linewidth}'

        with self.doc.create(Section(self.mutation_title, numbering=False)):

            for region_name in mutations.index.tolist():

                region_mutations = mutations[region_name].copy()

                with self.doc.create(Subsection(region_name, numbering=False)):
                    if (region_mutations.shape[0] == 0):
                        self.doc.append('None')
                        continue

                    region_mutations.iloc[:,
                                          1] = region_mutations.iloc[:, 1].apply(
                                              lambda x: '{:,}'.format(x))

                    with self.doc.create(Tabular(table_format)) as table:
                        table.add_row(
                            ('Reference contig', 'Position', 'Reference',
                             'Alternate', 'Drug', 'Note'))
                        table.add_hline()
                        for i in range(region_mutations.shape[0]):
                            table.add_row(region_mutations.iloc[
                                i, [0, 1, 3, 4, 5, 6]].values.tolist())

        method = self.analysis.mutations_read_type + ' reads were mapped to the reference sequence using minimap2 (v '\
            + self.analysis.versions['minimap2'] + ').'
        self.methods[self.mutation_methods_title] = self.methods[
            self.mutation_methods_title].append(pd.Series(method))

        method = ' '.join([
            'Mutations were identified using'
            'samtools mpileup (v', self.analysis.versions['samtools'], ')',
            'and varscan (v', self.analysis.versions['varscan'], ').'
        ])
        self.methods[self.mutation_methods_title] = self.methods[
            self.mutation_methods_title].append(pd.Series(method))

    def add_amr_matrix(self):

        # Make sure that we have an AMR matrix to plot
        if not getattr(self.analysis, 'did_draw_amr_matrix', False):
            return

        amr_matrix_png = self.analysis.amr_matrix_png

        self.doc.append(NewPage())

        with self.doc.create(Section(self.amr_matrix_title, numbering=False)):

            self.doc.append(
                'AMR genes and mutations with their corresponding drugs.')

            self.doc.append(Command('graphicspath{{../}}'))

            with self.doc.create(Figure(position='h!')) as figure:
                figure.add_image(amr_matrix_png, width='7in')

    def add_large_indels(self):

        # Make sure we looked for mutations
        if len(self.analysis.large_indels) == 0:
            return

        large_indels = self.analysis.large_indels

        self.doc.append(NewPage())

        with self.doc.create(Section(self.large_indel_title, numbering=False)):

            for genome in ['Reference insertions', 'Query insertions']:

                genome_indels = large_indels[genome].copy()

                with self.doc.create(Subsection(genome, numbering=False)):
                    if (genome_indels.shape[0] == 0):
                        self.doc.append('None')
                        continue

                    genome_indels.iloc[:, 1] = genome_indels.iloc[:, 1].apply(
                        lambda x: '{:,}'.format(x))
                    genome_indels.iloc[:, 2] = genome_indels.iloc[:, 2].apply(
                        lambda x: '{:,}'.format(x))
                    genome_indels.iloc[:, 3] = genome_indels.iloc[:, 3].apply(
                        lambda x: '{:,}'.format(x))

                    table_format = 'l' * genome_indels.shape[1]

                    with self.doc.create(Tabular(table_format)) as table:
                        table.add_row(
                            ('Reference contig', 'Start', 'Stop', 'Size (bp)'))
                        table.add_hline()
                        for i in range(genome_indels.shape[0]):
                            table.add_row(
                                genome_indels.iloc[i, :].values.tolist())

        method = 'Large insertions or deletions were found as the complement of aligned ' + \
            'regions using bedtools (v ' + self.analysis.versions['bedtools'] + ').'
        self.methods[self.reference_methods_title] = self.methods[
            self.reference_methods_title].append(pd.Series(method))

    def add_plasmids(self):

        if not getattr(self.analysis, 'did_call_plasmids', False):
            return

        # Make sure we looked for mutations
        plasmids = self.analysis.plasmids

        if plasmids is None:
            return

        plasmids = plasmids.copy()

        self.doc.append(NewPage())

        with self.doc.create(
                Section(self.analysis.plasmid_title, numbering=False)):

            if (plasmids.shape[0] == 0):
                self.doc.append('None')
                return

            plasmids.iloc[:, 3] = plasmids.iloc[:, 3].apply(
                lambda x: '{:,}'.format(x))
            plasmids.iloc[:, 4] = plasmids.iloc[:, 4].apply(
                lambda x: '{:,}'.format(x))
            plasmids.iloc[:, 5] = plasmids.iloc[:, 5].apply(
                lambda x: '{:,}'.format(x))

            table_format = 'p{0.1\linewidth}p{0.3\linewidth}p{0.15\linewidth}p{0.08\linewidth}p{0.08\linewidth}p{0.08\linewidth}'

            with self.doc.create(Tabular(table_format)) as table:
                table.add_row(('Genome contig', 'Plasmid hit', 'Plasmid acc.',
                               'Contig size', 'Aliged', 'Plasmid size'))
                table.add_hline()
                for i in range(plasmids.shape[0]):
                    table.add_row(plasmids.iloc[i, 0:6].values.tolist())

        method = ' '.join([
            'The plasmid reference database was queried against the genome assembly using minimap2 (v',
            self.analysis.versions['minimap2'], ').'
        ])
        self.methods[self.plasmid_methods_title] = self.methods[
            self.plasmid_methods_title].append(pd.Series(method))

        method = 'The resulting SAM was converted to a PSL using a custom version of sam2psl.'
        self.methods[self.plasmid_methods_title] = self.methods[
            self.plasmid_methods_title].append(pd.Series(method))

        method = 'Plasmid-to-genome hits were resolved using the pChunks algorithm.'
        self.methods[self.plasmid_methods_title] = self.methods[
            self.plasmid_methods_title].append(pd.Series(method))

    def add_methods(self):

        if len(self.methods) == 0:
            return

        self.doc.append(NewPage())

        with self.doc.create(Section(self.methods_title, numbering=False)):

            for methods_section in self.methods.index.tolist():

                if len(self.methods[methods_section]) == 0:
                    continue

                with self.doc.create(
                        Subsection(methods_section, numbering=False)):
                    self.doc.append(' '.join(self.methods[methods_section]))

    def make_tex(self):

        self.doc.generate_tex(self.analysis.report_prefix)

    def make_report(self):

        self.start_doc()
        self.add_header()
        self.add_summary()
        self.add_contamination()
        self.add_alignment()
        self.add_features()
        self.add_feature_plots()
        self.add_mutations()
        self.add_large_indels()
        self.add_plasmids()
        self.add_amr_matrix()
        #self.add_snps()
        self.add_methods()
        self.make_tex()
示例#24
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,
    )
示例#25
0
    def create(self):
        try:
            self.status['text'] = 'Загрузка, подождите'
            self.root.update()
            # Настройки отступов, языка
            geometry_options = {
                "tmargin": "2cm",
                "lmargin": "3cm",
                "rmargin": "1.5cm",
                "bmargin": "2cm"
            }
            doc = Document(geometry_options=geometry_options)
            doc.packages.add(
                Package('grffile',
                        options=['encoding', 'filenameencoding=utf8']))
            doc.packages.add(Package('babel', options=['russian']))

            # Вставляем логотип МИРЭА
            image_filename = os.path.join(os.path.dirname(__file__),
                                          'логотип.png')
            with doc.create(Figure(position='h!')) as logo:
                logo.add_image(image_filename, width='80px')

            # Обложка
            doc.change_length(r"\TPHorizModule", "1mm")
            doc.change_length(r"\TPVertModule", "1mm")
            with doc.create(MiniPage(width=r"\textwidth")) as page:
                # Центральная часть обложки
                with page.create(TextBlock(180, 0, 0)):
                    page.append(Command('centering'))
                    page.append('МИНОБРНАУКИ РОССИИ\n')
                    page.append(
                        'Федеральное государственное бюджетное образовательное учреждение высшего образования\n'
                    )
                    page.append(
                        MediumText(
                            bold(
                                '«МИРЭА - Российский Технологический Университет»\n'
                            )))
                    page.append(LargeText(bold('РТУ МИРЭА\n')))
                    page.append(LineBreak())
                    page.append(
                        MediumText(
                            bold(
                                'Институт комплексной безопасности и специального приборостроения\n'
                            )))
                    page.append(LineBreak())
                    page.append(
                        'Кафедра КБ-8 «Информационное Противоборство»\n')
                    page.append(LineBreak())
                    page.append(LineBreak())
                    page.append(LineBreak())
                    page.append(LargeText('Отчёт\n'))
                    page.append(f'{str(self.entry1.get())}\n')

                # Правая часть обложки
                with page.create(TextBlock(80, 88, 120)):
                    if self.your_var.get() == 0:
                        page.append('Выполнил:\n')
                        page.append(
                            f'Студент {str(self.entry2.get())} курса\n')
                    else:
                        page.append('Выполнила:\n')
                        page.append(
                            f'Студентка {str(self.entry2.get())} курса\n')
                    page.append(f'Группа {str(self.entry3.get())}\n')
                    page.append(f'Шифр {str(self.entry4.get())}\n')
                    page.append(f'{str(self.entry5.get())}\n')
                    page.append(LineBreak())
                    page.append(LineBreak())
                    if self.var.get() == 0:
                        page.append('Проверил:\n')
                    else:
                        page.append('Проверила:\n')
                    page.append(f'{str(self.entry6.get())}\n')

            # Нижний колонтитул
            header = PageStyle("header")
            with header.create(Foot("C")):
                header.append(f'Москва, {time.now().timetuple().tm_year}\n')
            doc.preamble.append(header)
            doc.change_document_style("header")

            doc.generate_pdf("title", clean_tex=False)
            self.status['text'] = 'Готово!'

        except FileNotFoundError as e:
            self.status['text'] = str(e)
示例#26
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)
示例#27
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)
示例#28
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')
示例#29
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')
示例#30
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)