Пример #1
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)
Пример #2
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
Пример #3
0
 def _document_init_params(self) -> None:
     """Add initialization parameters to the traceability document.
     """
     with self.doc.create(Section("Parameters")):
         model_ids = {
             FEID(id(model))
             for model in self.system.network.models
             if isinstance(model, (tf.keras.Model, torch.nn.Module))
         }
         datasets = {
             FEID(id(self.system.pipeline.data.get(title, None))):
             (title, self.system.pipeline.data.get(title, None))
             for title in ['train', 'eval', 'test']
         }
         for tbl in self.config_tables:
             name_override = None
             toc_ref = None
             extra_rows = None
             if issubclass(tbl.type, Estimator):
                 toc_ref = "Estimator"
             if issubclass(tbl.type, BaseNetwork):
                 toc_ref = "Network"
             if issubclass(tbl.type, Pipeline):
                 toc_ref = "Pipeline"
             if tbl.fe_id in model_ids:
                 # Link to a later detailed model description
                 name_override = Hyperref(
                     Marker(name=str(tbl.name), prefix="subsec"),
                     text=NoEscape(r'\textcolor{blue}{') + bold(tbl.name) +
                     NoEscape('}'))
                 toc_ref = tbl.name
             if tbl.fe_id in datasets:
                 title, dataset = datasets[tbl.fe_id]
                 name_override = bold(f'{tbl.name} ({title.capitalize()})')
                 toc_ref = f"{title.capitalize()} Dataset"
                 # Enhance the dataset summary
                 if isinstance(dataset, FEDataset):
                     extra_rows = list(
                         dataset.summary().__getstate__().items())
                     for idx, (key, val) in enumerate(extra_rows):
                         key = f"{prettify_metric_name(key)}:"
                         if isinstance(val, dict) and val:
                             if isinstance(
                                     list(val.values())[0],
                                 (int, float, str, bool, type(None))):
                                 val = jsonpickle.dumps(val,
                                                        unpicklable=False)
                             else:
                                 subtable = Tabular('l|l')
                                 for k, v in val.items():
                                     if hasattr(v, '__getstate__'):
                                         v = jsonpickle.dumps(
                                             v, unpicklable=False)
                                     subtable.add_row((k, v))
                                 val = subtable
                         extra_rows[idx] = (key, val)
             tbl.render_table(self.doc,
                              name_override=name_override,
                              toc_ref=toc_ref,
                              extra_rows=extra_rows)
Пример #4
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
Пример #5
0
    def gen_smpl(self, idx, n_digits, n_nums, var_digits=0):
        """ generate an example of a simple addition 
        """
        assert (n_digits >= 1)
        assert (var_digits < n_digits)
        q_tab = Tabular(' c r ', row_height=1.2)

        # contents...
        nums = [gen_rnd(n_digits, var_digits) for n in range(0, n_nums)]
        sgns = [sign(randint(-1000000, 1000000)) for n in range(0, n_nums)]

        sign_syms = list(map(lambda x: '+' if x == 1 else '-', sgns))

        sum_str = ''.join(
            [sign_syms[n] + str(nums[n]) for n in range(0, n_nums)])
        if sum_str[0] == '+':
            sum_str = sum_str[1:]  # tail if leading with a '+'

        mth = Math(escape=False, inline=True)
        mth.append(NoEscape(sum_str + '='))
        q_tab.add_row((bold(str(idx) + ':'), mth))

        a_tab = Tabular(' l l ', row_height=1.1)
        a_idx = bold(str(idx) + ":")
        res = sum(multiply(nums, sgns))
        a_tab.add_row((a_idx, res))

        #print(sum_str, '=', res)
        return (q_tab, a_tab)
