Пример #1
0
def de_table(s: env.Table):
    col, row = s.shape

    c = Center()
    # c.append(NoEscape(r"\newlength\q"))
    c.append(
        NoEscape(
            r"\setlength\tablewidth{{\dimexpr (\textwidth -{}\tabcolsep)}}".
            format(2 * col)))
    c.append(NoEscape(r"\arrayrulecolor{tablelinegray!75}"))
    c.append(NoEscape(r"\rowcolors{2}{tablerowgray}{white}"))

    ratios = s.cacu_col_ratio()
    format = "|".join(
        [r"p{{{r}\tablewidth}}<{{\centering}}".format(r=r) for r in ratios])
    format = "|{format}|".format(format=format)

    t = Tabular(format)
    t.add_hline()
    for i, row in enumerate(s.iter_rows()):
        if i == 0:
            t.append(NoEscape(r"\rowcolor{tabletopgray}"))

        row = [de_line(c) for c in row]
        if i == 0:
            row = [bold(c) for c in row]

        t.add_row(row)
        t.add_hline()

    c.append(t)
    return c
Пример #2
0
    def fromTable(self, s: Table):
        c = Center()
        # c.append(NoEscape(r"\newlength\q"))
        c.append(
            NoEscape(
                rf"\setlength\tablewidth{{\dimexpr (\textwidth -{2*s.col_num}\tabcolsep)}}"
            ))
        c.append(NoEscape(r"\arrayrulecolor{tablelinegray!75}"))
        c.append(NoEscape(r"\rowcolors{2}{tablerowgray}{white}"))

        ratios = s.cacu_col_ratio()
        # format = "|".join([rf"p{{{r}\textwidth}}<{{\centering}}" for r in ratios])
        format = "|".join(
            [rf"p{{{r}\tablewidth}}<{{\centering}}" for r in ratios])
        format = f"|{format}|"

        t = Tabular(format)
        t.add_hline()
        for i, row in enumerate(s.tables):
            if i == 0:
                t.append(NoEscape(r"\rowcolor{tabletopgray}"))

            row = [self.fromTokenLine(c) for c in row]
            if i == 0:
                row = [bold(c) for c in row]

            t.add_row(row)
            t.add_hline()

        c.append(t)
        return c
Пример #3
0
def gen_example(idx, n_digits, n_nums, var_digits=0):
    assert(n_digits > 1)
    assert(var_digits < n_digits)

    sum = 0
    
    q_tab = Tabular(' c r ', row_height=1.2)
    a_tab = Tabular(' l l ', row_height=1.1)
    for n in range(0, n_nums):
        dgts_offst = randint(0, var_digits)

        min, max = pow(10, n_digits - 1 - dgts_offst), pow(10, n_digits - dgts_offst)
        assert(min < max)
        rnum = randint(min, max)
        if (n == 0) :
            q_tab.add_row(("", rnum))
        else:
            q_tab.add_row(("+", rnum))
        sum += rnum

    q_tab.add_hline()
    q_tab.add_empty_row()
    q_tab.add_empty_row()

    a_idx = bold(str(idx) + ":")
    a_tab.add_row((a_idx, sum))
        
    return (q_tab, a_tab)
Пример #4
0
def test_table():
    # Tabular
    t = Tabular(table_spec='|c|c|', data=None, pos=None)

    t.add_hline(start=None, end=None)

    t.add_row(cells=(1, 2), escape=False)

    t.add_multicolumn(size=2,
                      align='|c|',
                      content='Multicol',
                      cells=None,
                      escape=False)

    t.add_multirow(size=3,
                   align='*',
                   content='Multirow',
                   hlines=True,
                   cells=None,
                   escape=False)

    # MultiColumn/MultiRow.
    t.add_row((MultiColumn(size=2, align='|c|', data='MultiColumn'), ))

    t.add_row((MultiRow(size=2, width='*', data='MultiRow'), ))
 def create_migration_nodes_table():
     row = ['node']
     for metric in metrics.migration_platform_metrics:
         row.append(metrics.MetricLegends[metric]['name'])
     tabular = len(metrics.migration_platform_metrics) + 1
     table = Tabular('|' + 'c|' * tabular)
     table.add_hline()
     table.add_row(row)
     table.add_hline()
     return table
Пример #6
0
 def middle_fork(self):
     with self.create(Section('Middle Fork')) as section_mf:
         df = self.capacity.models['middle_fork']
         mask = (df['prod_date'] >= self.dt_start) & (df['prod_date'] <
                                                      self.dt_end)
         table_df = df.loc[mask]
         summary_table_mf = Tabular('ccc|ccc|ccc',
                                    row_height=.40,
                                    width=9,
                                    booktabs=True)
         avg_tablemaker(summary_table_mf, table_df, self.month1,
                        self.month2, self.month3)
         self.append(summary_table_mf)
         with self.create(Figure(position='h!')) as mf_plot:
             mf_fig, (ax1) = plt.subplots(nrows=1,
                                          ncols=1,
                                          sharex=True,
                                          sharey=False,
                                          squeeze=True,
                                          figsize=(14, 4))
             self.append(NoEscape(r''))
             ax1.stackplot(self.x,
                           df.base_volume,
                           df.wedge_volume,
                           df.offload_volume,
                           df.gas_lift_volume,
                           df.berry_volume,
                           df.garden_gulch_volume,
                           labels=[
                               'Base', 'Wedge', 'Offload', 'Gas Lift',
                               'Berry', 'Garden Gulch'
                           ],
                           colors=[
                               'blue', 'cornflowerblue', 'orange', 'gold',
                               'goldenrod', 'red'
                           ])
             ax1.plot(self.x, df.max_volume, label='Capacity')
             ax1.legend(loc='upper left')
             ax1.tick_params(labelsize=14)
             mf_plot.add_plot(width=NoEscape(r'1\textwidth'))
             table_mf = Tabular('ccc|ccc|ccc',
                                row_height=.10,
                                width=9,
                                booktabs=True)
             table_mf.add_row('Date', 'Gas, MCF', 'Delta', 'Date',
                              'Gas, MCF', 'Delta', 'Date', 'Gas, MCF',
                              'Delta')
             table_mf.add_hline()
             tablemaker(table_mf,
                        table_df.prod_date.astype(str).tolist(),
                        table_df.forecast.values.tolist(),
                        table_df.report_overflow.values.tolist(),
                        self.month1, self.month2, self.month3)
         section_mf.append(table_mf)
     self.append(NewPage())
