Exemple #1
0
    def gen(self,
            n_nums,
            n_digits,
            var_digits,
            n_ex,
            n_cols,
            n_answ_cols=7,
            out_file=None):
        print('generating.... ', n_ex, ',', n_nums, ',', n_digits, ',',
              var_digits, ',', n_cols)
        ttl = self.tst_nm + ' - ' + str(n_nums) + (
            ' up to' if var_digits > 0 else
            '') + ' numbers, ' + str(n_digits) + ' digits'
        pdf_base.start(self, ttl, [12, 14])
        self.init()

        nme = self.f_nm + '_digits_' + str(n_nums) + '_' + str(
            n_digits) + '_' + str(var_digits)
        q_out_file = self.out_dir + '/' + nme + '_Q'
        a_out_file = self.out_dir + '/' + nme + '_A'
        if out_file != None:
            q_out_file = out_file + '_Q'
            a_out_file = out_file + '_A'

        # round number of problems to fill all columns on the question sheet
        n_probs = int(n_ex / n_cols + 1) * n_cols

        questions_and_answers = [
            self.gen_smpl(n, n_digits, n_nums, var_digits)
            for n in range(n_probs)
        ]
        questions = list(map(lambda x: x[0], questions_and_answers))
        answers = list(map(lambda x: x[1], questions_and_answers))

        with self.q_doc.create(LongTabu("X[l] " * n_cols,
                                        row_height=2.0)) as q_tbl:
            for row in range(ceil(n_probs / n_cols)):
                q_row = questions[row * n_cols:(row + 1) * n_cols]
                if row % 2 == 0:
                    q_tbl.add_row(q_row, color="cream")
                else:
                    q_tbl.add_row(q_row)

        with self.a_doc.create(LongTabu("X[l] " * n_answ_cols,
                                        row_height=2.0)) as a_tbl:
            for row in range(ceil(n_probs / n_answ_cols)):
                a_row = answers[row * n_answ_cols:(row + 1) * n_answ_cols]
                # top up missing cells with empty string
                for i in range(0, n_answ_cols - len(a_row)):
                    a_row.append("")
                if row % 2 == 0:
                    a_tbl.add_row(a_row, color="cream")
                else:
                    a_tbl.add_row(a_row)

        self.q_doc.generate_pdf(q_out_file, clean_tex=True)
        self.a_doc.generate_pdf(a_out_file, clean_tex=True)
Exemple #2
0
 def quadro_planejamento(self, planejamento_acoes):
     with self.create(
             LongTabu("|X[1,l]|X[3,l]|X[6,l]|")) as tabela_planejamento:
         tabela_planejamento.add_hline()
         tabela_planejamento.add_row(
             (MultiColumn(3, align='|c|',
                          data=bold('Cronograma de Ações')), ))
         tabela_planejamento.add_hline()
         tabela_planejamento.add_row(
             (bold('Prazo'), bold('Ação'), bold('Prioridade')))
         tabela_planejamento.add_hline()
         tabela_planejamento.end_table_header()
         tabela_planejamento.add_hline()
         tabela_planejamento.add_row(
             (MultiColumn(3, align='|r|',
                          data='Continua na próxima página'), ))
         tabela_planejamento.add_hline()
         tabela_planejamento.end_table_footer()
         tabela_planejamento.end_table_last_footer()
         for acao in planejamento_acoes:
             metas = acao['metas']
             if not len(metas):
                 continue
             col_meta = MultiRow(len(metas),
                                 data=acao['prazo'].capitalize())
             row = [col_meta, acao['acao'], '1. ' + metas[0]]
             tabela_planejamento.add_row(row)
             for meta in metas[1:]:
                 tabela_planejamento.add_row(
                     ('', '', (str(metas.index(meta) + 1) + '. ' + meta)))
             tabela_planejamento.add_hline()
Exemple #3
0
def generate_info_table(doc):
		"""
		Generate a table which contains last 2 line of tests from log.txt
		:param doc: LaTeX object, a instance of Document Class
		:return: null
		"""

		## Create a long table object in LaTeX object
		with doc.create(LongTabu("X[l] X[r]")) as info_table:
				header_row1 = ["Test Number", "Info"]

				info_table.add_row(header_row1, mapper=[bold])
				info_table.add_hline()
				info_table.add_empty_row()
				info_table.end_table_header()

				## Add last 2 lines
				for i in range(3):
						row_1 = [str(i + 1), get_log(i + 1)[0]]
						row_2 = [" ", get_log(i + 1)[1]]
						info_table.add_row(row_1)
						info_table.add_empty_row()
						info_table.add_row(row_2)
						info_table.add_hline()
						info_table.add_empty_row()
Exemple #4
0
 def quadro_epis(self, fichas_exposicao):
     with self.create(LongTabu("|X[l]|X[l]|")) as tabela_epi:
         tabela_epi.add_hline()
         tabela_epi.add_row(
             (MultiColumn(2,
                          align='|c|',
                          data=bold('Quadro Demonstrativo de EPIs')), ))
         tabela_epi.add_hline()
         tabela_epi.add_row((bold('Função'), bold('EPIs Indicados')))
         tabela_epi.add_hline()
         tabela_epi.end_table_header()
         tabela_epi.add_row(
             (MultiColumn(2, align='|c|',
                          data='Continua na próxima página'), ))
         tabela_epi.add_hline()
         tabela_epi.end_table_footer()
         tabela_epi.end_table_last_footer()
         for ficha in fichas_exposicao:
             epis = ficha['epis']
             if not len(epis):
                 continue
             col_cargo = MultiRow(len(epis), data=ficha['cargo'])
             row = [col_cargo, epis[0]]
             tabela_epi.add_row(row)
             for epi in epis[1:]:
                 tabela_epi.add_row(('', epi))
             tabela_epi.add_hline()
def create_pdf_document(rows):
    geometry_options = {
        "head": "30pt",
        "bottom": "0.5in",
        "margin": "0.6in",
        "includeheadfoot": True
    }
    doc = Document(geometry_options=geometry_options)

    with doc.create(LongTabu("X[l] X[2l] X[r] X[r]",
                             row_height=1.5)) as my_table:
        my_table.add_row(["Full name", "Email", "Contact", "Address"], \
             mapper=bold, color="pink"
            )
        my_table.add_empty_row()
        my_table.add_hline()

        for index, row in enumerate(rows):
            data_list = [row[1], row[2], row[3], row[4]]

            if (index % 2 == 0):
                my_table.add_row(data_list, color="gray")
            else:
                my_table.add_row(data_list, color="lightgray")

    doc.generate_pdf("users-details", clean_tex=False)
def genenerate_longtabu():
    geometry_options = {
        "landscape": True,
        "margin": "0.5in",
        "headheight": "20pt",
        "headsep": "10pt",
        "includeheadfoot": True
    }
    doc = Document(page_numbers=True, geometry_options=geometry_options)

    # Generate data table
    with doc.create(LongTabu("X[r] X[r] X[r] X[r] X[r] X[r]")) as data_table:
        header_row1 = ["Prov", "Num", "CurBal", "IntPay", "Total", "IntR"]
        data_table.add_row(header_row1, mapper=[bold])
        data_table.add_hline()
        data_table.add_empty_row()
        data_table.end_table_header()
        data_table.add_row(
            ["Prov", "Num", "CurBal", "IntPay", "Total", "IntR"])
        row = [
            "PDADASDASDSADSADSADASDASDSADASDASA", "9", "$100", "%10", "$1000",
            "Test"
        ]
        for i in range(50):
            data_table.add_row(row)

    doc.append(bold("Grand Total:"))
    doc.append(HFill())
    doc.append(bold("Total"))

    doc.generate_pdf("longtabu", clean_tex=False)