Пример #6
0
def test_errors():
    # Errors

    # TableRowSizeError

    # General test

    try:
        raise TableRowSizeError
    except TableRowSizeError:
        pass

    # Positive test, expected to raise Error

    t = Tabular(table_spec='|c|c|', data=None, pos=None)
    try:
        # Wrong number of cells in table should raise an exception
        t.add_row(cells=(1, 2, 3), escape=False, strict=True)
    except TableRowSizeError:
        pass

    # Negative test, should not raise
    try:
        # Wrong number with strict=False should not raise an exception
        t.add_row(cells=(1, 2, 3), escape=False, strict=False)
    except TableRowSizeError:
        raise
Пример #7
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
Пример #8
0
def test_errors():
    # Errors

    # TableRowSizeError

    # General test

    try:
        raise TableRowSizeError
    except TableRowSizeError:
        pass

    # Positive test, expected to raise Error

    t = Tabular(table_spec='|c|c|', data=None, pos=None)
    # TODO: this does not actually check if the error is raised
    try:
        # Wrong number of cells in table should raise an exception
        t.add_row((1, 2, 3), escape=False, strict=True)
    except TableRowSizeError:
        pass

    # Negative test, should not raise
    try:
        # Wrong number with strict=False should not raise an exception
        t.add_row((1, 2, 3), escape=False, strict=False)
    except TableRowSizeError:
        raise
Пример #9
0
    def add_row_basic(
        tabular: pylatex.Tabular,
        optics: typ.Union[esis.optics.Optics, typ.Tuple[esis.optics.Optics,
                                                        esis.optics.Optics]],
        name_major: str = '',
        name_minor: str = '',
        value_str: str = '',
        psf_size: u.Quantity = 0 * u.um,
        mtf_actual: u.Quantity = 1.0 * u.dimensionless_unscaled,
    ):

        mtf = to_mtf(psf_size)

        tabular.add_row([
            name_major,
            name_minor,
            value_str,
            f'{psf_size.to(u.pix).value:0.2f}',
            f'{(psf_size * optics.plate_scale.y).to(u.arcsec).value:0.2f}',
            f'{mtf.value:0.3f}',
            f'{mtf_actual.value:0.3f}',
        ])

        accumulator['psf_size_squared'] += np.square(psf_size)
        accumulator['mtf_actual'] *= mtf_actual
        accumulator['mtf'] *= mtf
Пример #10
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')
Пример #11
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()
 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
Пример #13
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())
Пример #14
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
Пример #16
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)
Пример #17
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)
    def create_platform_unit_legend():
        rows = '|c|'
        title_row = [bold('Metric')]
        unit_row = [bold('Unit')]

        rows2 = '|c|'
        title_row2 = [bold('Metric')]
        unit_row2 = [bold('Unit')]
        i = 0
        for metric in metrics.MetricLegends:
            if i < 10:
                rows += 'c|'
                title_row.append(metrics.MetricLegends[metric]['name'])
                unit_row.append(metrics.MetricLegends[metric]['unit'])
            else:
                rows2 += 'c|'
                title_row2.append(metrics.MetricLegends[metric]['name'])
                unit_row2.append(metrics.MetricLegends[metric]['unit'])
            i += 1
        table = Tabular(rows)
        table.add_hline()
        table.add_row(tuple(title_row))
        table.add_hline()
        table.add_row(tuple(unit_row))
        table.add_hline()

        table2 = Tabular(rows2)
        table2.add_hline()
        table2.add_row(tuple(title_row2))
        table2.add_hline()
        table2.add_row(tuple(unit_row2))
        table2.add_hline()

        return table, table2
Пример #19
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())
Пример #20
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
Пример #21
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
Пример #22
0
 def gen_smpl(self, idx, n_digits, n_nums, var_digits=0):
     """ generate an example of a simple addition 
     """
     assert (n_digits >= 1)
     assert (var_digits < n_digits)
     q_tab = Tabular(' c r ', row_height=1.2)
     nums = [gen_rnd(n_digits, var_digits) for n in range(0, n_nums)]
     sum_str = functools.reduce(lambda x, y: str(x) + '-' + str(y), nums)
     mth = Math(escape=False, inline=True)
     mth.append(NoEscape(sum_str + '='))
     q_tab.add_row((bold(str(idx) + ':'), mth))
     a_tab = Tabular(' l l ', row_height=1.1)
     a_idx = bold(str(idx) + ":")
     a_tab.add_row((a_idx, nums[0] - sum(nums[1:])))
     return (q_tab, a_tab)
 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