Пример #7
0
def test_table():
    # Tabular
    t = Tabular(table_spec="|c|c|", data=None, pos=None)

    t.add_hline(start=None, end=None)

    t.add_row(cells=(1, 2), escape=False)

    # MultiColumn/MultiRow.
    t.add_row((MultiColumn(size=2, align="|c|", data="MultiColumn"),))

    t.add_row((MultiRow(size=2, width="*", data="MultiRow"),))
Пример #8
0
def add_evaluation():
	(doc, currfile) = add_section('evaluation')
	doc.append('We perform an evaluation on TODO benchmark by comparing the effectiveness of our \\toolname. To evaluate the effectiveness of our approach, we aim to address the following research questions:')
	with doc.create(Description()) as desc:
		desc.add_item("RQ1", "What is the overall")
		desc.add_item("RQ2", "How many")
		desc.add_item("RQ3", "How many")
	
	doc.append(Subsection('Experimental Setup'))
	doc.append("We evaluate \\toolname\\ on X subjects. Table~\\ref{substat} lists information about these subjects")

	with doc.create(Table(position='!ht')) as wtable:	
		table1 = Tabular('|c|c|c|c|')	
		table1.add_hline()
		table1.add_row(("Subject", "Description", "kLoc", "Tests"))
		table1.add_hline()
		table1.add_row(('x', 2, 1000, 4))
		table1.add_hline()
		table1.add_row(('y', 6, 1000, 8))
		table1.add_hline()
		wtable.append(table1)	
		wtable.add_caption('Subject Program and Their Basic Statistics')
		wtable.append('\\label{substat}')
			#doc.append(table1)
	doc.append("All experiments were performed on "+machine_config())
	doc.generate_tex(currfile)
Пример #9
0
def produce_table():
    # create document structure
    doc = Document("testtable")
    section = Section('Produce accessories table')
    test1 = Subsection('Test accessories table production')

    # test input code
    bench = [('Incline BP (4 x 12)'), ('Pull up (4 x Max)')]

    # test code
    accesory = bench
    table = Tabular('|c|c|c|c|c|c|c|c|c|')
    table.add_hline()
    table.add_row((MultiColumn(9, align='|c|', data='Accessories'), ))
    table.add_hline()
    table.add_row(('Exercise', 'Weight', 'Reps', 'Weight', 'Reps', 'Weight',
                   'Reps', 'Weight', 'Reps'))
    table.add_hline()
    for i in range(len(accesory)):
        table.add_row((str(accesory[i]), '', '', '', '', '', '', '', ''))
        table.add_hline()

    # append table to document
    test1.append(table)
    section.append(test1)
    doc.append(section)
    doc.generate_pdf(clean_tex=True)
Пример #10
0
def test_table():
    # Tabular
    t = Tabular(table_spec='|c|c|', data=None, pos=None)

    t.add_hline(start=None, end=None)

    t.add_row(cells=(1, 2), escape=False)

    # MultiColumn/MultiRow.
    t.add_row((MultiColumn(size=2, align='|c|', data='MultiColumn'),))

    t.add_row((MultiRow(size=2, width='*', data='MultiRow'),))

    repr(t)
Пример #11
0
 def story_gulch(self):
     with self.create(Section('Story Gulch')) as section_sg:
         df = self.capacity.models['story_gulch']
         mask = (df['prod_date'] >= self.dt_start) & (df['prod_date'] <
                                                      self.dt_end)
         table_df = df.loc[mask]
         summary_table_sg = Tabular('ccc|ccc|ccc',
                                    row_height=.40,
                                    width=9,
                                    booktabs=True)
         avg_tablemaker(summary_table_sg, table_df, self.month1,
                        self.month2, self.month3)
         self.append(summary_table_sg)
         with self.create(Figure(position='h!')) as sg_plot:
             sg_fig, (ax1) = plt.subplots(nrows=1,
                                          ncols=1,
                                          sharex=True,
                                          sharey=False,
                                          squeeze=True,
                                          figsize=(14, 4))
             self.append(NoEscape(r''))
             ax1.stackplot(
                 self.x,
                 df.base_volume + df.wedge_volume,
                 df.gas_lift_volume,
                 df.lp_base + df.lp_wedge,
                 df.mp_base + df.mp_wedge,
                 labels=[
                     'Base', 'Gas Lift', 'Low Pressure', 'Medium Pressure'
                 ],
                 colors=['blue', 'gold', 'cornflowerblue', 'goldenrod'])
             ax1.plot(self.x, df.max_volume, label='Capacity')
             ax1.legend(loc='upper left')
             ax1.tick_params(labelsize=14)
             sg_plot.add_plot(width=NoEscape(r'1\textwidth'))
             table_sg = Tabular('ccc|ccc|ccc',
                                row_height=.10,
                                width=9,
                                booktabs=True)
             table_sg.add_row('Date', 'Gas, MCF', 'Delta', 'Date',
                              'Gas, MCF', 'Delta', 'Date', 'Gas, MCF',
                              'Delta')
             table_sg.add_hline()
             tablemaker(table_sg,
                        table_df.prod_date.astype(str).tolist(),
                        table_df.forecast.values.tolist(),
                        table_df.report_overflow.values.tolist(),
                        self.month1, self.month2, self.month3)
         section_sg.append(table_sg)
     self.append(NewPage())
