示例#1
0
    def __init__(self):
        self.doc = pylatex.Document(args.experiment)

        self.doc.packages.append(Package("hyperref", options=["hidelinks"]))
        self.doc.packages.append(Package("etoc"))

        self.doc.preamble.append(Command("title", "DATA Leakage Report"))
        self.doc.preamble.append(Command("author", "Fraunhofer AISEC"))
        self.doc.preamble.append(Command("date", pylatex.NoEscape(r"\today")))

        self.doc.append(
            NoEscape(
                "\lstdefinestyle{stylecpp}{\n"
                "language=C++,\n" + Report.lstlisting_default_style
            )
        )
        self.doc.append(
            NoEscape(
                "\lstdefinestyle{styleasm}{\n"
                "language=[x86masm]Assembler,\n" + Report.lstlisting_default_style
            )
        )

        self.doc.append(NoEscape(r"\maketitle"))
        self.doc.append(NewPage())

        self.doc.append(NoEscape(r"\setcounter{tocdepth}{1}"))
        self.doc.append(NoEscape(r"\tableofcontents"))
        self.doc.append(NoEscape(r"\setcounter{tocdepth}{2}"))
        self.doc.append(NewPage())
示例#2
0
def create_doc(title, with_tikz=False):
    logging.info("Creating PDF...")
    doc = pylatex.Document(geometry_options={'margin': '1.5cm'})
    doc.packages.append(pylatex.Package('hyperref'))
    doc.packages.append(pylatex.Package('amssymb'))
    doc.packages.append(pylatex.Package('amsmath'))
    doc.packages.append(pylatex.Package('float'))
    doc.packages.append(
        pylatex.Package('caption', {
            'labelformat': 'empty',
            'justification': 'centering'
        }))
    #doc.packages.append(pylatex.Package('todonotes'))

    # I don't think these are needed
    #doc.packages.append(pylatex.Package('needspace'))
    #doc.packages.append(pylatex.Package('pgfplots'))

    if with_tikz:
        doc.packages.append(pylatex.Package('tikz'))
        doc.preamble.append(
            pylatex.Command('usetikzlibrary', 'decorations.markings'))
        doc.preamble.append(pylatex.Command('usetikzlibrary', 'fit'))
        doc.preamble.append(pylatex.Command('usetikzlibrary', 'plotmarks'))

    doc.preamble.append(pylatex.Command('title', title))
    doc.preamble.append(pylatex.Command('date', ''))

    doc.append(pylatex.NoEscape(r"\maketitle"))
    doc.append(pylatex.NoEscape(r"\tableofcontents"))
    doc.append(pylatex.NoEscape(r"\newpage"))
    doc.append(
        pylatex.NoEscape(r"\captionsetup[subfigure]{labelformat=empty}"))

    return doc
示例#3
0
def main():

    if not os.path.exists("report"):
        os.mkdir("report")

    global tumor
    global max_distance
    global e_method

    for t in tumors:
        print(t)
        doc = pylatex.Document('report/results' + t)
        doc.append(pylatex.NewPage())
        with doc.create(pylatex.Section(t)):
            for m in e_methods:
                for d in max_distances:
                    tumor = t
                    max_distance = d
                    e_method = m
                    with doc.create(
                            pylatex.Subsection("Score = " + m.tag +
                                               ", Max dist. = " + str(d))):
                        do_analysis(doc)

        doc.generate_pdf(clean_tex=False)
示例#4
0
    def __init__(self, name, number, bank):
        self.name = name
        self.number = number
        self.bank = bank

        geometry_options = {
            "tmargin": "35mm",
            "lmargin": "25mm",
            "textwidth": "160mm",
            "textheight": "237mm",
        }

        self.doc = tex.Document(f"AccountReport_{self.name}",
                                documentclass="article",
                                document_options=['10pt', "a4paper"],
                                geometry_options=geometry_options,
                                lmodern=False)
        self.doc.preamble.append(
            tex.NoEscape(r"\renewcommand{\familydefault}{\sfdefault}"))
        self.doc.preamble.append(tex.Command('usepackage', 'helvet'))
        self.doc.preamble.append(
            tex.Command('usepackage', arguments='placeins', options="section"))

        self.addHeader()

        self.doc.preamble.append(tex.Command('title', "Financial Report"))
        # self.doc.preamble.append(Command('bank', 'Anonymous author'))
        self.doc.preamble.append(tex.Command('date', tex.NoEscape(r'\today')))
