def finalize(self): if self.write_operators and os.path.isfile(self.op_yaml_file): os.remove(self.op_yaml_file) self.data_handler.findAveragedData() doc = util.create_doc( f"Averaged Correlators and Effective Energies: {self.ensemble_name} - {self.task_name}" ) for channel in self.averaged_channels: data_files = self.data_files + self.data_handler.getChannelDataFiles( channel) operators = self.data_handler.getChannelOperators(channel) if self.write_operators: operator_info.operator_set.write_operators( self.op_file(channel), operators, True, False) operator_info.operator_set.write_operators_to_yaml( self.op_yaml_file, repr(channel), operators, True) result_operators, original_operators, coefficients = self.final_info[ channel] with doc.create(pylatex.Section(str(channel))): with doc.create(pylatex.Subsection("Operators averaged")): for result_operator in result_operators: with doc.create(pylatex.Itemize()) as itemize: itemize.add_item(result_operator.op_str()) with doc.create(pylatex.Itemize()) as sub_itemize: for original_operator in original_operators: the_op = original_operator[result_operator] the_coeff = coefficients.get(the_op, 1.) sub_itemize.add_item( f"{the_coeff} {the_op.op_str()}") doc.append(pylatex.NoEscape(r"\newpage")) self.addPlotsToPDF(doc, data_files, operators, repr(channel)) filename = os.path.join(self.results_dir, util.str_to_file(self.task_name)) util.compile_pdf(doc, filename, self.latex_compiler)
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)
def printLtx(self, doc, precio_ejec_mat): precision = 2 with doc.create(pylatex.Itemize()) as itemize: itemize.add_item(u'Total presupuesto de ejecución material ') itemize.append(pylatex.Command('dotfill')) itemize.append( basic_types.human_readable(precio_ejec_mat, precision)) precio_gg = basic_types.ppl_price(self.GGenerales(precio_ejec_mat)) itemize.add_item(str(self.gg * 100) + u'% Gastos generales ') itemize.append(pylatex.Command('dotfill')) itemize.append(basic_types.human_readable(precio_gg, precision)) precio_bi = basic_types.ppl_price( self.BIndustrial(precio_ejec_mat)) itemize.add_item(str(self.bi * 100) + u'% Beneficio industrial ') itemize.append(pylatex.Command('dotfill')) itemize.append(basic_types.human_readable(precio_bi, precision)) suma_gg_bi = precio_ejec_mat + precio_gg + precio_bi itemize.add_item('Suma ') itemize.append(pylatex.Command('dotfill')) itemize.append(basic_types.human_readable(suma_gg_bi, precision)) precio_iva = basic_types.ppl_price(self.IVA(suma_gg_bi)) itemize.add_item(str(self.iva * 100) + u'% I.V.A. ') itemize.append(pylatex.Command('dotfill')) itemize.append(basic_types.human_readable(precio_iva, precision)) total = suma_gg_bi + precio_iva doc.append( pylatex.utils.bold(u'Presupuesto de ejecución por contrata:') + pylatex.NoEscape('\dotfill') + pylatex.utils.bold(basic_types.human_readable(total, precision))) doc.append(pylatex.VerticalSpace('0.5cm')) doc.append(pylatex.NewLine()) doc.append( u'Asciende el presente presupuesto de ejecución por contrata a la expresada cantidad de: ' ) doc.append( pylatex_utils.textsc( basic_types.to_words(total, False) + ' euros.'))
def ImprLtxResumen(self, doc, sect, recurre): if len(self): with doc.create(pylatex.Itemize()) as itemize: for j in self: (j).ImprLtxResumen(itemize,sect,recurre)
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)
def _add_list_itemize_latex(self, doc, title, elements): with doc.create(pylatex.Subsection(title)): with doc.create(pylatex.Itemize()) as itemize: [itemize.add_item(x.name) for x in elements]