Пример #24
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
Пример #25
0
    def add_mtf(
        tabular: pylatex.Tabular,
        name_major: str = '',
        name_minor: str = '',
        value_str: str = '',
        mtf: u.Quantity = 0 * u.dimensionless_unscaled,
    ):
        accumulator['mtf'] *= mtf

        tabular.add_row([
            name_major,
            name_minor,
            value_str,
            f'',
            f'',
            f'{mtf.value:0.3f}',
        ])
Пример #26
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'))
Пример #27
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'))
Пример #28
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}'))
Пример #29
0
def gen_accessory_table(accessorys):
    """Function to return a table for accessory exercises.

    Function to return a 'table' object for a given set of accessory exercises.

    Arguments:
        3 x n table with [name, sets, reps]

    Return:
        Table with the required columns for sets reps and weights.
    """
    table = Tabular('|c|c|c|c|c|c|c|c|c|')
    table.add_hline()
    table.add_row(('Exercise', 'Weight', 'Reps', 'Weight', 'Reps', 'Weight',
                   'Reps', 'Weight', 'Reps'))
    table.add_hline()
    for i in range(len(accessorys)):
        table.add_row((str(accessorys[i]), '', '', '', '', '', '', '', ''))
        table.add_hline()
    return table
Пример #30
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'), ))
Пример #31
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)
Пример #32
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)
Пример #33
0
    def _write_tables(self,
                      tables: List[FeSummaryTable],
                      model_ids: Set[FEID],
                      datasets: Dict[FEID, Tuple[Set[str], Any]]) -> None:
        """Insert a LaTeX representation of a list of tables into the current doc.

        Args:
            tables: The tables to write into the doc.
            model_ids: The ids of any known models.
            datasets: A mapping like {ID: ({modes}, dataset)}. Useful for augmenting the displayed information.
        """
        for tbl in tables:
            name_override = None
            toc_ref = None
            extra_rows = None
            if tbl.fe_id in model_ids:
                # Link to a later detailed model description
                name_override = Hyperref(Marker(name=str(tbl.name), prefix="subsec"),
                                         text=NoEscape(r'\textcolor{blue}{') + bold(tbl.name) + NoEscape('}'))
            if tbl.fe_id in datasets:
                modes, dataset = datasets[tbl.fe_id]
                title = ", ".join([s.capitalize() for s in modes])
                name_override = bold(f'{tbl.name} ({title})')
                # Enhance the dataset summary
                if isinstance(dataset, FEDataset):
                    extra_rows = list(dataset.summary().__getstate__().items())
                    for idx, (key, val) in enumerate(extra_rows):
                        key = f"{prettify_metric_name(key)}:"
                        if isinstance(val, dict) and val:
                            if isinstance(list(val.values())[0], (int, float, str, bool, type(None))):
                                val = jsonpickle.dumps(val, unpicklable=False)
                            else:
                                subtable = Tabular('l|l')
                                for k, v in val.items():
                                    if hasattr(v, '__getstate__'):
                                        v = jsonpickle.dumps(v, unpicklable=False)
                                    subtable.add_row((k, v))
                                val = subtable
                        extra_rows[idx] = (key, val)
            tbl.render_table(self.doc, name_override=name_override, toc_ref=toc_ref, extra_rows=extra_rows)
Пример #34
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)
Пример #35
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"),))
Пример #36
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)
Пример #37
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)
Пример #38
0
                    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]
        mytime = gtime
Пример #39
0
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'),))


# Command
Пример #40
0
"""

# 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))
table2.add_hline(2, 3)
Пример #41
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)