示例#5
0
def generate_tex_revision_sheet(filepath, result_path, lines, starting_item):

    geometry_options = {"tmargin": "2.54cm", "lmargin": "2.54cm"}
    doc = pylatex.Document(geometry_options=geometry_options)

    with doc.create(pylatex.Section('Revision sheet')):

        with doc.create(pylatex.LongTable('|r|p{8cm}|p{8cm}|')) as table:
            table.add_hline()
            table.add_row(('Nr.', 'Comment', 'How the comment is addressed'))
            table.add_hline()
            for line in lines:
                if not line.strip():
                    continue
                table.add_row(
                    (starting_item, line.replace('\\newline',
                                                 '').replace(' ', ''), ''))
                table.add_hline()
                starting_item += 1

    if result_path:
        doc.generate_pdf(result_path, clean_tex=False)
    else:
        doc.generate_pdf(filepath[:-4] + '_revision_sheet.tex',
                         clean_tex=False)

    return
示例#6
0
    def create(self):
        """Create the LaTeX document.

        :return: ``True`` if the document can have been created, else
        ``False``.
        :rtype: bool
        """

        path = self.path_pattern.format(self.cow)
        dirname = os.path.dirname(path)

        if not os.path.isdir(dirname):
            os.makedirs(dirname)

        if (os.path.isfile("{}.{}".format(path, self.EXT))
                and not stg.FORCE_VIEW):
            return False

        self.doc = pylatex.Document(path,
                                    title="Cow {} - {}".format(
                                        self.cow, self.title),
                                    maketitle=True)

        self.doc.packages.append(
            pylatex.Package(
                'geometry',
                options=['left=1cm', 'right=1cm', 'top=1cm', 'bottom=1cm']))
        self.doc.packages.append(pylatex.Package('float'))
        self.doc.append(pylatex.command.Command('pagenumbering', 'gobble'))

        return True
示例#7
0
 async def latex(self, ctx, *, tex: str):
     msg = await self._generating_embed(ctx)
     loop = asyncio.get_event_loop()
     doc = pylatex.Document(documentclass=DOCUMENT_CLASS,
                            document_options=DOCUMENT_OPTIONS,
                            geometry_options=GEOMETRY_OPTIONS,
                            lmodern=True,
                            font_size='LARGE')
     doc.preamble.append(
         pylatex.utils.NoEscape('\\everymath{\\displaystyle}\n'))
     doc.packages.append(pylatex.Package('xcolor'))
     tex = pylatex.utils.NoEscape('\\color{white}\n' + tex + '\n')
     doc.append(tex)
     temp_name = ASSETS_FOLDER + str(uuid.uuid4())
     with concurrent.futures.ProcessPoolExecutor() as pool:
         args = (temp_name, doc)
         try:
             await loop.run_in_executor(pool, gen_tex_images, *args)
         except subprocess.CalledProcessError:
             await msg.delete()
             await self._syntax_embed_log(ctx, temp_name)
             return
     await msg.delete()
     attachment = discord.File(fp=f'{temp_name}.png')
     msg = await ctx.send(file=attachment)
     await self.bot.messenger.publish(Events.on_set_deletable,
                                      msg=msg,
                                      author=ctx.author,
                                      timeout=60)
     _cleanup_files(temp_name)
示例#8
0
def make_table_file(
    name: str,
    strings_per_bar: tuple,
    title_per_bar=None,
    available_columns_per_bar=None,
) -> None:
    if not available_columns_per_bar:
        available_columns_per_bar = tuple(37 for i in strings_per_bar)

    if title_per_bar is None:
        title_per_bar = tuple([
            "Fret positions for bar {0}".format(idx + 1)
            for idx in range(len(strings_per_bar))
        ])
    tables = tuple(
        make_string_table(strings, available_columns=available_columns)
        for strings, available_columns in zip(strings_per_bar,
                                              available_columns_per_bar))
    doc = pylatex.Document(document_options=["landscape", "a4paper"])
    doc.preamble.append(pylatex.Command("usepackage", arguments="lscape"))
    doc.preamble.append(pylatex.Command("usepackage", arguments="xcolor"))
    doc.preamble.append(
        pylatex.NoEscape(r"\usepackage[a4paper,bindingoffset=0.2in,%"))
    doc.preamble.append(
        pylatex.NoEscape(r"left=0.5cm,right=1cm,top=1.5cm,bottom=1cm,%"))
    doc.preamble.append(pylatex.NoEscape(r"footskip=.25in]{geometry}"))
    doc.preamble.append(pylatex.NoEscape(r"\pagenumbering{gobble}"))
    for title, table in zip(title_per_bar, tables):
        # doc.append(pylatex.utils.bold(pylatex.LargeText(title)))
        doc.append(pylatex.LargeText(pylatex.utils.bold(title)))
        doc.append(table)
    doc.generate_pdf(name)
    doc.generate_tex(name)