Exemple #7
0
def generate_table(book):
    '''
    this is used to generate in table style.
    suitable for language learning: e.g. Spanish / English etc
    '''
    print 'generating book: {title}'.format(title=book['title'])
    doc = Document(geometry_options=GEOMETRY_OPTIONS)
    doc = _setup_doc(doc, book)
    # doc.append(NoEscape(r'\maketitle'))

    section_count = 0
    for section in book['sections']:
        with doc.create(Section(section['title'], numbering=False)):
            with doc.create(LongTabu(_TABLE_FORMAT, row_height=1.5)) as table:
                table.end_table_header()
                row_elements = []
                for exercise in section['exercises']:
                    row_elements.append(NoEscape(exercise[0]))
                    row_elements.append(NoEscape(exercise[1]))
                    if len(row_elements) == 6:
                        table.add_row(row_elements)
                        row_elements = []
                    # table.add_hline()
        section_count += 1
        if section_count % 2 == 0:
            doc.append(NewPage())

    book_name = '{target_path}/{user} {title}'.format(target_path=TARGET_PATH,
                                                      user=book['user'],
                                                      title=book['title'])
    doc.generate_pdf(book_name, clean_tex=True, compiler='xelatex')
Exemple #8
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)
Exemple #9
0
    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)
Exemple #10
0
def gen(f_nm, n_ex, n_digits, digit_var, n_nums, n_cols):
    print("----- START -----")

    ttl = 'Column addition - ' + str(n_nums) + ' ' + str(n_digits) + '-digit values with ' + str(digit_var) + '-digit variance'
    
    q_doc = Document(geometry_options = pge_geom, lmodern=True)
    a_doc = Document(geometry_options = pge_geom, lmodern=True)
    
    with q_doc.create(Section("Questions: " + ttl, numbering=False)):
        q_doc.append('Solve the following questions!')

    with a_doc.create(Section("Answers: " + ttl, numbering=False)):
        a_doc.append('Answers to problem sheet')

    q_doc.add_color(name="cream", model="rgb", description=cream_clr_def)
    q_doc.append(Command('fontsize', arguments = ['16', '18']))
    q_doc.append(Command('fontfamily', arguments = ['pcr']))
    q_doc.append(Command('selectfont'))
    q_doc.append(FlushRight())

    a_doc.add_color(name="cream", model="rgb", description=cream_clr_def)
    
    # Add statement table
    with a_doc.create(LongTabu("X[l] " * n_cols,  row_height=2.0)) as a_tbl:
        with q_doc.create(LongTabu("X[r] " * n_cols,  row_height=2.0)) as q_tbl:
            for i in range(round(n_ex/n_cols)):
                row = ['  ' + str(n + i*n_cols) + '.' for n in range(0, n_cols)]
                q_tbl.add_row(row, mapper=bold, color="cream")

                row = [gen_example(n + i*n_cols, n_digits, n_nums, digit_var) for n in range(0, n_cols)]
                q_tbl.add_row([r[0] for r in row])

                if i % 2 == 0:
                    #a_tbl.add_row([r[1] for r in row], color = 'lightgray')
                    a_tbl.add_row([r[1] for r in row], color = 'cream')
                else:
                    a_tbl.add_row([r[1] for r in row])

    # write the file
    q_doc.generate_pdf(out_dir + '/' + f_nm + str(n_digits) + '_digits_Q', clean_tex=False)
    a_doc.generate_pdf(out_dir + '/' + f_nm + str(n_digits) + '_digits_A', clean_tex=False)
    print("----- DONE -----")
Exemple #11
0
 def quadro_responsavel(self, profissionais, data_emissao):
     with self.create(LongTabu("|X[l]|X[l]|")) as tabela_resp:
         tabela_resp.add_hline()
         tabela_resp.add_row(
             (MultiColumn(2,
                          align='|c|',
                          data=bold('Responsável pela elaboração')), ))
         tabela_resp.add_hline()
         tabela_resp.add_row((bold('Nome'), profissionais[0]['nome']))
         tabela_resp.add_hline()
         tabela_resp.add_row((bold('Função'), profissionais[0]['titulo']))
         tabela_resp.add_hline()
         tabela_resp.add_row((bold('Data da elaboração'), data_emissao))
         tabela_resp.add_hline()
         tabela_resp.add_row((bold('Revisão Programada'), data_emissao))
         tabela_resp.add_hline()
    def table(self, csvFile=None, cType=None, pType=None):
        with self.doc.create(Section(cType)):
            self.doc.append('{} evaluation'.format(cType))
            with self.doc.create(Subsection('Accuracy')):

                with self.doc.create(LongTabu('|c|c|c|c|c|')) as table:
                    table.add_hline()
                    table.add_row(("eval", "type", "Precision", "Recall", "F1 Score"))
                    table.add_hline()

                    with open(csvFile) as f:
                        f_csv = csv.reader(f)
                        for row in f_csv:
                            e, t, p, r, f1 = row
                            table.add_row((e,t, p, r, f1))
                            table.add_hline()
Exemple #13
0
def h_table(doc):
    head_str = "X[l]"
    col_names = ["Income Type"]
    for key in ref_dict:
        head_str += " X[c]"
        col_names.append(key)
    rowlist = make_rows()
    with doc.create(LongTabu(head_str, row_height=2.0)) as data_table:
        data_table.add_hline()
        data_table.add_row(col_names)
        data_table.add_hline()
        data_table.add_row(rowlist[0])
        data_table.add_row(rowlist[1])
        data_table.add_row(rowlist[2])
        data_table.add_row(rowlist[3])
        data_table.add_row(rowlist[4])
        data_table.add_hline()
Exemple #14
0
def genenerate_tabus():
    geometry_options = {
        "landscape": True,
        "margin": "1.5in",
        "headheight": "20pt",
        "headsep": "10pt",
        "includeheadfoot": True
    }
    doc = Document(page_numbers=True, geometry_options=geometry_options)

    # Generate data table with 'tight' columns
    fmt = "X[r] X[r] X[r] X[r] X[r] X[r]"
    with doc.create(LongTabu(fmt, spread="0pt")) as data_table:
        header_row1 = ["Prov", "Num", "CurBal", "IntPay", "Total", "IntR"]
        data_table.add_row(header_row1, mapper=[bold])
        data_table.add_hline()
        data_table.add_empty_row()
        data_table.end_table_header()
        data_table.add_row(
            ["Prov", "Num", "CurBal", "IntPay", "Total", "IntR"])
        row = [
            "aduiashdDASDASDASDSADSAuiasuidhasuidhasi", "9", "$100", "%10",
            "$1000", "Test"
        ]
        for i in range(40):
            data_table.add_row(row)

    with doc.create(Center()) as centered:
        with centered.create(Tabu("X[r] X[r]", spread="1in")) as data_table:
            header_row1 = ["X", "Y"]
            data_table.add_row(header_row1, mapper=[bold])
            data_table.add_hline()
            row = [randint(0, 1000), randint(0, 1000)]
            for i in range(4):
                data_table.add_row(row)

    with doc.create(Center()) as centered:
        with centered.create(Tabu("X[r] X[r]", to="4in")) as data_table:
            header_row1 = ["X", "Y"]
            data_table.add_row(header_row1, mapper=[bold])
            data_table.add_hline()
            row = [randint(0, 1000), randint(0, 1000)]
            for i in range(4):
                data_table.add_row(row)

    doc.generate_pdf("tabus", clean_tex=False)