Пример #12
0
 def create_table():
     name = 'name'
     avg_latency = 'avg latency'
     avg_throughput = 'avg throughput'
     q09_latency = 'q0.9 latency'
     q09_throughput = 'q0.9 throughput'
     mbw_local = 'mbw local'
     mbw_remote = 'mbw remote'
     table = Tabular('|c|c|c|c|c|c|c|c|c|c|c|')
     table.add_hline()
     table.add_row((name, avg_latency, avg_throughput, q09_latency, q09_throughput,
                    NUMA_NODE_0, NUMA_NODE_1, NUMA_NODE_2, NUMA_NODE_3, mbw_local, mbw_remote))
     table.add_hline()
     return table
Пример #13
0
    def cria_primeira_secao(self, cabecalho):
        colunas_section_1 = Tabularx('c c c')
        colunas_section_1.add_row([MultiColumn(3, align='c')])

        info_aluno = MiniPage(width=NoEscape(r'0.25\textwidth'),
                              pos='b',
                              align='l')
        graf_media = StandAloneGraphic(filename=self.path_graf_medias,
                                       image_options='width = 180 px')
        box_medias_aluno = MiniPage(width=NoEscape(r'0.23\textwidth'),
                                    pos='b',
                                    align='l')

        info_aluno.append(f'Nome: {self.resumo[1]} {self.resumo[2]}')
        info_aluno.append(NewLine())
        info_aluno.append(f'Número: {self.resumo[5]}')
        info_aluno.append(NewLine())
        info_aluno.append(f'Série: {self.resumo[4]}º ano')
        info_aluno.append(NewLine())
        info_aluno.append(f'Turma: {self.resumo[3]}')
        info_aluno.append(NewLine())
        info_aluno.append(NewLine())
        if self.resumo[9] >= 45:
            info_aluno.append(LargeText(f'Aprovado'))
        else:
            info_aluno.append(LargeText(f'Reprovado'))

        for i in range(3):
            info_aluno.append(NewLine())

        media_final = LargeText(f'Média final: {self.resumo[9]}')
        info_aluno_medias = Tabular('c | c | c', pos='b')
        info_aluno_medias.add_row(cabecalho, mapper=[bold])
        info_aluno_medias.add_hline()
        info_aluno_medias.add_empty_row()
        info_aluno_medias.add_row(
            [self.resumo[6], self.resumo[7], self.resumo[8]])

        box_medias_aluno.append(media_final)
        for i in range(3):
            box_medias_aluno.append(NewLine())

        box_medias_aluno.append(info_aluno_medias)
        for i in range(3):
            box_medias_aluno.append(NewLine())

        colunas_section_1.add_row([info_aluno, graf_media, box_medias_aluno])

        return colunas_section_1
Пример #14
0
def test_table():
    # Tabular
    t = Tabular(table_spec='|c|c|', data=None, pos=None, width=2)

    t.add_hline(start=None, end=None)

    t.add_row((1, 2), escape=False, strict=True, mapper=[bold])
    t.add_row(1, 2, escape=False, strict=True, mapper=[bold])

    # MultiColumn/MultiRow.
    t.add_row((MultiColumn(size=2, align='|c|', data='MultiColumn'), ),
              strict=True)

    # One multiRow-cell in that table would not be proper LaTeX,
    # so strict is set to False
    t.add_row((MultiRow(size=2, width='*', data='MultiRow'), ), strict=False)

    repr(t)

    # TabularX
    tabularx = Tabularx(table_spec='X X X',
                        width_argument=NoEscape(r"\textwidth"))
    tabularx.add_row(["test1", "test2", "test3"])

    # Long Table
    longtable = LongTable(table_spec='c c c')
    longtable.add_row(["test", "test2", "test3"])
    longtable.end_table_header()

    # Colored Tabu
    coloredtable = Tabu(table_spec='X[c] X[c]')
    coloredtable.add_row(["test", "test2"], color="gray", mapper=bold)

    # Colored Tabu with 'spread'
    coloredtable = Tabu(table_spec='X[c] X[c]', spread="1in")
    coloredtable.add_row(["test", "test2"], color="gray", mapper=bold)

    # Colored Tabu with 'to'
    coloredtable = Tabu(table_spec='X[c] X[c]', to="5in")
    coloredtable.add_row(["test", "test2"], color="gray", mapper=bold)

    # Colored Tabularx
    coloredtable = Tabularx(table_spec='X[c] X[c]')
    coloredtable.add_row(["test", "test2"], color="gray", mapper=bold)

    # Column
    column = ColumnType("R", "X", r"\raggedleft", parameters=2)
    repr(column)