示例#9
0
def generate_latex(dataset1, dataset2, output):
    doc = pl.Document(page_numbers=True,
                      geometry_options={
                          "tmargin": "1cm",
                          "lmargin": "1cm"
                      })

    doc.packages.append(pl.Package('booktabs'))
    doc.preamble.append(
        pl.Command('title', 'VH/VL Packing for Gradient Boosted Regression'))
    doc.preamble.append(pl.Command('author', 'Veronica A. Boron'))
    doc.append(pl.NoEscape(r'\maketitle'))
    doc.append(
        'This document summarizes results for predicting VHVL packing angles using Gradient Boosted Regression via the \
        Scikit Learn framework.')
    doc.append(pl.NoEscape(r'\maketitle'))

    _add_data(doc, dataset1)
    doc.append(pl.NoEscape(r'\newpage'))

    _add_data(doc, dataset2)
    doc.append(pl.NoEscape(r'\newpage'))

    print('Generating PDF...')
    doc.generate_pdf(output, clean_tex=False)
示例#10
0
    def sum_sample(self):
        """Summarize the analysis data and plots in a report
        """
        for i in range(len(self.infiles)):
            self.logger.info('\nCreating pdf for sample {} results.\n'.format(
                self.sample[i]))
            geometry_options = {
                'tmargin': '3cm',
                'bmargin': '3cm',
                'rmargin': '3cm',
                'lmargin': '3cm'
            }
            doc = px.Document(documentclass='article',
                              geometry_options=geometry_options)
            doc.preamble.append(
                px.Command('title',
                           'Sequencing results for sample ' + self.sample[i]))
            doc.preamble.append(px.Command('date', px.NoEscape(r'\today')))
            doc.append(px.NoEscape(r'\maketitle'))

            with doc.create(px.Section('Genome coverage')):
                #include table of results with statistics of coverage
                with doc.create(px.Subsection('Coverage results')):
                    with doc.create(px.Tabular(table_spec='l  l')) as table:
                        with open(self.stats_file, 'r') as stats:
                            table.add_hline()
                            stats_data = pd.read_csv(stats, sep='\t')
                            for num in range(len(stats_data.iloc[0])):
                                table.add_row([
                                    stats_data.columns[num],
                                    stats_data.iloc[0][num]
                                ])
                            table.add_hline()
                #include coverage plot
                with doc.create(px.Figure(position='htb!')) as plot:
                    plot.add_image(self.cov_plot[i],
                                   width=px.NoEscape(r'\linewidth'))
                    plot.add_caption(
                        'Genome coverage for sample ' + self.sample[i] +
                        '. Calculated using samtools depth with zero-coverage positions included.'
                    )
            #include mismatch plot comparing the sample to the reference
            with doc.create(px.Section('Comparison to reference genome')):
                with doc.create(px.Figure(position='htb!')) as plot:
                    plot.add_image(self.basefreq_plot + '_' + self.sample[i] +
                                   '.png',
                                   width=px.NoEscape(r'\linewidth'))
                    plot.add_caption(
                        'Mismatch fraction per position for sample ' +
                        self.sample[i] +
                        '. Calculated compared to reference {}.'.format(
                            self.config['folder_locations']['ref_fasta']))

            doc.generate_pdf(
                filepath=os.path.join(self.outputdir, self.sample_info[i] +
                                      '.Report'))
            self.logger.info(
                '\nDone creating pdf for sample {} results.\n'.format(
                    self.sample[i]))
