예제 #1
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
예제 #2
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
예제 #3
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
예제 #4
0
        def InsDatosFamiliares():
            with self.doc.create(SectionUnnumbered("Datos Familiares")):
                Command("vspace", NoEscape("-1ex"))
                self.doc.append(NoEscape(\
                 r"{}: {} {}: {}\\{}: {} {}: {}\\"\
                 .format(bold("Nombre del Padre"), makeUnderline(self.data["Nombre del Padre"], 2.75),bold("Teléfono"), makeUnderline(self.data["Teléfono Padre"], 1.65),\
                  bold("Domicilio"), makeUnderline(self.data["Dirección Padre"], 3.35),bold("Empresa"), makeUnderline(self.data["Negocio Padre"], 1.63))
                 ))

                with self.doc.create(Tabular(
                        NoEscape("m{2in}m{2in}m{2in}"))) as table:
                    table.add_row((self.data["Teléfono Padre"],
                                   self.data["Celular Padre"],
                                   self.data["Correo Padre"]))
                    table.add_hline()
                    table.add_row(
                        (bold("Teléfono Particular"), bold("Teléfono Celular"),
                         bold("Correo Electrónico")))

                self.doc.append(NoEscape(\
                 r"{}: {} {}: {}\\{}: {} {}: {}\\"\
                 .format(bold("Nombre de la Madre"), makeUnderline(self.data["Nombre de la Madre"], 2.75),bold("Teléfono"), makeUnderline(self.data["Teléfono Madre"], 1.55),\
                  bold("Domicilio"), makeUnderline(self.data["Dirección Madre"], 3.35),bold("Empresa"), makeUnderline(self.data["Negocio Madre"], 1.63))
                 ))

                with self.doc.create(Tabular(
                        NoEscape("m{2in}m{2in}m{2in}"))) as table:
                    table.add_row((self.data["Teléfono Madre"],
                                   self.data["Celular Madre"],
                                   self.data["Correo Madre"]))
                    table.add_hline()
                    table.add_row(
                        (bold("Teléfono Particular"), bold("Teléfono Celular"),
                         bold("Correo Electrónico")))
예제 #5
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
예제 #6
0
        def InsDatosDomicilio():
            with self.doc.create(SectionUnnumbered("Domicilio Particular")):
                Command("vspace", NoEscape("-1ex"))
                with self.doc.create(
                        Tabular(NoEscape(
                            "m{1.33in}m{0.6in}m{2in}m{1.9in}"))) as table:
                    table.add_row(
                        (self.data["Calle"], self.data["Número"],
                         self.data["Colonia"], self.data["Población"]))
                    table.add_hline()
                    table.add_row((bold("Calle"), bold("Número"),
                                   bold("Colonia"), bold("Poblacion")))

                with self.doc.create(Tabular(
                        NoEscape("m{2in}m{2in}m{2in}"))) as table:
                    table.add_row((self.data["Municipio"], self.data["Estado"],
                                   self.data["C.P."]))
                    table.add_hline()
                    table.add_row(
                        (bold("Municipio"), bold("Estado"), bold("C.P.")))

                with self.doc.create(Tabular(
                        NoEscape("m{2in}m{2in}m{2in}"))) as table:
                    table.add_row(
                        (self.data["Teléfono Particular"],
                         self.data["Teléfono Celular"], self.data["Correo"]))
                    table.add_hline()
                    table.add_row(
                        (bold("Teléfono Particular"), bold("Teléfono Celular"),
                         bold("Correo Electrónico")))
예제 #7
0
def test():
    doc = Document("multirow_cm")

    with doc.create(Section('Multirow Test')):
        with doc.create(Subsection('Multicol')):
            # we need to keep track of the object here
            with doc.create(Tabular('|c|c|')) as table1:
                table1.add_hline()
                table1.add_multicolumn(2, '|c|', 'Multicol')
                table1.add_hline()
                table1.add_row((1, 2))
                table1.add_hline()
                table1.add_row((3, 4))
                table1.add_hline()

        with doc.create(Subsection('Multirow')):
            with doc.create(Tabular('|c|c|c|')) as table2:
                table2.add_hline()
                table2.add_multirow(3, '*', 'Multirow', cells=((1, 2), (3, 4),
                                                               (5, 6)))
                table2.add_hline()
                table2.add_multirow(3, '*', 'Multirow2')
                table2.add_hline()

    doc.generate_pdf()