Пример #15
0
def test_table():
    # Tabular
    t = Tabular(table_spec='|c|c|', data=None, pos=None, width=2)

    t.add_hline(start=None, end=None)

    t.add_row((1, 2), escape=False, strict=True, mapper=[bold])
    t.add_row(1, 2, escape=False, strict=True, mapper=[bold])

    # MultiColumn/MultiRow.
    t.add_row((MultiColumn(size=2, align='|c|', data='MultiColumn'),),
              strict=True)

    # One multiRow-cell in that table would not be proper LaTeX,
    # so strict is set to False
    t.add_row((MultiRow(size=2, width='*', data='MultiRow'),), strict=False)

    repr(t)

    # TabularX
    tabularx = Tabularx(table_spec='X X X',
                        width_argument=NoEscape(r"\textwidth"))
    tabularx.add_row(["test1", "test2", "test3"])

    # Long Table
    longtable = LongTable(table_spec='c c c')
    longtable.add_row(["test", "test2", "test3"])
    longtable.end_table_header()

    # Colored Tabu
    coloredtable = Tabu(table_spec='X[c] X[c]')
    coloredtable.add_row(["test", "test2"], color="gray", mapper=bold)

    # Colored Tabu with 'spread'
    coloredtable = Tabu(table_spec='X[c] X[c]', spread="1in")
    coloredtable.add_row(["test", "test2"], color="gray", mapper=bold)

    # Colored Tabu with 'to'
    coloredtable = Tabu(table_spec='X[c] X[c]', to="5in")
    coloredtable.add_row(["test", "test2"], color="gray", mapper=bold)

    # Colored Tabularx
    coloredtable = Tabularx(table_spec='X[c] X[c]')
    coloredtable.add_row(["test", "test2"], color="gray", mapper=bold)

    # Column
    column = ColumnType("R", "X", r"\raggedleft", parameters=2)
    repr(column)
Пример #16
0
def create_latex_file(pokemon, list_of_normal_ivs, list_of_boosted_ivs):
    geometry_options = {
        "landscape": True,
        "margin": "0.5in",
        "headheight": "20pt",
        "headsep": "10pt",
        "includeheadfoot": True
    }

    doc = Document(page_numbers=True, geometry_options=geometry_options)

    doc.add_color('color100', 'rgb', rgb_to_dumb_string(0, 207, 194))
    doc.add_color('color98', 'rgb', rgb_to_dumb_string(60, 141, 1))
    doc.add_color('color96', 'rgb', rgb_to_dumb_string(72, 165, 6))
    doc.add_color('color93', 'rgb', rgb_to_dumb_string(242, 183, 8))
    doc.add_color('color91', 'rgb', rgb_to_dumb_string(246, 96, 0))

    section = Section(f'{pokemon.name} IV Chart')

    table = Tabular('|c|c|c|c|c|c|', row_height=1.5)
    table.add_hline()
    table.add_row((MultiColumn(
        6, align='|c|', data=TextColor('white',
                                       pokemon.name), color='black'), ), )

    table.add_row(
        (MultiColumn(1, align='|c',
                     data='Lv20'), MultiColumn(1, align='c|', data='Lv25'),
         MultiColumn(3, align='c|',
                     data='IV'), MultiColumn(1, align='|c|', data='%')))

    for index in range(len(list_of_normal_ivs)):
        n_iv = list_of_normal_ivs[index]
        b_iv = list_of_boosted_ivs[index]

        row_data = (f'{n_iv.cp}', f'{b_iv.cp}', f'{n_iv.attack}',
                    f'{n_iv.defense}', f'{n_iv.stamina}',
                    f'{n_iv.perfection_percent_rounded}')

        table.add_hline()
        table.add_row(row_data,
                      color=color_by_iv(n_iv.perfection_percent_rounded))

    section.append(table)
    doc.append(section)

    doc.generate_tex(f'latex/{pokemon.name}')
    doc.generate_pdf(f'pdf/{pokemon.name}')
Пример #17
0
def test_table():
    # Tabular
    t = Tabular(table_spec='|c|c|', data=None, pos=None)

    t.add_hline(start=None, end=None)

    t.add_row(cells=(1, 2), escape=False, strict=True)

    # MultiColumn/MultiRow.
    t.add_row((MultiColumn(size=2, align='|c|', data='MultiColumn'), ),
              strict=True)

    # One multiRow-cell in that table would not be proper LaTeX,
    # so strict is set to False
    t.add_row((MultiRow(size=2, width='*', data='MultiRow'), ), strict=False)

    repr(t)
Пример #18
0
def test_table():
    # Tabular
    t = Tabular(table_spec='|c|c|', data=None, pos=None)

    t.add_hline(start=None, end=None)

    t.add_row(cells=(1, 2), escape=False, strict=True)

    # MultiColumn/MultiRow.
    t.add_row((MultiColumn(size=2, align='|c|', data='MultiColumn'),),
              strict=True)

    # One multiRow-cell in that table would not be proper LaTeX,
    # so strict is set to False
    t.add_row((MultiRow(size=2, width='*', data='MultiRow'),), strict=False)

    repr(t)