示例#11
0
def compile_latex_str(latex: str, filename: str):
    """Compiles the string latex into a PDF, and saves it to filename.
    """
    document = pylatex.Document()
    document.packages.append(pylatex.Package('amsfonts'))
    document.packages.append(pylatex.Package('amsmath'))
    document.append(pylatex.NoEscape(r'\thispagestyle{empty}'))
    document.append(pylatex.NoEscape(' $' + latex + '$ '))
    document.generate_pdf(filename, compiler='pdflatex')
示例#12
0
def create_tikz_doc():
    logging.info("Creating PDF...")
    doc = pylatex.Document(documentclass='standalone',
                           document_options=['crop', 'tikz'])
    doc.packages.append(pylatex.Package('tikz'))
    doc.preamble.append(
        pylatex.Command('usetikzlibrary', 'decorations.markings'))
    doc.preamble.append(pylatex.Command('usetikzlibrary', 'fit'))
    doc.preamble.append(pylatex.Command('usetikzlibrary', 'plotmarks'))
    return doc
示例#13
0
文件: box.py 项目: cunni/pyspherepack
    def tex_best(cls,
                 filenames=None,
                 texname=None,
                 scaled_rad=None,
                 clamp_edge=None):
        filenames = filenames if filenames is not None else [
            'data/mb_50_2x1.pkl', 'data/mb_50_3x1.pkl'
        ]
        texname = texname if texname is not None else 'data/aggregated_results'
        # set up pylatex doc
        geometry_options = {"margin": "1in"}
        doc = pylatex.Document(texname, geometry_options=geometry_options)
        dapne = lambda s: doc.append(pylatex.NoEscape(s))
        with doc.create(pylatex.Section('Introduction')):
            doc.append(
                'Each section that follows shows an optimized layout for a given number of circles and an approximate aspect ratio of the sheet. Throughout, the following parameters are assumed: clamp edge of 10.0mm, circle diameter of 20mm, spacing between circles of 0.50mm.'
            )
        for fn in filenames:
            mb = cls.load(filename=fn)
            b = mb.best_box['box']
            b.plot(clamp_edge=clamp_edge, scaled_rad=scaled_rad)
            # pylatex to put this in tex
            #matplotlib.use('Agg')
            with doc.create(
                    pylatex.Section(pylatex.NoEscape(
                        r'{} circles, box aspect ratio of roughly ${}\times{}$'
                        .format(b.n_balls, b.box[0], b.box[1])),
                                    label=fn)):
                with doc.create(pylatex.Figure(position='htbp')) as plot:
                    plot.add_plot(width=pylatex.NoEscape(r'0.8\textwidth'))
                    #plot.add_caption('Optimized circle packing for this sheet size.')

            x = b.box_warp(b.logits)
            rad = b.ball_radius(x)
            clamp_edge = clamp_edge if clamp_edge is not None else 0.0
            scaled_rad = scaled_rad if scaled_rad is not None else rad
            scaled_box = scaled_rad / rad * (b.box + 2 * rad)
            scaled_x = scaled_rad / rad * (x + rad)
            #doc.append(pylatex.NoEscape('\noindent Density %:'))
            dapne(r'\noindent Density \%: {:04.2f}\% \\'.format(b.density()))
            dapne(r'Waste \%: {:04.2f}\% \\'.format(100 - b.density()))
            dapne(r'Density with clamp edge \%: {:04.2f}\% \\'.format(
                (b.density() * np.prod(scaled_box) /
                 (scaled_box[1] * (scaled_box[0] + 2 * clamp_edge)))))
            dapne(r'Waste with clamp edge \%: {:04.2f}\% \\'.format(
                100 - (b.density() * np.prod(scaled_box) /
                       (scaled_box[1] * (scaled_box[0] + 2 * clamp_edge)))))

            dapne(r'Circle center coordinates: \\')
            for i in range(b.n_balls):
                #dapne(r'$c_{{{}}}$: {}\\'.format(i+1,scaled_x[i,:]))
                dapne(r'$[{}~~{}]$ \\'.format(scaled_x[i, 0], scaled_x[i, 1]))
            dapne(r'\clearpage')

        doc.generate_tex()