Exemple #15
0
def generate_info_table(doc):

    with doc.create(LongTabu("X[l] X[r]")) as info_table:
        header_row1 = ["Test Number", "Info"]

        info_table.add_row(header_row1, mapper=[bold])
        info_table.add_hline()
        info_table.add_empty_row()
        info_table.end_table_header()

        for i in range(3):
            row_1 = [str(i + 1), get_log(i + 1)[0]]
            row_2 = [" ", get_log(i + 1)[1]]
            info_table.add_row(row_1)
            info_table.add_empty_row()
            info_table.add_row(row_2)
            info_table.add_hline()
            info_table.add_empty_row()
Exemple #16
0
    def table(self, csvFile=None, cType=None, pType=None, level=None):
        with self.doc.create(Section(cType)):
            self.doc.append('{} evaluation'.format(cType))
            with self.doc.create(Subsection('Qps/Mem detail')):

                with self.doc.create(LongTabu('|c|c|c|')) as table:
                    table.add_hline()
                    table.add_row(("Model", "Qps", "Mem"))
                    table.add_hline()

                    with open(csvFile) as f:
                        f_csv = csv.reader(f)
                        for row in f_csv:
                            m, q, e = row
                            if level == 2:
                                e = '-'
                            table.add_row((m, q, e))
                            table.add_hline()
Exemple #17
0
def generate_status_tabel(doc):

    with doc.create(LongTabu("X[c] X[c] X[r]")) as status_table:
        header_row1 = ["Test Number", "Status", "Exec time"]

        status_table.add_row(header_row1, mapper=[bold])
        status_table.add_hline()
        status_table.add_empty_row()
        status_table.end_table_header()

        for i in range(15):
            row = [
                str(i + 1),
                get_tests_status(i + 1),
                get_exec_time(i + 1) + '[sec]'
            ]
            status_table.add_row(row)
            get_evac_time(i + 1)
Exemple #18
0
def generate_status_tabel(doc):
		"""
		Generate a table which contains status of tests
		:param doc: LaTeX object, a instance of Document Class
		:return: null
		"""
		## Create a long table object in LaTeX object
		with doc.create(LongTabu("X[c] X[c]")) as status_table:
				header_row1 = ["Test Number", "Status"]

				status_table.add_row(header_row1, mapper=[bold])
				status_table.add_hline()
				status_table.add_empty_row()
				status_table.end_table_header()


				for i in range(3):
						row = [str(i+1), get_tests_status(i+1)]
						status_table.add_row(row)
Exemple #19
0
def semiannual_table(doc, year1, month1, data_list, init, final):

    with doc.create(
            LongTabu(
                "X[0.4,c] X[1.3,c] X[1.2,c] X[c] X[1.1,c] X[0.4,c] X[0.4,c] X[4,l]",
                row_height=1)) as data_table:
        data_table.add_row(
            NoEscape(r"\scriptsize\sffamily\bfseries N"),
            NoEscape(r"\scriptsize\sffamily\bfseries FECHA"),
            NoEscape(r"\scriptsize\sffamily\bfseries H:M:S"),
            NoEscape(r"\scriptsize\sffamily\bfseries LAT"),
            NoEscape(r"\scriptsize\sffamily\bfseries LON"),
            NoEscape(r"\scriptsize\sffamily\bfseries Z"),
            NoEscape(r"\scriptsize\sffamily\bfseries M"),
            NoEscape(r"\scriptsize\sffamily\bfseries UBICACION"),
            color="sgc2")
        #data_table.add_empty_row()
        data_table.end_table_header()

        # para cada elemento en la lista list_to_table (lista con info de sismos)
        for i in range(init, final):
            if (i % 2) == 0:
                data_table.add_row(Command("tiny", str(i + 1)),
                                   Command("tiny", data_list[i][0]),
                                   Command("tiny", data_list[i][1]),
                                   Command("tiny", data_list[i][2]),
                                   Command("tiny", data_list[i][3]),
                                   Command("tiny", data_list[i][4]),
                                   Command("tiny", data_list[i][5]),
                                   Command("tiny", data_list[i][6]),
                                   color="sgc2!20")
            else:
                data_table.add_row(Command("tiny", str(i + 1)),
                                   Command("tiny", data_list[i][0]),
                                   Command("tiny", data_list[i][1]),
                                   Command("tiny", data_list[i][2]),
                                   Command("tiny", data_list[i][3]),
                                   Command("tiny", data_list[i][4]),
                                   Command("tiny", data_list[i][5]),
                                   Command("tiny", data_list[i][6]),
                                   color="white")
    def create_automatic_context_topics(self):

        with self.doc.create(
                Section(Constants.ITEM_TYPE.title() +
                        ' context-rich topic models (automatic)')):
            num_context_topics = len(
                self.lda_based_context.context_rich_topics)

            with self.doc.create(LongTabu(self.table_format)) as table:
                table.add_hline()
                table.add_row(self.headers, mapper=bold_mapper)
                table.add_hline()

                for topic in self.lda_based_context.context_rich_topics:
                    topic_id = topic[0]
                    ratio = topic[1]
                    color_id = self.automatic_context_topic_colors[topic_id]
                    color = self.rgb_tuples[color_id]
                    id_cell = str(topic_id) + str('|||') + str(color[0]) + \
                        '|||' + str(color[1]) + '|||' + str(color[2])
                    ratio_cell = str(ratio) + str('|||') + str(color[0]) + \
                        '|||' + str(color[1]) + '|||' + str(color[2])
                    row = [id_cell, ratio_cell]
                    # row = [str(topic_id + 1)]
                    topic_words =\
                        self.lda_based_context.print_topic(
                            topic_id, self.num_cols).split(' + ')
                    for word in topic_words:
                        word_color = word + str('|||') + str(color[0]) +\
                                     '|||' + str(color[1]) + '|||' +\
                                     str(color[2])
                        row.append(word_color)
                    # row.extend(topic_words)
                    table.add_row(row, mapper=background_color_mapper)

                table.add_hline()

            self.doc.append(UnsafeCommand('par'))
            self.doc.append('Number of context-rich topics: %d' %
                            num_context_topics)
Exemple #21
0
def v2_table(doc, column_list=column_list, table_vars_dict=table_vars_dict, column_label=column_label):
    """
    This function generates a table with the variables in 'column_list'
    ----------
    The function takes the column_list variables (listed in the notebook)
    and looks up their corresponding tokens in table_vars_dict. It then executes
    the tokens and assembles a table row.
    """
    global token_list
    token_list = []
    head_str = ""
    for var in column_list:
        head_str += " X[c]"
        token_list.append(table_vars_dict[var])

    # begin generating table
    with doc.create(LongTabu(head_str, row_height=2.0)) as data_table:
        data_table.add_hline()

        # change label of column list
        del column_list[0]
        global column_list_adj
        column_list_adj = [column_label]
        column_list_adj = column_list_adj + column_list
        data_table.add_row(column_list_adj)

        data_table.add_hline()
        for key in calc_dict:
            key1 = key
            for key in calc_dict[key]:
                    key2 = key
                    global ex_token_list
                    ex_token_list = []
                    for token in token_list:
                        ex_token = eval(token)
                        ex_token_list.append(ex_token)
                    data_table.add_row(ex_token_list)
        data_table.add_hline()