Пример #19
0
def tabela(self: Funkcija) -> NoEscape:
    """
    Vrni tabelo v LaTeX jeziku
    
    fn:Funkcija
        Funkcija
    """
    pravilnostna_tabela = Tabular('|'.join('c' * (self.n + 1)))
    pravilnostna_tabela.add_row(list(self.imena_spr) + [self.tex()])
    pravilnostna_tabela.add_hline()
    if self.n == 0:
        pravilnostna_tabela.add_row(self.pravilni_biti)
        return pravilnostna_tabela
    for minterm, vrednost in zip(range(2**self.n), self.pravilni_biti):
        niz_vhodnih_bitov = minterm_v_niz(minterm, self.n)
        pravilnostna_tabela.add_row(list(niz_vhodnih_bitov) + [vrednost])
    return pravilnostna_tabela
Пример #20
0
    def _subtable(self, idx, subK, octets):
        """
        Generates latex code for a ccsds keys table

        Args:
          * idx (int): the index of the current sub-table in case the
            trousseau needs to be split into several tables
          * subK (list of keys): the list of keys to generate table on
          * octets (bool): corresponding to trousseau.octets
        """
        titles = ('Name', 'Start', 'Len', 'Value')
        table = Tabular('|'.join(['l'] + ['c'] * (len(titles) - 1)))
        if idx > 0:
            table.add_row((MultiColumn(len(titles),
                                       align='c',
                                       data=italic("Continued")), ))
        table.add_row(titles)
        unit = "octets" if octets else "bits"
        table.add_hline()
        table.add_hline()
        start_bit = 0
        for cle in subK:
            if not cle.relative_only:
                start_bit = cle.start
            # if no padding, allows flexible len of the ccsdskey
            the_len = cle.len if cle.pad else "[0..{:d}]".format(cle.len)
            if cle.isdic:
                if cle.dic_force is not None:
                    the_type = repr(cle.dic[cle.dic_force])
                else:
                    the_type = repr(cle.dic.values())
            else:
                the_type = re.search(r'type *= *([\S ]+)',
                                     getattr(cle._fctunpack, 'func_doc', ''))
                if the_type is None:
                    the_type = '-'
                else:
                    the_type = the_type.group(1)
            table.add_row((cle.name, start_bit, the_len, the_type))
            start_bit += cle.len
        table.add_row((MultiColumn(len(titles), align='c',
                                   data='"Start" and "Len" are given in {}'\
                                        .format(unit)),))
        return table
Пример #21
0
    def add_table(self, data=None):
        """ 添加表格

        :param list data: 表格数据
        :return: 无返回值
        """
        nrow = len(data)
        ncol = len(data[0])

        tabsize = '|' + '|'.join(['c'] * ncol) + '|'
        mtable = Tabular(tabsize)

        for i in range(nrow):
            mtable.add_hline()
            mtable.add_row(tuple([str(item) for item in data[i]]))
        mtable.add_hline()
        self.doc.append(Command('begin', arguments='center'))
        self.doc.append(mtable)
        self.doc.append(Command('end', arguments='center'))
Пример #22
0
    def add_table(self, data=None):
        """ 添加表格

        :param list data: 表格数据
        :return: 无返回值
        """
        nrow = len(data)
        ncol = len(data[0])

        tabsize = '|' + '|'.join(['c']*ncol) + '|'
        mtable = Tabular(tabsize)

        for i in range(nrow):
            mtable.add_hline()
            mtable.add_row(tuple([str(item) for item in data[i]]))
        mtable.add_hline()
        self.doc.append(Command('begin',arguments='center'))
        self.doc.append(mtable)
        self.doc.append(Command('end',arguments='center'))
Пример #23
0
    def cria_subsecao(self, cabecalho, tri):

        notas = []
        for n in range(4):
            if self.notas[tri][n + 1] < 0:
                notas.append(0)
            else:
                notas.append(self.notas[tri][n + 1])

        colunas_subsection_1 = Tabular('c c')
        colunas_subsection_1.add_row([MultiColumn(2, align='c')])

        if tri == 0:
            graf_1tri = StandAloneGraphic(filename=self.path_graf_1tri,
                                          image_options='width = 190 px')
        elif tri == 1:
            graf_1tri = StandAloneGraphic(filename=self.path_graf_2tri,
                                          image_options='width = 190 px')
        elif tri == 2:
            graf_1tri = StandAloneGraphic(filename=self.path_graf_3tri,
                                          image_options='width = 190 px')

        box_1tri = MiniPage(width=NoEscape(r'0.49\textwidth'), pos='b')

        info_aluno_1tri = Tabular('c | c | c | c', pos='b')
        info_aluno_1tri.add_row(cabecalho, mapper=[bold])
        info_aluno_1tri.add_hline()
        info_aluno_1tri.add_empty_row()

        info_aluno_1tri.add_row([notas[0], notas[1], notas[2], notas[3]])

        box_1tri.append(info_aluno_1tri)
        box_1tri.append(NewLine())
        box_1tri.append(NewLine())
        box_1tri.append('*As notas das redações estão entre 0 e 8')
        for i in range(3):
            box_1tri.append(NewLine())

        colunas_subsection_1.add_row([graf_1tri, box_1tri])

        return colunas_subsection_1
Пример #24
0
 def print_ensemble_models(self, row):
     # - create a sub_sub_section to easily indent #
     # - subsubsection title is the ensmble name #
     # - table of the ensemble models (layer 0) #
     ensemble_method = row[0]  # name of the ensmble method
     with self.doc.create(
             Subsubsection(self.get_model_name(ensemble_method),
                           numbering=False)):
         # create  table for the ensmeble models #
         self.doc.append(NoEscape(r'\leftskip=40pt'))  # indentation
         self.doc.append('Score: ' + str(row[1]) + '\n\n')
         table = Tabular('|c|c|c|l|')
         table.add_hline()
         # add header of table #
         table.add_row(('Learner', 'Score', 'Parameters', 'weight'))
         table.add_hline()
         # foreach model in the ensemble add row in the table #
         for k in row[3]:
             cur_model = self.experiments.loc[k]
             data = [
                 cur_model[0], cur_model[1],
                 self.format_dict(cur_model[3]), row[3][k]
             ]
             table.add_row(data)
             table.add_hline()
         self.doc.append(table)