示例#14
0
 def getLatexDocument(self):
     '''get the construction budget in LaTeX format.'''
     retval = pylatex.Document(documentclass='book')
     retval.packages.append(pylatex.Package('minitoc'))
     retval.append(pylatex.Command('doparttoc'))
     self.writeQuantitiesIntoLatexDocument(retval)  #Quantities.
     self.writePriceTablesIntoLatexDocument(retval)  #Price lists.
     self.ImprLtxPreParc(retval)  #Presupuestos parciales.
     self.ImprLtxResumen(retval)  #Resument presup. parciales.
     self.ImprLtxPresGen(retval)  #Presupuestos generales.
     return retval
示例#15
0
    def _init_doc(self, name, add_date=True):
        doc = pyl.Document(name, geometry_options=geometry_options)
        doc.packages.append(pyl.Package('hyperref'))
        doc.preamble.append(pyl.Command('title', f'Supplementary Figures for {name}'))
        if add_date:
            doc.preamble.append(pyl.Command('date', pyl.NoEscape(r'\today')))
        else:
            doc.preamble.append(pyl.Command('date', pyl.NoEscape(r'')))
        doc.append(pyl.NoEscape(r'\maketitle'))
        doc.append(pyl.NewPage())

        return doc
示例#16
0
    def print_latex(self):
        """
            Gerador de arquivos .tex e .pdf
        """

        pdf = pylatex.Document("default")

        with pdf.create(pylatex.Section("Equações Diofantinas")) as section:

            section.append("Equação:")
            ultimo = self.numbers[-1]
            eq = []
            cont = 1
            for i in self.numbers:
                simbolo = "+"
                if i == ultimo:
                    simbolo = "= 1"
                eq.append(
                    pylatex.NoEscape(" {}x_{} {}".format(i, cont, simbolo)))
                cont = cont + 1

            section.append(pylatex.Math(data=eq))

            text = "n = {}".format(self.order)
            section.append(text)

            m = pylatex.Matrix(self.take_vec(), mtype='b')
            matrix = pylatex.Math(data=['b = ', m])
            section.append(matrix)

            m = pylatex.Matrix(self.take_matrix(), mtype='b')
            matrix = pylatex.Math(data=['A = ', m])
            section.append(matrix)

            section.append("Resposta = {}".format(self.cofactor_matrix()))

            section.append(pylatex.LineBreak())
            section.append("Confirmando:")
            section.append(pylatex.LineBreak())
            s = 0
            for i in range(len(self.numbers)):
                r = self.numbers[i] * self.cofactor_matrix()[i]
                s = s + r
                resp = "\t {}\t{} \t* \t{} \t= \t{} \t({})\n".format(
                    i, self.numbers[i],
                    self.cofactor_matrix()[i], r, s)
                section.append(resp)

        if self.create_pdf:
            pdf.generate_pdf()

        pdf.generate_tex()
示例#17
0
def gen_doc(file_output):
    '''
    function to return a latex document with a table for Brazilian bonds
    input:
    -----
    - file_output: str
    returnt:
    str - latex output.
    '''
    doc = pl.Document('./latex/{}'.format(file_output), font_size='normalsize',
                      documentclass='standalone',
                      document_options=['article', 'crop=false'])
    return doc
示例#18
0
def main():
    doc = pylatex.Document("basic")

    for saga in Saga.objects.order_by("name"):
        with doc.create(pylatex.Section(saga.name)):
            with doc.create(pylatex.Enumerate()) as elements:
                for book in saga.books:
                    color = "red"
                    if book.owned:
                        color = "blue"
                    txt = pylatex.TextColor(color, book.title)
                    elements.add_item(txt)

    doc.generate_pdf("saga_completion", clean_tex=True)