Exemple #22
0
def v_table(doc, policy_key=True):
    """
    Creates a vertical table, with reforms on y-axis and metrics on x-axis
    ----------
    policy_key : This determines the listing on the y-axis, By default it is set
    so that key1=True.
        policy_key = True : Uses policy reforms
        policy_key = False : Uses behavioral reforms
    """
    with doc.create(LongTabu("X[c] X[c] X[c] X[c] X[c] X[c]", row_height=2.0)) as data_table:
        data_table.add_hline()
        data_table.add_row(['Elasticity of Charitable Giving',
                            'Taxpayers Receiving Tax Hike (millions)',
                            'Itemizers (millions)',
                            'Wght. Ave. MTR on Charitable Contributions',
                            'Total Charitable Contributions (billions)',
                            '10-Year Revenue Change (billions)'])
        data_table.add_hline()
        for key in calc_dict:
            key1 = key
            for key in calc_dict[key]:
                key2 = key
                if policy_key == True:
                    data_table.add_row([key1,
                                       '{:,.1f}'.format(num_taxhike(calc_cl, calc_dict[key1][key2]) / 10.0**6),
                                       '{:,.1f}'.format(num_ided(calc_dict[key1][key2]) / 10.0**6),
                                       '{:.2f}'.format(100 * charity_wmtr(calc_cl)),
                                       currency_fmt(num_charity(calc_dict[key1][key2])),
                                       currency_fmt(ten_year_cost(calc_cl, calc_dict[key1][key2]))])
                if policy_key == False:
                    data_table.add_row([key2,
                                       '{:,.1f}'.format(num_taxhike(calc_cl, calc_dict[key1][key2]) / 10.0**6),
                                       '{:,.1f}'.format(num_ided(calc_dict[key1][key2]) / 10.0**6),
                                       '{:.2f}'.format(100 * charity_wmtr(calc_cl)),
                                       currency_fmt(num_charity(calc_dict[key1][key2])),
                                       currency_fmt(ten_year_cost(calc_cl, calc_dict[key1][key2]))])
        data_table.add_hline()
Exemple #23
0
 def quadro_funcionarios(self, quadro_funcionarios, total_masc, total_fem,
                         total_fun):
     with self.create(
             LongTabu("|X[3,c]|X[c]|X[c]|")) as tabela_funcionarios:
         tabela_funcionarios.add_hline()
         tabela_funcionarios.add_row(
             (MultiRow(2, data=bold('Função')),
              MultiColumn(2,
                          align='c|',
                          data=bold('Número de Funcionários'))))
         tabela_funcionarios.add_hline(2, 3)
         tabela_funcionarios.add_row(
             ('', bold('Masculino'), bold('Feminino')))
         tabela_funcionarios.end_table_header()
         tabela_funcionarios.add_row(
             (MultiColumn(3, align='|r|',
                          data='Continua na próxima página'), ))
         tabela_funcionarios.add_hline()
         tabela_funcionarios.end_table_footer()
         tabela_funcionarios.add_hline()
         tabela_funcionarios.add_row(
             (MultiRow(2,
                       data=bold('Total Funcionários')), bold(total_masc),
              bold(total_fem)))
         tabela_funcionarios.add_hline(2, 3)
         tabela_funcionarios.add_row(
             ('', MultiColumn(2, align='c|', data=bold(total_fun))))
         tabela_funcionarios.add_hline()
         tabela_funcionarios.end_table_last_footer()
         for funcao in quadro_funcionarios:
             row = [
                 funcao['funcao'], funcao['qtdMasculino'],
                 funcao['qtdFeminino']
             ]
             tabela_funcionarios.add_hline()
             tabela_funcionarios.add_row(row)
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)
Exemple #25
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')
Exemple #26
0
from pylatex import Document, Section, Subsection, Tabular, MultiColumn, LongTabu
from pylatex import Math
from pylatex.utils import italic, bold

pge_geom = {"tmargin" : "1cm",  "bmargin" : "1cm",  "lmargin" : "1cm",  "rmargin" : "1cm" }

if __name__ == '__main__' :
    print("----- START -----")

    doc = Document(geometry_options = pge_geom)

    with doc.create(Section('The simple stuff', numbering=False)):
        doc.append('Some regular text and some')
        doc.append(italic('italic text. '))
        doc.append('\nAlso some crazy characters: $&#{}')

    # Add statement table
    with doc.create(LongTabu("X[l] X[l] X[r]",  row_height=2.0)) as data_table:
        for i in range(30):
            row = [str(i) + " :>", "2016-JUN-01", "$100"]
            if (i % 2) == 0:
                data_table.add_row(row, color="lightgray")
            else:
                data_table.add_row(row)

    doc.generate_pdf('full', clean_tex = False)
    
    print("----- DONE -----")
Exemple #27
0
    def pile_report(self, pile, pile2, F, factor=1.25):
        """添加桩基长度计算内容"""

        self.soil = pile.soil
        llist = pl.get_l(self.soil, pile.d, F, factor, pile.h1, pile.rho,
                         pile.t, pile.k2, pile2.type, pile2.completion)
        ra_1, ra_2 = pl.pile_l(llist, self.soil, pile.d, F, pile.h1, pile.rho,
                               pile.t, pile.k2, pile2.type, pile2.completion)

        if ra_1.max() > ra_2.max():
            ptype = '摩擦桩'
            ra = ra_1.max()
        else:
            ptype = '端承桩'
            ra = ra_2.max()

        t1 = f'''桩基直径:$d={pile.d:.2f}\,m$\n
        桩基周长:$u={pile.u:.2f}\,m$\n
        桩基截面积:$A_p={pile.pd:.2f}\,m^2$\n
        桩基密度:$\gamma={pile.rho:.1f}\,kN/m^3$\n
        容许承载力随深度的修正系数:$k_2={pile.k2:.1f}$\n
        各土层加权平均重度:$\gamma_2={self.soil.rho:.1f}\,kN/m^3$\n
        清底系数:$m_0={pile.m0:.1f}$
        '''

        t2 = '根据规范5.3.3可得,摩擦桩单桩承载力为'
        m1 = ['[R_a]', '=\\frac{1}{2}u\\sum_{i=1}^nq_{ik}l_i+A_pq_r']
        t3 = '根据规范5.3.4可得,端承桩单桩承载力为'
        m2 = [
            '[R_a]=', 'c_1A_pf_{rk}', '+u\\sum_{i=1}^mc_{2i}h_if_{rki}',
            '+\\frac{1}{2}\\xi_su\sum_{i=1}^nl_iq_{ik}'
        ]
        t4 = '考虑桩身自重与置换土重,桩基承载力为'
        m3 = ['R_a', '=[R_a]-G_p+G_s']
        t5 = '代入不同长度桩长,可得摩擦桩与端承桩承载力如下图所示'
        t6 = '不同桩长具体承载力如下表所示'
        t7 = f'由上述分析可知,当桩长为{max(llist)}m时,{ptype}承载力为{ra:.0f}kN,安全系数为{ra/F:.2f},桩基承载力可满足规范要求。'

        with self.doc.create(Section('地基基本情况')):
            with self.doc.create(LongTabu("p{4cm}XXXXX")) as soil_table:
                header_row1 = self.soil.prop.columns.to_list()[:-1]
                soil_table.add_hline()
                soil_table.add_row(header_row1, mapper=[bold])
                soil_table.add_hline()
                for i in self.soil.prop.index:
                    soil_table.add_row(self.soil.prop.iloc[i].to_list()[:-1])
                soil_table.add_hline()

        with self.doc.create(Section('桩基及其他参数取值')):
            self.doc.append(NoEscape(t1))

        with self.doc.create(Section('桩长计算')):
            self.doc.append(t2)
            self.doc.append(Math(data=m1, escape=False))
            self.doc.append(NoEscape('\n'))
            self.doc.append(t3)
            self.doc.append(Math(data=m2, escape=False))
            self.doc.append(NoEscape('\n'))
            self.doc.append(t4)
            self.doc.append(Math(data=m3, escape=False))
            self.doc.append(NoEscape('\n'))
            self.doc.append(t5)
            with self.doc.create(Figure(position='htbp')) as plot:
                plot.add_plot(width=NoEscape(r'1\textwidth'), dpi=300)
            self.doc.append(NoEscape('\n'))
            self.doc.append(t6)
            with self.doc.create(LongTable('p{1.5cm}|ll|ll')) as pll:
                pll.add_hline()
                pll.add_row(['桩长', '摩擦桩承载力', '安全系数', '端承桩承载力', '安全系数'])
                pll.add_hline()
                for i, j in enumerate(llist):
                    pll.add_row([
                        j, f'{ra_1[i]:.0f}', f'{ra_1[i]/F:.2f}',
                        f'{ra_2[i]:.0f}', f'{ra_2[i]/F:.2f}'
                    ])
                pll.add_hline()
            self.doc.append(t7)