Пример #25
0
def gen_main_lift(lift, one_rm, no):
    """Function to return a table for the reps and weights for a given week.

    Arguments:
        lift: Name of the lift
        one_rm: One rep max for the lift
        no: Number of workout (1 - 4)

    Return:
        pylatex table object
    """
    r_and_w = calc_main_lift(one_rm, no)

    table = Tabular('|c|c|c|c|c|c|')
    # table.add_hline()
    # table.add_row((MultiColumn(3, align='|c|', data=lift + " workout " +
    #                str(no)),))
    table.add_hline()
    table.add_row(('Warm up', 'Warm up', 'Warm up', 'Set 1', 'Set 2', 'Set 3'))
    table.add_hline()
    table.add_row(('', '', '', str(r_and_w[1][0]) + ' x ' + str(r_and_w[0][0]),
                   str(r_and_w[1][1]) + ' x ' + str(r_and_w[0][1]),
                   str(r_and_w[1][2]) + ' x ' + str(r_and_w[0][2])))
    table.add_hline()
    return table
Пример #26
0
 def print_ensemble(self, row):
     d = row[3]  # dictionary of dictionaries(of ensembles)
     cnt = 1
     with self.doc.create(
             Subsubsection('Ensemble Selection', numbering=False)):
         self.doc.append(NoEscape(r'\leftskip=40pt'))  # indentation
         self.doc.append('Score: ' + str(row[1]) + '\n\n')
         for sub_d in d:
             self.doc.append('Bag: ' + str(cnt) + '\n\n')
             cnt += 1
             # for every ensemble print it
             table = Tabular('|c|c|c|l|')
             table.add_hline()
             # add header of table #
             table.add_row(('Learner', 'Score', 'Parameters', 'weight'))
             table.add_hline()
             for k in sub_d:
                 cur_model = self.experiments.loc[k]
                 data = [
                     cur_model[0],
                     round(cur_model[1], 4),
                     self.format_dict(cur_model[3]), sub_d[k]
                 ]
                 table.add_row(data)
                 table.add_hline()
             self.doc.append(table)
             self.doc.append('\n\n\n\n')
Пример #27
0
def mostrarDigitos(digitos, doc):
    with doc.create(Subsection('Prueba de Huecos Digitos')):
        jiCuadrado = 0.0
        total = pruebasRandom.sumarTablas(digitos, 20, 10, True)
        sumaTemporal = 0
        frecuenciaTemporal = 0.0

        tablaDigitos = Tabular('|c|c|c|c|c|c|c|')
        tablaDigitos.add_row(
            ('Huecos', 'Pe', 'Fo', 'Fe', '(Fo-Fe)', '(Fo-Fe)2', '(Fo-Fe)2/Fe'))
        for i in range(21):
            if (i != 20):
                promedio = 0.1 * (0.9)**i
                frecuenciaObs = digitos[i][10]
                frecuenciaTemporal = frecuenciaObs
                sumaTemporal += frecuenciaObs

            else:
                promedio = (0.9)**i
                sumaTemporal += digitos[i][10]
                frecuenciaObs = digitos[i][10]
                frecuenciaTemporal = total - sumaTemporal
                frecuenciaTemporal += digitos[i][10]

            frecuenciaEsperada = promedio * total
            fObs_fEsp = frecuenciaTemporal - frecuenciaEsperada
            fObs_fEsp2 = fObs_fEsp**2
            formula = fObs_fEsp2 / frecuenciaEsperada

            fila = (i, promedio, frecuenciaObs, frecuenciaEsperada, fObs_fEsp,
                    fObs_fEsp2, formula)

            tablaDigitos.add_hline()
            tablaDigitos.add_row(fila)

            jiCuadrado += formula
        doc.append(tablaDigitos)
        doc.append(Math(data=['Total', '=', total]))
        doc.append(Math(data=['X2(0)', '=', jiCuadrado]))
Пример #28
0
 def get_table(xdata, ydata):
     N = len(xdata)
     table = Tabular('|c|' + 'c|' * N)
     table.add_hline()
     table.add_row(('x_i', ) + xdata)
     table.add_hline()
     table.add_row(('y_i', ) + ydata)
     table.add_hline()
     return table.dumps()
Пример #29
0
    def latex(self):
        from pylatex import Document, Section, Subsection, Tabular, MultiColumn,\
                            MultiRow

        width = '|'
        for i in range(0, self.__maxColumns()):
            width += 'c|'
        t = Tabular(width)

        colsWidth = []
        for c in self.children[0].children:
            colsWidth.append(c.width)
        for r in self.children:
            if r.hasHline:
                if r.isFullWidthHline():
                    t.add_hline()
                else:
                    start = 1
                    cellsCount = 0
                    end = 0
                    hline = False
                    lastCell = None
                    for i, c in enumerate(r.children):
                        if c.isHline:
                            if start == 1:
                                start = r.children.index(c) + 1
                            cellsCount += c.colspan
                            if i == len(r.children) - 1:
                                end = start + cellsCount - 1
                                t.add_hline(start=start, end=end)
                        else:
                            end = start + cellsCount - 1
                            if (start > 0 and end >= start):
                                t.add_hline(start=start, end=end)
                                start = end + 1
                            else:
                                start = start + c.colspan
                            cellsCount = 0
                            end = 0
            else:
                cellsObjects = r.children
                cells = []

                i = 0
                for c in cellsObjects:
                    if c.colspan == 1:
                        cells.append(str(c.content))
                    else:
                        cells.append(
                            MultiColumn(c.colspan,
                                        align='|c|',
                                        data=str(c.content)))

                t.add_row(cells)
        return t
