/
latex.py
308 lines (250 loc) · 9.15 KB
/
latex.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
"""
Routines for converting python objects to latex.
Parallel rountines as html.py has for HTML conversion.
"""
#***************************************************************************************************
# Copyright 2015, 2019 National Technology & Engineering Solutions of Sandia, LLC (NTESS).
# Under the terms of Contract DE-NA0003525 with NTESS, the U.S. Government retains certain rights
# in this software.
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
# in compliance with the License. You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0 or in the LICENSE file in the root pyGSTi directory.
#***************************************************************************************************
import cmath
import numpy as _np
'''
table() and cell() functions are used by table.py in table creation
everything else is used in creating formatters in formatters.py
'''
def table(custom_headings, col_headings_formatted, rows, spec):
"""
Create a LaTeX table
Parameters
----------
custom_headings : None, dict
optional dictionary of custom table headings
col_headings_formatted : list
formatted column headings
rows : list of lists of cell-strings
Data in the table, pre-formatted
spec : dict
options for the formatter
Returns
-------
dict : contains key 'latex', which corresponds to a latex string representing the table
"""
longtables = spec['longtables']
table = "longtable" if longtables else "tabular"
if custom_headings is not None \
and "latex" in custom_headings:
latex = custom_headings['latex']
else:
latex = "\\begin{%s}[l]{%s}\n\hline\n" % \
(table, "|c" * len(col_headings_formatted) + "|")
latex += ("%s \\\\ \hline\n"
% (" & ".join(col_headings_formatted)))
for formatted_rowData in rows:
if len(formatted_rowData) > 0:
formatted_rowData_latex = [
(formatted_cell['latex'] if isinstance(formatted_cell, dict)
else formatted_cell) for formatted_cell in formatted_rowData]
latex += " & ".join(formatted_rowData_latex)
#MULTI-ROW support for *data* (non-col-header) rows of table. Currently
# unused (unneeded) - see multirow formatter that is commented out in formatters.py
#multirows = [ ("multirow" in el) for el in formatted_rowData_latex ]
#if any(multirows):
# latex += " \\\\ "
# last = True; lineStart = None; col = 1
# for multi,data in zip(multirows,formatted_rowData_latex):
# if last == True and multi == False:
# lineStart = col #line start
# elif last == False and multi == True:
# latex += "\cline{%d-%d} " % (lineStart,col) #line end
# last=multi
# res = _re.search("multicolumn{([0-9])}",data)
# if res: col += int(res.group(1))
# else: col += 1
# if last == False: #need to end last line
# latex += "\cline{%d-%d} "%(lineStart,col-1)
# latex += "\n"
#else:
latex += " \\\\ \hline\n"
latex += "\end{%s}\n" % table
return {'latex': latex}
def cell(data, label, spec):
"""
Format the cell of a latex table
Parameters
----------
data : string
string representation of cell content
label : string
optional cell label, used for tooltips
spec : dict
options for the formatters
Returns
-------
string
"""
addMathMode = bool(("^" in data or "_" in data) and "$" not in data)
return "$" + data + "$" if addMathMode else data
def list(l, specs):
"""
Convert a python list to latex tabular column.
Parameters
----------
l : list
list to convert into latex. sub-items pre formatted
specs : dictionary
Dictionary of user-specified and default parameters to formatting
Returns
-------
string
latex string for l.
"""
return "\\begin{tabular}{c}\n" + \
" \\\\ \n".join(l) + "\n \end{tabular}\n"
def vector(v, specs):
"""
Convert a 1D numpy array to latex.
Parameters
----------
v : numpy array
1D array to convert into latex.
specs : dictionary
Dictionary of user-specified and default parameters to formatting
Returns
-------
string
latex string for v.
"""
lines = []
for el in v:
lines.append(value(el, specs, mathmode=True))
if specs['brackets']:
return "\\ensuremath{ \\begin{pmatrix}\n" + \
" \\\\ \n".join(lines) + "\n \end{pmatrix} }\n"
else:
return "\\ensuremath{ \\begin{pmatrix}\n" + \
" \\\\ \n".join(lines) + "\n \end{pmatrix} }\n"
def matrix(m, specs):
"""
Convert a 2D numpy array to latex.
Parameters
----------
m : numpy array
2D array to convert into latex.
specs : dictionary
Dictionary of user-specified and default parameters to formatting
Returns
-------
string
latex string for m.
"""
lines = []
prefix = ""
fontsize = specs['fontsize']
if fontsize is not None:
prefix += "\\fontsize{%f}{%f}\selectfont " % (fontsize, fontsize * 1.2)
for r in range(m.shape[0]):
lines.append(" & ".join(
[value(el, specs, mathmode=True) for el in m[r, :]]))
if specs['brackets']:
return prefix + "\\ensuremath{ \\begin{pmatrix}\n" + \
" \\\\ \n".join(lines) + "\n \end{pmatrix} }\n"
else:
return prefix + "\\ensuremath{ \\begin{pmatrix}\n" + \
" \\\\ \n".join(lines) + "\n \end{pmatrix} }\n"
def value(el, specs, mathmode=False):
"""
Convert a floating point or complex value to latex.
Parameters
----------
el : float or complex
Value to convert into latex.
specs : dictionary
Dictionary of user-specified and default parameters to formatting
mathmode : bool, optional
Whether this routine should assume that math-mode is already enabled and
output is free to contain math-mode instructions. When False, whenever
math-mode instructions are needed the output is wrapped in an
'ensuremath' block.
Returns
-------
string
latex string for el.
"""
# ROUND = digits to round values to
TOL = 1e-9 # tolerance for printing zero values
precision = specs['precision']
sciprecision = specs['sciprecision']
polarprecision = specs['polarprecision']
complexAsPolar = specs['complex_as_polar']
def render(x):
"""Render a single float (can be real or imag part)"""
if abs(x) < 5 * 10**(-(precision + 1)):
s = "%.*e" % (sciprecision, x)
elif abs(x) < 1:
s = "%.*f" % (precision, x)
elif abs(x) <= 10**precision:
s = "%.*f" % (precision - int(_np.log10(abs(x))), x) # round to get precision+1 digits when x is > 1
else:
s = "%.*e" % (sciprecision, x)
#Fix scientific notition
p = s.split('e')
if len(p) == 2:
ex = str(int(p[1])) # exponent without extras (e.g. +04 => 4)
if mathmode:
s = p[0] + "\\times 10^{" + ex + "}"
else: # ensure math mode so \times and ^ will work
s = "\\ensuremath{ " + p[0] + "\\times 10^{" + ex + "} }"
#Strip superfluous endings
if "." in s:
while s.endswith("0"): s = s[:-1]
if s.endswith("."): s = s[:-1]
return s
if isinstance(el, str):
return el
if isinstance(el, (int, _np.int64)):
return "%d" % el
try:
if el is None or _np.isnan(el): return "--"
except TypeError: pass # if isnan fails b/c a non-numeric type, just proceed
try:
if abs(el.real) > TOL:
if abs(el.imag) > TOL:
if complexAsPolar:
r, phi = cmath.polar(el)
ex = ("i%.*f" % (polarprecision, phi / _np.pi)) if phi >= 0 \
else ("-i%.*f" % (polarprecision, -phi / _np.pi))
if mathmode:
s = "%se^{%s\\pi}" % (render(r), ex)
else: # ensure math mode so ^ will work
s = "\\ensuremath{ %se^{%s\\pi} }" % (render(r), ex)
else:
s = "%s%s%si" % (render(el.real), '+' if el.imag > 0 else '-', render(abs(el.imag)))
else:
s = "%s" % render(el.real)
else:
if abs(el.imag) > TOL:
s = "%si" % render(el.imag)
else:
s = "0"
except:
s = str(el)
return s
def escaped(txt, specs):
"""
Escape txt so it is latex safe.
Parameters
----------
txt : string
value to escape
specs : dictionary
Dictionary of user-specified and default parameters to formatting
Returns
-------
string
"""
ret = txt.replace("_", "\_")
return ret