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
def _gen_title(self): """Add metadata to preamble and `\\\\maketitle` to body.""" date = pl.NoEscape(r'\today') self.doc.preamble.append(pl.Command('title', self.args['title'])) self.doc.preamble.append(pl.Command('author', self.args['author'])) self.doc.preamble.append(pl.Command('date', date)) self.doc.append(pl.NoEscape(r'\maketitle'))
def section(doc: kgpy.latex.Document) -> pylatex.Section: result = pylatex.Section(pylatex.NoEscape(r'The \ESIS\ Instrument')) result.escape = False result.append( pylatex.NoEscape( r"""\ESIS\ is a multi-projection slitless spectrograph that obtains line intensities, Doppler shifts, and widths in a single snapshot over a 2D \FOV. Starting from the notional instrument described in Sec.~\ref{sec:TheESISConcept}, \ESIS\ has been designed to ensure all of the science requirements set forth in Table~\ref{table:scireq} are met. The final design parameters are summarized in Table~\ref{table:prescription}. A schematic diagram of a single \ESIS\ channel is presented in Fig.~\ref{fig:schematic}a, while the mechanical features of the primary mirror and gratings are detailed in Figs.~\ref{fig:schematic}b and \ref{fig:schematic}c, respectively.""" )) result.append(tables.prescription.table()) result.append(optics.subsection()) result.append(optimization_and_tolerancing.subsection(doc)) result.append(vignetting.subsection()) result.append(distortion.subsection()) result.append(coatings_and_filters.subsection()) result.append(sensitivity_and_cadence.subsection(doc)) result.append(alignment_and_focus.subsection()) result.append(apertures_and_baffles.subsection()) result.append(cameras.subsection()) result.append(avionics.subsection()) result.append(pointing_system.subsection()) result.append(mechanical.subsection()) return result
def make_subfigure(self, fig_funcs, layout=(5, 4), close=True): #todo figure out how to iterate properly n = np.product(layout) chunks = grouper(n, fig_funcs) w = str(1 / layout[1]) pbar = tqdm(total=len(fig_funcs)) for chunk in chunks: with self.doc.create(pyl.Figure(position='ht')) as tex_fig: for i, fig_func in enumerate(chunk): if fig_func is None: continue with self.doc.create( pyl.SubFigure( position='b', width=pyl.NoEscape(w + r'\linewidth'))) as subfig: fig = fig_func() file_path = self._save_fig( fig, bbox_inches='tight') # todo access these kwargs if close: plt.close(fig) subfig.add_image(file_path, width=pyl.NoEscape(r'\linewidth')) if i % layout[1] == layout[1] - 1: self.doc.append('\n') pbar.update(1) self.doc.append(pyl.NewPage())
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')))
def add2document(self, document) -> None: def add_hline(document): if self.has_label: cmd = r"\cline{" + "2-{0}".format(self.amount_elements + 1) + "}" document.append(pylatex.NoEscape(cmd)) else: document.append(pylatex.Command("hline")) amount_columns = int(self.amount_elements) - 1 if self.has_label: amount_columns += 1 columns = r" ".join((r"l", ) * amount_columns) table_start = r"\begin{tabular*}{\textwidth} {l @{\extracolsep{\fill}} " table_start += columns + r"}" document.append(pylatex.NoEscape(table_start)) if self.tempo_line: document.append(pylatex.NoEscape(str(self.tempo_line))) for melodic_line in self.melodic_lines: add_hline(document) document.append(pylatex.NoEscape(str(melodic_line))) add_hline(document) document.append(pylatex.NoEscape(r"\end{tabular*}"))
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)
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)
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]))
def createFig(self, imagePath, caption, width=tex.NoEscape(r'0.5\linewidth')): fig = tex.SubFigure(position='b', width=width) fig.add_image(str(imagePath), width=tex.NoEscape(r'\linewidth')) fig.add_caption(caption) return fig
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')
def test_mpl(self): fig = plt.figure() plt.plot([2,3,42,1]) file_path = self._save_fig(fig) with self.doc.create(pyl.Figure(position='htbp')) as plot: plot.add_image(pyl.NoEscape(file_path), width=pyl.NoEscape(r'1\textwidth')) plot.add_caption('I am a caption.')
def append_a_lsg(doc, lsg): doc.append(pylatex.Command('item')) doc.append(pylatex.Command('(')) doc.append(pylatex.Command('displaystyle')) doc.append(pylatex.NoEscape('\\mathbb{L} = \\{(')) doc.append(", ".join( map(str, map(int, lsg)) )) doc.append(pylatex.NoEscape(')\\}')) doc.append(pylatex.Command(')'))
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()
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
def _make_img(path: str, width: float = 1, add_figure: bool = True, position="H") -> pylatex.Figure: graphic = pylatex.Command( "includegraphics", options=[pylatex.NoEscape("width={}".format(width) + r"\textwidth")], arguments=pylatex.NoEscape(path), ) if add_figure: return pylatex.Figure(arguments=graphic, position=position) else: return graphic
def render_table_cell_latex(cell, c, top_space, btm_space, widths): cell = cell.walk(links_to_table_notes) cell_wrapper = lc.Span() content = utils.panflute2output(cell.content, format="latex") style = "" if cell.heading == 1: style = "\\sffamily " elif cell.heading == 2: style = "\\sffamily\\small " content = style + content cell_width = widths[c] if cell.col_span > 1: cell_width = sum(widths[c:c + cell.col_span]) minipage = pl.MiniPage( width="{}\\columnwidth".format(cell_width), pos="t", align="left", content_pos="t", ) minipage.append(pl.Command("setstretch", arguments="0.6")) if cell.vertical: minipage.append(lc.RotateBox(pl.NoEscape(content))) else: minipage.append(pl.NoEscape(content)) cell_wrapper.append(pl.Command("noindent")) cell_wrapper.append(minipage) if c == 0: if top_space: cell_wrapper.append(pl.Command("T")) if btm_space: cell_wrapper.append(pl.Command("B")) if cell.col_span > 1: margins = "@{}" if cell.rm_horizontal_margins else "" multicolumn = pl.MultiColumn(cell.col_span, align=pl.NoEscape(f"{margins}l{margins}"), data=cell_wrapper) return multicolumn elif not cell.covered: return cell_wrapper
def create_caption(section, superscript, text): """ Adds a caption preceded by superscripted characters to a table :param section: LateX section object :param superscript: character(s) to superscript :param text: descriptive text """ section.append('\n') # Superscript section.append(bold(pl.NoEscape(r'{\footnotesize \textsuperscript {' + superscript + '}}'))) # Text section.append(italic(pl.NoEscape(r'{\footnotesize {' + text + '}}')))
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
def add_hline(document): if self.has_label: cmd = r"\cline{" + "2-{0}".format(self.amount_elements + 1) + "}" document.append(pylatex.NoEscape(cmd)) else: document.append(pylatex.Command("hline"))
def add2document(self, doc) -> None: with doc.create(pylatex.Section(self.name)): for table in self.tables: table.add2document(doc) doc.append(pylatex.NoEscape("")) doc.append(pylatex.Command("newline")) doc.append(pylatex.NoEscape("")) doc.append( pylatex.Command( "vspace", arguments="{0}mm".format( self.VERTICAL_SPACE_BETWEEN_TABLE), )) doc.append(pylatex.NoEscape("")) doc.append(pylatex.Command("newline")) doc.append(pylatex.NoEscape(""))
def make_tex(A, B): tex = "" for mat in [A, B]: if len(tex): tex += "\\cdot" tex += make_matr_tex(mat) return pylatex.NoEscape(tex)
def ImprLtxPie(data_table, totalr): data_table.add_row([ pylatex.table.MultiColumn(5, align='r', data=pylatex.NoEscape("Suma\\ldots")), pylatex.utils.bold(totalr) ])
def textsc(s, escape=True): r"""Make a string appear textsc in LaTeX formatting. textsc() wraps a given string in the LaTeX command \textsc{}. Args ---- s : str The string to be formatted. escape: bool If true the textsc text will be escaped Returns ------- NoEscape The formatted string. Examples -------- >>> textsc("hello") '\\textsc{hello}' >>> print(textsc("hello")) \textsc{hello} """ if escape: s = pylatex.escape_latex(s) return pylatex.NoEscape(r'\textsc{' + s + '}')
def input(s, escape=True): r"""Make LaTeX to read from a file. input() wraps a given string in the LaTeX command \input{}. Args ---- s : str The string to be formatted. escape: bool If true the input text will be escaped Returns ------- NoEscape The formatted string. Examples -------- >>> input("hello.tex") '\\input{hello.tex}' >>> print(input("hello.tex")) \input{hello.tex} """ if escape: s = pylatex.escape_latex(s) return pylatex.NoEscape(r'\input{' + s + '}')
def dumps_content(self, **kwargs): content = '' content += super(pl.base_classes.Environment, self).dumps_content(**kwargs) return pl.NoEscape(content)
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())
def finalize(self): doc = util.create_doc( f"Correlator Fits: {self.ensemble_name} - {self.task_name}") for operator_set, operator_fits in self.operator_fits.items(): with doc.create(pylatex.Section(str(operator_set))): for operator, fits in operator_fits.items(): with doc.create(pylatex.Subsection(str(operator))): for fit, fit_infos in fits.items(): # normal fits logfile = self.logfile(operator_set, operator, fit.name) fit_log = sigmond_info.sigmond_log.FitLog(logfile) if self.fit_plots: plotdir = self.fit_plotdir( operator_set, operator, fit.name) util.dirGrace2pdf(plotdir) section_title = f"{fit.name} - Model: {fit.model.short_name}" with doc.create( pylatex.Subsubsection(section_title)): self._add_fits(doc, fit_log, fit.name, operator_set, fit.ratio, fit.model.has_gap, fit.model.has_const) # tmin fits if self.tmin_plots: plotdir = self.tmin_fit_plotdir( operator_set, operator, fit.name) util.dirGrace2pdf(plotdir) tmin_fit_infos = list() for fit_info in fit_infos['tmin']: plotfile = self.tmin_fit_plotfile( operator_set, fit.name, fit_info, extension=util.PlotExtension.pdf) if os.path.isfile(plotfile): tmin_fit_infos.append(fit_info) if len(tmin_fit_infos) == 0: continue tmin_fit_infos.sort( key=lambda fit_info: fit_info.tmax) section_title = f"$t_{{\\rm min}}$ plots - {fit.name} - Model: {fit.model.short_name}" with doc.create( pylatex.Subsubsection( pylatex.NoEscape(section_title))): self._add_tmins(doc, tmin_fit_infos, fit.name, operator_set, fit.ratio) results_dir = self.results_dir os.makedirs(results_dir, exist_ok=True) filename = os.path.join(results_dir, self.task_name) util.compile_pdf(doc, filename, self.latex_compiler)
def append(self, obj): """""" if isinstance(obj, str): self.data.append(self._conv_str_to_math(obj)) else: assert isinstance(obj, plx.Math) self.data.extend([plx.NoEscape(s) for s in obj.data])
def table() -> pylatex.Table: result = pylatex.Table(position='!htb') result._star_latex_name = True with result.create(pylatex.Center()) as centering: with centering.create(pylatex.Tabular(table_spec='llll', )) as tabular: tabular.escape = False tabular.add_row( ['Parameter', 'Requirement', 'Science Driver', 'Capabilities']) tabular.add_hline() tabular.add_row([ r'Spectral line', r'\OV', r'\EEs', r'\OVion, \MgXion, \HeIion, Figure~\ref{fig:bunch}', ]) tabular.add_row([ r'Spectral sampling', r'\spectralResolutionRequirement', r'Broadening from \MHD\ waves', r'\dispersionDoppler, Table~\ref{table:prescription}', ]) tabular.add_row([ r'Spatial resolution', r'\angularResolutionRequirement (\spatialResolutionRequirement)', r'\EEs', r'\spatialResolutionTotal, Table~\ref{table:errorBudget}', ]) tabular.add_row([ r'\SNRShort', r'\snrRequirement\ (\CHShort)', r'\MHD\ waves in \CHShort', r'\StackedCoronalHoleSNR\ ($\NumExpInStack \times \text{\detectorExposureLength}$ exp.), ' r'Table~\ref{table:counts}', ]) tabular.add_row([ r'Cadence', r'\cadenceRequirement', r'Torsional waves', r'\detectorExposureLength\ eff., Section~\ref{subsec:SensitivityandCadence}', ]) tabular.add_row([ r'Observing time', r'\observingTimeRequirement', r'\EEs', r'\SI{270}{\second}, Section~\ref{sec:MissionProfile}', ]) tabular.add_row([ r'\FOV\ diameter', r'\fovRequirement', r'Span \QSShort, \ARShort, and limb', r'\fov, Table~\ref{table:prescription}', ]) result.add_caption( pylatex.NoEscape( r"""\ESIS\ instrument requirements and capabilties. Note that MTF exceeds the Rayleigh criterion of 0.109.""" )) result.append(kgpy.latex.Label('table:scireq')) return result