Пример #1
0
def latex_table(inner_tabular: str,
                position="H",
                caption=None,
                escape_caption=False,
                label=None,
                output_filepath=None):
    table = Table(position=position)
    table.append(NoEscape(inner_tabular))

    if caption:
        caption_ = caption if escape_caption else NoEscape(caption)
        table.add_caption(caption_)

    if label:
        table.append(NoEscape("\label{{tab:{label}}}".format(label=label)))

    if output_filepath:
        table.generate_tex(output_filepath)

    return table.dumps()
Пример #2
0
def build_document(transcript):
    """
    Processes a Transcript object to build a LaTeX document.
    """
    # Open temporary file
    doc = Document(documentclass='scrartcl',
                   title=transcript.title,
                   subtitle=transcript.school,
                   author=transcript.student,
                   date=transcript.date.strftime('%d %B %Y'),
                   temporary=True)

    doc.packages.append(Package('geometry', option='margin=1.0in'))
    doc.preamble.append(
        Command('renewcommand', argument=['\\familydefault', '\\sfdefault']))

    doc.append(Command('maketitle'))

    # Iterate through each transcript section
    for t_section in transcript.sections:
        # Create new section
        s = Section(escape_latex(t_section.title))
        # Add content to section
        for s_line in t_section.content:
            s_line = '\t'.join(s_line)
            s.append(escape_latex(s_line) + ' \\\n')

        # Add subsections to section
        for t_subsection in t_section.subsections:
            ss = Subsection(escape_latex(t_subsection.title))
            num_cols = max(len(l) for l in t_subsection.content)
            ss_table = Table(' l ' * num_cols)
            # Add content to subsection
            for ss_line in t_subsection.content:

                ss_line = '\t'.join(ss_line)
                if ss_line.startswith('Course Topic'):
                    ss_table.append('&')
                    ss_table.add_multicolumn(num_cols - 1, 'l',
                                             escape_latex(ss_line))
                    ss_table.append(r'\\')
                elif not ss_line[:3].isupper() and not ss_line.startswith(
                        'Test'):
                    ss_table.add_multicolumn(num_cols, 'l',
                                             escape_latex(ss_line))
                    ss_table.append(r'\\')
                else:
                    if ss_line.startswith('TERM'):
                        ss_table.add_hline()
                    filled = escape_latex(ss_line).split('\t')
                    filled += (num_cols - len(filled)) * ['']
                    ss_table.add_row(filled)

            ss.append(ss_table)
            s.append(ss)

        doc.append(s)
    doc.generate_pdf(clean=True)

    return doc
def build_document(transcript):
    """
    Processes a Transcript object to build a LaTeX document.
    """
    # Open temporary file
    doc = Document(documentclass='scrartcl', title=transcript.title,
                   subtitle=transcript.school,
                   author=transcript.student,
                   date=transcript.date.strftime('%d %B %Y'), temporary=True)

    doc.packages.append(Package('geometry', option='margin=1.0in'))
    doc.preamble.append(Command('renewcommand', argument=['\\familydefault', '\\sfdefault']))

    doc.append(Command('maketitle'))

    # Iterate through each transcript section
    for t_section in transcript.sections:
        # Create new section
        s = Section(escape_latex(t_section.title))
        # Add content to section
        for s_line in t_section.content:
            s_line = '\t'.join(s_line)
            s.append(escape_latex(s_line) + ' \\\n')

        # Add subsections to section
        for t_subsection in t_section.subsections:
            ss = Subsection(escape_latex(t_subsection.title))
            num_cols = max(len(l) for l in t_subsection.content)
            ss_table = Table(' l ' * num_cols)
            # Add content to subsection
            for ss_line in t_subsection.content:

                ss_line = '\t'.join(ss_line)
                if ss_line.startswith('Course Topic'):
                    ss_table.append('&')
                    ss_table.add_multicolumn(num_cols-1, 'l',
                                             escape_latex(ss_line))
                    ss_table.append(r'\\')
                elif not ss_line[:3].isupper() and not ss_line.startswith('Test'):
                    ss_table.add_multicolumn(num_cols, 'l', escape_latex(ss_line))
                    ss_table.append(r'\\')
                else:
                    if ss_line.startswith('TERM'):
                        ss_table.add_hline()
                    filled = escape_latex(ss_line).split('\t')
                    filled += (num_cols - len(filled)) * ['']
                    ss_table.add_row(filled)

            ss.append(ss_table)
            s.append(ss)

        doc.append(s)
    doc.generate_pdf(clean=True)

    return doc