Exemple #28
0
    doc.preamble.append(Command('title', 'Report'))
    doc.preamble.append(Command('author', 'Stream Processor Performance Testing-' + path))

    doc.preamble.append(Command('date', NoEscape(r'\today')))
    doc.append(NoEscape(r'\maketitle'))
    doc.append(NoEscape(r'\newpage'))

# Generating summary results chart for each run
# throughput summary table and chart

with doc.create(
        Section('Average Throughput During 60-180 seconds time period since the start of the benchmarking experiment')):
    doc.append(NoEscape(r'\hfill \break'))
    fmt = "X[r] X[r]"
    with doc.create(Subsection('Summary Table')):
        with doc.create(LongTabu(fmt, spread="0pt")) as data_table:
            header_row = ['Experiment runs', 'Average Throughput(million events/second)']
            data_table.add_row(header_row, mapper=[bold])
            data_table.add_hline()
            data_table.add_empty_row()
            data_table.end_table_header()

            # Iterates through throughput array and no_file_array and append rescpective run and throughput in the row
            for x, y in np.c_[no_of_file, throughput]:
                row = [x, y]
                data_table.add_row(row)
    doc.append(NoEscape(r'\newpage'))
    # append graph into the pdf report
    with doc.create(Subsection("Graph")):
        with doc.create(Figure(position='h!')) as throughput_chart:
            throughput_chart.add_image(throughput_image_dir, width='450px')
