9 Common base class of all Latex Wrapper objects
14 Constructor, initialize output with empty string
21 Transform object to string, in this case, just returns .the generated latex-code
27 Add latex-code to the output string.
28 This method is usually overriden in the subclasses
34 Finishes the generation of latex-code.
35 E.g. adds end latex-commands
36 This method is usually overriden in the subclasses
40 def save(self, filename, compile=False):
42 Saves the latex-code into a file, adds preamble and end of document,
43 and compiles the code if requested.
44 @param filename latex-code is stored in this file, should end on .tex
45 @param compile compile the .tex file using pdflatex into a .pdf file
48 \documentclass[10pt,a4paper]{article}
49 \usepackage[latin1]{inputenc}
50 \usepackage[T1]{fontenc}
60 \usetikzlibrary{shapes.arrows,chains, positioning}
61 \usepackage{booktabs} %professional tables
62 \usepackage[left=2cm,right=2cm,top=2cm,bottom=2cm]{geometry}
63 \usepackage{microtype} %optimises spacing, needs to go after fonts
64 \usepackage{hyperref} %adds links (also in TOC), should be loaded at the very end
65 \usepackage{longtable}
69 \definecolor{gray}{rgb}{0.4,0.4,0.4}
70 \definecolor{darkblue}{rgb}{0.0,0.0,0.6}
71 \definecolor{cyan}{rgb}{0.0,0.6,0.6}
74 basicstyle=\ttfamily\scriptsize,
76 showstringspaces=false,
77 commentstyle=\color{gray}\upshape
80 \lstdefinelanguage{XML}
84 morecomment=[s]{<?}{?>},
85 stringstyle=\color{black},
86 identifierstyle=\color{darkblue},
87 keywordstyle=\color{cyan},
88 morekeywords={xmlns,version,type}% list your attributes here
91 \usepackage[load-configurations=abbreviations]{siunitx}
93 % In newer versions of latex there is a problem with the calc package and tikz
94 % http://tex.stackexchange.com/questions/289551/how-to-resolve-conflict-between-versions-of-texlive-and-pgf
95 \def\pgfmathparse@#1{%
96 % Stuff for calc compatiability.
97 \let\real=\pgfmath@calc@real
98 \let\minof=\pgfmath@calc@minof
99 \let\maxof=\pgfmath@calc@maxof
100 \let\ratio=\pgfmath@calc@ratio
101 \let\widthof=\pgfmath@calc@widthof
102 \let\heightof=\pgfmath@calc@heightof
103 \let\depthof=\pgfmath@calc@depthof
104 % No (math) units yet.
105 \global\pgfmathunitsdeclaredfalse
106 \global\pgfmathmathunitsdeclaredfalse
107 % Expand expression so any reamining CSs are registers
108 % or box dimensions (i.e. |\wd|, |\ht|, |\dp|).
109 \edef\pgfmath@expression{#1}%
111 \expandafter\pgfmathparse@trynumber@loop\pgfmath@expression\pgfmath@parse@stop
113 % this here is the _real_ parser. it is invoked by
114 % \pgfmathparse@trynumber@loop if that says "this is no number"
115 %\pgfmathparse@@\pgfmath@parse@stop%
121 output +=
r"\end{document}"
123 with open(filename,
'w')
as f:
126 for i
in range(0, 2):
127 ret = subprocess.call([
'pdflatex',
'-halt-on-error',
'-interaction=nonstopmode', filename])
129 raise RuntimeError(
"pdflatex failed to create FEI summary PDF, please check.")
135 Convinience class implementing += operator, can be used instead of raw LatexObject to collect
136 all the latex code in your project which should go into a common file.
141 Adds an object to the output
142 @param text string or object with implicit string conversion (like LatexObject)
149 Adds an object to the output
150 @param text string or object with implicit string conversion (like LatexObject)
158 Used for wrapping conventionel text into latex-code.
159 Has to possibility to handle python-style format-placeholders
164 Calls super-class initialize and adds initial text to output
165 @param text intial text, usually you want to give a raw string r"some text"
173 Adds an object to the output, can contain python-placeholders
174 @param text string or object with implicit string conversion (like LatexObject)
181 Finish the generation of the string by replacing possible placehholders with the given dictionary
182 @param kwargs dictionary used to replace placeholders
191 Used for wrapping code in a listing environment
196 Calls super-class initialize and adds initial text to output
197 @param text intial text, usually you want to give a raw string r"some text"
201 self.
output +=
r'\lstset{language=' + language +
'}\n'
202 self.
output +=
r'\begin{lstlisting}[breaklines=true]' +
'\n'
206 Adds code to the output
207 @param code which is wrapped in the listing environment
214 Finish the generation of the lsiting environment
217 self.
output +=
r'\end{lstlisting}'
223 Defines the colourlist latex-command, which draws a bargraph with relative
224 fractions indicated by colours using tikz.
225 After including this object in you latex code the command \\bargraph is available.
226 You should include only one of these objects in your latex code.
230 colours = [
"red",
"green",
"blue",
"orange",
"cyan",
"purple"]
234 Calls super-class init, adds definition of colourlist to latex code.
236 super(DefineColourList, self).
__init__()
237 self.
output +=
r"\def\colourlist{{" +
', '.join(
'"%s"' % (c)
for c
in self.
colours) +
r"}}" +
'\n'
239 \tikzset{nodeStyle/.style={text height=\heightof{A},text depth=\depthof{g}, inner sep = 0pt, node distance = -0.15mm}}
240 \newcount\colourindex \colourindex=-1
241 \newcommand{\plotbar}[1]{
242 \begin{tikzpicture}[start chain=going right, nodes = {font=\sffamily}]
243 \global\colourindex=-1
244 \foreach \percent/\name in {
247 \ifx\percent\empty\else % If \percent is empty, do nothing
248 \global\advance\colourindex by 1
251 self.
output +=
r"""5<\colourindex %back to first colour if we run out
252 \global\colourindex=0
254 \pgfmathparse{\colourlist[\the\colourindex]} % Get color from cycle list
255 \edef\color{\pgfmathresult} % and store as \color
256 \node[nodeStyle, draw, on chain, fill={\color!40}, minimum width=\percent*1.0, minimum height=12] {\name};
266 Adds a new section to your latex code with some additional commands
267 to force a pagebreak and add a barrier for figure objects.
272 Calls super-class init and adds necessary latex commands to output.
275 self.
output +=
r"\raggedbottom" +
'\n'
276 self.
output +=
r"\pagebreak[0]" +
'\n'
277 self.
output +=
r"\FloatBarrier" +
'\n'
278 self.
output +=
r"\section{" + str(name) +
r"}" +
'\n'
283 Adds a new subsection to your latex code.
288 Calls super-class init and adds necessary latex commands to output.
291 self.
output +=
r"\subsection{" + str(name) +
r"}" +
'\n'
296 Adds a new subsubsection to your latex code.
301 Calls super-class init and adds necessary latex commands to output.
303 super(SubSubSection, self).
__init__()
304 self.
output +=
r"\subsubsection{" + str(name) +
r"}" +
'\n'
309 Includes a series of image files into your latex code and centers them.
314 Calls super-class init and begins centered environment.
317 self.
output +=
r"\begin{center}" +
'\n'
319 def add(self, filename, width=0.7):
321 Include a image file.
322 @param filename containing the image
323 @param width texwidth argument of includegraphics
325 self.
output +=
r"\includegraphics[width=" + str(width) +
r"\textwidth]"
326 self.
output +=
r"{" + str(filename) +
r"}" +
'\n'
331 Ends centered environment
333 self.
output +=
r"\end{center}" +
'\n'
339 Creates a itemized list in latex.
344 Calls super-class init and begins itemize
349 self.
output +=
r"\begin{itemize}"
354 @param item string or object with implicit string conversion used as item
357 self.
output +=
r"\item " + str(item) +
'\n'
362 Finishes the generation of latex-code.
366 self.
output +=
r"\end{itemize}"
372 Creates a longtable in latex. A longtable can span multiple pages
373 and is automatically wrapped.
376 def __init__(self, columnspecs, caption, format_string, head):
378 Calls super-class init, begins centered environment and longtable environment.
379 Defines caption and head of the table.
380 @param columnspecs of the longtable, something like:
381 rclp{7cm} 4 columns, right-center-left aligned and one paragraph column with a width of 7cm
382 @param caption string or object with implicit string conversion used as caption.
383 @param format_string python-style format-string used to generate a new row out of a given dictionary.
384 @param head of the table
387 self.
output +=
r"\begin{center}" +
'\n'
388 self.
output +=
r"\begin{longtable}{" + str(columnspecs) +
r"}" +
'\n'
389 self.
output +=
r"\caption{" + str(caption) +
r"}\\" +
'\n'
390 self.
output +=
r"\toprule" +
'\n'
391 self.
output += head +
r"\\" +
'\n'
392 self.
output +=
r"\midrule" +
'\n'
396 def add(self, *args, **kwargs):
398 Add a new row to the longtable by generating the row using the format_string given in init
399 and the provided dictionary.
400 @param args positional arguments used to generate the row using the python-style format string.
401 @param kwargs dictionary used to generate the row using the python-style format-string.
408 Adds optional tail of the table, ends longtable and centered environment.
409 @param tail optional tail, like head but at the bottom of the table.
411 self.
output +=
r"\bottomrule" +
'\n'
413 self.
output += str(tail) +
r"\\" +
'\n'
414 self.
output +=
r"\bottomrule" +
'\n'
415 self.
output +=
r"\end{longtable}" +
'\n'
416 self.
output +=
r"\end{center}" +
'\n'
422 Creates a latex title-page and optionally abstract and table-of-contents.
423 You should include only one of these objects in your latex code.
426 def __init__(self, title, authors, abstract, add_table_of_contents=True, clearpage=True):
428 Sets author, date, title property, calls maketitle, optionalla adds abstract and table-of-contents.
429 @param title of the latex file.
430 @param authors of the latex file, so the person who write the corresponding python-code with this framework :-)
431 @param abstract optional abstract placed on the title-page.
432 @param add_table_of_contents bool indicating of table-of-contents should be included.
435 self.
output +=
r"\author{"
436 for author
in authors:
437 self.
output += author +
r"\\"
438 self.
output +=
r"}" +
'\n'
439 self.
output +=
r"\date{\today}" +
'\n'
440 self.
output +=
r"\title{" + title +
r"}" +
'\n'
441 self.
output +=
r"\maketitle" +
'\n'
443 self.
output +=
r"\begin{abstract}" +
'\n'
445 self.
output +=
'\n' +
r'\end{abstract}' +
'\n'
448 self.
output +=
r"\clearpage" +
'\n'
449 if add_table_of_contents:
450 self.
output +=
r"\tableofcontents" +
'\n'
451 self.
output +=
r"\FloatBarrier" +
'\n'
453 self.
output +=
r"\clearpage" +
'\n'
456 if __name__ ==
'__main__':
461 o +=
TitlePage(title=
'Automatic Latex Code Example',
462 authors=[
'Thomas Keck'],
463 abstract=
'This is an example for automatic latex code generation in basf2.',
464 add_table_of_contents=
True).
finish()
467 o +=
String(
r"In the following subsection there's:")
471 table =
LongTable(
r"lr",
"A long table",
"{name} & {value:.2f}",
r"Name & Value in $\mathrm{cm}$")
473 table.add(name=
'test' + str(i), value=random.gauss(0.0, 1.0))
476 o +=
SubSection(
"A table with color and tail")
478 o += colour_list.finish()
481 caption=
"A coloured table for " +
482 ', '.join((
'\\textcolor{%s}{%s}' % (c, m)
for c, m
in zip(colour_list.colours[:3],
"RGB"))),
483 format_string=
"{name} & {bargraph} & {r:.2f} & {g:.2f} & {b:.2f}",
484 head=
r"Name & Relative fractions & R - Value & G - Value & B - Value")
487 r = random.uniform(0.1, 0.9)
488 g = random.uniform(0.1, 0.9)
489 b = random.uniform(0.1, 0.9)
490 n = (r + g + b) / 100.0
494 table.add(name=
'test' + str(i), bargraph=
r'\plotbar{ %g/, %g/, %g/,}' % (r / n, g / n, b / n), r=r, g=g, b=b)
495 n = (sr + sg + sb) / 100.0
496 o += table.finish(tail=
r"Total & \plotbar{ %g/, %g/, %g/,} & %g & %g & %g" % (sr / n, sg / n, sb / n, sr, sg, sb))
498 o +=
Section(
"Graphic section")
500 images = subprocess.check_output(
"locate .png", shell=
True).split(
'\n')[:-1]
502 image = random.choice(images)
503 graphics.add(image, width=0.49)
504 o += graphics.finish()
507 o +=
Section(
"Format section e.g. " + format.decayDescriptor(
"B+ ==> mu+ nu gamma"))
508 o +=
r"Some important channels in B physics"
510 items.add(format.decayDescriptor(
"B+ ==> mu+ nu gamma"))
511 items.add(format.decayDescriptor(
"B0 ==> J/Psi K_S0"))
512 items.add(format.decayDescriptor(
"B+ ==> tau+ nu"))
515 o +=
r"Use format.variable to add hyphenations to long variable names, so latex can do line breaks "
516 o += format.variable(
"daughterProductOf(extraInfo(SignalProbability))")
517 o +=
r" . Use format.string for stuff that contains special latex characters like " + format.string(
r"_ ^ \ ")
518 o +=
r" . Use format.duration for durations " + format.duration(20000) +
" " + format.duration(0.00010)
521 o.save(
"test.tex", compile=
True)