def generate_latex_tables(df, filepath=None):
    from pylatex import Document, Tabular
    from pylatex.utils import bold

    doc = Document()
    # print(df.columns)
    # print(df.index)
    # print(df)
    header = df.index
    header_str = header.insert(0, 'Measure')
    # header_frmt ="X[l]"
    # header_frmt += " X[c]" * len(header)
    # print(header_str)
    header_frmt = "l"
    header_frmt += "c" * len(header)
    table = Tabular(header_frmt)
    table.add_hline()
    table.add_row(header_str, mapper=[bold])
    table.add_hline()

    # rows = []
    for col in df.columns:
        acol = df[col]
        minval = acol.min()
        minval_loc = acol.argmin()
        # print(minval_loc)
        row = [col]
        for idx, val in acol.iteritems():
            # if idx == minval_loc:
            if val == minval:
                # print("*", val)
                row.append(bold('%.2f' % val))
            else:
                # print(val)
                row.append('%.2f' % val)
        # rows.append(row)
        table.add_row(row)
    table.add_hline()

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

    doc.append(table)
    if filepath is not None:
        print("Saving:", os.path.splitext(filepath)[0])
        doc.generate_pdf(os.path.splitext(filepath)[0], clean_tex=False)
    return doc
Пример #31
0
    def __init__(self, xdata, ydata, basis='1,x,x^2'):
        N = xdata.shape[0]

        table = Tabular('|c|' + 'c|' * N)
        table.add_hline()
        table.add_row(('$x_i$', ) + xdata)
        table.add_hline()
        table.add_row(('$y_i$', ) + ydata)
        table.add_hline()

        template = '用一组基$\\{{{basis}}\\}$拟合数据 %s.' % table.dumps()
        parameter = {'basis': basis, 'xdata': xdata, 'ydata': ydata}
        super(LeastSquareProblem, self).__init__(template, parameter)
Пример #32
0
 def build_statistics_table(self):
     if not self.statistics:
         return
     self.doc.append(Command('centering'))
     with self.doc.create(Section('DP Statistics')):
         table1 = Tabular('|c|c|')
         table1.add_hline()
         table1.add_row((MultiColumn(2, align='|c|', data='Summary'), ))
         table1.add_hline()
         for stat in self.statistics:
             table1.add_row((stat['statistic'], stat['result']['value']))
             table1.add_hline()
         self.doc.append(table1)
Пример #33
0
 def create_platform_unit_legend():
     rows = '|c|'
     for _ in metrics.MetricLegends:
         rows += 'c|'
     table = Tabular(rows)
     title_row = [bold('Metric')]
     unit_row = [bold('Unit')]
     for metric in metrics.MetricLegends:
         title_row.append(metrics.MetricLegends[metric]['name'])
         unit_row.append(metrics.MetricLegends[metric]['unit'])
     table.add_hline()
     table.add_row(tuple(title_row))
     table.add_hline()
     table.add_row(tuple(unit_row))
     table.add_hline()
     return table
 def create_unit_legend():
     rows = '|c|'
     for _ in RESULTS_METADATA:
         rows += 'c|'
     table = Tabular(rows)
     title_row = [bold('Metric')]
     unit_row = [bold('Unit')]
     for metric in RESULTS_METADATA.keys():
         title_row.append(RESULTS_METADATA[metric][NAME])
         unit_row.append(RESULTS_METADATA[metric][UNIT])
     table.add_hline()
     table.add_row(tuple(title_row))
     table.add_hline()
     table.add_row(tuple(unit_row))
     table.add_hline()
     return table
Пример #35
0
def generate_comparison(dims, algorithm_names, algorithm_results, mode='COST'):

    # Creating the document
    from_mode = ''
    if mode == 'COST':
        doc = Document('latex_tables/generated_table_cost_comparison')
        section = Section("Table of Costs")
        from_mode = "{:.2f}"
    if mode == 'TIME':
        doc = Document('latex_tables/generated_table_time_comparison')
        section = Section("Table of Times")
        from_mode = "{:.2e}"

    # Setting tabular property
    tabular_header = 'c'
    for i in algorithm_names:
        tabular_header += 'c'

    # Creation of the Table
    table = Tabular(tabular_header)
    table.add_row((MultiColumn(len(algorithm_names) + 1,
                               align='c',
                               data='Costs'), ))
    table.add_hline()
    table.add_hline()
    table.add_row(['Nodi'] + algorithm_names)
    table.add_hline()

    for i in range(len(dims)):

        table.add_row((dims[i], from_mode.format(algorithm_results[0][i]),
                       from_mode.format(algorithm_results[1][i]),
                       from_mode.format(algorithm_results[2][i]),
                       from_mode.format(algorithm_results[3][i]),
                       from_mode.format(algorithm_results[4][i])))

    # We close the table
    table.add_hline()

    # And finally we compose and generate the new document with the embedded table
    section.append(table)
    doc.append(section)
    doc.generate_tex()
