def _add_overview(self, doc: Document, title: str = 'Overview') -> None: """Add overview section to document. :param doc: :param title: :return: """ with doc.create(Section(title)): doc.append('Overview of kernel search results.') doc.append("\n") doc.append(VerticalSpace("10pt")) doc.append(LineBreak()) best_kern_short = str(self.best_gp_model) best_kern_long = self.best_gp_model.covariance.infix_full with doc.create(MiniPage()): doc.append(bold("Best Kernel:")) doc.append("\n") doc.append(VerticalSpace("1pt")) doc.append(LineBreak()) doc.append(italic("Short Form:")) doc.append("\n") doc.append(best_kern_short) doc.append("\n") doc.append(VerticalSpace("2.5pt")) doc.append(LineBreak()) doc.append(italic("Long Form:")) doc.append("\n") doc.append(best_kern_long)
def make_doc(self, foirequest): doc = Document( lmodern=True, geometry_options={ "a4paper": True, "margin": "1in", }, ) # Change font doc.packages.append(Package('fontspec,xunicode,array')) doc.packages.append(Package('sectsty')) doc.preamble.append(NoEscape("\\usepackage{helvet}")) doc.preamble.append( NoEscape("\\sectionfont{\\fontsize{12}{15}\\selectfont}")) # Adjust description list doc.packages.append(Package('enumitem')) doc.preamble.append( NoEscape( "\\setlist[description]{labelindent=0cm,style=multiline,leftmargin=1.5cm}" )) # Hyphenation doc.append(NoEscape("\\lefthyphenmin=5")) doc.append(NoEscape("\\sloppy")) # doc.preamble.append(Command('title', foirequest.title)) # doc.preamble.append(Command('author', foirequest.get_absolute_domain_short_url())) # doc.preamble.append(Command('date', NoEscape('\\today'))) # doc.append(NoEscape('\\maketitle')) # Set up header and footer header = PageStyle("header") with header.create(Foot("L")): header.append(italic(settings.SITE_NAME)) with header.create(Head("C")): header.append(foirequest.title) with header.create(Foot("R")): header.append( str( _('Request #{request_no}').format( request_no=foirequest.pk))) with header.create(Foot("C")): header.append( italic(NoEscape(r'Seite \thepage\ von \pageref{LastPage}'))) doc.preamble.append(header) doc.change_document_style("header") for i, message in enumerate(foirequest.messages): last = i == len(foirequest.messages) - 1 add_message_to_doc(doc, message) if not last: doc.append(NewPage()) return doc
def test_utils(): # Utils escape_latex(s='') fix_filename(path='') dumps_list(l=[], escape=False, token='\n') bold(s='') italic(s='') verbatim(s='', delimiter='|')
def writeReportFree(filename, questions, results): doc = prepareDocFree() for i in range(len(questions)): figpie = plot_module.preparePie(results[i]) figbar = plot_module.prepareBar(results[i]) writeQuestion(doc, questions[i], results[i], figpie, figbar) if settings.eliminate: doc.append(italic(bold("Not: "))) doc.append(italic("Değerlendirmeye hepsi '{}' olarak işaretlenmiş cevaplar katılmamıştır.".format(settings.eliminate_choice))) status = createPdf(doc, filename, settings.debug) return status
def test_utils(): # Utils escape_latex(s="") fix_filename(path="") dumps_list(l=[], escape=False, token="\n") bold(s="") italic(s="") verbatim(s="", delimiter="|")
def make_doc(self, foirequest): doc = Document( lmodern=True, geometry_options={ "a4paper": True, "margin": "1in", }, ) # Change font doc.packages.append(Package('fontspec,xunicode,array')) doc.packages.append(Package('sectsty')) doc.preamble.append(NoEscape("\\usepackage{helvet}")) doc.preamble.append(NoEscape("\\sectionfont{\\fontsize{12}{15}\\selectfont}")) # Adjust description list doc.packages.append(Package('enumitem')) doc.preamble.append(NoEscape("\\setlist[description]{labelindent=0cm,style=multiline,leftmargin=1.5cm}")) # Hyphenation doc.append(NoEscape("\\lefthyphenmin=5")) doc.append(NoEscape("\\sloppy")) # doc.preamble.append(Command('title', foirequest.title)) # doc.preamble.append(Command('author', foirequest.get_absolute_domain_short_url())) # doc.preamble.append(Command('date', NoEscape('\\today'))) # doc.append(NoEscape('\\maketitle')) # Set up header and footer header = PageStyle("header") with header.create(Foot("L")): header.append(italic(settings.SITE_NAME)) with header.create(Head("C")): header.append(foirequest.title) with header.create(Foot("R")): header.append(str( _('Request #{request_no}').format(request_no=foirequest.pk))) with header.create(Foot("C")): header.append(italic(NoEscape(r'Seite \thepage\ von \pageref{LastPage}'))) doc.preamble.append(header) doc.change_document_style("header") for i, message in enumerate(foirequest.messages): last = i == len(foirequest.messages) - 1 add_message_to_doc(doc, message) if not last: doc.append(NewPage()) return doc
def add_to_book(self, book: Book): with book.create(MdFramed()) as box: box.append(bold(self.name)) box.append(NoEscape("\\hspace*{\\fill}")) box.append(bold(self.__get_cost())) box.append(" ¥€$\n") box.append(NoEscape(r"\noindent\rule{\columnwidth}{1pt}")) box.append(LineBreak()) box.append(NoEscape(self.desc)) box.append(LineBreak()) box.append(LineBreak()) with box.create(Tabularx("X|l|r")) as tab: for effect, perma_effect, effector in itertools.zip_longest(self.effects, self.permanent_effects, self.effectors): row = [] if effect is not None: row.append(effect + ":" + get_effect_str(self.effects[effect])) else: row.append("") if perma_effect is not None: row.append(perma_effect + ":" + get_effect_str(self.permanent_effects[perma_effect])) else: row.append("") if effector is not None: row.append(italic(effector.name)) else: row.append("") tab.add_row(row)
def createParagraph(self, doc, line): # Normal Line if line.lineType == "normal": doc.append(line.content) # Line with formula if line.lineType == "math": with doc.create(Alignat(numbering=True, escape=False)) as math_eq: math_eq.append(line.content) # Example Lines if line.lineType == "example": if not line.title == "": doc.append(bold(line.title+"\n")) else: doc.append(italic(line.content)) if line.lineType == "image": imgPath = self.findImageAndConvert( line.content) if not imgPath == None: with doc.create(Figure(position='H')) as image: image.add_image( imgPath) return doc
def arxiv_search(search_query): url = 'http://export.arxiv.org/api/query?search_query=all:' + \ search_query + '&start=0&max_results=5' data = urllib.request.urlopen(url).read() soup = bs(data, features='xml') title_array = [] summary_array = [] for i in soup.findAll('title'): title_array.append(i) for i in soup.findAll('summary'): summary_array.append(i) doc = Document() doc.packages.append( Package( 'geometry', options=[ 'tmargin=1cm', 'lmargin=1cm', 'rmargin=1cm'])) with doc.create(Section('Search results for \"' + search_query + '\"')): for i in range(1, 5): doc.append(Subsection(italic(title_array[i].string))) doc.append(summary_array[i].string) doc.generate_pdf()
def append_liquor_list(doc, df, own_page): # TODO no interaction with dataframe? kinds = df[df.Category.isin(['Spirit', 'Vermouth', 'Liqueur'])][['Kind', 'Type']] if own_page: print "Appending list as new page" doc.append(NewPage()) listing = SamepageEnvironment() block = Center() if not own_page: block.append(HRuleFill()) block.append(Command('\\')) block.append(VerticalSpace('16pt')) block.append(TitleText("Included Ingredients")) block.append(Command('\\')) listing.append(block) listing.append(VerticalSpace('12pt')) cols = add_paracols_environment(listing, 2, '8pt', sloppy=False) with cols.create(FlushRight()): for item in kinds.Kind: cols.append(LargeText(item)) cols.append(Command('\\')) cols.append(Command('switchcolumn')) with cols.create(FlushLeft()): for item in kinds.Type: cols.append(LargeText(italic(item))) cols.append(Command('\\')) doc.append(listing)
def latex(self): _content = "" for c in self.children: _content += c.latex() if self.delimiter == '/': return italic(_content, escape=False) elif self.delimiter == '*': return bold(_content, escape=False)
def fill_document(self): """Add a section, a subsection and some text to the document.""" with self.create(Section('A section')): self.append('Some regular text and some ') self.append(italic('italic text. ')) with self.create(Subsection('A subsection')): self.append('Also some crazy characters: $&#{}')
def question_with_help(phrase, vocabulary, doc): dictionary = rnd_remove(phrase) gapped_phrase = dictionary['phrase'] entry = phrase[dictionary['entry']] doc.append(to_string(gapped_phrase)) doc.append('\n\n') doc.append(italic(to_string(show_help(entry, phrase, vocabulary))))
def addExperience(self, jobs): self.doc.append(Command("begin", ["rSection", "Related Work Experience"])) for job in jobs: self.doc.append(Command("begin", ["rSubsection", job[0], italic(job[1]), job[2], ''])) self.doc.append(Command("item", job[3])) self.doc.append(Command("end", "rSubsection")) self.doc.append(Command("end", "rSection"))
def GENP(A, b): section = Section('The first section') n = len(A) if b.size != n: raise ValueError("Invalid argument: incompatible sizes between A & b.", b.size, n) for pivot_row in range(n-1): section.append("Considering Column " + (str)(pivot_row+1)) for row in range(pivot_row+1, n): section.append(italic("Row" +(str)(row+1))) section.append(Subsection('\t', data=[Math(data=["\tmultiplier", '=', A[row][pivot_row], " / ", A[pivot_row][pivot_row]])])) multiplier = A[row][pivot_row]/A[pivot_row][pivot_row] multiplier = round(multiplier,2) section.append(Math(data=["\t\tmultiplier", '=', multiplier])) section.append("\n") #the only one in this column since the rest are zero section.append("\tapplying multiplier to the row") section.append(Math(data=[ NoEscape("\t\tr_"+(str)(row+1))," - ", multiplier,NoEscape("r_"+(str)(pivot_row+1)) ])) for col in range(pivot_row, n): section.append(Math(data=["\t\t", A[row][col]," - (", multiplier, " x ", A[pivot_row][col], ")"])) A[row][col] = A[row][col] - multiplier * A[pivot_row][col] section.append(Math(data=["\t\t\t = ", A[row][col]])) #Equation solution column section.append(Math(data=["\t\t", b[row]," - (", multiplier, " x ", b[pivot_row], ")"])) b[row] = b[row] - multiplier * b[pivot_row] section.append(Subsection('\t\t\t', data=[Math(data=['=', b[row]])])) section.append(Math(data=['A', '=', Matrix(A)])) section.append(Math(data=['b', '=', b])) section.append("\n") section.append("Performing back substitution") x = np.zeros(n) k = n-1 section.append(Math(data=[NoEscape("\tr_"+(str)(k+1)),"=", b[k], " / ", A[k,k]])) x[k] = round(b[k]/A[k,k],2) section.append(Math(data=["\t\t= ", x[k]])) k-=1 while k >= 0: eqn = [NoEscape("\tr_"+(str)(k+1)),"=", b[k], " - "] eqn.extend(print_dot(A[k,k+1:],x[k+1:])) eqn.extend([" / ", A[k,k]]) section.append(Math(data=eqn)) x[k] = round((b[k] - np.dot(A[k,k+1:],x[k+1:]))/A[k,k],2) section.append(Math(data=["\t\t= ", x[k]])) k = k-1 return section
def render_metric(value, best, second, decimals, format_string): if isinstance(value, numbers.Number): rendered = format_string.format(value, prec=decimals) if value == best: rendered = bold(rendered) elif value == second: rendered = italic(rendered) return rendered else: return value
def add_song_to_doc(doc, song): """Insert info for the given Song into the Document.""" doc.append(chapter(song.title)) doc.append(label(song.slug)) doc.append('By ') doc.append(italic(song.author)) doc.append(NewLine()) doc.append(song.lyrics()) return doc
def fill_document(doc): """Add a section, a subsection and some text to the document. :param doc: the document :type doc: :class:`pylatex.document.Document` instance """ with doc.create(Section('A section')): doc.append('Some regular text and some ') doc.append(italic('italic text. ')) with doc.create(Subsection('A subsection')): doc.append('Also some crazy characters: $&#{}')
def add_page2(self): doc = self.m_doc with doc.create(pl.Section('A section 2')): doc.append('Some regular text and some ') doc.append(italic('italic text. ')) with doc.create(pl.Figure(position='h!')) as kitten_pic: kitten_pic.add_image("meso.png", width=NoEscape(r'0.75\textwidth')) doc.append(pl.NewPage())
def fill_document(doc): with doc.create(Section('A section')): doc.append('Some regular text and some ') doc.append(italic('italic text. ')) doc.append(bold('bold text. ')) with doc.create(Subsection('A subsection')): doc.append('Also some crazy characters: $&#{}') doc.append( NoEscape( r"$$f'(a) = \lim_{x \to a} \frac{f(x) - f(a)}{x-a}$$"))
def complexStuff(doc): with doc.create(Section('The simple stuff')): doc.append('Some regular text and some') doc.append(italic('italic text. ')) doc.append('\nAlso some crazy characters: $&#{}') with doc.create(Subsection('Math that is incorrect')): doc.append(Math(data=['2*3', '=', 9])) with doc.create(Subsection('Table of something')): with doc.create(Tabular('rc|cl')) as table: table.add_hline() table.add_row((1, 2, 3, 4)) table.add_hline(1, 2) table.add_empty_row() table.add_row((4, 5, 6, 7)) a = np.array([[100, 10, 20]]).T M = np.matrix([[2, 3, 4], [0, 0, 1], [0, 0, 2]]) with doc.create(Section('The fancy stuff')): with doc.create(Subsection('Correct matrix equations')): doc.append(Math(data=[Matrix(M), Matrix(a), '=', Matrix(M * a)])) with doc.create(Subsection('Alignat math environment')): with doc.create(Alignat(numbering=False, escape=False)) as agn: agn.append(r'\frac{a}{b} &= 0 \\') agn.extend([Matrix(M), Matrix(a), '&=', Matrix(M * a)]) with doc.create(Subsection('Beautiful graphs')): with doc.create(TikZ()): plot_options = 'height=4cm, width=6cm, grid=major' with doc.create(Axis(options=plot_options)) as plot: plot.append(Plot(name='model', func='-x^5 - 242')) coordinates = [ (-4.77778, 2027.60977), (-3.55556, 347.84069), (-2.33333, 22.58953), (-1.11111, -493.50066), (0.11111, 46.66082), (1.33333, -205.56286), (2.55556, -341.40638), (3.77778, -1169.24780), (5.00000, -3269.56775), ] plot.append(Plot(name='estimate', coordinates=coordinates)) # with doc.create(Subsection('Cute kitten pictures')): # with doc.create(Figure(position='h!')) as kitten_pic: # kitten_pic.add_image(image_filename, width='120px') # kitten_pic.add_caption('Look it\'s on its back') doc.generate_pdf('full', clean_tex=False)
def fill_document(doc): """Adds a section, a subsection and some text to the document. :param doc: the document :type doc: :class:`pylatex.Document` instance """ with doc.create(Section('A section')): doc.append('Some regular text and some ' + italic('italic text. ')) with doc.create(Subsection('A subsection')): doc.append(escape_latex('Also some crazy characters: $&#{}'))
def format_recipe(recipe, display_opts): """ Return the recipe in a paragraph in a samepage """ recipe_page = SamepageEnvironment() name_line = LargeText(recipe.name) if display_opts.origin and 'schubar original' in recipe.origin.lower(): name_line.append(superscript('*')) #name_line.append(superscript(NoEscape('\dag'))) if display_opts.prices and recipe.max_cost: price = util.calculate_price(recipe.max_cost, display_opts.markup) name_line.append(DotFill()) name_line.append(superscript('$')) name_line.append(price) name_line.append('\n') recipe_page.append(name_line) if display_opts.prep_line: recipe_page.append( FootnoteText(recipe.prep_line(extended=True, caps=False) + '\n')) if display_opts.info and recipe.info: recipe_page.append(SmallText(italic(recipe.info + '\n'))) for item in recipe.ingredients: recipe_page.append(item.str() + '\n') if display_opts.variants: for variant in recipe.variants: recipe_page.append(HorizontalSpace('8pt')) recipe_page.append(SmallText(italic(variant + '\n'))) if display_opts.examples and recipe.examples: # and recipe.name != 'The Cocktail': for e in recipe.examples: recipe_page.append( FootnoteText( "${cost:.2f} | {abv:.2f}% | {std_drinks:.2f} | {kinds}\n". format(**e._asdict()))) recipe_page.append(Command('par')) return recipe_page
def fill_document(doc): """Add a section, a subsection and some text to the document. :param doc: the document :type doc: :class:`pylatex.document.Document` instance """ with doc.create(Section('ِش سثؤفهخى')): doc.append('إخع ساخعمي شمصشغس سحثشن فاث فقعفا') doc.append(italic('فشمهؤ ؤخىفثىفس شقث شمسخ ىهؤث')) with doc.create(Subsection('آثص ٍعلاسثؤفهخى')): doc.append('بشةخعس ؤقشئغ ؤاشقشؤفثقس: $&#{}')
def fill_document(doc): """Add a section, a subsection and some text to the document. :param doc: the document :type doc: :class:`pylatex.document.Document` instance """ test = "je suis un titre plutot long mais court a lafois ciic" with doc.create(Section(test)): doc.append('Some regular text and some ') doc.append(italic('italic text. ')) with doc.create(Subsection('A subsection')): doc.append('Also some crazy characters: $&#{}')
def fill_document(doc): """Add a section, a subsection and some text to the document. :param doc: the document :type doc: :class:`pylatex.document.Document` instance """ with doc.create(Section("A section")): doc.append("Some regular text and some ") doc.append(italic("italic text. ")) with doc.create(Subsection("A subsection")): doc.append("Also some crazy characters: $&#{}")
def render_table(self, doc: Document, name_override: Optional[LatexObject] = None, toc_ref: Optional[str] = None, extra_rows: Optional[List[Tuple[str, Any]]] = None) -> None: """Write this table into a LaTeX document. Args: doc: The LaTeX document to be appended to. name_override: An optional replacement for this table's name field. toc_ref: A reference to be added to the table of contents. extra_rows: Any extra rows to be added to the table before the kwargs. """ with doc.create(Table(position='htp!')) as table: table.append(NoEscape(r'\refstepcounter{table}')) table.append(Label(Marker(name=str(self.fe_id), prefix="tbl"))) if toc_ref: table.append(NoEscape(r'\addcontentsline{toc}{subsection}{' + escape_latex(toc_ref) + '}')) with doc.create(Tabularx('|lX|', booktabs=True)) as tabular: package = Package('xcolor', options='table') if package not in tabular.packages: # Need to invoke a table color before invoking TextColor (bug?) tabular.packages.append(package) package = Package('seqsplit') if package not in tabular.packages: tabular.packages.append(package) tabular.add_row((name_override if name_override else bold(self.name), MultiColumn(size=1, align='r|', data=TextColor('blue', self.fe_id)))) tabular.add_hline() type_str = f"{self.type}" match = re.fullmatch(r'^<.* \'(?P<typ>.*)\'>$', type_str) type_str = match.group("typ") if match else type_str tabular.add_row(("Type: ", escape_latex(type_str))) if self.path: if isinstance(self.path, LatexObject): tabular.add_row(("", self.path)) else: tabular.add_row(("", escape_latex(self.path))) for k, v in self.fields.items(): tabular.add_hline() tabular.add_row((f"{k.capitalize()}: ", v)) if self.args: tabular.add_hline() tabular.add_row(("Args: ", self.args)) if extra_rows: for (key, val) in extra_rows: tabular.add_hline() tabular.add_row(key, val) if self.kwargs: tabular.add_hline() for idx, (kwarg, val) in enumerate(self.kwargs.items()): tabular.add_row((italic(kwarg), val), color='white' if idx % 2 else 'black!5')
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 create_reading_section(document, medium): with document.create(Subsection('Reading')): with document.create(Itemize()) as itemize: try: df = pd.read_csv(os.path.join(medium, 'reading.csv')) except pd.errors.EmptyDataError: return for _, row in df.iterrows(): title = row.Title link = row.Link itemize.add_item(italic(title)) itemize.append(NewLine()) arguments = Arguments(link, link) itemize.append(Command('href', arguments=arguments))
def fill_document(doc): """Add a section, a subsection and some text to the document. :param doc: the document :type doc: :class:`pylatex.document.Document` instance """ with doc.create(Section('Details of Original Notes')): doc.append('Word count: ') doc.append(italic('something')) with doc.create(Subsection('Key Words')): with doc.create(Itemize()) as itemize: itemize.add_item("the first item") itemize.add_item("the second item") itemize.add_item("the third etc") # you can append to existing items itemize.append(Command("ldots"))
def add_text(doc): (idoc, introfile) = add_section("introduction") idoc.append('Some regular text and some ') idoc.generate_tex(introfile) (bdoc, backgroundfile) = add_section("background") bdoc.append('Some regular text and some ' + italic('italic text. ')) bdoc.generate_tex(backgroundfile) add_evaluation() doc.append(Section('Introduction')) doc.append(Command('input', arguments='introduction.tex')) doc.append(Section('Background')) doc.append(Command('input', arguments='background.tex')) doc.append(Section('Experiments')) doc.append(Command('input', arguments='evaluation.tex')) return doc
def add_finding(doc, finding): """Add a section, a subsection and some text to the document. :param doc: the document :type doc: :class:`pylatex.document.Document` instance """ with doc.create(Subsection(finding.name)): # doc.append(evidence.created_at) doc.append(finding.description) doc.append(italic('italic text. ')) for proof in finding.proofs: project_path = os.path.join('projects', str(finding.project_id)) relative_path = os.path.join( str(finding.id), str(proof.id) + os.path.splitext(proof.path)[-1]) absolute_path = os.path.join(project_path, relative_path) if os.path.exists(absolute_path): add_proof(doc, proof, relative_path)
def _subtable(self, idx, subK, octets): """ Generates latex code for a ccsds keys table Args: * idx (int): the index of the current sub-table in case the trousseau needs to be split into several tables * subK (list of keys): the list of keys to generate table on * octets (bool): corresponding to trousseau.octets """ titles = ('Name', 'Start', 'Len', 'Value') table = Tabular('|'.join(['l'] + ['c'] * (len(titles) - 1))) if idx > 0: table.add_row((MultiColumn(len(titles), align='c', data=italic("Continued")), )) table.add_row(titles) unit = "octets" if octets else "bits" table.add_hline() table.add_hline() start_bit = 0 for cle in subK: if not cle.relative_only: start_bit = cle.start # if no padding, allows flexible len of the ccsdskey the_len = cle.len if cle.pad else "[0..{:d}]".format(cle.len) if cle.isdic: if cle.dic_force is not None: the_type = repr(cle.dic[cle.dic_force]) else: the_type = repr(cle.dic.values()) else: the_type = re.search(r'type *= *([\S ]+)', getattr(cle._fctunpack, 'func_doc', '')) if the_type is None: the_type = '-' else: the_type = the_type.group(1) table.add_row((cle.name, start_bit, the_len, the_type)) start_bit += cle.len table.add_row((MultiColumn(len(titles), align='c', data='"Start" and "Len" are given in {}'\ .format(unit)),)) return table
def render_metric(value, best, second, decimals, format_string, highlight_top, relative_to): if isinstance(value, numbers.Number): if relative_to is None or relative_to == 0 or not np.isfinite( relative_to): # absolute number rendered = format_string.format(value, prec=decimals) else: # percent rendered = format_ratio_percent(value, relative_to, decimals=decimals) if highlight_top: if value == best: rendered = bold(rendered) elif value == second: rendered = italic(rendered) return rendered else: return value
def strip_tags(self, string): while '\\' in string: # Find slash, grab the text before the slash (left), find the other locations # that are key - the braces - and grab the key and the emphaszied text, then # send the rest of the rest of the string back through the while loop in case # there are other tags that need to be stripped # TODO: what happens if text is both italicized and underlined? slashLocation = string.find('\\') left = string[:slashLocation] textStart = string.find('{') tag = string[slashLocation + 1:textStart] tagEnd = string.find('}') emphasizedText = string[textStart + 1:tagEnd] # if '\\' in emphasizedText: # so ... with a double tag ... you have to # update where the tagEnd is, put the left stuff in the document # put the first tag in and the first part of the emphasized text in # then the strip the tags from the new emphasized text # and what do you do with the right side ... hmmmm # self.strip_tags(emphasizedText) # Append the text as appropriate self.doc.append(left) if tag == 'underline': self.doc.append(Command('underline', emphasizedText)) elif tag == 'textit': self.doc.append(italic(emphasizedText)) elif tag == 'textbf': self.doc.append(bold(emphasizedText)) else: self.doc.append(emphasizedText) if string[tagEnd + 1:tagEnd + 2] == ' ': # Force a space self.doc.append(bold(' ')) string = string[ tagEnd + 1:] # remove what was added to the doc already from the string # After the while loop is done, if there is any string left, append it (it is not emphasized) self.doc.append(string)
def createDocument(filename, documentResults): doc = Document('full') imageFilename = os.path.join(os.path.dirname(__file__), 'plots/Beni_Anliker.png') with doc.create(Section('Leistungstest Feuerwehr Derendingen 2017', numbering=False)): with doc.create(Subsection('Persönliche Daten', numbering=False)): doc.append('Name ') doc.append('\nAlter ') doc.append('\nGrösse ') doc.append(italic('\nitalic text. ')) with doc.create(Subsection('Aktuelle Testresultate', numbering=False)): doc.append('Standweitsprung: ' + documentResults['slj']) doc.append('\nGesamtpunktzahl Leistungstest: ' + documentResults['totalScore'] + ' von 125 Punkten = ' + documentResults['numberToLabel']) with doc.create(Subsection('Längsschnittvergleich', numbering=False)): with doc.create(Figure(position = 'h!')) as diagram: diagram.add_image(imageFilename, width = '350px') diagram.add_caption('Beurteilung: 1 = Ungenügend, 2 = Genügend, 3 = Gut, 4 = Sehr gut, 5 = Hervorragend') #doc.generate_pdf(clean_tex=False) #doc.generate_tex() print(doc.dumps())
def setup_header_footer(doc, pdf_opts, display_opts): # Header with title, tagline, page number right, date left # Footer with key to denote someting about drinks title = pdf_opts.title or '@Schubar' if display_opts.prices: tagline = 'Tips never required, always appreciated' tagline = pdf_opts.tagline or 'Tips for your drinks never required, always appreciated' else: tagline = 'Get Fubar at Schubar on the good stuff' tagline = pdf_opts.tagline or 'Get Fubar at Schubar, but, like, in a classy way' hf = PageStyle("schubarheaderfooter", header_thickness=0.4, footer_thickness=0.4) with hf.create(Head('L')): hf.append(TitleText(title)) hf.append(Command('\\')) hf.append(FootnoteText(italic(tagline))) with hf.create(Head('R')): hf.append(FootnoteText(time.strftime("%b %d, %Y"))) if display_opts.origin: with hf.create(Foot('L')): hf.append(superscript("*")) #hf.append(superscript(NoEscape("\dag"))) hf.append(FootnoteText(r"Schubar Original")) with hf.create(Foot('C')): if display_opts.prices: hf.append(HorizontalSpace('12pt')) hf.append( FootnoteText( NoEscape( r"\$ amount shown is recommended tip, calculated from cost of ingredients" ))) with hf.create(Foot('R')): hf.append(FootnoteText(Command('thepage'))) doc.preamble.append(hf) doc.change_document_style("schubarheaderfooter")
v = VectorName(name='') M = np.matrix([[2, 3, 4], [0, 0, 1], [0, 0, 2]]) m = Matrix(matrix=M, name='', mtype='p', alignment=None) # Package p = Package(name='', base='usepackage', options=None) # PGFPlots tikz = TikZ(data=None) a = Axis(data=None, options=None) p = Plot(name=None, func=None, coordinates=None, options=None) # Utils escape_latex(s='') fix_filename(filename='') dumps_list(l=[], escape=False, token='\n') bold(s='') italic(s='') verbatim(s='', delimiter='|')
def GeneratePDF(pre1,pre2,pre,read1,read2,read,out,logger): #Function to generate pdf report summary of all the stats logger.info("Generating PDF report of summary data") doc = Document() doc.packages.append(Package('geometry', options=['tmargin=1cm','lmargin=1cm','rmargin=1cm'])) doc.preamble.append(Command('title', 'Combined Summary Report')) doc.append(NoEscape(r'\maketitle')) with doc.create(Section('Pre-Processing Data')): doc.append(italic("This section contains the input read data before processing.")) with doc.create(Subsection('Base Quality Graph')): doc.append(italic("This graph shows an overview of the range of quality values across all bases at each position in the FastQ file.")) if read == 'Na': with doc.create(Figure(position='h!')) as pic: pic.add_image("preFastqcMetrics/"+read1.split('/')[-1].split('.')[0]+"_fastqc/Images/per_base_quality.png", width='160px') pic.add_caption(pre1.split('/')[-1].split('.')[0]) with doc.create(Figure(position='h')) as pic2: pic2.add_image("preFastqcMetrics/"+read2.split('/')[-1].split('.')[0]+"_fastqc/Images/per_base_quality.png", width='160px') pic2.add_caption(pre2.split('/')[-1].split('.')[0]) else: with doc.create(Figure(position='h')) as pic2: pic2.add_image("preFastqcMetrics/"+read.split('/')[-1].split('.')[0]+"_fastqc/Images/per_base_quality.png", width='160px') pic2.add_caption(pre.split('/')[-1].split('.')[0]) with doc.create(Subsection('Per Base Sequence Content Graph')): doc.append(italic("This graph plots out the proportion of each base position in a file for which each of the four normal DNA bases has been called.")) if read == 'Na': with doc.create(Figure(position='h!')) as pic: pic.add_image("preFastqcMetrics/"+read1.split('/')[-1].split('.')[0]+"_fastqc/Images/per_base_sequence_content.png", width='160px') pic.add_caption(pre1.split('/')[-1].split('.')[0]) with doc.create(Figure(position='h')) as pic2: pic2.add_image("preFastqcMetrics/"+read2.split('/')[-1].split('.')[0]+"_fastqc/Images/per_base_sequence_content.png", width='160px') pic2.add_caption(pre2.split('/')[-1].split('.')[0]) else: with doc.create(Figure(position='h')) as pic2: pic2.add_image("preFastqcMetrics/"+read.split('/')[-1].split('.')[0]+"_fastqc/Images/per_base_sequence_content.png", width='160px') pic2.add_caption(pre.split('/')[-1].split('.')[0]) with doc.create(Subsection('Data Summary')): with doc.create(Itemize()) as itemize: if read == 'Na': itemize.add_item(pre1.split('/')[-1].split('.')[0]) with open(out+"/"+read1.split('/')[-1].split('.')[0]+"_preprocess_Summary.txt") as f: for line in f: doc.append(line) itemize.add_item(pre2.split('/')[-1].split('.')[0]) with open(out+"/"+read2.split('/')[-1].split('.')[0]+"_preprocess_Summary.txt") as f: for line in f: doc.append(line) else: itemize.add_item(pre.split('/')[-1].split('.')[0]) with open(out+"/"+read.split('/')[-1].split('.')[0]+"_preprocess_Summary.txt") as f: for line in f: doc.append(line) with doc.create(Section('Post-Processing Data')): doc.append("") with doc.create(Subsection('Base Quality Graph')): doc.append(italic("This graph shows an overview of the range of quality values across all bases at each position in the FastQ file.")) if read == "Na": with doc.create(Figure(position='h!')) as pic3: pic3.add_image("postFastqcMetrics/"+read1.split('/')[-1].split('.')[0]+"_fastqc/Images/per_base_quality.png", width='160px') pic3.add_caption(pre1.split('/')[-1].split('.')[0]) with doc.create(Figure(position='h')) as pic4: pic4.add_image("postFastqcMetrics/"+read2.split('/')[-1].split('.')[0]+"_fastqc/Images/per_base_quality.png", width='160px') pic4.add_caption(pre2.split('/')[-1].split('.')[0]) else: with doc.create(Figure(position='h')) as pic4: pic4.add_image("postFastqcMetrics/"+read.split('/')[-1].split('.')[0]+"_fastqc/Images/per_base_quality.png", width='160px') pic4.add_caption(pre.split('/')[-1].split('.')[0]) with doc.create(Subsection('Per Base Sequence Content Graph')): doc.append(italic("This graph plots out the proportion of each base position in a file for which each of the four normal DNA bases has been called.")) if read == 'Na': with doc.create(Figure(position='h!')) as pic: pic.add_image("postFastqcMetrics/"+read1.split('/')[-1].split('.')[0]+"_fastqc/Images/per_base_sequence_content.png", width='160px') pic.add_caption(pre1.split('/')[-1].split('.')[0]) with doc.create(Figure(position='h')) as pic2: pic2.add_image("postFastqcMetrics/"+read2.split('/')[-1].split('.')[0]+"_fastqc/Images/per_base_sequence_content.png", width='160px') pic2.add_caption(pre2.split('/')[-1].split('.')[0]) else: with doc.create(Figure(position='h')) as pic2: pic2.add_image("postFastqcMetrics/"+read.split('/')[-1].split('.')[0]+"_fastqc/Images/per_base_sequence_content.png", width='160px') pic2.add_caption(pre.split('/')[-1].split('.')[0]) with doc.create(Subsection('Data Summary')): with doc.create(Itemize()) as itemize: if read == 'Na': itemize.add_item(pre1.split('/')[-1].split('.')[0]) with open(out+"/"+read1.split('/')[-1].split('.')[0]+"_postprocess_Summary.txt") as f: for line in f: doc.append(line) itemize.add_item(pre2.split('/')[-1].split('.')[0]) with open(out+"/"+read2.split('/')[-1].split('.')[0]+"_postprocess_Summary.txt") as f: for line in f: doc.append(line) else: itemize.add_item(pre.split('/')[-1].split('.')[0]) with open(out+"/"+read.split('/')[-1].split('.')[0]+"_postprocess_Summary.txt") as f: for line in f: doc.append(line) if os.path.exists(out+"/PostMappingMetrics.txt"): with doc.create(Section('Post Mapping Data')): doc.append("") with doc.create(Subsection('Data Summary')): with open(out+"/PostMappingMetrics.txt") as f: for line in f: doc.append(line) if os.path.exists(out+"/"+out+".qual.heatmap.pdf"): cmd = "sips -s format png "+out+"/"+out+".qual.heatmap.pdf --out "+out+"/"+out+".qual.heatmap.png" os.system(cmd) cmd = "sips -s format png "+out+"/"+out+".DupRate_plot.pdf --out "+out+"/"+out+".Duprate_plot.png" os.system(cmd) with doc.create(Subsection('Visual Summary')): doc.append(italic("This graph shows an overview of the range of quality values across all bases at each position in the alignment file.")) with doc.create(Figure(position='h!')) as pic: pic.add_image(out+".qual.heatmap.png", width='160px') pic.add_caption("Alignment Quality") doc.append(italic("This graph shows read duplication rate.")) with doc.create(Figure(position='h')) as pic2: pic2.add_image(out+".DupRate_plot.png", width='160px') pic2.add_caption("Duplication Rate") with doc.create(Itemize()) as itemize: itemize.add_item(italic("Sequence based: reads with identical sequence are regarded as duplicated reads.")) itemize.add_item(italic("Mapping based: reads mapped to the exactly same genomic location are regarded as duplicated reads.")) else: logger.info("No Post Mapping Data available. The rest of the informtation can be accessed from 'Summary_Report.pdf'") doc.generate_pdf(out+'/Summary_Report', clean=False)
def tabulateAll(self): """ Create a table that summarises all input variables and additive components, including the constant kernel as baseline and the final full additive model. """ # 1-D variables ks = self.best1d[:] # Baseline: constant kernel ks.append(self.constker) # Additive components, if not 1-D for k in self.summands: if len(k.getActiveDims()) > 1: ks.append(k) # Full additive model, if involves more than one additive term best = self.history[-1] if len(self.summands) > 1: ks.append(best) ks.sort(key=lambda k: round(k.getNLML(), 2)) ks.sort(key=lambda k: round(k.error(), 4)) data = ks[0].data ds = data.getDataShape() nlml_min = round(min([k.getNLML() for k in ks]), 2) error_min = round(min([k.error() for k in ks]), 4) doc = self.doc with doc.create(pl.Table(position='htbp!')) as tab: caption_str = "Classification performance of the full model, its additive components (if any), all input variables, and the baseline." tab.add_caption(ut.NoEscape(caption_str)) t = pl.Tabular('rlrr') # Header t.add_hline() t.add_row(( pl.MultiColumn(1, align='c', data='Dimensions'), pl.MultiColumn(1, align='c', data='Kernel expression'), pl.MultiColumn(1, align='c', data='NLML'), pl.MultiColumn(1, align='c', data='Error') )) t.add_hline() # Entries for k in ks: if k is self.constker: row = [ ut.italic('--', escape=False), ut.italic('$' + k.latex() + '$ (Baseline)', escape=False), ut.italic('{0:.2f}'.format(k.getNLML()), escape=False), ut.italic(r'{0:.2f}\%'.format(k.error()*100), escape=False) ] else: dims = sorted(k.getActiveDims()) row = [ ut.NoEscape(', '.join([str(d + 1) for d in dims])), ut.NoEscape('$' + k.latex() + '$'), ut.NoEscape('{0:.2f}'.format(k.getNLML())), ut.NoEscape(r'{0:.2f}\%'.format(k.error()*100)) ] if round(k.getNLML(), 2) == nlml_min: row[2] = ut.bold(row[2]) if round(k.error(), 4) == error_min: row[3] = ut.bold(row[3]) t.add_row(tuple(row)) t.add_hline() tab.append(ut.NoEscape(r'\centering')) tab.append(t)
def tabulateVariables(self): """ Create a table that summarises all input variables. """ ks = self.best1d[:] ks.append(self.constker) ks.sort(key=lambda k: round(k.getNLML(), 2)) ks.sort(key=lambda k: round(k.error(), 4)) data = ks[0].data ds = data.getDataShape() nlml_min = round(min([k.getNLML() for k in ks]), 2) error_min = round(min([k.error() for k in ks]), 4) doc = self.doc with doc.create(pl.Table(position='htbp!')) as tab: tab.add_caption(ut.NoEscape("Input variables")) t = pl.Tabular('rlrrrcrr') # Header t.add_hline() t.add_row(( '', '', pl.MultiColumn(3, align='c', data='Statistics'), pl.MultiColumn(3, align='c', data='Classifier Performance') )) t.add_hline(start=3, end=8) t.add_row(( pl.MultiColumn(1, align='c', data='Dimension'), pl.MultiColumn(1, align='c', data='Variable'), pl.MultiColumn(1, align='c', data='Min'), pl.MultiColumn(1, align='c', data='Max'), pl.MultiColumn(1, align='c', data='Mean'), pl.MultiColumn(1, align='c', data='Kernel'), pl.MultiColumn(1, align='c', data='NLML'), pl.MultiColumn(1, align='c', data='Error') )) t.add_hline() # Entries for k in ks: if k is self.constker: row = [ ut.italic('--', escape=False), ut.italic('Baseline', escape=False), ut.italic('--', escape=False), ut.italic('--', escape=False), ut.italic('--', escape=False), ut.italic(k.shortInterp(), escape=False), ut.italic('{0:.2f}'.format(k.getNLML()), escape=False), ut.italic(r'{0:.2f}\%'.format(k.error()*100), escape=False) ] else: dim = k.getActiveDims()[0] row = [ dim+1, data.XLabel[dim], '{0:.2f}'.format(ds['x_min'][dim]), '{0:.2f}'.format(ds['x_max'][dim]), '{0:.2f}'.format(ds['x_mu'][dim]), k.shortInterp(), ut.NoEscape('{0:.2f}'.format(k.getNLML())), ut.NoEscape(r'{0:.2f}\%'.format(k.error()*100)) ] if round(k.getNLML(), 2) == nlml_min: row[6] = ut.bold(row[6]) if round(k.error(), 4) == error_min: row[7] = ut.bold(row[7]) t.add_row(tuple(row)) t.add_hline() tab.append(ut.NoEscape(r'\centering')) tab.append(t)
from pylatex import Document, Section, Subsection, Tabular, Math, TikZ, Axis, \ Plot, Figure, Package from pylatex.numpy import Matrix from pylatex.utils import italic, escape_latex import os if __name__ == '__main__': image_filename = os.path.join(os.path.dirname(__file__), 'kitten.jpg') doc = Document() doc.packages.append(Package('geometry', options=['tmargin=1cm', 'lmargin=10cm'])) with doc.create(Section('The simple stuff')): doc.append('Some regular text and some ' + italic('italic text. ')) doc.append(escape_latex('\nAlso some crazy characters: $&#{}')) with doc.create(Subsection('Math that is incorrect')): doc.append(Math(data=['2*3', '=', 9])) with doc.create(Subsection('Table of something')): with doc.create(Tabular('rc|cl')) as table: table.add_hline() table.add_row((1, 2, 3, 4)) table.add_hline(1, 2) table.add_empty_row() table.add_row((4, 5, 6, 7)) a = np.array([[100, 10, 20]]).T M = np.matrix([[2, 3, 4], [0, 0, 1],
def main(): parser = argparse.ArgumentParser(prog='rnaseq',description="Program to help run RNA-seq Analysis") required = parser.add_argument_group("Required Options") required.add_argument('-t','--type',dest='type',help="Enter the type of analysis you want to do (F=Fast, S=Slow, N=Novel) [default=F]",choices=['F','S','N'],required=True, default="F") required.add_argument('-f','--folder',dest='folder',help="Enter the location of the folder containing the reads", metavar="\b",default="Na",required=True) required.add_argument('-i','--index',dest='index',help="Enter the location of the index file for the run u choose",default="Na",required=True) parser.add_argument('-g','--gtf',dest='gtf',help="Enter the location of the gtf file", default='Na') parser.add_argument('-m','--ribo',dest='ribo',help="Enter the location of the ribosomal file", default='Na') args = parser.parse_args() logger = logging.getLogger('Main') logger.setLevel(logging.DEBUG) stream = logging.StreamHandler() stream.setLevel(logging.DEBUG) formats = logging.Formatter('[%(asctime)s %(name)s %(levelname)s]: %(message)s') stream.setFormatter(formats) logger.addHandler(stream) if not os.path.exists(args.index): logger.error("The index file is not readable") sys.exit() reads = os.listdir(args.folder) extension = '' #Running the pipeline for read in reads: logger.info("Processing "+read+" ...") out = read.split('/')[-1].split('.')[0] read = args.folder+"/"+read if args.type == "F" and not os.path.exists(out+"_Kallisto"): call(["time","./rnaseq.py","-t","F","-r",read,"--kindex",args.index,"-l","54","-s","10","-o",out+"_Kallisto"]) logger.info("Ouputs written into "+out+"_Kallisto") extension = "_Kallisto" elif args.type == "S" and not os.path.exists(out+"_BWA"): extra = '' if args.ribo != 'Na': extra = "-m "+args.ribo call(["time","./rnaseq.py","-t","S","-r",read,"--bindex",args.index,"-o",out+"_BWA",extra]) logger.info("Ouputs written into "+out+"_BWA") extension = "_BWA" elif args.type == "N" and not os.path.exists(out+"_TopHat"): extra = '' if args.gtf != 'Na': extra = "-g "+args.gtf if args.ribo != 'Na': extra = extra+" -m "+args.ribo call(["time","./rnaseq.py","-t","N","-r",read,"--bowindex",args.index,"-o",out+"_TopHat",extra]) extension = "_TopHat" else: logger.info("Skipping this read as folder already exists...") #Converging Report doc = Document() doc.packages.append(Package('geometry', options=['tmargin=1cm','lmargin=1cm','rmargin=1cm'])) with doc.create(Section('Base Quality Graph')): doc.append(italic("This graph shows an overview of the range of quality values across all bases at each position in the FastQ file.")) extension = "_BWA" for read in reads: logger.info("Converging Pre Graphs Reports "+read+" ...") out = read.split('/')[-1].split('.')[0]+extension with doc.create(Figure(position='h!')) as baseQuality: with doc.create(SubFigure(position='b',width=NoEscape(r'0.45\linewidth'))) as prepic: prepic.add_image(out+"/preFastqcMetrics/triM"+read.split('/')[-1].split('.')[0]+"_fastqc/Images/per_base_quality.png", width='160px') prepic.add_caption("Pre "+read.split('/')[-1].split('.')[0]) with doc.create(SubFigure(position='b',width=NoEscape(r'0.45\linewidth'))) as postpic: postpic.add_image(out+"/postFastqcMetrics/triM"+read.split('/')[-1].split('.')[0]+"_fastqc/Images/per_base_quality.png", width='160px') postpic.add_caption("Post "+read.split('/')[-1].split('.')[0]) with doc.create(Section('Per Base Sequence Content Graph')): doc.append(italic("This graph plots out the proportion of each base position in a file for which each of the four normal DNA bases has been called.")) for read in reads: out = read.split('/')[-1].split('.')[0]+extension with doc.create(Figure(position='h!')) as baseQuality: with doc.create(SubFigure(position='b',width=NoEscape(r'0.45\linewidth'))) as prepic: prepic.add_image(out+"/preFastqcMetrics/triM"+read.split('/')[-1].split('.')[0]+"_fastqc/Images/per_base_sequence_content.png", width='160px') prepic.add_caption("Pre "+read.split('/')[-1].split('.')[0]) with doc.create(SubFigure(position='b',width=NoEscape(r'0.45\linewidth'))) as postpic: postpic.add_image(out+"/postFastqcMetrics/triM"+read.split('/')[-1].split('.')[0]+"_fastqc/Images/per_base_sequence_content.png", width='160px') postpic.add_caption("Post "+read.split('/')[-1].split('.')[0]) with doc.create(Section('Data Summary')): doc.append(italic("This section contains post trimming FastQC summary results.")) for read in reads: out = read.split('/')[-1].split('.')[0]+extension with doc.create(Subsection(read)): doc.append("") with open(out+"/triM"+read.split('/')[-1].split('.')[0]+"_postprocess_Summary.txt") as f: for line in f: doc.append(line) if os.path.exists(out+"/PostMappingMetrics.txt"): with doc.create(Section('Post Mapping Data')): doc.append("") for read in reads: out = read.split('/')[-1].split('.')[0]+extension with doc.create(Subsection(read)): with open(out+"/PostMappingMetrics.txt") as f: for line in f: doc.append(line) if os.path.exists(out+"/"+out+".qual.heatmap.pdf"): cmd = "sips -s format png "+out+"/"+out+".qual.heatmap.pdf --out "+out+"/"+out+".qual.heatmap.png" os.system(cmd) cmd = "sips -s format png "+out+"/"+out+".DupRate_plot.pdf --out "+out+"/"+out+".Duprate_plot.png" os.system(cmd) with doc.create(Section('Post Mapping Visual Data')): doc.append("") for read in reads: out = read.split('/')[-1].split('.')[0]+extension if os.path.exists(out+"/"+out+".qual.heatmap.png"): with doc.create(Figure(position='h!')) as VisualSummary: with doc.create(SubFigure(position='b',width=NoEscape(r'0.45\linewidth'))) as pic: pic.add_image(out+"/"+out+".qual.heatmap.png", width='160px') pic.add_caption("Alignment Quality") with doc.create(SubFigure(position='b',width=NoEscape(r'0.45\linewidth'))) as pic2: pic2.add_image(out+"/"+out+".DupRate_plot.png", width='160px') pic2.add_caption("Duplication Rate") VisualSummary.add_caption(read) doc.generate_pdf('Summary_Report', clean=False)
#!/usr/bin/python3 import numpy as np from pylatex import Document, Section, Subsection, Table, Math from pylatex.numpy import Matrix from pylatex.utils import italic doc = Document() section = Section('Yaay the first section, it can even be ' + italic('italic')) section.append('Some regular text') math = Subsection('Math', data=[Math(data=['2*3', '=', 6])]) section.append(math) table = Table('rc|cl') table.add_hline() table.add_row((1, 2, 3, 4)) table.add_hline(1, 2) table.add_empty_row() table.add_row((4, 5, 6, 7)) table = Subsection('Table of something', data=[table]) section.append(table) a = np.array([[100, 10, 20]]).T M = np.matrix([[2, 3, 4], [0, 0, 1], [0, 0, 2]])
from pylatex import Document, Section, Subsection, Tabular, Math, TikZ, Axis, \ Plot, Figure, Package, Matrix from pylatex.utils import italic import os if __name__ == '__main__': image_filename = os.path.join(os.path.dirname(__file__), 'kitten.jpg') doc = Document() doc.packages.append(Package('geometry', options=['tmargin=1cm', 'lmargin=10cm'])) with doc.create(Section('The simple stuff')): doc.append('Some regular text and some') doc.append(italic('italic text. ')) doc.append('\nAlso some crazy characters: $&#{}') with doc.create(Subsection('Math that is incorrect')): doc.append(Math(data=['2*3', '=', 9])) with doc.create(Subsection('Table of something')): with doc.create(Tabular('rc|cl')) as table: table.add_hline() table.add_row((1, 2, 3, 4)) table.add_hline(1, 2) table.add_empty_row() table.add_row((4, 5, 6, 7)) a = np.array([[100, 10, 20]]).T M = np.matrix([[2, 3, 4], [0, 0, 1],
#!/usr/bin/python import numpy as np from pylatex import Document, Section, Subsection, Table, Math, TikZ, Axis, \ Plot from pylatex.numpy import Matrix from pylatex.utils import italic doc = Document(filename='example_add') section = doc.add(Section('Yaay the first section, it can even be ' + italic('italic'))) section.append('Some regular text') section.add(Subsection('Math that is incorrect', data=[Math(data=['2*3', '=', 9])])) table = Table('rc|cl') table.add_hline() table.add_row((1, 2, 3, 4)) table.add_hline(1, 2) table.add_empty_row() table.add_row((4, 5, 6, 7)) section.add(Subsection('Table of something', data=[table])) a = np.array([[100, 10, 20]]).T M = np.matrix([[2, 3, 4], [0, 0, 1], [0, 0, 2]]) math = Math(data=[Matrix(M), Matrix(a), '=', Matrix(M*a)]) section.add(Subsection('Matrix equation', data=[math]))