示例#19
0
def make_introduction(make_graphics: bool = False):
    import os

    from aml import globals_

    from mutools import mus

    if make_graphics:
        _make_graphics()

    images = {}
    for iname in os.listdir(globals_.INTRODUCTION_PICTURES_PATH):
        splitted_iname = iname.split(".")
        if splitted_iname[1] == "png":
            ipath = r"{}/{}".format(globals_.INTRODUCTION_PICTURES_PATH, iname)
            images.update({splitted_iname[0]: os.path.realpath(ipath)})

    language_options = {"en": "english", "de": "ngerman"}

    # (2) writing document
    for paper_format in (mus.A4, mus.A3):
        for language in ("de", "en"):
            texts_path = "aml/introduction/texts/{}".format(language)
            texts = {}
            for fname in os.listdir(texts_path):
                subtexts = {}
                for subtext in os.listdir("{}/{}".format(texts_path, fname)):
                    with open("{}/{}/{}".format(texts_path, fname, subtext),
                              "r") as f:
                        subtexts.update({subtext: f.read()})

                texts.update({fname: subtexts})

            path = "{}/introduction_{}_{}".format(globals_.INTRODUCTION_PATH,
                                                  paper_format.name, language)
            document = pylatex.Document(default_filepath=path)
            _prepare_document(document, language_options, language,
                              paper_format)

            document.append(
                pylatex.Section(title=texts["title"]["title"],
                                label=False,
                                numbering=False))

            _add_setup_notes(document, texts, images)
            _add_string_notes(document, texts, images)
            _add_keyboard_notes(document, texts, images)

            print("gen doc {}".format(path))
            document.generate_pdf()
示例#20
0
    def latex(self, fpath: Path, tex: bool = False):
        if self.params["seed"] is not None:
            random.seed(self.params["seed"])

        self.PALLETE = self._PALLETE.copy()
        random.shuffle(self.PALLETE)

        doc = pylatex.Document(documentclass="standalone",
                               document_options=["tikz"])
        doc.packages.append(
            pylatex.Package("firasans", options=["light", "sfdefault"]))
        with doc.create(pylatex.TikZ()) as pic:
            self._grid(pic)

        doc.generate_pdf(fpath, clean_tex=not tex)
示例#21
0
    def __init__(self, **kwargs):
        self.tables = []
        geometry = {
            "landscape": True,
            "margin": "0.5in",
            "headheight": "20pt",
            "headsep": "10pt",
            "includeheadfoot": True
        }
        geometry.update(kwargs)
        self.doc = pylatex.Document(page_numbers=True,
                                    geometry_options=geometry)
        self.doc.packages.append(pylatex.Package("xcolor", options='table'))

        self.fpath = None
        self.len_last_page = 0
示例#22
0
    def _init_doc(self, add_date=True):
        doc = pyl.Document(geometry_options=geometry_options)
        doc.packages.append(pyl.Package("float"))
        doc.packages.append(pyl.Package("hyperref"))

        doc.preamble.append(pyl.Command("title", self.title))
        if add_date:
            doc.preamble.append(pyl.Command("date", pyl.NoEscape(r"\today")))
        else:
            doc.preamble.append(pyl.Command("date", pyl.NoEscape(r"")))
        doc.append(pyl.NoEscape(r"\maketitle"))
        doc.append(pyl.NewPage())
        doc.append(pyl.Command("tableofcontents"))
        doc.append(pyl.NewPage())

        return doc
示例#23
0
    def __init__(self, **kwargs):
        """Generates a PDF report.

        :param author: The author of the paper.
        :type author: str
        :param title: The title of the paper.
        :type title: str
        :param toc: Display table of contents if True.
        :type toc: bool
        :param root: The root directory.
        :type root: str
        :param glossary_file: A file containing def/thm/cor/prop/lemma.
        :type glossary_file: str
        :param outline_file: A file containing the section outline.
        :type outline_file: str
        :param bib_file: A file containing a bibliography.
        :type bib_file: str
        :param refs: A dictionary of labels and their associated environments.
        :type refs: {str: str,...}
        :param packages: Required LaTeX packages.
        :type packages: [str,...]
        """
        self.args = kwargs
        self.doc = pl.Document(geometry_options={'margin': '1in'})
        options = ['12pt']
        if self.args.get('twocolumn') is True:
            options.append('twocolumn')
        self.doc.documentclass = pl.Command(
            'documentclass',
            options=options,
            arguments=['article'],
        )

        self.args['headers'] = [
            'lhead', 'chead', 'rhead', 'lfoot', 'cfoot', 'rfoot'
        ]
        self.args['heads'] = {}
        for pos in self.args['headers']:
            self.args['heads'][pos] = self.args.get(pos)

        if 'bib_file' in self.args:
            self.args['packages'].append('biblatex')
        self.sections = {}
        self.glossary = {}
        self.outline = []
        self.kinds = {}
