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
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')
class Form(pl.base_classes.Environment): """A class to wrap hyperref's form environment.""" _latex_name = 'Form' packages = [pl.Package('hyperref')] escape = False content_separator = "\n"
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
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)
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 document() -> kgpy.latex.Document: plt.rcParams['text.usetex'] = True plt.rcParams['font.family'] = 'serif' plt.rcParams['font.size'] = 9 plt.rcParams['lines.linewidth'] = 1 doc = kgpy.latex.Document( default_filepath=str(path_pdf), documentclass='aastex631', document_options=[ 'twocolumn', # 'linenumbers', ]) doc.packages.append(pylatex.Package('paralist')) doc.packages.append(pylatex.Package('amsmath')) doc.packages.append(pylatex.Package('acronym')) doc.packages.append(pylatex.Package('savesym')) doc.preamble += preamble.body() variables.append_to_document(doc) doc.append(kgpy.latex.Title('The EUV Snapshot Imaging Spectrograph')) doc += authors.author_list() doc.append(sections.abstract.section()) doc.append(sections.introduction.section()) doc.append(sections.esis_concept.section()) doc.append(sections.science_objectives.section()) doc.append(sections.esis_instrument.section(doc)) doc.append(sections.mission_profile.section()) doc.append(sections.conclusion.section()) doc.append(pylatex.Command('bibliography', arguments='sources')) return doc
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)
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
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
class TableNotes(pl.lists.List): """TableNotes implementation""" packages = [pl.Package('threeparttablex', options=['referable'])] _latex_name = 'TableNotes' def __init__(self, *args, prefix=None, **kwargs): super().__init__(*args, **kwargs) self._prefix = prefix def add_item(self, s, l): self.append(TableNoteItem(s, l, prefix=self._prefix))
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 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
class SubFigureForMultiPagePDF(FigureForMultiPagePDF): """A class that represents a subfigure from the subcaption package.""" _latex_name = "subfigure" packages = [plx.Package('subcaption')] #: By default a subfigure is not on its own paragraph since that looks #: weird inside another figure. separate_paragraph = False _repr_attributes_mapping = { 'width': 'arguments', } def __init__(self, width=plx.NoEscape(r'0.45\linewidth'), **kwargs): """ Args ---- width: str Width of the subfigure itself. It needs a width because it is inside another figure. """ super().__init__(arguments=width, **kwargs) def add_image(self, filename, *, width=plx.NoEscape(r'\linewidth'), page=None, placement=None): """Add an image to the subfigure. Args ---- filename: str Filename of the image. width: str Width of the image in LaTeX terms. page: int The page number of the PDF file for the image placement: str Placement of the figure, `None` is also accepted. """ super().add_image(filename, width=width, page=page, placement=placement)
def __init__(self, title): super().__init__(geometry_options={ "tmargin": "1cm", "lmargin": "1cm", "rmargin": "1cm", "bmargin": "2cm"}) self.preamble.append(tex.Package('graphicx')) self.preamble.append(tex.Command('title', title)) self.preamble.append(tex.Command('author', 'Charles Wilmot')) self.preamble.append(tex.Command('date', tex.utils.NoEscape(r'\today'))) self.append(tex.utils.NoEscape(r'\maketitle')) self.clearpage() self.append(tex.Command("tableofcontents")) self.clearpage()
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)
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
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
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)
def _prepare_document( document: pylatex.Document, language_options: tuple, language: str, paper_format: mus.PaperFormat, ) -> None: document.packages.remove(pylatex.Package("lastpage")) document.packages.append( pylatex.Package( "geometry", options=[ "{}paper".format(paper_format.name), "bindingoffset=0.2in", "left=0.8cm", "right=1cm", "top=1cm", "bottom=1cm", "footskip=.25in", ], )) document.packages.append(pylatex.Package("microtype")) document.packages.append(pylatex.Package("float")) document.packages.append(pylatex.Package("graphicx")) document.packages.append(pylatex.Package("fancyhdr")) document.packages.append( pylatex.Package("setspace", options=["onehalfspacing"])) document.packages.append( pylatex.Package("babel", options=[language_options[language]])) document.preamble.append( pylatex.NoEscape(r"\fancyhf{} % clear all header and footers")) document.preamble.append(pylatex.NoEscape(r"\setlength{\parindent}{0pt}")) # suppress page number document.preamble.append(pylatex.NoEscape(r"\pagenumbering{gobble}")) document.preamble.append(pylatex.NoEscape(r"\linespread{1.213}"))
def makePreamble(self): doc = self.doc doc.packages.append(pl.Package('geometry', options=['margin=25mm'])) doc.packages.append(pl.Package('hyperref')) doc.packages.append(pl.Package('babel', options=['UKenglish'])) doc.packages.append(pl.Package('isodate', options=['UKenglish'])) doc.packages.append(pl.Package('times')) doc.packages.append(pl.Package('siunitx')) doc.packages.append( ut.NoEscape( r'\sisetup{round-precision=2,round-mode=figures,scientific-notation=true}' )) title_str = r'AutoGPC Data Analysis Report on ' + self.name + ' Dataset' doc.preamble.append(pl.Command('title', ut.NoEscape(title_str))) doc.preamble.append(pl.Command('author', 'The Automatic Statistician')) doc.preamble.append(pl.Command('date', ut.NoEscape(r'\today'))) doc.append(ut.NoEscape(r'\maketitle'))
class Landscape(pylb.Environment): _latex_name = "landscape" packages = [pyl.Package("lscape")]
class ThreePartTable(pl.base_classes.Environment): """ThreePartTable implementation""" packages = [pl.Package('threeparttablex', options=['referable'])] _latex_name = 'ThreePartTable'
def generate_latex(output): top10 = 'top10.csv' top10_df = pd.read_csv(top10) top10_o = 'top10_out.csv' top10_o_df = pd.read_csv(top10_o) 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 Angle Pipeline Results')) doc.preamble.append(pl.Command('author', 'Veronica A. Boron')) doc.append(pl.NoEscape(r'\maketitle')) doc.append( 'This document summarizes the results obtained by running `packing_angle_pipeline.py` on various datasets.' ) # TODO table of contents is broken and doesn't show all sections # doc.append(pl.NoEscape(r'\tableofcontents')) doc.append(pl.NoEscape(r'\newpage')) with doc.create(pl.Section(f'Summary of Results')): with doc.create(pl.Table(position='!htbp')) as table: table.add_caption( 'Rakings of the top 20 combinations of methods, datasets, non-redundatizing, \ and correction factors. They were ranked according to a combination parameter which was calcuated \ in the following way: Combined-parameter = |(1/Pearsons coefficient)| + |mean-error| + |RMSE| + \ |RELRMSE|. The smallest combined-para value indicates a combination of low errors and \ high correlation coefficient.') table.append(pl.Command('centering')) table.append(pl.NoEscape(r'\resizebox{\textwidth}{!}{')) table.append(pl.NoEscape(top10_df.to_latex(escape=False))) table.append(pl.NoEscape(r'}')) with doc.create(pl.Table(position='!htbp')) as table: table.add_caption( 'Rakings of the top 20 combinations of methods, datasets, non-redundatizing, \ and correction factors for outlier prediction. They were ranked in according to a combination parameter.' ) table.append(pl.Command('centering')) table.append(pl.NoEscape(r'\resizebox{\textwidth}{!}{')) table.append(pl.NoEscape(top10_o_df.to_latex(escape=False))) table.append(pl.NoEscape(r'}')) # for ds, nr, cr in itertools.product(Dataset, NonRedundantization, Correction): # for ds, nr, in itertools.product(Dataset, NonRedundantization): # _add_data(doc, ds, nr, MLMethod.XvalWeka, cr) # doc.append(pl.NoEscape(r'\newpage')) # for tt, nr, meth, cr in itertools.product(get_all_testtrain(), NonRedundantization, MLMethod, Correction): for tt, nr, meth in itertools.product(get_all_testtrain(), NonRedundantization, MLMethod): # if meth is not MLMethod.XvalWeka: # _add_data(doc, tt.testing, nr, meth, cr) _add_data(doc, tt.testing, nr, meth) doc.append(pl.NoEscape(r'\newpage')) print('Generating PDF...') doc.generate_pdf(output, clean_tex=False)
# Read the data df_original = pd.read_csv(csv_file) df = df_original.copy() # Calculte DCF df['DCF'] = df.apply(lambda row: row['CF'] / (1.1**row['Months Passed']), axis=1) SDCF = df['DCF'].sum() if SDCF >= 0: sentence = f'The project has a profit of ${SDCF:,.0f}.' else: sentence = f'The project has a loss of ${-1 * SDCF:,.0f}.' # Create document doc = pl.Document() doc.packages.append(pl.Package('booktabs')) # Add preamble doc.preamble.append(pl.Command('title', report_title)) doc.preamble.append(pl.Command('author', repot_author)) doc.preamble.append(pl.Command('date', pl.NoEscape(r'\today'))) doc.append(pl.NoEscape(r'\maketitle')) # Create section 1 with doc.create(pl.Section('Data')): doc.append('The cash flow data is as follows.') with doc.create(pl.Table(position='htbp')) as table: table.add_caption('Cash Flow') table.append(pl.Command('centering')) table.append( pl.NoEscape(df_original.to_latex(escape=False, index=False)))
class MDFramed(pylatex.base_classes.Environment): _latex_name = 'mdframed' packages = [pylatex.Package('mdframed')]
def render_facts(): """ Render facts to a latex document """ import pylatex from pylatex.base_classes.command import Options # NOQA import pyqrcode fact_data = load_facts() class MDFramed(pylatex.base_classes.Environment): _latex_name = 'mdframed' packages = [pylatex.Package('mdframed')] class SamePage(pylatex.base_classes.Environment): _latex_name = 'samepage' class ComposeContexts: def __init__(self, *contexts): self.contexts = contexts def __enter__(self): return [c.__enter__() for c in self.contexts] def __exit__(self, a, b, c): return [c.__exit__(a, b, c) for c in self.contexts[::-1]] # class NewUnicodeChar(pylatex.base_classes.CommandBase): # pass # Dont use fontenc, lmodern, or textcomp # https://tex.stackexchange.com/questions/179778/xelatex-under-ubuntu doc = pylatex.Document('fact_document', inputenc=None, page_numbers=False, indent=False, fontenc=None, lmodern=False, textcomp=False) doc.preamble.append(pylatex.Package('graphicx')) # For PNG images # doc.preamble.append(pylatex.Package('svg', options=dict(inkscapearea='page'))) # doc.preamble.append(pylatex.Command('title', 'Facts')) # doc.preamble.append(pylatex.Command('author', 'Anonymous author')) # doc.preamble.append(pylatex.Command('date', pylatex.NoEscape(r'\today'))) # doc.append(pylatex.NoEscape(r'\maketitle')) # doc.preamble.append(pylatex.Package('newunicodechar')) # doc.preamble.append(pylatex.NoEscape(r'\newunicodechar{±}{$\pm$}')) # doc.append(pylatex.NoEscape('13.787±0.020')) # print(doc.dumps()) # doc.generate_pdf(clean_tex=False, compiler='xelatex') # return QR_REFERENCE = True stop_flag = 0 image_dpath = ub.Path('~/misc/facts/images').expand().ensuredir() # image_dpath = for fact in ub.ProgIter(fact_data['facts']): contexts = ComposeContexts( # doc.create(SamePage()), doc.create(MDFramed()), doc.create(pylatex.MiniPage(width=r'0.99\textwidth'))) # with doc.create(pylatex.MiniPage(width=r'\textwidth')): with contexts: doc.append(pylatex.NoEscape(r'\paragraph{Fact:}')) text = ub.paragraph(fact['text']) if r'\[' in text: found = list( re.finditer( '(' + re.escape(r'\[') + '|' + re.escape(r'\]') + ')', text)) prev_x = 0 for a, b in ub.iter_window(found, step=2): part = text[prev_x:a.span()[0]] doc.append(part) ax, bx = a.span()[1], b.span()[0] part = pylatex.NoEscape(r'$' + text[ax:bx] + r'$ ') doc.append(part) prev_x = b.span()[1] part = text[prev_x:] doc.append(part) else: # if '$' in text: # parts = text.split('$') # for idx, p in enumerate(parts): # if idx % 2 == 1: # doc.append(pylatex.NoEscape('$' + p + '$ ')) # else: # doc.append(p) # else: doc.append(text) if QR_REFERENCE: doc.append('\n') num_refs = 0 for refline in fact['references'].split('\n'): if refline.startswith('http'): found = refline image_fname = ub.hash_data(found, base='abc')[0:16] + '.png' image_fpath = image_dpath / image_fname if not image_fpath.exists(): # pyqrcode.create(found).svg(fpath, scale=6) pyqrcode.create(found).png(str(image_fpath), scale=2) doc.append( pylatex.NoEscape(r'\includegraphics[width=90px]{' + str(image_fpath) + '}')) # doc.append(pylatex.NoEscape(r'\includesvg[width=120px]{' + fpath + '}')) num_refs += 1 if num_refs > 3: break else: doc.append(pylatex.NoEscape(r'\paragraph{References:}')) with doc.create(pylatex.Itemize()) as itemize: for refline in fact['references'].split('\n'): if refline: refline = refline.strip() itemize.add_item(refline) doc.append(pylatex.NoEscape(r'\bigskip')) if stop_flag: break print(doc.dumps()) print('generate pdf') doc.generate_pdf(str(ub.Path('~/misc/facts/fact_document').expand()), clean_tex=True)
expName, 'Result']: print("Doing {} of category {}".format(expName, cat)) rda = RawDataAnalyser(expName=expName, dirpath=NIXPath) freqSecNames = rda.getContStats() for freq, secNames in freqSecNames.iteritems(): data['Category'].append(cat) data['Experiment ID'].append(expName) data['Frequency (Hz)'].append(freq) data['number of Trials'].append(len(secNames)) rawDF = pd.DataFrame(data) catFreqGrouped = rawDF.groupby(['Category', 'Frequency (Hz)']) statsDF = pd.DataFrame() statsDF['(number of Exps., number of Trials)'] = catFreqGrouped[ 'number of Trials'].agg(lambda x: (len(x), sum(x))) statsDFUnstacked = statsDF.unstack() statsDFTexTable = statsDFUnstacked.to_latex( column_format='c' + 'c' * len(statsDFUnstacked.columns)) statsDF2Write = rawDF.set_index( ["Category", "Experiment ID", "Frequency (Hz)"]) statsDF2Write.to_excel(contStimDetailedStatsFile) outDoc = pylatex.Document(contStimsResultsFile, documentclass='standalone', page_numbers=False, indent=False) outDoc.packages.append(pylatex.Package('booktabs')) outDoc.append(pylatex.utils.NoEscape(statsDFTexTable)) outDoc.generate_tex()
class Enumerate(pylatex.base_classes.Environment): """A class to wrap LaTeX's enumerate environment.""" packages = [pylatex.Package('enumitem')] escape = False content_separator = "\n"
class Preview(pylatex.base_classes.Environment): packages = [pylatex.Package('preview', ['active', 'tightpage', 'pdftex'])] escape = False content_separator = "\n"