예제 #8
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)
예제 #9
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
예제 #10
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)
예제 #11
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
예제 #12
0
파일: args.py 프로젝트: markdoerr/PyLaTeX
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"),))
예제 #13
0
def mostrarPoker(poker, doc):
    with doc.create(Subsection('Prueba de Poker')):
        nombrePoker = [
            "Diferentes", "Un Par", "Dos Pares", "Tercia", "Full House",
            "Poker", "Quintilla"
        ]
        promedio = [0.3024, 0.504, 0.108, 0.072, 0.009, 0.0045, 0.0001]
        total = pruebasRandom.sumarPoker(poker)
        jiCuadrado = 0.0

        with doc.create(Tabular('|c|c|c|c|c|c|c|')) as table:
            table.add_row(('Clase', 'Pe', 'Fo', 'Fe', '(Fo-Fe)', '(Fo-Fe)2',
                           '(Fo-Fe)2/Fe'))
            for i in range(7):
                prom = promedio[i]
                frecuenciaObs = poker[i][1]
                frecuenciaEsperada = prom * total
                fObs_fEsp = frecuenciaObs - frecuenciaEsperada
                fObs_fEsp2 = fObs_fEsp**2
                formula = fObs_fEsp2 / frecuenciaEsperada

                fila = (nombrePoker[i], prom, frecuenciaObs,
                        frecuenciaEsperada, fObs_fEsp, fObs_fEsp2, formula)

                table.add_hline()
                table.add_row(fila)

                jiCuadrado += formula

        doc.append(Math(data=['Total', '=', total]))
        doc.append(Math(data=['X2(0)', '=', jiCuadrado]))
예제 #14
0
def generateTexTable(fname, colTitles, rowNames, rowDataList):

    # make sure all rows have same length
    max_data_length = max([len(rowdata) for rowdata in rowDataList])
    print("max data length: ", max_data_length)
    for rowdata in rowDataList:
        while len(rowdata) < max_data_length:
            rowdata += ['/']

    print colTitles
    colBaseTitle = colTitles[-1]
    colTitles = [colTitles[0]]
    j = 0
    while len(colTitles) < max_data_length + 1:
        colTitles.append(str(2**j) + " Layers " + colBaseTitle)
        j += 1

    geometry_options = {"tmargin": "1cm"}  #, "lmargin": "1cm"}
    doc = Document(geometry_options=geometry_options)

    with doc.create(Subsection('Table of something')):
        layout = ['|l'] * len(colTitles) + ['|']
        layout = ''.join(layout)
        print(layout)
        with doc.create(Tabular(layout)) as table:
            table.add_hline()
            table.add_row((colTitles))
            table.add_hline()
            for rowName, rowData in zip(rowNames, rowDataList):
                rowList = [rowName] + rowData
                print rowList
                table.add_row(tuple(rowList))
                table.add_hline(1, 1)
            table.add_hline()
    doc.generate_pdf(storeDir + fname, clean_tex=False)
예제 #15
0
        def InsDatosEscolares(hasImage):

            with self.doc.create(
                    Tabular(
                        NoEscape("m{0.8in}m{0.6in}m{0.9in}m{1.5in}m{2.3in}"))
            ) as table:
                if hasImage:
                    image = MultiRow(
                        3,
                        data=Command(
                            "includegraphics",
                            NoEscape(self.data["Foto"]
                                     [self.data["Foto"].rfind("/") +
                                      1:][:self.data["Foto"].rfind(".")]),
                            ["width=1.5in", "height=1in"]))
                else:
                    image = ""
                table.add_row(("", "", "", "", ""))
                table.add_row(("", "", "", "", image))
                table.add_row(
                    (bold("Matrícula: "), self.data["Matrícula"],
                     bold("Licenciatura: "), self.data["Licenciatura"], ""))
                table.add_row(
                    (bold("Semestre: "), self.data["Semestre"],
                     bold("Generación: "), self.data["Generación"], ""))