Пример #4
0
])
spf_desc_stat.iloc[8, :] = np.array([
    stats.skew(spf_bal_RGDP_1Y.iloc[:, 0].values, axis=0),
    stats.skew(spf_bal_RGDP_2Y.iloc[:, 0].values, axis=0),
    stats.skew(spf_bal_HICP_1Y.iloc[:, 0].values, axis=0),
    stats.skew(spf_bal_HICP_2Y.iloc[:, 0].values, axis=0),
    stats.skew(spf_bal_UNEM_1Y.iloc[:, 0].values, axis=0),
    stats.skew(spf_bal_UNEM_2Y.iloc[:, 0].values, axis=0),
])

# create table object
tabl = Table()
tabl.add_caption(
    "Descriptive statistics of the SPF target macroeconomic variables for the euro area"
)
tabl.append(NoEscape('\label{tab: spf_Desc_Stats}'))
# create tabular object
tabr = Tabular(table_spec="l|cc|cc|cc")
tabr.add_hline()
tabr.add_hline()
# header row

tabr.add_row(
    (MultiRow(2, data="Statistic"), MultiColumn(2, align='|c|', data="RGDP"),
     MultiColumn(2, align='|c|',
                 data="HICP"), MultiColumn(2, align='|c', data="UNEM")))
