16 Common base class of all Latex Wrapper objects
21 Constructor, initialize output with empty string
28 Transform object to string, in this case, just returns .the generated latex-code
34 Add latex-code to the output string.
35 This method is usually overriden
in the subclasses
41 Finishes the generation of latex-code.
42 E.g. adds end latex-commands
43 This method is usually overriden
in the subclasses
47 def save(self, filename, compile=False):
49 Saves the latex-code into a file, adds preamble and end of document,
50 and compiles the code
if requested.
51 @param filename latex-code
is stored
in this file, should end on .tex
52 @param compile compile the .tex file using pdflatex into a .pdf file
55 \documentclass[10pt,a4paper]{article}
56 \usepackage[latin1]{inputenc}
57 \usepackage[T1]{fontenc}
67 \usetikzlibrary{shapes.arrows,chains, positioning}
68 \usepackage{booktabs} %professional tables
69 \usepackage[left=2cm,right=2cm,top=2cm,bottom=2cm]{geometry}
70 \usepackage{microtype} %optimises spacing, needs to go after fonts
71 \usepackage{hyperref} %adds links (also in TOC), should be loaded at the very end
72 \usepackage{longtable}
76 \definecolor{gray}{rgb}{0.4,0.4,0.4}
77 \definecolor{darkblue}{rgb}{0.0,0.0,0.6}
78 \definecolor{cyan}{rgb}{0.0,0.6,0.6}
81 basicstyle=\ttfamily\scriptsize,
83 showstringspaces=false,
84 commentstyle=\color{gray}\upshape
87 \lstdefinelanguage{XML}
91 morecomment=[s]{<?}{?>},
92 stringstyle=\color{black},
93 identifierstyle=\color{darkblue},
94 keywordstyle=\color{cyan},
95 morekeywords={xmlns,version,type}% list your attributes here
98 \usepackage[load-configurations=abbreviations]{siunitx}
100 % In newer versions of latex there is a problem
with the calc package
and tikz
101 % http://tex.stackexchange.com/questions/289551/how-to-resolve-conflict-between-versions-of-texlive-
and-pgf
103 % Stuff
for calc compatiability.
104 \let\real=\pgfmath
@calc@real
105 \let\minof=\pgfmath
@calc@minof
106 \let\maxof=\pgfmath
@calc@maxof
107 \let\ratio=\pgfmath
@calc@ratio
108 \let\widthof=\pgfmath
@calc@widthof
109 \let\heightof=\pgfmath
@calc@heightof
110 \let\depthof=\pgfmath
@calc@depthof
111 % No (math) units yet.
112 \
global\pgfmathunitsdeclaredfalse
113 \
global\pgfmathmathunitsdeclaredfalse
114 % Expand expression so any reamining CSs are registers
115 %
or box dimensions (i.e. |\wd|, |\ht|, |\dp|).
116 \edef\pgfmath
@expression{
118 \expandafter\pgfmathparse
@trynumber@loop\pgfmath
@expression\pgfmath
@parse@stop
120 % this here
is the _real_ parser. it
is invoked by
121 % \pgfmathparse
@trynumber@loop if that says
"this is no number"
122 %\pgfmathparse@@\pgfmath
@parse@stop%
128 output += r"\end{document}"
130 with open(filename,
'w')
as f:
133 for i
in range(0, 2):
134 ret = subprocess.call([
'pdflatex',
'-halt-on-error',
'-interaction=nonstopmode', filename])
136 raise RuntimeError(
"pdflatex failed to create FEI summary PDF, please check.")
142 Convinience class implementing += operator, can be used instead of raw LatexObject to collect
143 all the latex code
in your project which should go into a common file.
148 Adds an object to the output
149 @param text string
or object
with implicit string conversion (like LatexObject)
156 Adds an object to the output
157 @param text string
or object
with implicit string conversion (like LatexObject)
165 Used for wrapping conventionel text into latex-code.
166 Has to possibility to handle python-style format-placeholders
171 Calls super-class initialize and adds initial text to
output
172 @param text intial text, usually you want to give a raw string
r"some text"
180 Adds an object to the output, can contain python-placeholders
181 @param text string
or object
with implicit string conversion (like LatexObject)
188 Finish the generation of the string by replacing possible placehholders with the given dictionary
189 @param kwargs dictionary used to replace placeholders
198 Used for wrapping code
in a listing environment
203 Calls super-class initialize and adds initial text to
output
204 @param text intial text, usually you want to give a raw string
r"some text"
208 self.output += r'\lstset{language=' + language +
'}\n'
209 self.
output +=
r'\begin{lstlisting}[breaklines=true]' +
'\n'
213 Adds code to the output
214 @param code which
is wrapped
in the listing environment
221 Finish the generation of the lsiting environment
224 self.output += r'\end{lstlisting}'
230 Defines the colourlist latex-command, which draws a bargraph with relative
231 fractions indicated by colours using tikz.
232 After including this object
in you latex code the command \\bargraph
is available.
233 You should include only one of these objects
in your latex code.
237 colours = ["red",
"green",
"blue",
"orange",
"cyan",
"purple"]
241 Calls super-class init, adds definition of colourlist to latex code.
244 self.output += r"\def\colourlist{{" +
', '.join(f
'"{c}"' for c
in self.
colours) +
r"}}" +
'\n'
246 \tikzset{nodeStyle/.style={text height=\heightof{A},text depth=\depthof{g}, inner sep = 0pt, node distance = -0.15mm}}
247 \newcount\colourindex \colourindex=-1
248 \newcommand{\plotbar}[1]{
249 \begin{tikzpicture}[start chain=going right, nodes = {font=\sffamily}]
250 \global\colourindex=-1
251 \foreach \percent/\name
in {
254 \ifx\percent\empty\
else % If \percent
is empty, do nothing
255 \
global\advance\colourindex by 1
258 self.output += r"""5<\colourindex %back to first colour if we run out
259 \
global\colourindex=0
261 \pgfmathparse{\colourlist[\the\colourindex]} % Get color
from cycle list
262 \edef\color{\pgfmathresult} %
and store
as \color
263 \node[nodeStyle, draw, on chain, fill={\color!40}, minimum width=\percent*1.0, minimum height=12] {\name};
271class Section(LatexObject):
273 Adds a new section to your latex code with some additional commands
274 to force a pagebreak
and add a barrier
for figure objects.
279 Calls super-class init and adds necessary latex commands to
output.
282 self.output += r"\raggedbottom" +
'\n'
283 self.
output +=
r"\pagebreak[0]" +
'\n'
284 self.
output +=
r"\FloatBarrier" +
'\n'
285 self.
output +=
r"\section{" + str(name) +
r"}" +
'\n'
290 Adds a new subsection to your latex code.
295 Calls super-class init and adds necessary latex commands to
output.
298 self.output += r"\subsection{" + str(name) +
r"}" +
'\n'
303 Adds a new subsubsection to your latex code.
308 Calls super-class init and adds necessary latex commands to
output.
311 self.output += r"\subsubsection{" + str(name) +
r"}" +
'\n'
316 Includes a series of image files into your latex code and centers them.
321 Calls super-class init and begins centered environment.
324 self.output += r"\begin{center}" +
'\n'
326 def add(self, filename, width=0.7):
328 Include a image file.
329 @param filename containing the image
330 @param width texwidth argument of includegraphics
332 self.output += r"\includegraphics[width=" + str(width) +
r"\textwidth]"
333 self.
output +=
r"{" + str(filename) +
r"}" +
'\n'
338 Ends centered environment
340 self.output += r"\end{center}" +
'\n'
346 Creates a itemized list in latex.
351 Calls super-class init and begins itemize
356 self.output += r"\begin{itemize}"
361 @param item string
or object
with implicit string conversion used
as item
364 self.output += r"\item " + str(item) +
'\n'
369 Finishes the generation of latex-code.
373 self.
output +=
r"\end{itemize}"
379 Creates a longtable in latex. A longtable can span multiple pages
380 and is automatically wrapped.
383 def __init__(self, columnspecs, caption, format_string, head):
385 Calls super-class init, begins centered environment and longtable environment.
386 Defines caption
and head of the table.
387 @param columnspecs of the longtable, something like:
388 rclp{7cm} 4 columns, right-center-left aligned
and one paragraph column
with a width of 7cm
389 @param caption string
or object
with implicit string conversion used
as caption.
390 @param format_string python-style format-string used to generate a new row out of a given dictionary.
391 @param head of the table
394 self.output += r"\begin{center}" +
'\n'
395 self.
output +=
r"\begin{longtable}{" + str(columnspecs) +
r"}" +
'\n'
396 self.
output +=
r"\caption{" + str(caption) +
r"}\\" +
'\n'
397 self.
output +=
r"\toprule" +
'\n'
398 self.
output += head +
r"\\" +
'\n'
399 self.
output +=
r"\midrule" +
'\n'
403 def add(self, *args, **kwargs):
405 Add a new row to the longtable by generating the row using the format_string given in init
406 and the provided dictionary.
407 @param args positional arguments used to generate the row using the python-style format string.
408 @param kwargs dictionary used to generate the row using the python-style format-string.
415 Adds optional tail of the table, ends longtable and centered environment.
416 @param tail optional tail, like head but at the bottom of the table.
418 self.output += r"\bottomrule" +
'\n'
420 self.
output += str(tail) +
r"\\" +
'\n'
421 self.
output +=
r"\bottomrule" +
'\n'
422 self.
output +=
r"\end{longtable}" +
'\n'
423 self.
output +=
r"\end{center}" +
'\n'
429 Creates a latex title-page and optionally abstract
and table-of-contents.
430 You should include only one of these objects
in your latex code.
433 def __init__(self, title, authors, abstract, add_table_of_contents=True, clearpage=True):
435 Sets author, date, title property, calls maketitle, optionalla adds abstract and table-of-contents.
436 @param title of the latex file.
437 @param authors of the latex file, so the person who write the corresponding python-code
with this framework :-)
438 @param abstract optional abstract placed on the title-page.
439 @param add_table_of_contents bool indicating of table-of-contents should be included.
442 self.output += r"\author{"
443 for author
in authors:
444 self.
output += author +
r"\\"
445 self.
output +=
r"}" +
'\n'
446 self.
output +=
r"\date{\today}" +
'\n'
447 self.
output +=
r"\title{" + title +
r"}" +
'\n'
448 self.
output +=
r"\maketitle" +
'\n'
450 self.
output +=
r"\begin{abstract}" +
'\n'
452 self.
output +=
'\n' +
r'\end{abstract}' +
'\n'
455 self.
output +=
r"\clearpage" +
'\n'
456 if add_table_of_contents:
457 self.
output +=
r"\tableofcontents" +
'\n'
458 self.
output +=
r"\FloatBarrier" +
'\n'
460 self.
output +=
r"\clearpage" +
'\n'
463if __name__ ==
'__main__':
467 o +=
TitlePage(title=
'Automatic Latex Code Example',
468 authors=[
'Thomas Keck'],
469 abstract=
'This is an example for automatic latex code generation in basf2.',
470 add_table_of_contents=
True).
finish()
473 o +=
String(
r"In the following subsection there's:")
477 table =
LongTable(
r"lr",
"A long table",
"{name} & {value:.2f}",
r"Name & Value in $\mathrm{cm}$")
479 table.add(name=
'test' + str(i), value=random.gauss(0.0, 1.0))
482 o +=
SubSection(
"A table with color and tail")
484 o += colour_list.finish()
487 caption=
"A coloured table for " +
488 ', '.join((f
'\\textcolor{{{c}}}{{{m}}}' for c, m
in zip(colour_list.colours[:3],
"RGB"))),
489 format_string=
"{name} & {bargraph} & {r:.2f} & {g:.2f} & {b:.2f}",
490 head=
r"Name & Relative fractions & R - Value & G - Value & B - Value")
493 r = random.uniform(0.1, 0.9)
494 g = random.uniform(0.1, 0.9)
495 b = random.uniform(0.1, 0.9)
496 n = (r + g + b) / 100.0
500 table.add(name=
'test' + str(i), bargraph=
r'\plotbar{{ {:g}/, {:g}/, {:g}/,}}'.format(r / n, g / n, b / n), r=r, g=g, b=b)
501 n = (sr + sg + sb) / 100.0
502 o += table.finish(tail=
r"Total & \plotbar{{ {:g}/, {:g}/, {:g}/,}} & {:g} & {:g} & {:g}".format(sr /
503 n, sg / n, sb / n, sr, sg, sb))
505 o +=
Section(
"Graphic section")
507 images = subprocess.check_output(
"locate .png", shell=
True).split(
'\n')[:-1]
509 image = random.choice(images)
510 graphics.add(image, width=0.49)
511 o += graphics.finish()
513 from B2Tools
import format
514 o +=
Section(
"Format section e.g. " + format.decayDescriptor(
"B+ ==> mu+ nu gamma"))
515 o +=
r"Some important channels in B physics"
517 items.add(format.decayDescriptor(
"B+ ==> mu+ nu gamma"))
518 items.add(format.decayDescriptor(
"B0 ==> J/Psi K_S0"))
519 items.add(format.decayDescriptor(
"B+ ==> tau+ nu"))
522 o +=
r"Use format.variable to add hyphenations to long variable names, so latex can do line breaks "
523 o += format.variable(
"daughterProductOf(extraInfo(SignalProbability))")
524 o +=
r" . Use format.string for stuff that contains special latex characters like " + format.string(
r"_ ^ \ ")
525 o +=
r" . Use format.duration for durations " + format.duration(20000) +
" " + format.duration(0.00010)
528 o.save(
"test.tex", compile=
True)
def __init__(self, title, authors, abstract, add_table_of_contents=True, clearpage=True)