예제 #16
0
파일: ba_report.py 프로젝트: abconley/pima
    def add_contig_info(self):

        if self.analysis.contig_info is None:
            return

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

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

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

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

                self.doc.append('')

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

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

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

        self.doc.append(NewPage())

        table_format = 'l' * 4

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

            for region_name in mutations.index.tolist():

                region_mutations = mutations[region_name].copy()

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

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

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

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

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

        if plasmids is None:
            return

        self.doc.append(NewPage())

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

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

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

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

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

        primeri_naloge = naloga.primeri()

        imena_skupin = primeri_naloge[0]['skupine']
        nastavitve_tabele = ['p{4cm}' for skupina in imena_skupin]

        center = Center()
        with center.create(Tabular('|{}|'.format(
                '|'.join(nastavitve_tabele)))) as tabela:
            tabela.add_hline()
            tabela.add_row(tuple(imena_skupin))
            tabela.add_hline()
            tabela.add_row(
                tuple([Command('vspace', arguments=['4cm'])] *
                      len(imena_skupin)))
            tabela.add_hline()

        primeri = []
        for primer in primeri_naloge:
            primeri.append(Command('podnaloga'))
            primeri.extend([', '.join(primer['besede'])])
            primeri.append(Command('vspace', ['0.5cm']))
            primeri.append(center)
            primeri.append(Command('vspace', ['0.5cm']))

        return primeri
예제 #20
0
def genenerate_table_rates(table_rates):
    doc = Document('basic', indent=True, page_numbers=False)

    steps = sorted(list(set([t["qty_dx"] for t in table_rates])))
    print(steps)
    basises = sorted(list(set([t["qty_bas"] for t in table_rates])))
    rates_L1 = {}
    rates_L2 = {}
    for t in table_rates:
        rates_L1[str(t["qty_dx"]) + "-" + str(t["qty_bas"])] = t["L1"]
        rates_L2[str(t["qty_dx"]) + "-" + str(t["qty_bas"])] = t["L2"]
    print(rates_L1)
    format_header = "".join(["|c|" for i in range(len(steps))])
    # Generate data table
    with doc.create(Tabular(format_header)) as table:
        table.add_hline()
        table.add_row(steps)
        table.add_hline()
        for basis in basises:
            row = []
            for step in steps:
                if (str(step) + "-" + str(basis) in rates_L1):
                    row.append(rates_L1[str(step) + "-" + str(basis)])
                else:
                    row.append('')
            table.add_row(row)

    print(table)
    doc.generate_pdf("rates", clean_tex=False)
    pages = convert_from_path('rates.pdf', 500)
    for page in pages:
        page.save('out.jpg', 'JPEG')
def render(img_filepath, output_list):
    image_filename = img_filepath.split('/')[-1]
    cwd = os.getcwd() + '/' + output_list[2]
    shutil.copy2(img_filepath, cwd)

    #print(image_filename)

    geometry_options = {"tmargin": "1cm", "lmargin": "1cm"}
    doc = Document(geometry_options=geometry_options)
    #creates image section in LaTeX

    with doc.create(Section("Xcos")):
        with doc.create(Figure(position='h!')) as abs_pic:
            abs_pic.add_image(image_filename, width='450px')
            doc.append("\n\n\n")
    #creates Context section in LaTeX if context exists
    if output_list[1]:
        with doc.create(Subsection("Context")):
            with doc.create(Itemize()) as itemize:
                for data in output_list[1]:
                    itemize.add_item(data)
    #creates Block section in LaTeX
    with doc.create(Subsection("Blocks")):
        for i in output_list[0]:
            if i is not None:
                doc.append("\n\n\n")
                with doc.create(Tabular('|c|c|')) as table:
                    table.add_hline()
                    for key, value in i.parameters().items():
                        table.add_row(key, value)
                        table.add_hline()

    file_path = output_list[2] + '/' + output_list[2]
    doc.generate_pdf(file_path, clean_tex=False)
예제 #22
0
def mostrarSeries(series, doc):
    with doc.create(Subsection('Prueba de Series')):
        n = pruebasRandom.sumarLista(series)
        frecuenciaEsperada = n / 25
        jiCuadrado = 0.0

        with doc.create(Tabular('|c|c|c|c|c|c|')) as table:
            table.add_row(
                ('Celda', 'Fo', 'Fe', '(Fo-Fe)', '(Fo-Fe)2', '(Fo-Fe)2/Fe'))

            for i in range(25):
                frecuenciaObs = series[i]
                fObs_fEsp = frecuenciaObs - frecuenciaEsperada
                fObs_fEsp2 = fObs_fEsp**2

                formula = fObs_fEsp2 / frecuenciaEsperada

                fila = (i + 1, frecuenciaObs, frecuenciaEsperada, fObs_fEsp,
                        fObs_fEsp2, formula)

                table.add_hline()
                table.add_row(fila)

                jiCuadrado += (frecuenciaObs -
                               frecuenciaEsperada)**2 / frecuenciaEsperada

    doc.append(Math(data=['Total', '=', (int)(n)]))
    doc.append(Math(data=['X2(0)', '=', jiCuadrado]))
