Debian Codegraph @

pymzml/plot.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2 # encoding: utf-8
3 """
4 Plotting functions for pymzML.
5 The Factory object can hold several plots with several data traces each.
6 The data can be visualized as an interactive plotly plot or be exported as JSON.
7 """
8
9 # Python mzML module - pymzml
10 # Copyright (C) 2010-2019 M. Kösters, C. Fufezan
11 # The MIT License (MIT)
12
13 # Permission is hereby granted, free of charge, to any person obtaining a copy
14 # of this software and associated documentation files (the "Software"), to deal
15 # in the Software without restriction, including without limitation the rights
16 # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
17 # copies of the Software, and to permit persons to whom the Software is
18 # furnished to do so, subject to the following conditions:
19
20 # The above copyright notice and this permission notice shall be included in all
21 # copies or substantial portions of the Software.
22
23 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
24 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
25 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
26 # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
27 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
28 # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
29 # SOFTWARE.
30
31 import sys
32 import math
33 import warnings
34
35
36 # Fail gracefully if no plotly installed
37 try:
38 import plotly as plt
39
40 # import plotly.offline as plt
41 import plotly.graph_objs as go
42 from plotly import subplots
43 except ImportError:
44 warnings.warn("Plotly is required for plotting support.", ImportWarning)
45
46
47 from . import spec
48
49
50 class Factory(object):
51 def __init__(self, filename=None):
52 """
53 Interface to visualize m/z or profile data using plotly (https://plot.ly/).
54
55 Arguments:
56 filename (str): Name for the output file. Default = "spectrum_plot.html"
57
58 """
59 self.filename = filename
60 self.plots = []
61 self.titles = []
62 self.lookup = dict()
63 self.y_max = []
64 self.y_min = []
65 self.x_max = []
66 self.x_min = []
67 self.offset = 1
68 self.MS_precisions = []
69 self.function_mapper = {
70 "-__splineOffset__0": self.__return_neg_offset_0,
71 "max_intensity": self.__return_max_y,
72 }
73 self.style_options = {"line.width": 1} # default value
74
75 def __return_max_y(self, i):
76 """ """
77 return self.y_max[i]
78
79 def __return_neg_offset_0(self, i):
80 """ """
81 return 0.0 - (self.y_max[i] * (self.offset * 0.05))
82
83 def new_plot(self, MS_precision="5e-6", title=None):
84 """
85 Add new plot to the plotting Factory.
86 Every plot will be put into the x * 2 grid of one single figure.
87
88 Keyword Arguments:
89 title (str): an optional title that will be printed above the plot
90 MS_precision (float): measuring MS_precision used in handler.
91 Default 5e-6.
92
93 Note:
94 Old function newPlot() is still working. However, the new syntax
95 should be used.
96
97 """
98 self.MS_precisions.append(MS_precision)
99 self.plots.append([])
100 self.titles.append(title)
101 return
102
103 def newPlot(self, MS_precision="5e-6", title=None):
104 """Deprecated since version 1.2."""
105 # Is this ok, pass the Factory.self to Spectrum class???
106 # Id just make deprecation warning a function independent of any class
107 # Also, this just looks wrong
108 spec.Spectrum.deprecation_warning(
109 self, function_name=sys._getframe().f_code.co_name
110 )
111 self.new_plot(MS_precision=MS_precision, title=title)
112
113 def add(
114 self,
115 data,
116 color=(0, 0, 0),
117 style="sticks",
118 mz_range=None,
119 int_range=None,
120 opacity=0.8,
121 dash="solid",
122 name=None,
123 plot_num=-1,
124 title=None,
125 ):
126 """
127 Add data to the graph.
128
129 Arguments:
130 data (list): The data added to the graph. Must be list of tuples with
131 the following format. Note that i can be set to 'max_intensity' for
132 setting the label position to the maximum intensity.
133 * (mz,i) for all styles, except label,
134 * (mz,i, string) for label.hoverinfo, .sticks and .triangle
135 * (mz1, mz2, i, string) for label.linear and .spline
136
137 Keyword Arguments:
138 color (tuple): color encoded in RGB. Default = (0,0,0)
139 style (str): plotting style. Default = "sticks".
140 Currently supported styles are:
141 * 'lines':
142 Datapoints connected by lines
143 * 'points':
144 Datapoints without connection
145 * 'sticks':
146 Vertical line at given m/z (corresponds to centroided peaks)
147 * 'triangle' (MS_precision, micro, tiny, small, medium, big):
148 The top of the triangle corresponds to the given m/z, the width
149 corresponds to he given format, e.g. 'triangle.MS_precision'
150 * 'label.hoverinfo':
151 Label string appears as plotly hover info
152 * 'label.linear' (top, medium or bottom)
153 * 'label.spline' (top, medium or bottom)
154 * 'label.sticks'
155 * 'label.triangle' (small, medium or big)
156 mz_range (list): Boundaries that should be added to the current
157 plot
158 int_range (list): Boundaries that should be added to the current
159 plot
160 opacity (float): opacity of the data points
161 dash (str): type of line ('solid', 'dash', 'longdash', 'dot', 'dashdot', 'longdashdot')
162 name (str): name of data in legend
163 plot_num (int): Add data to plot[plot_num]
164 title (str): an optional title that will be printed above the plot
165
166 Note:
167 The mz_range and int_range in the add() function sets the limits of datapoints
168 added to the plot. This is in contrast to defining a range in the layout, which
169 only defines the area that is depicted (i.e. the zoom) but still adds the datapoints to the plot
170 (can be seen by zooming out).
171
172 """
173 if len(self.plots) == 0:
174 self.new_plot(title=title)
175 if mz_range is None:
176 mz_range = [-float("Inf"), float("Inf")]
177 if int_range is None:
178 int_range = [-float("Inf"), float("Inf")]
179 if len(self.x_max) < len(self.plots):
180 self.x_max.append(mz_range[1])
181 self.x_min.append(mz_range[0])
182 if len(self.y_max) < len(self.plots):
183 self.y_max.append(int_range[1])
184 self.y_min.append(int_range[0])
185
186 # Init variables
187 filling = None
188 mode = "lines"
189 x_values = []
190 y_values = []
191 txt = []
192
193 style = style.split(".")
194 MS_precision = float(self.MS_precisions[plot_num])
195
196 if len(style) == 3:
197 pos = style[2]
198 available_pos = [
199 "MS_precision",
200 "micro",
201 "tiny",
202 "small",
203 "medium",
204 "big",
205 "top",
206 "bottom",
207 ]
208 if pos not in available_pos:
209 raise Exception(
210 "Position must one of the following: {0}".format(available_pos)
211 )
212 else:
213 pos = None
214 if style[0] == "label":
215 mode = "text+lines"
216 if len(data[0]) < 3:
217 raise Exception(
218 """
219 Must have at least (mz, i, annotation) in data
220 when using labels
221 """
222 )
223 if style[1] == "hoverinfo":
224 shape = "linear"
225 mode = None
226 filling = None
227 for data_tuple in data:
228 x_values.append(data_tuple[0])
229 y_values.append(data_tuple[1])
230 txt.append(data_tuple[2])
231
232 elif style[1] == "sticks":
233 shape = "linear"
234 filling = "tozeroy"
235 for x in data:
236 y_pos = x[1]
237 x_values += x[0], x[0], x[0], None
238 y_values += 0.0, y_pos, 0.0, None
239 txt += None, x[2], None, None
240
241 elif style[1] == "triangle":
242 if not pos:
243 pos = "medium"
244 triangle_pos_list = [
245 "MS_precision",
246 "micro",
247 "tiny",
248 "small",
249 "medium",
250 "big",
251 ]
252 if pos not in triangle_pos_list:
253 raise Exception("Position must be in {0}".format(triangle_pos_list))
254
255 shape = "linear"
256 filling = "tozeroy"
257 for x in data:
258 x_max = self.x_max[plot_num]
259 y_max = x[1]
260 y_values += 0.0, y_max, 0.0, None
261 txt += None, x[2], None, None
262
263 if pos == "MS_precision":
264 x_values += (
265 x[0] - (x[0] * MS_precision),
266 x[0],
267 x[0] + (x[0] * MS_precision),
268 None,
269 )
270 continue
271 elif pos == "micro":
272 rel_width = 1 / float(10000)
273 elif pos == "tiny":
274 rel_width = 1 / float(2000)
275 elif pos == "small":
276 rel_width = 1 / float(200)
277 elif pos == "medium":
278 rel_width = 1 / float(100)
279 elif pos == "big":
280 rel_width = 1 / float(50)
281 x_values += (
282 x[0] - (x_max * rel_width),
283 x[0],
284 x[0] + (x_max * rel_width),
285 None,
286 )
287
288 elif style[1] == "spline":
289 mode = "lines+markers+text"
290 shape = "spline"
291 txt = []
292 if not pos:
293 pos = "top"
294 for x in data:
295 if x[2] == "max_intensity":
296 y_max = self.y_max[plot_num]
297 else:
298 y_max = x[1]
299 if pos == "top":
300 y_pos = y_max
301 offset = y_max + (y_max * 0.1)
302
303 elif pos == "medium":
304 print(
305 """'
306 {0}
307 is not working atm for
308 {1}
309 """.format(
310 pos, style
311 )
312 )
313 sys.exit(0)
314 y_pos = x[2] / 2
315 offset = "__splineOffset__"
316
317 elif pos == "bottom":
318 y_pos = 0.0
319 offset = "-__splineOffset__0"
320
321 x_values += x[0], (x[0] + x[1]) / 2, x[1], None
322 y_values += y_pos, str(offset), y_pos, None
323 txt += None, x[3], None, None
324
325 elif style[1] == "linear":
326 shape = "linear"
327 if not pos:
328 pos = "bottom"
329 for x in data:
330 if x[2] == "max_intensity":
331 y_max = self.y_max[plot_num]
332 else:
333 y_max = x[1]
334 if pos == "top":
335 y_pos = y_max
336 offset = y_max + (y_max * 0.1)
337 elif pos == "medium":
338 print(
339 """'
340 {0}
341 is not working atm for
342 {1}
343 """.format(
344 pos, style
345 )
346 )
347 sys.exit(0)
348 y_pos = x[2] / 2
349 offset = "+__splineOffset__"
350 elif pos == "bottom":
351 y_pos = 0.0
352 offset = "-__splineOffset__0"
353
354 x_values += x[0], (x[0] + x[1]) / 2, x[1], None
355 y_values += str(offset), str(offset), str(offset), None
356 txt += None, x[3], None, None
357
358 # elif style[1] == 'lines':
359 # shape = 'linear'
360 # filling = 'tozeroy'
361 # for x in data:
362 # y_pos = 'self.y_max[i]'
363 # x_values += x[0], x[0], x[0], None
364 # y_values += .0, y_pos, .0, None
365 # txt += None, x[2], None, None
366
367 else:
368 raise Exception(
369 """
370 Unknown label type
371 Currently supported are:
372 -> linear
373 -> spline
374 -> sticks
375 -> triangle
376 """
377 )
378
379 elif style[0] in ["sticks", "triangle", "lines", "points"]:
380 x_vals = [
381 mz
382 for mz, i in data
383 if mz_range[0] <= mz <= mz_range[1]
384 and int_range[0] <= i <= int_range[1]
385 ]
386 y_vals = [
387 i
388 for mz, i in data
389 if mz_range[0] <= mz <= mz_range[1]
390 and int_range[0] <= i <= int_range[1]
391 ]
392 y_max = max(y_vals)
393 y_min = min(y_vals)
394 x_max = max(x_vals)
395 x_min = min(x_vals)
396
397 if self.x_max[plot_num] == float("Inf") or self.x_max[plot_num] < x_max:
398 self.x_max[plot_num] = x_max
399 if self.x_min[plot_num] == -float("Inf") or self.x_min[plot_num] > x_min:
400 self.x_min[plot_num] = x_min
401 if self.y_max[plot_num] == float("Inf") or self.y_max[plot_num] < y_max:
402 self.y_max[plot_num] = y_max
403 if self.y_min[plot_num] == -float("Inf") or self.y_min[plot_num] > y_min:
404 self.y_min[plot_num] = y_min
405
406 if style[0] == "sticks":
407 shape = "linear"
408 mode = "lines"
409 filling = "tozeroy"
410 for x in zip(x_vals, y_vals):
411 y_pos = x[1]
412 x_values += x[0], x[0], x[0], None
413 y_values += 0.0, y_pos, 0.0, None
414
415 elif style[0] == "triangle":
416 if len(style) == 2:
417 pos = style[1]
418 else:
419 pos = "medium"
420 triangle_pos_list = [
421 "MS_precision",
422 "micro",
423 "tiny",
424 "small",
425 "medium",
426 "big",
427 ]
428 if pos not in triangle_pos_list:
429 raise Exception("Position must be in {0}".format(triangle_pos_list))
430 shape = "linear"
431 filling = "tozeroy"
432 for x in zip(x_vals, y_vals):
433 x_max = self.x_max[plot_num]
434 y_pos = x[1]
435 y_values += 0.0, y_pos, 0.0, None
436 if pos == "MS_precision":
437 x_values += (
438 x[0] - (x[0] * MS_precision),
439 x[0],
440 x[0] + (x[0] * MS_precision),
441 None,
442 )
443 continue
444 elif pos == "micro":
445 rel_width = 1 / float(10000)
446 elif pos == "tiny":
447 rel_width = 1 / float(2000)
448 elif pos == "small":
449 rel_width = 1 / float(200)
450 elif pos == "medium":
451 rel_width = 1 / float(100)
452 elif pos == "big":
453 rel_width = 1 / float(50)
454 x_values += (
455 x[0] - (x_max * rel_width),
456 x[0],
457 x[0] + (x_max * rel_width),
458 None,
459 )
460
461 elif style[0] == "lines":
462 mode = "lines"
463 shape = "linear"
464 for x in zip(x_vals, y_vals):
465 x_values.append(x[0])
466 y_values.append(x[1])
467
468 elif style[0] == "points":
469 mode = "markers"
470 shape = "linear"
471 x_values = x_vals
472 y_values = y_vals
473
474 else:
475 raise Exception(
476 """
477 Invalid plotting style
478 Currently supported are:
479 -> lines
480 -> points
481 -> sticks
482 -> triangle
483 """
484 )
485
486 trace = go.Scatter(
487 {
488 "x": x_values,
489 "y": y_values,
490 "text": txt,
491 "textfont": {"family": "Helvetica", "size": 10, "color": "#000000"},
492 "textposition": "top center",
493 "visible": True,
494 "marker": {
495 "size": 10,
496 "color": "rgba({0},{1},{2},{3})".format(
497 color[0], color[1], color[2], opacity
498 ),
499 },
500 "mode": mode,
501 "name": name,
502 "line": {
503 "color": "rgba({0},{1},{2},{3})".format(
504 color[0], color[1], color[2], opacity
505 ),
506 "width": self.style_options["line.width"],
507 "shape": shape,
508 "dash": dash,
509 },
510 "fill": filling,
511 "fillcolor": "rgba({0},{1},{2},{3})".format(
512 color[0], color[1], color[2], opacity
513 ),
514 "opacity": opacity,
515 }
516 )
517
518 self.plots[plot_num].append(trace)
519 return trace
520
521 def info(self):
522 """
523 Prints summary about the plotting factory, i.e. how many plots and how
524 many datasets per plot.
525 """
526 print(
527 """
528 Factory holds {0} unique plots
529 """.format(
530 len(self.plots)
531 )
532 )
533 for i, plot in enumerate(self.plots):
534 print("\t\tPlot {0} holds {1} unique datasets".format(i, len(plot)))
535 for j, dataset in enumerate(plot):
536 print(
537 "\t\t\tDataset {0} holds {1} datapoints".format(
538 j, len(dataset["x"])
539 )
540 )
541
542 print()
543 return
544
545 def save(
546 self, filename=None, mz_range=None, int_range=None, layout=None, write_pdf=False
547 ):
548 """
549 Saves all plots and their data points that have been added to the
550 plotFactory.
551
552 Keyword Arguments:
553 filename (str): Name for the output file. Default = "spectrum_plot.html"
554 mz_range (list): m/z range which should be considered [start, end].
555 Default = None
556 int_range (list): intensity range which should be considered [min, max].
557 Default = None
558 layout (dict): dictionary containing layout information in plotly style
559 write_pdf (bool): Set "True" in order to save plots as pdf file (on Unix systems,
560 this requires Orca to be installed)
561
562 Note:
563 mz_range and int_range defined here will be applied to all subplots in
564 the current plot, i.e. ranges defined when adding a subplot will be
565 overwritten. To avoid this, a list of lists can be given in the order
566 corresponding to the subplots.
567 """
568 plot_number = len(self.plots)
569 rows, cols = int(math.ceil(plot_number / float(2))), 2
570 if plot_number % 2 == 0:
571 my_figure = subplots.make_subplots(
572 rows=rows,
573 cols=cols,
574 vertical_spacing=0.6 / rows,
575 subplot_titles=self.titles,
576 )
577 else:
578 specs = [[{}, {}] for x in range(rows - 1)]
579 specs.append([{"colspan": 2}, None])
580 my_figure = subplots.make_subplots(
581 rows=rows,
582 cols=cols,
583 vertical_spacing=0.6 / rows,
584 specs=specs,
585 subplot_titles=self.titles,
586 )
587
588 for i, plot in enumerate(self.plots):
589 print(int(math.floor((i / 2) + 1)), (i % 2) + 1)
590 for j, trace in enumerate(plot):
591 trace["y"] = [
592 self.function_mapper[x](i) if x in self.function_mapper else x
593 for x in trace["y"]
594 ]
595 my_figure.append_trace(trace, int(math.floor((i / 2) + 1)), (i % 2) + 1)
596
597 for i in range(plot_number):
598 xaxis_key = "xaxis{0}".format(i + 1)
599 if mz_range:
600 if mz_range[0] == list or mz_range[0] == tuple:
601 # if list and not list of lists, apply same for all
602 my_figure["layout"][xaxis_key].update(range=mz_range[i])
603 my_figure["layout"][xaxis_key]["autorange"] = False
604 elif mz_range[0] == int or mz_range[0] == float:
605 my_figure["layout"][xaxis_key]["range"] = mz_range
606 my_figure["layout"][xaxis_key]["autorange"] = False
607 yaxis_key = "yaxis{0}".format(i + 1)
608 if int_range:
609 if int_range[0] == list or int_range[0] == tuple:
610 # if list and not list of lists, apply same for all
611 my_figure["layout"][yaxis_key].update(range=int_range[i])
612 my_figure["layout"][yaxis_key]["autorange"] = False
613 elif int_range[0] == int or int_range[0] == float:
614 my_figure["layout"][yaxis_key]["range"] = int_range
615 my_figure["layout"][yaxis_key]["autorange"] = False
616
617 my_figure["layout"][xaxis_key].update(title="m/z ")
618 my_figure["layout"][yaxis_key].update(title="Intensity")
619 my_figure["layout"][xaxis_key].update(
620 titlefont={"color": "#000000", "family": "Helvetica", "size": 18}
621 )
622 my_figure["layout"][yaxis_key].update(
623 titlefont={"color": "#000000", "family": "Helvetica", "size": 18}
624 )
625
626 my_figure["layout"]["legend"].update(font={"size": 10, "color": "#FF0000"})
627 if layout:
628 my_figure["layout"].update(layout)
629 if self.filename is None:
630 _filename = "spectrum_plot.html"
631 else:
632 _filename = self.filename
633
634 if filename is not None:
635 # save fkt name definition overrules original filename
636 _filename = filename
637
638 # plt.plot(my_figure, filename=_filename, auto_open=False)
639 plt.io.write_html(my_figure, _filename)
640 if write_pdf:
641 plt.io.write_image(my_figure, _filename.replace(".html", ".pdf"))
642 return
643
644 def get_data(self):
645 """
646 Return data and layout in JSON format.
647
648 Returns:
649 plots (dict): JSON compatible python dict
650
651 """
652 for i, plot in enumerate(self.plots):
653 for j, trace in enumerate(plot):
654 self.plots[i][j]["y"] = [
655 self.function_mapper[x](i) if x in self.function_mapper else x
656 for x in trace["y"]
657 ]
658 return self.plots
659
660
661 if __name__ == "__main__":
662 print(__doc__)