Debian Codegraph @

weblogo/logo_formatter.py

raw ◀ ▶
1 Debian patch touch this file
1 """
2 Logo formatting. Each formatter is a function f(data, format) that draws
3 a representation of the logo. The main graphical formatter is eps_formatter. A mapping
4 'formatters' containing all available formatters . Each formatter returns binary data. The eps
5 and data formats can decoded to strings, e.g. eps_as_string = eps_data.decode()
6 """
7
8 import os
9 import shutil
10 from math import log
11 from string import Template
12 from subprocess import PIPE, Popen
13 from typing import Optional
14
•15 import importlib.resources as importlib_resources
16
17 from .color import Color
18 from .logo import LogoData, LogoFormat
19
20 __all__ = [
21 "pdf_formatter",
22 "jpeg_formatter",
23 "svg_formatter",
24 "png_print_formatter",
25 "txt_formatter",
26 "eps_formatter",
27 "formatters",
28 "default_formatter",
29 "GhostscriptAPI",
30 ]
31
32 std_units = {
33 "bits": 1.0 / log(2),
34 "nats": 1.0,
35 "digits": 1.0 / log(10),
36 "kT": 1.0,
37 "kJ/mol": 8.314472 * 298.15 / 1000.0,
38 "kcal/mol": 1.987 * 298.15 / 1000.0,
39 "probability": None,
40 }
41 """Some text"""
42
43
44 def pdf_formatter(logodata: LogoData, logoformat: LogoFormat) -> bytes:
45 """Generate a logo in PDF format."""
46 eps = eps_formatter(logodata, logoformat).decode()
47 gs = GhostscriptAPI()
48 assert logoformat.logo_height is not None
49 assert logoformat.logo_width is not None
50 return gs.convert("pdf", eps, logoformat.logo_width, logoformat.logo_height)
51
52
53 def _bitmap_formatter(logodata: LogoData, logoformat: LogoFormat, device: str) -> bytes:
54 eps = eps_formatter(logodata, logoformat).decode()
55 gs = GhostscriptAPI()
56 return gs.convert(
57 device,
58 eps,
59 logoformat.logo_width,
60 logoformat.logo_height,
61 logoformat.resolution,
62 )
63
64
65 def jpeg_formatter(logodata: LogoData, logoformat: LogoFormat) -> bytes:
66 """Generate a logo in JPEG format."""
67 return _bitmap_formatter(logodata, logoformat, device="jpeg")
68
69
70 def svg_formatter(logodata: LogoData, logoformat: LogoFormat) -> bytes:
71 """Generate a logo in Scalable Vector Graphics (SVG) format.
72 Requires the program 'pdf2svg' be installed.
73 """
74 pdf = pdf_formatter(logodata, logoformat)
75
76 command = shutil.which("pdf2svg")
77 if command is None:
78 raise EnvironmentError(
79 "Scalable Vector Graphics (SVG) format requires the program" "'pdf2svg'."
80 ) # pragma: no cover
81
82 import tempfile
83
84 fpdfi, fname_pdf = tempfile.mkstemp(suffix=".pdf")
85 fsvgi, fname_svg = tempfile.mkstemp(suffix=".svg")
86 try:
87 fpdf2 = open(fname_pdf, "w")
88 fpdf2.buffer.write(pdf)
89 fpdf2.seek(0)
90
91 args = [command, fname_pdf, fname_svg]
92 p = Popen(args)
93 (out, err) = p.communicate()
94
95 fsvg = open(fname_svg)
96 return fsvg.read().encode()
97 finally:
98 os.remove(fname_svg)
99 os.remove(fname_pdf)
100
101
102 # def png_formatter(logodata: LogoData, logoformat: LogoFormat) -> bytes:
103 # """Generate a logo in PNG format."""
104 # return _bitmap_formatter(logodata, logoformat, device="png")
105
106
107 def png_print_formatter(logodata: LogoData, logoformat: LogoFormat) -> bytes:
108 """Generate a logo in PNG format with print quality (600 DPI) resolution."""
109 logoformat.resolution = 600
110 return _bitmap_formatter(logodata, logoformat, device="png")
111
112
113 def txt_formatter(logodata: LogoData, logoformat: LogoFormat) -> bytes:
114 """Create a text representation of the logo data."""
115 return str(logodata).encode()
116
117
118 def csv_formatter(logodata: LogoData, logoformat: LogoFormat) -> bytes:
119 """Create a csv representation of the logo data."""
120 return logodata.csv().encode()
121
122
123 def eps_formatter(logodata: LogoData, logoformat: LogoFormat) -> bytes:
124 """Generate a logo in Encapsulated Postscript (EPS)"""
125 substitutions = {}
126 from_format = [
127 "creation_date",
128 "logo_width",
129 "logo_height",
130 "lines_per_logo",
131 "line_width",
132 "line_height",
133 "line_margin_right",
134 "line_margin_left",
135 "line_margin_bottom",
136 "line_margin_top",
137 "title_height",
138 "xaxis_label_height",
139 "creator_text",
140 "logo_title",
141 "logo_margin",
142 "stroke_width",
143 "tic_length",
144 "stacks_per_line",
145 "stack_margin",
146 "yaxis_label",
147 "yaxis_tic_interval",
148 "yaxis_minor_tic_interval",
149 "xaxis_label",
150 "xaxis_tic_interval",
151 "number_interval",
152 "fineprint",
153 "shrink_fraction",
154 "errorbar_fraction",
155 "errorbar_width_fraction",
156 "errorbar_gray",
157 "small_fontsize",
158 "fontsize",
159 "title_fontsize",
160 "number_fontsize",
161 "text_font",
162 "logo_font",
163 "title_font",
164 "logo_label",
165 "yaxis_scale",
166 "end_type",
167 "debug",
168 "show_title",
169 "show_xaxis",
170 "show_xaxis_label",
171 "show_yaxis",
172 "show_yaxis_label",
173 "show_boxes",
174 "show_errorbars",
175 "show_fineprint",
176 "rotate_numbers",
177 "show_ends",
178 "stack_height",
179 "stack_width",
180 ]
181
182 for sf in from_format:
183 substitutions[sf] = getattr(logoformat, sf)
184
185 substitutions["shrink"] = str(logoformat.show_boxes).lower()
186
187 def format_color(color: Color) -> str: # (no fold)
188 return " ".join(("[", str(color.red), str(color.green), str(color.blue), "]"))
189
190 substitutions["default_color"] = format_color(logoformat.default_color)
191
192 data = []
193
194 # Unit conversion. 'None' for probability units
195 conv_factor = std_units[logoformat.unit_name]
196
197 data.append("StartLine")
198
199 # assert checks for logoformat attributes that are intialized to None
200 assert logoformat.logo_start is not None
201 assert logoformat.first_index is not None
202 assert logoformat.logo_end is not None
203
204 seq_from = logoformat.logo_start - logoformat.first_index
205 seq_to = logoformat.logo_end - logoformat.first_index + 1
206
207 # seq_index : zero based index into sequence data
208 # logo_index : User visible coordinate, first_index based
209 # stack_index : zero based index of visible stacks
210 for seq_index in range(seq_from, seq_to):
211 # logo_index = seq_index + logoformat.first_index
212 stack_index = seq_index - seq_from
213
214 if stack_index != 0 and (stack_index % logoformat.stacks_per_line) == 0:
215 data.append("")
216 data.append("EndLine")
217 data.append("StartLine")
218 data.append("")
219
220 data.append("(%s) StartStack" % logoformat.annotate[seq_index])
221
222 if conv_factor:
223 assert logodata.entropy is not None
224 assert logoformat.unit_name is not None
225
226 stack_height = logodata.entropy[seq_index] * std_units[logoformat.unit_name]
227 else:
228 stack_height = 1.0 # probability # pragma: no cover
229
230 # Sort by frequency. If equal frequency then reverse alphabetic
231 # (So sort reverse alphabetic first, then frequency)
232 # TODO: doublecheck this actual works
233 assert logodata.alphabet is not None
234 assert logodata.counts is not None
235 s = list(zip(logodata.counts[seq_index], logodata.alphabet))
236 s.sort(key=lambda x: x[1])
237 s.reverse()
238 s.sort(key=lambda x: x[0])
239
240 if not logoformat.reverse_stacks:
241 s.reverse() # pragma: no cover
242
243 C = float(sum(logodata.counts[seq_index]))
244 if C > 0.0:
245 fraction_width = 1.0
246
247 assert logoformat.scale_width is not None
248 if logoformat.scale_width:
249 assert logodata.weight is not None
250 fraction_width = float(logodata.weight[seq_index])
251
252 for rank, c in enumerate(s):
253 assert logoformat.color_scheme is not None
254 color = logoformat.color_scheme.symbol_color(seq_index, c[1], rank)
255
256 data.append(
257 " %f %f %s (%s) ShowSymbol"
258 % (
259 fraction_width,
260 c[0] * stack_height / C,
261 format_color(color),
262 c[1],
263 )
264 )
265
266 # Draw error bar on top of logo. Replaced by DrawErrorbarFirst above.
267 if logodata.entropy_interval is not None and conv_factor and C > 0.0:
268 low, high = logodata.entropy_interval[seq_index]
269
270 assert logodata.entropy is not None
271 center = logodata.entropy[seq_index]
272 low *= conv_factor
273 high *= conv_factor
274 center *= conv_factor
275
276 if high > logoformat.yaxis_scale:
277 high = logoformat.yaxis_scale # pragma: no cover
278
279 down = center - low
280 up = high - center
281 data.append(" %f %f DrawErrorbar" % (down, up))
282
283 data.append("EndStack")
284 data.append("")
285
286 data.append("EndLine")
287 substitutions["logo_data"] = "\n".join(data)
288
289 ref = importlib_resources.files("weblogo").joinpath("template.eps")
290 template = ref.read_bytes().decode()
291
292 logo = Template(template).substitute(substitutions)
293
294 return logo.encode()
295
296
297 formatters = {
298 "eps": eps_formatter,
299 "pdf": pdf_formatter,
300 "png": png_print_formatter,
301 "png_print": png_print_formatter,
302 "jpeg": jpeg_formatter,
303 "svg": svg_formatter,
304 "logodata": txt_formatter,
305 "csv": csv_formatter,
306 }
307 """Map between output format names and corresponding logo formatter"""
308
309
310 default_formatter = eps_formatter
311 """The default logo formatter."""
312
313
314 class GhostscriptAPI:
315 """Interface to the command line program Ghostscript ('gs')"""
316
317 formats = ("png", "pdf", "jpeg")
318
319 def __init__(self, path: Optional[os.PathLike] = None) -> None:
320 """
321 Raises:
322 EnvironmentError: If cannot find Ghostscript executable on
323 path
324 """
325 command = shutil.which("gs", path=path)
326 if command is None:
327 command = shutil.which("gswin64c.exe", path=path) # pragma: no cover
328 if command is None:
329 command = shutil.which("gswin32c.exe", path=path) # pragma: no cover
330 if command is None:
331 raise EnvironmentError(
332 "Could not find Ghostscript on path. "
333 "There should be either a gs executable or a gswin32c.exe on "
334 "your system's path"
335 ) # pragma: no cover
336
337 self.command = command
338
339 def version(self) -> bytes:
340 """Returns: The ghostscript version string"""
341
342 args = [self.command, "--version"]
343
344 try:
345 p = Popen(args, stdout=PIPE)
346 (out, err) = p.communicate()
347 except OSError: # pragma: no cover
348 raise RuntimeError(
349 "Cannot communicate with ghostscript."
350 ) # pragma: no cover
351 return out.strip()
352
353 def convert(
354 self,
355 format: str,
356 postscript: str,
357 width: Optional[int],
358 height: Optional[int],
359 resolution: int = 300,
360 ) -> bytes:
361 """Convert a string of postscript into a different graphical format
362
363 Supported formats are 'png', 'pdf', and 'jpeg'.
364
365 Raises:
366 ValueError: For an unrecognized format.
367 """
368 device_map = {"png": "png16m", "pdf": "pdfwrite", "jpeg": "jpeg"}
369
370 try:
371 device = device_map[format]
372 except KeyError: # pragma: no cover
373 raise ValueError("Unsupported format.")
374
375 args = [
376 self.command,
377 "-sDEVICE=%s" % device,
378 "-dPDFSETTINGS=/printer",
379 # "-q", # Quite: Do not dump messages to stdout.
380 "-sstdout=%stderr", # Redirect messages and errors to stderr
381 # fix issue 36, problems with ghostscript 9.10
382 "-dColorConversionStrategy=/LeaveColorUnchanged",
383 "-sOutputFile=-", # Stdout
384 "-dDEVICEWIDTHPOINTS=%s" % str(width),
385 "-dDEVICEHEIGHTPOINTS=%s" % str(height),
386 "-dSAFER", # For added security
387 "-dNOPAUSE",
388 ]
389
390 if device != "pdf":
391 args.append("-r%s" % str(resolution))
392 assert resolution is not None
393
394 if resolution < 300: # Antialias if resolution is Less than 300 DPI
395 args.append("-dGraphicsAlphaBits=4")
396 args.append("-dTextAlphaBits=4")
397 args.append("-dAlignToPixels=0")
398
399 args.append("-") # Read from stdin. Must be last argument.
400
401 error_msg = (
402 "Unrecoverable error : Ghostscript conversion failed "
403 "(Invalid postscript?). %s" % " ".join(args)
404 )
405
406 try:
407 p = Popen(args, stdin=PIPE, stdout=PIPE, stderr=PIPE)
408 (out, err) = p.communicate(postscript.encode())
409 except OSError: # pragma: no cover
410 raise RuntimeError(error_msg) # pragma: no cover
411
412 if p.returncode != 0: # pragma: no cover
413 error_msg += "\nReturn code: %i\n" % p.returncode
414 if err is not None:
415 error_msg += str(err)
416 raise RuntimeError(error_msg)
417
418 return out
419
420
421 # end class Ghostscript