예제 #23
0
    def GPIOLoopback_report(self):
        self.doc.append(NoEscape(r'\clearpage'))
        with self.doc.create(Section('GPIO Loopback')):
            with self.doc.create(Subsection('Description')):
                self.doc.append(
                    'This test asserts the correct assembly of the GPIO pins on both RFFEuC\'s headers.'
                )
                self.doc.append(
                    'In the TestBoard all GPIO pins are connected in pairs via a 1K1 resistor, so they\'re logically binded.\n'
                )
                self.doc.append(
                    'Each pin in the loopback pair is tested as an Input and Output, changing the logic level of its pair to assert the electrical connection.\n'
                )

            with self.doc.create(Subsection('Results')):
                with self.doc.create(Center()) as centered:
                    with centered.create(Tabular('|c|c|c|',
                                                 row_height=1.2)) as tbl:
                        tbl.add_hline()
                        tbl.add_row((MultiColumn(2,
                                                 align='|c|',
                                                 data=bold('Loopback Pair')),
                                     bold('Result')))
                        tbl.add_hline()
                        for key, val in self.test_results['gpio'].items():
                            if isinstance(val, dict):
                                tbl.add_row(
                                    val['pin1'],
                                    val['pin2'],
                                    ('Pass' if val['result'] else 'Fail'),
                                    color=('green'
                                           if val['result'] else 'red'))
                                tbl.add_hline()
예제 #24
0
    def LED_report(self):
        self.doc.append(NoEscape(r'\clearpage'))
        with self.doc.create(Section('LEDs')):
            with self.doc.create(Subsection('Description')):
                self.doc.append(
                    'This test asserts the correct assembly of the 4 LEDs on RFFEuC\'s edge.\n'
                )
                self.doc.append(
                    'A large LDR (20mm) is positioned in front of all LEDs and is connected to one of the Analogic-to-Digital converter ports - routed through the TestBoard Jn connector.\n'
                )
                self.doc.append(
                    'Each LED is activated separately and the LDR voltage is read and compared to a predefined mask.\n'
                )

            with self.doc.create(Subsection('Results')):
                with self.doc.create(Center()) as centered:
                    with centered.create(Tabular('|c|c|c|',
                                                 row_height=1.2)) as tbl:
                        tbl.add_hline()
                        tbl.add_row(bold('LED'), bold('LDR read [V]'),
                                    bold('Result'))
                        tbl.add_hline()
                        for key, val in self.test_results['led'].items():
                            if isinstance(val, dict):
                                tbl.add_row(
                                    bold(key), (val['value']),
                                    ('Pass' if val['result'] else 'Fail'),
                                    color=('green'
                                           if val['result'] else 'red'))
                                tbl.add_hline()
예제 #25
0
    def PowerSupply_report(self):
        self.doc.append(NoEscape(r'\clearpage'))
        with self.doc.create(Section('Power Supply')):
            with self.doc.create(Subsection('Description')):
                self.doc.append(
                    'This test asserts the correct assembly of the Voltage regulation circuit.\n'
                )
                self.doc.append(
                    'Both power supply lines (5V and 3.3V) are tested using a simple voltage divider circuit present on the TestBoard. Given that the voltage divider provides a half of the real value to the RFFEuC ADC circuit, the following convertion is applied: \n'
                )
                with self.doc.create(Alignat(numbering=False,
                                             escape=False)) as agn:
                    agn.append(r'V_{PS} = ADC_{read} * 3.3 * 2 \\')

            with self.doc.create(Subsection('Results')):
                with self.doc.create(Center()) as centered:
                    with centered.create(Tabular('|c|c|c|',
                                                 row_height=1.2)) as tbl:
                        tbl.add_hline()
                        tbl.add_row(bold('Power Supply'), bold('Measured [V]'),
                                    bold('Result'))
                        tbl.add_hline()
                        for key, val in self.test_results['powerSupply'].items(
                        ):
                            if isinstance(val, dict):
                                tbl.add_row(
                                    bold(key + 'V'),
                                    val['value'],
                                    ('Pass' if val['result'] else 'Fail'),
                                    color=('green'
                                           if val['result'] else 'red'))
                                tbl.add_hline()