示例#24
0
    def _export_pdf(self, fname: str):
        geometry_options = {"margin": "1in"}
        doc = pylatex.Document(geometry_options=geometry_options)
        header = pylatex.PageStyle("header")

        with doc.create(pylatex.MiniPage(align="c")):
            doc.append(
                pylatex.HugeText(pylatex.utils.bold("Practice Sessions")))
            doc.append(pylatex.LineBreak())

        with header.create(pylatex.Foot("L")):
            header.append("@2019 Musicavis")

        with header.create(pylatex.Foot("R")):
            header.append(pylatex.simple_page_number())

        doc.preamble.append(header)
        doc.change_document_style("header")

        for practice in self.practices:
            with doc.create(
                    pylatex.Section(
                        f"{practice.instrument.name.title()} ({practice.date:%a, %B %m %Y})"
                    )):
                self._add_list_itemize_latex(doc, "Goals",
                                             practice.goals.all())

                with doc.create(pylatex.Subsection("Exercises")):
                    with doc.create(pylatex.Itemize()) as itemize:
                        for x in practice.exercises.all():
                            itemize.add_item(
                                f"{x.name} at {x.bpm_start}-{x.bpm_end}bpm for {x.minutes}m"
                            )

                self._add_list_itemize_latex(doc, "Improvements",
                                             practice.improvements.all())
                self._add_list_itemize_latex(doc, "Positives",
                                             practice.positives.all())

            with doc.create(pylatex.Subsection("Notes:")):
                if practice.notes:
                    for note in practice.notes.split("\r\n"):
                        doc.append(note) if note else doc.append(
                            pylatex.NewLine())

        doc.generate_pdf(fname.split(".pdf")[0], clean=True)
示例#25
0
def compile_latex_str(latex: str, filename: str, display: bool = False):
    """Compiles the string latex into a PDF, and saves it to filename.
    """
    document = pylatex.Document()
    document.packages.append(pylatex.Package('amsmath'))
    document.packages.append(pylatex.Package('amssymb'))
    document.packages.append(pylatex.Package('amsfonts'))
    document.preamble.append(pylatex.Command('thispagestyle', 'empty'))
    # People seem to think \Z, \R and \Q exist, even though they don't. Just add them in to avoid problems.
    document.preamble.append(pylatex.NoEscape(r'\newcommand{\Z}{\mathbb{Z}}'))
    document.preamble.append(pylatex.NoEscape(r'\newcommand{\R}{\mathbb{R}}'))
    document.preamble.append(pylatex.NoEscape(r'\newcommand{\Q}{\mathbb{Q}}'))
    with document.create(Preview()):
        document.append(
            pylatex.NoEscape((r'\[' if display else r'\(') + latex +
                             (r'\]' if display else r'\)')))
    document.generate_pdf(filename, compiler='pdflatex')
    print(f"{filename}\t{latex}", flush=True)
示例#26
0
def df_to_pdf(df,
              out_file,
              print_index=True,
              debug=False,
              digit_round=1,
              caption=None,
              comma_separated_columns=[],
              gen_latex='False'):
    """
    convert data frame to pdf/latex. used to create tables for paper/thesis.
    """
    if digit_round is not None:
        df = df.round(digit_round)

    for column in comma_separated_columns:
        df[column] = df[column].map('{:,}'.format)

    table_columns = len(df.columns) + 1 if print_index else len(df.columns)

    if gen_latex:
        with open(table_path + out_file + '.tex', 'w') as f:
            f.write(
                df.to_latex(escape=False,
                            index=print_index,
                            column_format='c' * table_columns))
        return

    doc = pl.Document(documentclass='standalone', document_options='varwidth')
    doc.packages.append(pl.Package('booktabs'))

    with doc.create(pl.MiniPage()):
        with doc.create(pl.Table(position='htbp')) as table:
            table.append(pl.Command('centering'))
            table.append(
                pl.NoEscape(
                    df.to_latex(escape=False,
                                index=print_index,
                                column_format='c' * table_columns)))
            if caption is not None:
                table.add_caption(caption)
    if debug:
        return doc.dumps()

    doc.generate_pdf(output_path + out_file)