Пример #36
0
    def add_table_to_test(self, format_string, data, headings, caption=""):
        """Adds a figure to the current section of the report

        Adds a pdf image in the form of a figure to the current section of the report. 
        The image name specifies the image, without the pdf extension. 

        Args: 
            format_string (str): defines the format of the table.
            data (array or list of list): The data to fill the table.
            headings (list of str): The column headings.
            caption (str): The caption to be placed below the table.

        Returns:
        """

        self.doc.append(NoEscape(r'\begin{figure}[htbp]'))
        self.doc.append(NoEscape(r'\centering'))
        self.doc.append(NoEscape(r'\caption{' + caption + '}'))
        table = Tabular(format_string)
        table.add_hline()

        for index in range(len(headings)):
            table.add_row(headings[index])

        table.add_hline()

        for index in range(len(data)):

            data[index] = np.round_(data[index], 2)
            data[index] = data[index].tolist()
            if len(data[index]) > 20:
                data[index] = self._decimate_list(
                    data[index], 20)  # number of samples in table

        for iterations in range(len(data[0])):
            row = []
            for index in range(len(data)):
                row.append((data[index]).pop(0))
            table.add_row(row)
        table.add_hline()
        self.doc.append(table)
        self.doc.append(NoEscape(r'\end{figure}'))
Пример #37
0
                for i in range(0, len(times)):
                    coords.append((i, times[i]))
                plot.append(Plot(name=opt, coordinates=coords))

coords = {}
objs = {}
for o in options:
    coords[o] = []
    objs[o] = []
objs['syb'] = []
pol='SAT'
# Second summary
section = Section('Summary : %d problems, %d configurations.' % (len(fnames), len(options)))
doc.append(section)
table = Tabular('|l||c|c||c|c||c|')
table.add_hline()
table.add_row(("", MultiColumn(2, align='c||', data="CSP"), MultiColumn(2, align='c||',data='COP'), "Times best"))
table.add_row(("Config.", 'sat', "unsat", "best", "proof","< %.1f" % maxtime))
table.add_hline()
for opt in options:
    sat = 0
    unsat = 0
    proof = 0
    fbest = 0
    tbest = 0
    for fname in fnames:
        print(opt + '->' + fname)
        solutions = optPerSol[fname]
        gbest = solutions[0][4]
        mybest = gbest
        gtime = solutions[0][1]
Пример #38
0
doc.append('Some text.')

doc.generate_tex(filepath='')
doc.generate_pdf(filepath='', clean=True)

# SectionBase
s = Section(title='', numbering=True, data=None)

# Math
m = Math(data=None, inline=False)

# Tabular
t = Tabular(table_spec='|c|c|', data=None, pos=None)

t.add_hline(start=None, end=None)

t.add_row(cells=(1, 2), escape=False)

t.add_multicolumn(size=2, align='|c|', content='Multicol', cells=None,
                  escape=False)


t.add_multirow(size=3, align='*', content='Multirow', hlines=True, cells=None,
               escape=False)

# MultiColumn/MultiRow.
t.add_row((MultiColumn(size=2, align='|c|', data='MultiColumn'),))

t.add_row((MultiRow(size=2, width='*', data='MultiRow'),))
Пример #39
0
    :license: MIT, see License for more details.
"""

# begin-doc-include
from pylatex import Document, Section, Subsection, Tabular, MultiColumn, MultiRow

doc = Document("multirow")
section = Section("Multirow Test")

test1 = Subsection("MultiColumn")
test2 = Subsection("MultiRow")
test3 = Subsection("MultiColumn and MultiRow")
test4 = Subsection("Vext01")

table1 = Tabular("|c|c|c|c|")
table1.add_hline()
table1.add_row((MultiColumn(4, align="|c|", data="Multicolumn"),))
table1.add_hline()
table1.add_row((1, 2, 3, 4))
table1.add_hline()
table1.add_row((5, 6, 7, 8))
table1.add_hline()
row_cells = ("9", MultiColumn(3, align="|c|", data="Multicolumn not on left"))
table1.add_row(row_cells)
table1.add_hline()

table2 = Tabular("|c|c|c|")
table2.add_hline()
table2.add_row((MultiRow(3, data="Multirow"), 1, 2))
table2.add_hline(2, 3)
table2.add_row(("", 3, 4))
Пример #40
0
#!/usr/bin/python

from pylatex import Document, Section, Subsection, Tabular, MultiColumn,\
    MultiRow

doc = Document("multirow")
section = Section('Multirow Test')

test1 = Subsection('MultiColumn')
test2 = Subsection('MultiRow')
test3 = Subsection('MultiColumn and MultiRow')
test4 = Subsection('Vext01')

table1 = Tabular('|c|c|c|c|')
table1.add_hline()
table1.add_row((MultiColumn(4, '|c|', 'Multicolumn'),))
table1.add_hline()
table1.add_row((1, 2, 3, 4))
table1.add_hline()
table1.add_row((5, 6, 7, 8))
table1.add_hline()
row_cells = ('9', MultiColumn(3, '|c|', 'Multicolumn not on left'))
table1.add_row(row_cells)
table1.add_hline()

table2 = Tabular('|c|c|c|')
table2.add_hline()
table2.add_row((MultiRow(3, '*', 'Multirow'), 1, 2))
table2.add_hline(2, 3)
table2.add_row(('', 3, 4))
table2.add_hline(2, 3)