Exemple #29
0
def json2latex2pdf(json, mode="clean"):

    # on construit le nom du rapport
    #rapFile = "_TEX_report"
    name = json["comp_details"]["general"]["job_type"][0]
    rapFile = (name + "_report")

    #####################################################################
    #                                                                   #
    ## production du rapport en .tex                                 #
    #                                                                   #
    #####################################################################

    ### create document and import needed packages

    doc = (Document("article"))

    # packages
    doc.packages.append(Package('datetime'))
    doc.packages.append(NoEscape(r'\usepackage[margin=2cm]{geometry}'))
    doc.packages.append(NoEscape(r'\usepackage{extramarks}'))
    doc.packages.append(NoEscape(r'\usepackage{fancyhdr}'))
    doc.packages.append(NoEscape(r'\usepackage{svg}'))
    doc.packages.append(NoEscape(r'\usepackage[utf8]{inputenc}'))
    doc.packages.append(NoEscape(r'\usepackage{titlesec}'))
    #
    doc.packages.append(NoEscape(r'\pagestyle{fancy}'))
    doc.packages.append(NoEscape(r'\fancyhf{}'))
    # define header / footer texts
    doc.packages.append(NoEscape(r'\lhead{MOLECULAR CALCULATION REPORT}'))
    doc.packages.append(NoEscape(r'\rhead{Generated by QuChemReport}'))
    doc.packages.append(NoEscape(r'\lfoot{\today ~  \currenttime}'))
    doc.packages.append(NoEscape(r'\rfoot{Page \thepage}'))
    doc.packages.append(NoEscape(r'\cfoot{}'))
    # redefine rules for header / footer
    doc.packages.append(NoEscape(r'\renewcommand\headrulewidth{0.4pt}'))
    doc.packages.append(NoEscape(r'\renewcommand\footrulewidth{0.4pt}'))
    # redefine section
    doc.packages.append(NoEscape(r'\definecolor{ufrblue}{RGB}{0,161,140}'))
    doc.packages.append(NoEscape(r'\definecolor{bordeau}{RGB}{125,31,31}'))
    doc.packages.append(
        NoEscape(
            r'\titleformat{name=\section}[block]{\sc\large}{}{0pt}{\colorsection}'
        ))
    doc.packages.append(
        NoEscape(r'\titlespacing*{\section}{0pt}{\baselineskip}{5pt}'))
    doc.packages.append(
        NoEscape(r'\titlespacing{\subsection}{4pt}{\baselineskip}{5pt}'))
    doc.packages.append(
        NoEscape(
            r'\newcommand{\colorsection}[1]{' +
            r'\colorbox{ufrblue}{\parbox{\dimexpr\textwidth-2\fboxsep}{\textcolor{white}{'
            + r'\textbf{{\thesection.\ #1}}}}}}'))

    ### section 1 : authorship TODO with the DB !
    #########################################
    #    with doc.create(Section('AUTHORSHIP')):
    #        with doc.create(LongTabu("X[1,l] X[2,l]")) as tab:
    #            tab.add_row(['Original file', json["authorship"]["log_file"]])
    #            tab.add_row(['Primary author',  json["authorship"]["primary_author"]])
    #            add_row_filter(tab, ['ORCID',  json["authorship"]["primary_author_orcid"]])
    #            add_row_filter(tab, ['Affiliation',  json["authorship"]["primary_author_affiliation"]])
    #            add_row_filter(tab, ['Publication DOI',  json["authorship"]["publication_DOI"]])

    ### section 2 : molecule

    with doc.create(Section('MOLECULE')):
        taillePng = "6cm"
        nomPng = "img-TOPOLOGY.png"
        if (not os.path.isfile("img-TOPOLOGY.png")):
            print("No PNG named " + nomPng + " found. STOP.\n")
            sys.exit()

        # figure with Chemical structure diagram
        doc.append(NoEscape(r'\begin{figure}[h]'))
        doc.append(NoEscape(r'\begin{center}'))
        doc.append(
            NoEscape(r'\includegraphics[width=' + taillePng + ']{' + nomPng +
                     '}'))
        doc.append(NoEscape(r'\end{center}'))
        doc.append(NoEscape(r'\vspace{-5mm}'))
        doc.append(
            NoEscape(
                r'\caption*{Chemical structure diagram with atomic numbering.}'
            ))
        doc.append(NoEscape(r'\end{figure}'))

        with doc.create(LongTabu("X[1,l] X[2,l]")) as mol_table:
            inchi = (json["molecule"]["inchi"])[0].rstrip().split("=")[-1]
            mol_table.add_row(['InChI', inchi])
            mol_table.add_row(['SMILES', json["molecule"]["smi"]])
            mol_table.add_row([
                'Monoisotopic mass',
                "%.5f Da" % json["molecule"]["monoisotopic_mass"]
            ])
            mol_table.add_row(['Formula', json["molecule"]["formula"]])
            mol_table.add_row(['Charge', json["molecule"]["charge"]])
            mol_table.add_row(
                ['Spin multiplicity', json["molecule"]["multiplicity"]])

    ### section 2 : computational details
    #########################################
    software = json["comp_details"]["general"]["package"]
    with doc.create(Section('COMPUTATIONAL DETAILS')):
        #with doc.create(Subsection('General parameters')) :
        with doc.create(LongTabu("X[1,l] X[1,l]")) as param_table:
            try:
                param_table.add_row([
                    'Software',
                    json["comp_details"]["general"]["package"] + ' (' +
                    json["comp_details"]["general"]["package_version"] + ')'
                ])
            except KeyError:
                pass
            param_table.add_row([
                'Computational method',
                json["comp_details"]["general"]["last_theory"]
            ])
            add_row_filter(
                param_table,
                ['Functional', json["comp_details"]["general"]["functional"]])
            try:
                add_row_filter(param_table, [
                    'Basis set name',
                    json["comp_details"]["general"]["basis_set_name"]
                ])
            except KeyError:
                pass
            param_table.add_row([
                'Number of basis set functions',
                json["comp_details"]["general"]["basis_set_size"]
            ])
            param_table.add_row([
                'Closed shell calculation',
                json["comp_details"]["general"]["is_closed_shell"]
            ])
            add_row_filter(param_table, [
                'Integration grid',
                json["comp_details"]["general"]["integration_grid"]
            ])
            add_row_filter(
                param_table,
                ['Solvent', json["comp_details"]["general"]["solvent"]])
            #  TODO Test if solvent = gas in this case no Solvent reaction filed method
            #          add_row_filter(param_table, ['Solvent reaction filed method',
            #                                         json["comp_details"]["general"]["solvent_reaction_field"]])

            scfTargets = json["comp_details"]["general"]["scf_targets"][-1]
            if software == "Gaussian":  # Gaussian or GAUSSIAN (upper/lower?
                param_table.add_row([
                    "Requested SCF convergence on RMS density matrix",
                    scfTargets[0]
                ])
                param_table.add_row([
                    "Requested SCF convergence on MAX density matrix",
                    scfTargets[1]
                ])
                param_table.add_row(
                    ["Requested SCF convergence on energy", scfTargets[2]])
            if software == "GAMESS":
                param_table.add_row(
                    ["Requested SCF convergence on density", scfTargets[0]])

            #with doc.create(Subsection('Thermochemistry and normal modes calculation parameters')) :
            ## TODO tester si freq
            try:
                add_row_filter(param_table, [
                    'Temperature',
                    "%.2f K" % json["comp_details"]["freq"]["temperature"]
                ])
            except:
                pass
            T_len = False

            try:
                len(json["comp_details"]["freq"]["temperature"])
            except KeyError:
                json["comp_details"]["freq"]["temperature"] = []
            except TypeError:
                T_len = True
                if T_len is True:
                    try:
                        add_row_filter(param_table, [
                            'Anharmonic effects',
                            json["comp_details"]["freq"]["anharmonicity"]
                        ])

                    except KeyError:
                        pass
            if (json["comp_details"]["freq"]["temperature"]) != []:
                try:
                    add_row_filter(param_table, [
                        'Anharmonic effects',
                        json["comp_details"]["freq"]["anharmonicity"]
                    ])

                except KeyError:
                    pass

            #with doc.create(Subsection('Excited states calculation parameters')) :
            try:
                add_row_filter(param_table, [
                    'Number of excited states',
                    json["comp_details"]["excited_states"]["nb_et_states"]
                ])
            except KeyError:
                pass

    ### section 3 : results
    #########################################
    with doc.create(Section('RESULTS')):
        with doc.create(Subsection('Wavefunction')):

            with doc.create(LongTabu("X[l] X[l]")) as wavef_table:
                wavef_table.add_row([
                    'Total molecular energy',
                    "%.5f Hartrees" %
                    json["results"]["wavefunction"]["total_molecular_energy"]
                ])
                homo_indexes = [
                    i + 1
                    for i in json["results"]["wavefunction"]["homo_indexes"]
                ]
                wavef_table.add_row([
                    'H**O number', ("%s" % homo_indexes)[1:-1]
                ])  # indice begins at 0, remove brackets

            MO_energies = json["results"]["wavefunction"]["MO_energies"][-1]
            homo_nb = json["results"]["wavefunction"]["homo_indexes"][-1]
            doc.append(NoEscape(r'\begin{center}'))
            with doc.create(Table()) as motab:
                doc.append(NoEscape(r'\centering'))
                with doc.create(Tabular('p{1cm}ccccp{1cm}')) as mo_table:
                    row_cells = MultiColumn(
                        6,
                        align='c',
                        data=
                        'Calculated energies for the frontier molecular orbitals (in eV)'
                    )
                    mo_table.add_row([row_cells])
                    mo_table.add_row(
                        ['', 'H**O-1', 'H**O', 'LUMO', 'LUMO+1', ''])
                    mo_table.add_hline()
                    mo_table.add_row([
                        '',
                        "%.2f" % MO_energies[homo_nb - 1],
                        "%.2f" % MO_energies[homo_nb],
                        "%.2f" % MO_energies[homo_nb + 1],
                        "%.2f" % MO_energies[homo_nb + 2], ''
                    ])
            doc.append(NoEscape(r'\end{center}'))

            # figure with MO
            #### TODO : test autosize
            try:
                if len(json["results"]["excited_states"]['MO_png_list']) > 0:
                    figure_MO_table(
                        doc, ["LU1", "LUMO", "H**O", "HO1"],
                        json["results"]["excited_states"]['MO_png_list'],
                        caption=
                        ("Representation of the frontier molecular orbitals with a cutoff "
                         "value of 0.05. From up to bottom: LUMO+1, LUMO, H**O, H**O-1."
                         ))
            except:
                pass

            # figure skel for Atom numbering scheme
            try:
                figure_two_col(doc,
                               "skel",
                               json["results"]["geometry"]['skel_png_list'],
                               caption="Atom numbering scheme.",
                               pos="h")
            except:
                pass

            # Mulliken partial charges table
            try:
                mulliken = json["results"]["wavefunction"][
                    "Mulliken_partial_charges"]
            except KeyError:
                mulliken = []
            if len(mulliken) != 0:
                mulliken = np.array(mulliken)
                mean_m = np.mean(mulliken)
                dev_m = np.std(mulliken)
                thres_max = mean_m + dev_m
                thres_min = mean_m - dev_m
                doc.append(NoEscape(r'\begin{center}'))
                ind = np.argsort(mulliken)
                with doc.create(Tabular('p{0.5cm}rrrp{0.5cm}')) as tableau:
                    row_cells = [
                        MultiColumn(
                            5,
                            align='c',
                            data='Most intense Mulliken atomic charges')
                    ]
                    tableau.add_row(row_cells)
                    row_cells = [
                        MultiColumn(5,
                                    align='c',
                                    data='mean = %.3f e, std = %.3f' %
                                    (mean_m, dev_m))
                    ]
                    tableau.add_row(row_cells)
                    tableau.add_row(
                        ["", "Atom", "number", "Mulliken charges", ""])
                    tableau.add_hline()

                    for ielt in ind:
                        if (mulliken[ielt] > thres_max) or (mulliken[ielt] <
                                                            thres_min):
                            tableau.add_row([
                                "",
                                PeriodicTable().element[json['molecule']
                                                        ["atoms_Z"][ielt]],
                                (1 + ielt),
                                "%.3f" % mulliken[ielt], ""
                            ])
                    tableau.add_hline()
                doc.append(NoEscape(r'\end{center}'))

            # figure MEP
            try:
                if len(json["results"]["wavefunction"]['MEP_png_list']) > 0:
                    figure_two_col(
                        doc,
                        "MEP",
                        json["results"]["wavefunction"]['MEP_png_list'],
                        caption=
                        ("Representation of the molecular electrostatic potential "
                         "at the distance of the van der Waals radii of the atoms. "
                         "The red/blue regions depict the most negative (-0.1) / "
                         "positive (+0.1) regions."),
                        pos="h")
            except:
                pass

        with doc.create(Subsection('Geometry')):
            ######## PB
            atomic = json["results"]["geometry"][
                "elements_3D_coords_converged"]
            oxtrf, oytrf, oxtrd, oytrd = ('N/A', 'N/A', 'N/A', 'N/A')

            ### TODO
            # if singlePoint==1 :
            #      doc.append('This calculation is a single point ')
            try:
                is_opt = json["results"]["geometry"]["OPT_DONE"] == True
            except KeyError:
                is_opt = []
            if is_opt:
                doc.append(
                    NoEscape(
                        r"This calculation is the result of a geometry optimization process."
                    ))
            else:
                doc.append(
                    NoEscape(
                        r"\textcolor{bordeau}{Warning : this calculation does not include a geometry "
                        "optimization process. This geometry may not be a stationary "
                        "point for those computational parameters. In this case, results must be "
                        "used with caution.}"))

            if is_opt:
                ### TODO tests gaussian
                doc.append(NoEscape(r'\begin{center}'))
                geomTargets = json["comp_details"]["geometry"][
                    "geometric_targets"]
                geomValues = json["results"]["geometry"]["geometric_values"][
                    -1]
                with doc.create(Tabular('p{0cm}lrrp{0cm}')) as param_table:
                    row_cells = [
                        MultiColumn(
                            5,
                            align='c',
                            data='Geometry optimization convergence criteria')
                    ]
                    param_table.add_row(row_cells)
                    param_table.add_row(["", "", "Value", "Threshold", ""])
                    param_table.add_hline()
                    if software == "Gaussian":
                        param_table.add_row([
                            "", "Maximum Force",
                            "%.6f" % geomValues[0],
                            "%.6f" % geomTargets[0], ""
                        ])
                        param_table.add_row([
                            "", "RMS Force",
                            "%.6f" % geomValues[1],
                            "%.6f" % geomTargets[1], ""
                        ])
                        param_table.add_row([
                            "", "Maximum Displacement",
                            "%.6f" % geomValues[2],
                            "%.6f" % geomTargets[2], ""
                        ])
                        param_table.add_row([
                            "", "RMS Displacement",
                            "%.6f" % geomValues[3],
                            "%.6f" % geomTargets[3], ""
                        ])
                    if software == "GAMESS":
                        # in Hartrees per Bohr
                        param_table.add_row([
                            "", "Maximum Force",
                            "%.5f" % geomValues[0],
                            "%.5f" % geomTargets[0], ""
                        ])
                        param_table.add_row([
                            "", "RMS Force",
                            "%.5f" % geomValues[1],
                            "%.5f" % geomTargets[1], ""
                        ])
                    param_table.add_hline()
                doc.append(NoEscape(r'\end{center}'))

            with doc.create(LongTabu("X[l] X[l]")) as geom_table:
                geom_table.add_row([
                    'Nuclear repulsion energy',
                    "%.5f Hartrees" % json["results"]["geometry"]
                    ["nuclear_repulsion_energy_from_xyz"]
                ])

            doc.append(NoEscape(r'\begin{center}'))
            with doc.create(Tabular('p{0.5cm}rrrrp{0.5cm}')) as tableau:
                row_cells = [
                    MultiColumn(
                        6,
                        align='c',
                        data='Cartesian atomic coordinates in Angstroms')
                ]
                tableau.add_row(row_cells)
                tableau.add_row([
                    "", "Atom",
                    MultiColumn(1, align='c', data='X'),
                    MultiColumn(1, align='c', data='Y'),
                    MultiColumn(1, align='c', data='Z'), ""
                ])
                tableau.add_hline()
                atoms = np.array(json["results"]["geometry"]
                                 ["elements_3D_coords_converged"]).reshape(
                                     (-1, 3))
                for i, a in enumerate(atoms):
                    tableau.add_row([
                        "",
                        PeriodicTable().element[json['molecule']["atoms_Z"]
                                                [i]],
                        "%.4f" % a[0],
                        "%.4f" % a[1],
                        "%.4f" % a[2], ""
                    ])
                tableau.add_hline()
            doc.append(NoEscape(r'\end{center}'))

        ### Freq
        #### TODO : tests

        with doc.create(Subsection('Thermochemistry and normal modes')):
            rtemper = json["comp_details"]["freq"]["temperature"]
            # ND-arrays
            try:
                vibrational_int = np.array(
                    json["results"]["freq"]["vibrational_int"])
            except KeyError:
                vibrational_int = []
            try:
                vibrational_freq = np.array(
                    json["results"]["freq"]["vibrational_freq"])
            except KeyError:
                vibrational_freq = []

            try:
                vibrational_sym = np.array(
                    json["results"]["freq"]["vibrational_sym"])
            except KeyError:
                vibrational_sym = []

            # filtering & orderering
            if len(vibrational_int) == 0:
                vibrational_int = []
            else:
                vib_filter = vibrational_int > 50.
                vib_order = np.argsort(vibrational_freq[vib_filter])[::-1]
                vibrational_int = vibrational_int[vib_filter][vib_order]
                vibrational_freq = vibrational_freq[vib_filter][vib_order]
                vibrational_sym = vibrational_sym[vib_filter][vib_order]

            if (len(vibrational_int) != 0) and (rtemper != "N/A"):
                with doc.create(LongTabu("X[l] X[l]")) as thermo_table:
                    thermo_table.add_row([
                        'Sum of electronic and zero-point energy in Hartrees',
                        json["results"]["freq"]["zero_point_energy"]
                    ])
                    thermo_table.add_row([
                        "Sum of electronic and thermal at "
                        "%f K energies in atomic units" % rtemper,
                        json["results"]["freq"]["electronic_thermal_energy"]
                    ])
                    thermo_table.add_row([
                        "Entropy at %f K in atomic units" % rtemper,
                        json["results"]["freq"]["entropy"]
                    ])
                    thermo_table.add_row([
                        "Enthalpy at %f K in atomic units" % rtemper,
                        json["results"]["freq"]["enthalpy"]
                    ])
                    thermo_table.add_row([
                        "Gibbs free energy at %f K in atomic units" % rtemper,
                        json["results"]["freq"]["free_energy"]
                    ])

                doc.append(
                    "Table of the most intense molecular vibrations (> 20 km/mol) (%d)\n"
                    % len(vibrational_int))
                with doc.create(Tabular('rrrc')) as tableau:
                    tableau.add_row(
                        ["", "Frequencies", "Intensity", "Symmetry"])
                    for i in range(len(vibrational_freq)):
                        tableau.add_row([
                            "",
                            "%.4f" % vibrational_freq[i],
                            "%.4f" % vibrational_int[i], vibrational_sym[i]
                        ])
            else:
                doc.append(
                    NoEscape(
                        r"\textcolor{bordeau}{Warning : force constants and the "
                        "resulting vibrational frequencies were not computed.}"
                    ))

        ### Excited states
        try:
            et_energies = json["results"]["excited_states"]["et_energies"]
        except KeyError:
            et_energies = []
        rnbExci = len(et_energies)
        if rnbExci != 0 and et_energies != 'N/A':
            with doc.create(Subsection('Excited states')):
                doc.append(NoEscape(r'\begin{center}'))
                with doc.create(Tabular('p{0cm}rrrrrrp{0cm}')) as tableau:
                    row_cells = [
                        MultiColumn(
                            8,
                            align='c',
                            data="Calculated mono-electronic excitations")
                    ]
                    tableau.add_row(row_cells)
                    tableau.add_row([
                        "", "Number", "Energy", "Symmetry",
                        "Oscillator strength", "Rotatory strength",
                        "Transitions", ""
                    ])
                    tableau.add_hline()
                    for i in range(rnbExci):
                        etr_i = (json["results"]["excited_states"]["et_rot"][i]
                                 if json["results"]["excited_states"]["et_rot"]
                                 != 'N/A' else 'N/A')
                        tableau.add_row([
                            "", (1 + i),
                            "%.2f" % et_energies[i],
                            json["results"]["excited_states"]["et_sym"][i],
                            "%.6f" %
                            json["results"]["excited_states"]["et_oscs"][i],
                            etr_i,
                            len(json["results"]["excited_states"]
                                ["et_transitions"][i]), ""
                        ])
                    tableau.add_hline()
                doc.append(NoEscape(r'\end{center}'))

    #####################################################################
    #                                                                   #
    ## 3. compilation LaTeX                                             #
    #                                                                   #
    #####################################################################

    # on compile
    # on previent si le fichier PDF est present ou pas
    # par defaut dans pylatex tout ce qui concerne latex est efface

    ### compile and output

    # doc.generate_pdf(rapFile, clean_tex=True) # comportement en routine, avec False en mode dev/debug
    # OK sans SVG doc.generate_pdf(rapFile, clean_tex=False)
    # pas de chance !! doc.generate_pdf(rapFile, clean_tex=False,compiler="pdflatex  --shell-escape")

    texFile = rapFile + ".tex"
    if (os.path.isfile(texFile)):
        os.remove(texFile)

    pdfFile = rapFile + ".pdf"
    if (os.path.isfile(pdfFile)):
        os.remove(pdfFile)

    doc.generate_tex(rapFile)
    cmd = "pdflatex  --shell-escape " + rapFile

    # si cleanMode = "--clean" on redirige vers /dev/null
    if mode == "clean":
        cmd += " > /dev/null"

    # compilation LaTeX

    os.system(cmd)

    # un peu de nettoyage si cleanMode = "--clean"

    if mode == "clean":
        if os.path.isfile(rapFile + '.aux'):
            os.remove(rapFile + '.aux')
        if os.path.isfile(rapFile + '.log'):
            os.remove(rapFile + '.log')
        if os.path.isfile(rapFile + '.tex'):
            os.remove(rapFile + '.tex')

    # message de fin

    if (os.path.isfile(pdfFile)):
        print('Report file is ' + rapFile + ".pdf")
    else:
        print('Probably a LateX error.')