示例#27
0
    def __init__(self, path):
        # Declare data bank as empty dict
        self.mBank = {}
        # Set geometry options
        geometry_options = \
            {
                "landscape": True,
                "heightrounded": True,
                "a4paper": True,
                "headheight": "10mm",
                "tmargin": "15mm",
                "bottom": "10mm",
                "right": "15mm",
                "left": "15mm"
            }

        # Create document
        self.mDoc = pyl.Document(geometry_options=geometry_options,
                                 default_filepath=path + "/report")
        # Declare packages
        # self.mDoc.packages.append(pyl.Package("lscape", options="pdftex"))
        self.mDoc.packages.append(pyl.Package("float"))
        self.mDoc.add_color("LightGray", "rgb", "0.83, 0.83, 0.83")
        self.mDoc.add_color("DarkGray", "rgb", "0.66, 0.66, 0.66")
        # Create header
        header = pyl.PageStyle("header")
        # Create left header
        with header.create(pyl.Head("L")) as leftHeader:
            with leftHeader.create(
                    pyl.MiniPage(width=pyl.NoEscape(r"0.7\textwidth"),
                                 pos="c")) as logoWrapper:
                logoWrapper.append(
                    pyl.StandAloneGraphic(image_options="width=120px",
                                          filename="../Images/logo.png"))

        # Create right header
        with header.create(pyl.Head("R")):
            header.append("Electronics Workshop")

        # Append header to document
        self.mDoc.preamble.append(header)
        self.mDoc.change_document_style("header")

        return
示例#28
0
    def profile_likelihood(self, pl_directory, size=0.3, num_per_row=3):
        """
        compile any pdf, jpg and png files
        in directory into a latex pdf document
        :return:
        """
        if isinstance(self.file_types, str):
            self.file_types = [self.file_types]

        files = self.search_recursive(pl_directory)

        if files is []:
            raise errors.InputError(
                '''Cannot locate pdf, jpg or png files in "{}". Please 
                give the full path to where your model selection results are
                 plotted. 
                '''.format(pl_directory))
        doc = pylatex.Document(self.filename, documentclass='article')

        for k, v in list(files.items()):
            assert isinstance(v, list)
            if v is not None:
                with doc.create(
                        pylatex.Figure(
                            position='htbp!',
                            width=pylatex.NoEscape(r'\linewidth'))) as fig:
                    # [fig.add_image(i) for i in v]
                    for i in range(len(v)):
                        with doc.create(
                                pylatex.SubFigure(width=pylatex.NoEscape(
                                    str(size) + r'\linewidth'))) as sub:
                            sub.add_image(v[i])
                            sub.add_caption(os.path.split(v[i])[1])
                        if i is not 0 and i % num_per_row is 0:
                            doc.append(pylatex.NoEscape(r'\break'))
                            # sub.add_label(i)
                            #         # fig.add_caption(os.path.join(*Path(v[i]).parts[-3:-1]))

                        doc.append(pylatex.NoEscape(r'\hfill'))
                    fig.add_caption(os.path.split(k)[1])

        doc.generate_pdf()
        LOG.info('PDF generated at "{}"'.format(doc.default_filepath))
示例#29
0
    def __init__(self,
                 root='./latex',
                 name='default',
                 paper='a4paper',
                 fontsize='12pt',
                 history=None,
                 best1d=None,
                 constkernel=None):
        self.name = name
        self.history = history
        self.best1d = best1d
        self.constker = constkernel
        self.summands = history[-1].toSummands()
        self.kers, self.cums = cumulateAdditiveKernels(self.summands)

        # Prepare directory
        now = datetime.now().strftime('%Y%m%d%H%M%S')
        p = os.path.join(root, now + '_' + name)
        try:
            if os.path.exists(p): shutil.rmtree(p)
            os.makedirs(p)
        except Exception as e:
            print e
        self.path = p

        # Figure numbering
        self.fignum = 1

        # Make document
        self.doc = pl.Document(
            documentclass=pl.Command('documentclass',
                                     options=[fontsize, paper, 'twoside'],
                                     arguments='article'))
        self.makePreamble()
        self.makeIntro()
        self.makeSummary()
        self.describeVariables()
        self.describeAdditiveComponents()
示例#30
0
 def getPriceJustification(self):
     retval = pylatex.Document(documentclass='article')
     super(Obra, self).writePriceJustification(retval, 'root')
     retval.append(pylatex.Command('input{firmas}'))
     return retval