/
html.py
288 lines (239 loc) · 8.12 KB
/
html.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
"""
Routines for converting python objects to HTML. Parallel rountines as
latex.py has for latex conversion.
"""
from __future__ import division, print_function, absolute_import, unicode_literals
#*****************************************************************
# pyGSTi 0.9: Copyright 2015 Sandia Corporation
# This Software is released under the GPL license detailed
# in the file "license.txt" in the top-level pyGSTi directory
#*****************************************************************
import numpy as _np
import cmath
from ..tools import compattools as _compat
'''
table() and cell() functions are used by table.py in table creation
everything else is used in creating formatters in formatters.py
'''
def table(customHeadings, colHeadingsFormatted, rows, spec):
'''
Create an HTML table
Parameters
----------
customHeadings : None, dict
optional dictionary of custom table headings
colHeadingsFormatted : 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 keys 'html' and 'js', which correspond to a html and js strings representing the table
'''
tableclass = spec['tableclass']
tableID = spec['tableID']
html = ""
js = ""
if customHeadings is not None \
and "html" in customHeadings:
html += customHeadings['html'] % {'tableclass': tableclass,
'tableid': tableID}
else:
html += "<table"
if tableclass: html += ' class="%s"' % tableclass
if tableID: html += ' id="%s"' % tableID
html += "><thead><tr><th> %s </th></tr>" % \
(" </th><th> ".join(colHeadingsFormatted))
html += "</thead><tbody>"
for formatted_rowData in rows:
if len(formatted_rowData) > 0:
html += "<tr>"
for formatted_cell in formatted_rowData:
if isinstance(formatted_cell, dict):
#cell contains javascript along with html
js += formatted_cell['js'] + '\n'
formatted_cell = formatted_cell['html']
if formatted_cell is None:
pass #don't add anything -- not even td tags (this
# allows signals *not* to include a cell)
elif formatted_cell.startswith("<td"):
html += formatted_cell #assume format includes td tags
else: html += "<td>" + str(formatted_cell) + "</td>"
html += "</tr>"
html += "</tbody></table>"
return { 'html': html, 'js': js }
def cell(data, label, spec):
'''
Format the cell of an HTML 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
'''
if isinstance(data, dict) or label is None:
return data
return '<span title="{}">{}</span>'.format(label, data)
def list(l, specs):
"""
Convert a list to html.
Parameters
----------
l : list
list to convert into HTML. sub-items pre formatted
specs : dictionary
Dictionary of user-specified and default parameters to formatting
Returns
-------
string
html string for l.
"""
return "<br>".join(l)
def vector(v, specs):
"""
Convert a 1D numpy array to html.
Parameters
----------
v : numpy array
1D array to convert into HTML.
specs : dictionary
Dictionary of user-specified and default parameters to formatting
Returns
-------
string
html string for v.
"""
lines = [ ]
for el in v:
lines.append( value(el, specs, mathmode=True) )
if specs['brackets']:
return "$ \\begin{pmatrix}\n" + \
" \\\\ \n".join(lines) + "\n \end{pmatrix} $\n"
else:
return "$ \\begin{pmatrix}\n" + \
" \\\\ \n".join(lines) + "\n \end{pmatrix} $\n"
def matrix(m, specs):
"""
Convert a 2D numpy array to html.
Parameters
----------
m : numpy array
2D array to convert into HTML.
specs : dictionary
Dictionary of user-specified and default parameters to formatting
Returns
-------
string
html 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 + "$ \\begin{pmatrix}\n" + \
" \\\\ \n".join(lines) + "\n \end{pmatrix} $\n"
else:
return prefix + "$ \\begin{pmatrix}\n" + \
" \\\\ \n".join(lines) + "\n \end{pmatrix} $\n"
def value(el, specs, mathmode=False):
"""
Convert a floating point or complex value to html.
Parameters
----------
el : float or complex
Value to convert into HTML.
specs : dictionary
Dictionary of user-specified and default parameters to formatting
mathmode : bool, optional
Whether this routine should generate HTML for use within a math-rendered
HTML element (rather than a normal plain-HTML one). So when set to True
output is essentially the same as latex format.
Returns
-------
string
html 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['complexAsPolar']
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: #don't use <sup> in math mode
s = p[0] + "\\times 10^{" + ex + "}"
else:
s = p[0] + "×10<sup>" + ex + "</sup>"
#Strip superfluous endings
if "." in s:
while s.endswith("0"): s = s[:-1]
if s.endswith("."): s = s[:-1]
return s
if _compat.isstr(el):
return el
if type(el) in (int,_np.int64):
return "%d" % el
if el is None or _np.isnan(el): return "--"
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: #don't use <sup> in math mode
s = "%se^{%s\\pi}" % (render(r),ex)
else:
s = "%se<sup>%s π</sup>" % (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 html safe.
Parameters
----------
txt : string
value to escape
specs : dictionary
Dictionary of user-specified and default parameters to formatting
Returns
-------
string
"""
return txt