Exemple #30
0
    def generate_report(self):
        # Basic document
        # Document with `\maketitle` command activated
        doc = Document(default_filepath=(self.folder + r"/figures"))
        doc.documentclass = Command(
            'documentclass',
            options=['10pt', 'a4'],
            arguments=['article'],
        )
        doc.packages.append(NoEscape(r'\setcounter{tocdepth}{4}'))
        doc.packages.append(NoEscape(r'\setcounter{secnumdepth}{1}'))
        # usepackages
        doc.packages.append(Package('helvet'))
        doc.packages.append(Package('graphicx'))
        doc.packages.append(Package('geometry'))
        doc.packages.append(Package('float'))
        doc.packages.append(Package('amsmath'))
        doc.packages.append(Package('multicol'))
        doc.packages.append(Package('ragged2e'))
        doc.packages.append(Package('breakurl'))
        doc.packages.append(Package('booktabs, multirow'))
        doc.packages.append(Package('epstopdf'))
        doc.packages.append(
            NoEscape(r'\usepackage[nolist, nohyperlinks]{acronym}'))
        doc.packages.append(Package('hyperref'))

        # add commands
        doc.preamble.append(
            NoEscape(r"\renewcommand{\familydefault}{\sfdefault}"))
        doc.preamble.append(
            NoEscape(r"\newcommand\Tstrut{\rule{0pt}{3ex}}  % = `top' strut"))
        doc.preamble.append(
            NoEscape(
                r"\newcommand\Bstrut{\rule[1ex]{0pt}{0pt}}   % = `bottom' strut"
            ))

        # make title
        title = "Report for Session: " + self.session
        doc.preamble.append(Command('title', title))
        #doc.preamble.append(Command('author', 'Anonymous author'))
        doc.preamble.append(Command('date', NoEscape(r'\today')))
        doc.append(NoEscape(r'\maketitle'))
        doc.append(NoEscape(r'\tableofcontents'))
        doc.append(NewPage())
        doc.append(
            NoEscape(r'\newgeometry{vmargin={12mm}, hmargin={10mm,10mm}}'))
        doc.append(NoEscape(r'\bigskip'))

        # summary section
        with doc.create(Section('Session summary')):
            # create summary table
            with doc.create(LongTabu("X | X")) as summary_table:
                with doc.create(Tabular("r r")) as small_table:
                    small_table.add_row(["Summary", ""])
                    small_table.add_hline()
                    small_table.add_row(["Gamble side:", self.gamble_side])
                    small_table.add_hline()
                    small_table.add_row(
                        ["All trials",
                         self.all_trials_df.index.max()])
                    small_table.add_row(
                        ["Good trials",
                         self.good_trials_df.index.max()])
                    small_table.add_row([
                        "Selected trials",
                        self.selected_trials_df.index.max()
                    ])
                    small_table.add_hline()
                    small_table.add_row([
                        "Probability bins",
                        str(self.all_trials_df['probability'].unique())
                    ])

                # add overview plots
                doc.append(NoEscape(self.image_box("hist_fit", last=True)))
                doc.append(NoEscape(self.image_box("trial_length")))
                doc.append(NoEscape(self.image_box("cluster_hist", last=True)))
                doc.append(NewPage())

        # Add stuff to the document
        with doc.create(
                Section('Spike Trains and Histogram for Reward Events')):
            # create necessary variables
            for cluster in self.clusters_df.loc[self.clusters_df['group'] ==
                                                'good'].index:
                # create subsection title
                subsection = "Cluster " + str(cluster)
                with doc.create(Subsection(subsection, label=False)):
                    # create details table
                    with doc.create(LongTabu("X | X")) as details_table:

                        doc.append(
                            NoEscape(self.image_box_cluster("isi", cluster)))
                        doc.append(
                            NoEscape(
                                self.image_box_cluster("spk_train",
                                                       cluster,
                                                       last=True)))
                        details_table.add_hline()
                        details_table.add_row(
                            ["All Trials", "Rewarded Trials"])
                        doc.append(
                            NoEscape(
                                self.image_box_cluster(
                                    "spk_train_hist_all-events", cluster)))
                        doc.append(
                            NoEscape(
                                self.image_box_cluster(
                                    "spk_train_hist_all-events_reward-centered",
                                    cluster,
                                    last=True)))
                        details_table.add_hline()
                        details_table.add_row(
                            ["Gambl Side Reward", "Save Side Reward"])
                        #details_table.end_table_header()
                        doc.append(
                            NoEscape(
                                self.image_box_cluster(
                                    "spk_train_hist_gamble_reward", cluster)))
                        doc.append(
                            NoEscape(
                                self.image_box_cluster(
                                    "spk_train_hist_save_reward",
                                    cluster,
                                    last=True)))
                        #details_table.add_hline()
                        details_table.add_row(
                            ["Gambl Side No-Reward", "Save Side No-Reward"])
                        doc.append(
                            NoEscape(
                                self.image_box_cluster(
                                    "spk_train_hist_gamble_no-reward",
                                    cluster)))
                        doc.append(
                            NoEscape(
                                self.image_box_cluster(
                                    "spk_train_hist_save_no-reward",
                                    cluster,
                                    last=True)))
                doc.append(NewPage())

        # create file_name
        filepath = (self.folder + "/" + self.session + "-report")
        # create pdf
        doc.generate_pdf(
            filepath, clean=True, clean_tex=True
        )  #, compiler='latexmk -f -xelatex -interaction=nonstopmode')