예제 #26
0
    def add_result(self, image_id, quest_id, im_path, answer, questions):
        with self._doc.create(Section('quest_id: %d' % quest_id)):
            # add figure
            with self._doc.create(Figure(position='h!')) as fig:
                fig.add_image(im_path, width='%dpx' % _compute_width(im_path))
                fig.add_caption('Image: %d' % image_id)
            # add answer
            with self._doc.create(Subsection('%s' % answer)):
                if len(questions) % 2 == 1:
                    questions.append('')
                with self._doc.create(Tabular(table_spec='|l|l|')) as table:
                    num = int(len(questions) * 0.5)
                    table.add_hline()
                    for i in range(num):
                        a = '%s' % questions[2 * i].capitalize()
                        a = textwrap.fill(a, width=45).split('\n')
                        len_a = len(a)
                        b = '%s' % questions[2 * i + 1].capitalize()
                        b = textwrap.fill(b, width=45).split('\n')
                        len_b = len(b)
                        max_len = max(len_a, len_b)
                        a += [''] * (max_len - len_a)
                        b += [''] * (max_len - len_b)
                        for a_i, b_i in zip(a, b):
                            table.add_row((a_i, b_i))
                        table.add_hline()
                    # table.add_hline()

                # questions
                # for q in questions:
                #     self._doc.append('\n%s' % q.capitalize())
                # with self._doc.create(Itemize()) as item:
                #     for q in questions:
                #         item.add_item(q.capitalize())
            self._doc.append(NewPage())
예제 #27
0
        def InsDatosEmergencia():
            with self.doc.create(SectionUnnumbered("En caso de emergencia")):
                Command("vspace", NoEscape("-1ex"))
                self.doc.append(NoEscape(\
                 r"{}{} {}: {} \\{}: {}\\"\
                 .format(bold("¿Padece alguna enfermedad?"), makeUnderline(self.data["¿Enfermedad?"], 0.2),bold("Especifique"), makeUnderline(self.data["Enfermedad"], 3.4), bold("Tipo de Sangre"), makeUnderline(self.data["Tipo de Sangre"], .5))
                 ))

                self.doc.append(NoEscape(\
                 r"{}:\\{}: {} {}: {}\\ "\
                 .format(bold("Contactar a"), bold("Nombre"), makeUnderline(self.data["Nombre Contacto"], 3.52),bold("Parentesco"), makeUnderline(self.data["Parentesco"], 1.5))
                 ))

                with self.doc.create(Tabular(
                        NoEscape("m{2in}m{2in}m{2in}"))) as table:
                    table.add_row((self.data["Teléfono Contacto"],
                                   self.data["Celular Contacto"],
                                   self.data["Correo Contacto"]))
                    table.add_hline()
                    table.add_row(
                        (bold("Teléfono Particular"), bold("Teléfono Celular"),
                         bold("Correo Electrónico")))

                self.doc.append(NoEscape(\
                 r"{}: {} {}: {}\\"\
                 .format(bold("Domicilio"), makeUnderline(self.data["Dirección Contacto"], 3.35),bold("Empresa"), makeUnderline(self.data["Negocio Contacto"], 1.63))
                 ))
예제 #28
0
    def _report_attack_results(self):
        """
        Create subsubsection describing the most important results of the attack.

        This subsection contains results only for the first target model.
        """
        tm = 0  # Specify target model
        self.report_section.append(Subsubsection("Attack Results"))
        res = self.attack_results

        with self.report_section.create(MiniPage(width=r"0.49\textwidth")):
            self.report_section.append(Command("centering"))
            with self.report_section.create(Tabular("|l|c|")) as result_tab:
                result_tab.add_hline()
                result_tab.add_row(["True Positives", round(res["tp"][tm], 3)])
                result_tab.add_hline()
                result_tab.add_row(["True Negatives", round(res["tn"][tm], 3)])
                result_tab.add_hline()
                result_tab.add_row(["False Positives", round(res["fp"][tm], 3)])
                result_tab.add_hline()
                result_tab.add_row(["False Negatives", round(res["fn"][tm], 3)])
                result_tab.add_hline()
                result_tab.add_row(["Accuracy", round(res["accuracy"][tm], 3)])
                result_tab.add_hline()
                result_tab.add_row(["Precision", round(res["precision"][tm], 3)])
                result_tab.add_hline()
                result_tab.add_row(["Recall", round(res["recall"][tm], 3)])
                result_tab.add_hline()

            self.report_section.append(Command("captionsetup", "labelformat=empty"))
            self.report_section.append(
                Command("captionof", "table", extra_arguments="Attack Summary")
            )