tabr.add_hline(start=2, end=3, cmidruleoption="lr")
tabr.add_hline(start=4, end=5, cmidruleoption="lr")
tabr.add_hline(start=6, end=7, cmidruleoption="lr")
tabr.add_row([""] + ["1Y", "2Y"] + ["1Y", "2Y"] + ["1Y", "2Y"])
tabr.add_hline()
Пример #5
0
                                            str(w))

    # concatenate the tables together
    spf_multitable = pd.concat([
        acc_table_RGDP_1Y, acc_table_RGDP_2Y, acc_table_HICP_1Y,
        acc_table_HICP_2Y, acc_table_UNEM_1Y, acc_table_UNEM_2Y
    ],
                               axis=1,
                               join_axes=[acc_table_RGDP_1Y.index])

    # create table object
    tabl = Table()
    tabl.add_caption(
        "Performance of forecast combinations of ECB SPF forecasts using the training window of the length: "
        + str(w))
    tabl.append(NoEscape('\label{tab: spf_comb_perf_' + str(w) + '}'))
    # create tabular object
    tabr = Tabular(table_spec="c|l" + 6 * "|ccc")
    tabr.add_hline()
    tabr.add_hline()
    # header row
    tabr.add_row(
        (MultiRow(3,
                  data="Class"), MultiRow(3,
                                          data="Forecast Combination Method"),
         MultiColumn(6, align='|c|',
                     data="RGDP"), MultiColumn(6, align='|c|', data="HICP"),
         MultiColumn(6, align='|c', data="UNEM")))
    tabr.add_hline(start=3, end=20, cmidruleoption="lr")
    tabr.add_row(("", "", MultiColumn(3, align='|c|', data="1Y"),
                  MultiColumn(3, align='|c|',
Пример #6
0
    def build_latex(metrics: List[Metric], invert=False, caption=""):
        models, metric_labels, splits = {}, {}, {}
        score_map = defaultdict(lambda: "-")
        for metric in metrics:
            metric_vals = metric()
            score, metric_label, model_name, split_name = (
                metric_vals[SCORE],
                metric_vals[METRIC_LABEL],
                metric_vals[MODEL_NAME],
                metric_vals[SPLIT_NAME],
            )
            metric_labels[metric_label] = 1
            models[model_name] = 1
            splits[split_name] = 1
            score_map[(metric_label, model_name,
                       split_name)] = ("-" if math.isnan(score) else score)

        models = list(models.keys())
        splits = list(splits.keys())
        metric_labels = list(metric_labels.keys())

        if not invert:
            model_split_cols = "".join(
                ["c|" for _ in range(len(models) * len(splits))])
            table = Tabular("|c|" + model_split_cols)
            table.add_hline()
            row = (MultiRow(
                2, data="Metric"), ) if len(splits) > 1 else ("Metric", )
            for model_name in models:
                row += (MultiColumn(len(splits), align="|c|",
                                    data=model_name), )
            table.add_row(row)
            table.add_hline(1 if len(splits) == 1 else 2)
            if (len(splits)) > 1:
                row = ("", )
                for _ in range(len(models)):
                    for split_name in splits:
                        row += (split_name, )
                table.add_row(row)
                table.add_hline()
            for metric_label in metric_labels:
                row = (metric_label, )
                for model_name in models:
                    for split_name in splits:
                        row += (score_map[(metric_label, model_name,
                                           split_name)], )
                table.add_row(row)
                table.add_hline()
        else:
            metric_split_labels = "".join(
                ["c|" for _ in range(len(metric_labels))])
            table = Tabular("|c|" if len(splits) == 1 else "|c|c|" +
                            metric_split_labels)
            table.add_hline()
            row = (MultiColumn(2, align="|c|",
                               data=""), ) if len(splits) > 1 else ("", )
            for metric_label in metric_labels:
                row += (metric_label, )
            table.add_row(row)
            table.add_hline()
            for model_name in models:
                row = (MultiRow(len(splits), data=model_name), )
                for split_name in splits:
                    row += (split_name, )
                    for metric_label in metric_labels:
                        row += (score_map[(metric_label, model_name,
                                           split_name)], )
                    table.add_row(row)
                    if len(splits) > 1:
                        table.add_hline(start=2)
                    row = ("", )
                table.add_hline()

        latex_table = Table(position="h")
        latex_table.append(table)
        latex_table.add_caption(caption)
        return latex_table
Пример #7
0
    def to_tex(self):

        tab = self._create_tabular()
        tab.add_hline()
        for i in range(self.sheet.nrows):
            line = []
            merge_set = set()
            for j in range(self.sheet.ncols):
                res, mindex = self.in_merge_cell(i, j)

                if res == -1:
                    line.append(self.cell(i, j))
                else:
                    merge_set.add(mindex)
                    cres, cnum = self.ismulticol(mindex)
                    rres, rnum = self.ismultirow(mindex)
                    if res == 0:
                        if cres:
                            if rres:
                                line.append(
                                    MultiColumn(
                                        cnum,
                                        align=self._cacu_multicol_align(j),
                                        data=MultiRow(rnum,
                                                      data=self.cell(i, j))))
                            else:
                                line.append(
                                    MultiColumn(
                                        cnum,
                                        align=self._cacu_multicol_align(j),
                                        data=self.cell(i, j)))
                        else:
                            line.append(MultiRow(rnum, data=self.cell(i, j)))
                    elif res == 1:  # 不同行同列
                        if cres and rres:
                            line.append(
                                MultiColumn(cnum,
                                            align=self._cacu_multicol_align(j),
                                            data=""))
                        else:
                            line.append("")
                    elif res == 2:  # 不同列同行
                        pass

            tab.add_row(line)

            all_range = [[0, self.sheet.ncols - 1]]
            for mi in merge_set:
                merge_range = self.merge_col[mi]

                if merge_range[1] - merge_range[0] > 0 and merge_range[
                        1] - i > 0:
                    all_range = self._extract_range(all_range,
                                                    merge_range[2:4])

            if all_range[0][0] == 0 and all_range[0][1] == self.sheet.ncols - 1:
                tab.add_hline()
            else:
                for r in all_range:
                    tab.add_hline(r[0] + 1, r[1] + 1)

        table = TexTable(position=self.params["position"])
        table.append(tab)

        res = table
        if self.params["center"]:
            c = Center()
            c.append(
                NoEscape(
                    r"% \newlength\tablewidth % if haven't define the length 'tablewidth'"
                ))
            c.append(
                NoEscape(
                    rf"\setlength\tablewidth{{\dimexpr (\textwidth -{2*self.sheet.ncols}\tabcolsep)}}"
                ))
            c.append(table)
            res = c

        return self._format_tex(res.dumps())
Пример #8
0
def gen_tex_table(tbl, cap, file_name, r):
    """
    The function creates a tex file to which it export the given table from
    python.

    Parameters
    ----------
    tbl : DataFrame
        DataFrame containing the table to be exported.

    cap : Str
        Table caption.

    file_name : Str
        Name of the tex file in the "Tables" directory.


    r : Int
       Number of decimals to round up the metrics.
    """

    # create tabule object
    tabl = Table()
    tabl.add_caption(cap)
    tabl.append(NoEscape("\label{tab: " + cap + "}"))

    # create tabular object
    tabr = Tabular(table_spec="lccc")
    tabr.add_hline()
    tabr.add_hline()

    # header row
    tabr.add_row(["Forecast Combination Method"] + list(tbl))
    tabr.add_hline()

    # number of combination methods + additional rows
    R = tbl.shape[0]

    # specify format
    fmt = "{:." + str(r) + "f}"

    # fill in the rows for each combination method (-3 for individuals)
    for i in range(R-3):

        tabr.add_row([tbl.index[i]] + [
                fmt.format(item) for item in tbl.iloc[i, :]])

    tabr.add_hline()

    # additional rows
    for i in range(R-3, R):

        tabr.add_row([tbl.index[i]] + [
                fmt.format(item) for item in tbl.iloc[i, :]])

    # end of table
    tabr.add_hline()
    tabr.add_hline()

    # add tabular to table
    tabl.append(tabr)

    # export the table
    tabl.generate_tex("C:/Users/Marek/Dropbox/Master_Thesis/Latex/Tables/" +
                      file_name)

    return
                             index=ds_stats)
ret_desc_stat.iloc[0, :] = np.mean(ret.values, axis=0)
ret_desc_stat.iloc[1, :] = np.median(ret.values, axis=0)
ret_desc_stat.iloc[2, :] = stats.mode(ret.values, axis=0)[0]
ret_desc_stat.iloc[3, :] = np.std(ret.values, axis=0)
ret_desc_stat.iloc[4, :] = np.var(ret.values, axis=0)
ret_desc_stat.iloc[5, :] = np.min(ret.values, axis=0)
ret_desc_stat.iloc[6, :] = np.max(ret.values, axis=0)
ret_desc_stat.iloc[7, :] = stats.kurtosis(ret.values, axis=0)
ret_desc_stat.iloc[8, :] = stats.skew(ret.values, axis=0)

# create table object
tabl = Table()
tabl.add_caption(
    "Descriptive statistics of log-returns of U.S. Treasury futures")
tabl.append(NoEscape('\label{tab: Bond_ret_Desc_Stats}'))
# create tabular object
tabr = Tabular(table_spec="lcccc")
tabr.add_hline()
tabr.add_hline()
# header row
tabr.add_row(["Statistic"] + tickers)
tabr.add_hline()
# fill in the rows of tabular
for i in range(9):
    tabr.add_row([ds_stats[i]] +
                 ["{:.7f}".format(item) for item in ret_desc_stat.iloc[i, :]])
# end of table
tabr.add_hline()
tabr.add_hline()
# add tabular to table
Пример #10
0
# randomization inference p-values
p = np.mean(abs(beta_original) <= abs(beta_dist), axis=0)

# fill the output table
output_table.iloc[:, [4, 6]] = beta_original.reshape((3, 2))
output_table.iloc[:, [5, 7]] = p.reshape((3, 2))

########################
# Printing output table#
########################
# create tabule object
tabl = Table()
tabl.add_caption(
    "Estimates of the effects of changing price rules on differents variables for both categories along with the p-values from the randomization inference."
)
tabl.append(NoEscape("\label{tab: output_table}"))

# create tabular object
tabr = Tabular(table_spec="l|cc|cc|cc|cc")
tabr.add_hline()
tabr.add_hline()

# header row
tabr.add_row((MultiRow(3, data="Dependent Variable"),
              MultiColumn(4, align='|c|', data="Mobile Phones"),
              MultiColumn(4, align='|c', data="Water Heaters")))
tabr.add_hline(start=2, end=9, cmidruleoption="lr")
tabr.add_row(
    ("", MultiColumn(2, align='|c|', data="Pilot 1"),
     MultiColumn(2, align='|c|',
                 data="Pilot 2"), MultiColumn(2, align='|c|', data="Pilot 1"),