예제 #29
0
    def create_manual_context_topics(self):
        with self.doc.create(Section(
                Constants.ITEM_TYPE.title() +
                ' context-rich topic models (manual)')):

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

                for topic in context_words[Constants.ITEM_TYPE]:
                    color_id = self.manual_context_topic_colors[topic]
                    color = self.rgb_tuples[color_id]
                    id_cell = str(topic)+str('|||')+str(color[0]) + \
                        '|||'+str(color[1])+'|||'+str(color[2])
                    row = [id_cell]
                    for word in list(context_words[Constants.ITEM_TYPE][topic])[:self.num_cols + 1]:
                        word_color = word+str('|||')+str(color[0])+'|||' + \
                            str(color[1])+'|||'+str(color[2])
                        row.append(word_color)
                    table.add_row(row, mapper=background_color_mapper)

                table.add_hline()

            self.doc.append(UnsafeCommand('par'))
            # self.doc.append(
            #     'Number of context-rich topics: %d' %
            #     len(context_words[Constants.ITEM_TYPE]))
            self.doc.append(ColorBoxCommand(
                arguments=Arguments(
                    1, 1, 1, 'Number of context-rich topics: ' +
                            str(len(context_words[Constants.ITEM_TYPE])))))
예제 #30
0
def generate_heuristic_tex(G, matchings, output_dir, stats_filename):
    """
    print statistics for the hospital proposing heuristic as a tex file
    :param G: graph
    :param matchings: information about the matchings
    """
    # create a tex file with the statistics
    doc = Document('table')

    # add details about the graph, |A|, |B|, and # of edges
    n1, n2, m = len(G.A), len(G.B), sum(len(G.E[r]) for r in G.A)
    with doc.create(Subsection('graph details')):
        with doc.create(Tabular('|c|c|')) as table:
            table.add_hline()
            table.add_row('n1', n1)
            table.add_hline()
            table.add_row('n2', n1)
            table.add_hline()
            table.add_row('m', m)
        table.add_hline()

    M_s = matching_algos.stable_matching_hospital_residents(
        graph.copy_graph(G))
    with doc.create(Subsection('Size statistics')):
        with doc.create(Tabular('|c|c|c|c|c|c|c|')) as table:
            table.add_hline()
            table.add_row(('description', 'size', 'bp', 'bp ratio', 'block-R',
                           'rank-1', 'deficiency'))
            for desc in matchings:
                M = matchings[desc]
                sig = signature(G, M)
                bp = matching_utils.unstable_pairs(G, M)
                msize = matching_utils.matching_size(G, M)
                table.add_hline()
                table.add_row((
                    desc,
                    msize,
                    len(bp),
                    len(bp) / (m - msize),
                    len(blocking_residents(bp)),
                    sum_ranks(sig, (1, )),  #sum_ranks(sig, (1, 2, 3)),
                    total_deficiency(G, M_s)))
            table.add_hline()

    stats_abs_path = os.path.join(output_dir, stats_filename)
    doc.generate_pdf(filepath=stats_abs_path, clean_tex='False')
    doc.generate_tex(filepath=stats_abs_path)
예제 #31
0
파일: args.py 프로젝트: ycchen1989/PyLaTeX
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)
예제 #32
0
파일: tabela.py 프로젝트: aljazmedic/pyodv
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
예제 #33
0
파일: args.py 프로젝트: Oize/PyLaTeX
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)
예제 #34
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)
예제 #35
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(cells=(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', arguments=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 Tabularx
    coloredtable = Tabularx(table_spec='X[c] X[c]')
    coloredtable.add_row(["test", "test2"], color="gray", mapper=bold)

    # Column
    column = Column("R", "X", r"\raggedleft", parameters=2)
    repr(column)
예제 #36
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'))
예제 #37
0
                coords = []
                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
예제 #38
0
파일: multirow.py 프로젝트: JelteF/PyLaTeX
    :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)
예제 #39
0
파일: multirow.py 프로젝트: khyox/PyLaTeX
..  :copyright: (c) 2014 by Jelte Fennema.
    :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)
예제 #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)
예제 #41
0
파일: args.py 프로젝트: amitdash/PyLaTeX
    maketitle=False
)

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'),))
예제 #42
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)