# -*- coding: utf-8 -*-
# encoding: utf-8
"""
Plotting functions for pymzML.
The Factory object can hold several plots with several data traces each.
The data can be visualized as an interactive plotly plot or be exported as JSON.
"""
# pymzml
#
# Copyright (C) 2010-2016 M. Kösters, C. Fufezan, S. Schulze
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from __future__ import print_function
import sys
import math
import plotly.offline as plt
import plotly.graph_objs as go
from plotly import tools
[docs]class Factory(object):
[docs] def __init__(self, filename=None):
"""
Interface to visualize mz or profile data using plotly.
Args:
filename (str): Name for the output file. Default = "spectrum_plot.html"
"""
self.filename = filename
self.plots = []
self.titles = []
self.lookup = dict()
self.y_max = []
self.x_max = []
self.offset = 1
self.precisions = []
self.function_mapper = {
'-__splineOffset__0': self.__return_neg_offset_0,
'self.y_max[i]': self.__return_max_y,
'self.yMax[i]': self.__return_max_y
}
def __return_max_y(self, i):
"""
"""
return self.y_max[i]
def __return_neg_offset_0(self, i):
"""
"""
return .0 - (self.y_max[i] * (self.offset * 0.05))
[docs] def new_plot(
self,
precision='5e-6',
title=None
):
"""
Add new plot to the plotting Factory.
Every plot will be put into the x * 2 grid of one single figure.
Args:
title (str): an optional title that will be printed above the plot
precision (float): measuring precision used in handler.
Default 5e-6.
"""
self.precisions.append(precision)
self.plots.append([])
# Initialize current y_max and x_max with 0, see line 249
self.y_max.append(0)
self.x_max.append(0)
self.titles.append(title)
return
[docs] def add(
self,
data,
color = (0, 0, 0),
style = 'sticks',
mz_range = None,
opacity = 0.8,
dash = 'solid',
name = None,
plot_num = -1,
title = None
):
"""
Add data to the graph.
Arguments:
data (list): The data added to the graph. Must be list of
tuples, like (mz,i) or (mz1, mz2, i, string)
color (tuple): color encoded in RGB. Default = (0,0,0)
style (str): plotting style. Default = "sticks".\n
Currently supported styles are:\n
* 'sticks'\n
* 'triangle' (small, medium or big)\n
* 'lines'\n
* 'points'\n
* 'label.sticks'\n
* 'label.triangle' (small, medium or big)\n
* 'label.spline' (top, medium or bottom)\n
* 'label.linear' (top, medium or bottom)\n
* 'label.lines' (top, medium or bottom)\n
mz_range (tuple): Boundaries that should be added to the current
plot
opacity (float): opacity of the data points\n
dash (str): type of line ('solid', 'dash', 'longdash', 'dot', 'dashdot', 'longdashdot')\n
name (str): name of data in legend\n
plot_num (int): Add data to plot[plot_num]\n
title (str): an optional title that will be printed above the plot\n
Example:
>>> import pymzml, get_example_file
>>> mzMLFile = 'profile-mass-spectrum.mzml'
>>> example_file = get_example_file.open_example(mzMLFile)
>>> run = pymzml.run.Run("../mzML_example_files/"+mzMLFile,
... precisionMSn = 250e-6
... )
>>> p = pymzml.plot.Factory()
>>> for spec in run:
>>> p.new_plot()
>>> p.add(spec.peaks, color=(200,00,00), style='sticks')
>>> p.add(spec.centroided_peaks, color=(00,00,00), style='sticks')
>>> p.add(spec.reprofiled_peaks, color=(00,255,00), style='sticks')
>>> # add annotation 'My Annotation' at mz 100
>>> p.add([100, None, None, 'My Annotation'], style='label.triangle')
>>> p.save(
... filename="output/plotAspect.xhtml",
... mz_range = (50.2,745.6)
... )
"""
if mz_range is None:
mz_range = [-float('Inf'), float('Inf')]
if len(self.plots) == 0:
self.new_plot(title=title)
# Init variables
filling = None
mode = 'lines'
x_values = []
y_values = []
txt = []
style = style.split('.')
ms_precision = float(self.precisions[plot_num])
if len(style) == 3:
pos = style[2]
if pos not in ['small', 'medium', 'big', 'top', 'bottom']:
raise Exception('Position must be small, medium, big, top or bottom')
else:
pos = None
if style[0] == 'label':
mode = 'text + lines'
if len(data[0]) < 3:
raise Exception(
'Must have at least (mz, i, annotation) in data'
' when using labels'
)
if style[1] == 'sticks':
shape = 'linear'
filling = 'tozeroy'
for x in data:
y_pos = 'self.y_max[i]'
# NOTE self.y_max[plot_num] = __Y__
# FIXME: not - but x[0]-(x[0]*ms_prec)
x_values += x[0] - (x[0] * ms_precision), x[0], x[0] + \
(x[0] * ms_precision), None
y_values += .0, y_pos, .0, None
txt += None, x[2], None, None
elif style[1] == 'triangle':
shape = 'linear'
filling = 'tozeroy'
if not pos:
pos = 'medium'
rel_width = 1 / float(100)
for x in data:
if pos == 'small':
y_pos = 'self.y_max[i]'
rel_width = 1 / float(2000)
elif pos == 'medium':
y_pos = 'self.y_max[i]'
rel_width = 1 / float(100)
elif pos == 'big':
y_pos = 'self.y_max[i]'
rel_width = 1 / float(50)
y_max = 'self.y_max[i]' # NOTE self.y_max[plot_num] = __Y__
x_max = self.x_max[plot_num]
x_values += x[0] - \
(x_max * rel_width), x[0], x[0] + (x_max * rel_width), None
y_values += .0, y_max, .0, None
txt += None, x[2], None, None
pass
elif style[1] == 'spline':
mode='lines+markers+text'
shape = 'spline'
txt = []
if not pos:
pos = 'top'
for x in data:
y_max = self.y_max[plot_num] # NOTE self.y_max[plot_num] = __Y__
if pos == 'top':
y_pos = y_max
offset = y_max + (y_max * 0.1)
elif pos == 'medium':
print(''''
{1}
is not working atm for
{2}
'''.format(
pos,
style
)
)
sys.exit(0)
y_pos = x[2] / 2
offset = '__splineOffset__'
elif pos == 'bottom':
y_pos = .0
offset = '-__splineOffset__0'
x_values += x[0], (x[0] + x[1]) / 2, x[1], None
y_values += y_pos, str(offset), y_pos, None
txt += None, x[2], None, None
elif style[1] == 'linear':
shape = 'linear'
if not pos:
pos = 'bottom'
for x in data:
y_max = 'self.y_max[i]'
# NOTE self.y_max[plot_num] = __Y__
if pos == 'top':
y_pos = y_max
offset = '+__splineOffset1__'
elif pos == 'medium':
print(''''
{1}
is not working atm for
{2}
'''.format(
pos,
style
)
)
sys.exit(0)
y_pos = x[2] / 2
offset = '+__splineOffset__'
elif pos == 'bottom':
y_pos = .0
offset = '-__splineOffset__0'
x_values += x[0], (x[0] + x[1]) / 2, x[1], None
y_values += str(offset), str(offset), str(offset), None
txt += None, x[2], None, None
elif style[1] == 'lines':
shape = 'linear'
filling = 'tozeroy'
for x in data:
y_pos = 'self.yMax[i]'
x_values += x[0], x[0], x[0], None
y_values += .0, y_pos, .0, None
txt += None, x[3], None, None
else:
raise Exception(
'{0}\n{1}\n\t{2}\n\t{3}\n\t{4}\n\t{5}'.format(
'Unknown label type',
'Currently supported are:',
' -> sticks',
' -> triangle',
' -> spline',
' -> linear',
' -> lines'
)
)
elif style[0] in ['sticks', 'triangle', 'lines', 'points']:
x_vals = [mz for mz, i in data if mz_range[0] <= mz <= mz_range[1]]
y_vals = [i for mz, i in data if mz_range[0] <= mz <= mz_range[1]]
y_max = max(y_vals)
x_max = max(x_vals)
if self.x_max[plot_num] < x_max:
self.x_max[plot_num] = x_max
if self.y_max[plot_num] < y_max:
# NOTE self.y_max[plot_num] = __Y__
self.y_max[plot_num] = y_max
# NOTE self.y_max[plot_num] = __Y__
if style[0] == 'sticks':
shape = 'linear'
mode = 'lines'
filling = 'tozeroy'
for x in zip(x_vals, y_vals):
y_pos = x[1]
x_values += x[0] - \
(ms_precision), x[0], x[0] + (ms_precision), None
y_values += .0, y_pos, .0, None
elif style[0] == 'triangle':
if len(style) == 2:
pos = style[1]
else:
pos = 'medium'
if pos not in ['micro', 'tiny', 'small', 'medium', 'big']:
raise Exception('Position must be tiny, small, medium or big')
shape = 'linear'
filling = 'tozeroy'
for x in zip(x_vals, y_vals):
if pos =='micro':
rel_width = 1 / float(10000)
if pos =='tiny':
rel_width = 1 / float(2000)
elif pos == 'small':
rel_width = 1 / float(200)
elif pos == 'medium':
rel_width = 1 / float(100)
elif pos == 'big':
rel_width = 1 / float(50)
y_pos = x[1]
x_values += x[0] - \
(x_max * rel_width), x[0], x[0] + (x_max * rel_width), None
y_values += .0, y_pos, .0, None
elif style[0] == 'lines':
mode = 'lines'
shape = 'linear'
for x in zip(x_vals, y_vals):
x_values.append( x[0] )
y_values.append( x[1] )
elif style[0] == 'points':
mode = 'markers'
shape = ' linear'
x_values = x_vals
y_values = y_vals
else:
raise Exception('Invalid plotting style')
trace = go.Scatter({
'x': x_values,
'y': y_values,
'text': txt,
'textfont': {
'family': 'Helvetica',
'size': 10,
'color': '#000000'
},
'textposition': 'top center',
'visible': 'True',
'marker': {
'size' : 10,
'color' : 'rgba'+str((color[0], color[1], color[2], opacity)),
},
'mode': mode,
'name': name,
'line': {
'color': 'rgba'+str((color[0], color[1], color[2], opacity)),
'width': 1,
'shape': shape,
'dash' : dash,
},
'fill': filling,
'fillcolor': {
'color' : 'rgba' + str((color[0], color[1], color[2], opacity)),
'opacity' : opacity,
},
'opacity': opacity
})
self.plots[plot_num].append(trace)
[docs] def info(self):
"""
Prints summary about the plotting factory, i.e.how many plots and how
many datasets per plot.
"""
print("""
Factory holds {0} unique plots""".format(len(self.plots)))
for i, plot in enumerate(self.plots):
print(
"\t\tPlot {0} holds {1} unique datasets".format(
i,
len(plot)
)
)
for j, dataset in enumerate(plot):
print("\t\t\tDataset {0} holds {1} datapoints".format(
j,
len(dataset['x'])
))
print()
return
[docs] def save(self, filename=None, mz_range=None, layout=None):
"""
Saves all plots and their data points that have been added to the
plotFactory.
Args:
filename (str): Name for the output file. Default = "spectrum_plot.html"
mz_range (tuple): m/z range which should be considered [start, end].
Default = None
layout (dict): dictionary containing layout information in plotly style
"""
plot_number = len(self.plots)
rows, cols = int(math.ceil(plot_number/float(2))), 2
print(rows, cols)
# enable possibility to have different subplots in on Pic
if plot_number % 2 == 0:
my_figure = tools.make_subplots(
rows=rows, cols=cols, vertical_spacing=0.6/rows
)
else:
specs = [[{}, {}] for x in range(rows-1)]
specs.append([{'colspan': 2}, None])
my_figure = tools.make_subplots(
rows = rows,
cols = cols,
vertical_spacing = 0.6 / rows,
specs = specs,
subplot_titles = self.titles
)
for i, plot in enumerate(self.plots):
print(int(math.floor((i / 2) + 1)), (i % 2) + 1)
for j, trace in enumerate(plot):
trace['y'] = [
self.function_mapper[x](i) if x in self.function_mapper else x for x in trace['y']
]
my_figure.append_trace(
trace,
int(math.floor((i / 2) + 1)),
(i % 2) + 1
)
for i in range(plot_number):
if plot_number == 1:
xaxis_key = 'xaxis'
else:
xaxis_key = 'xaxis{0}'.format(i + 1)
if mz_range:
if mz_range[0] == list or mz_range[0] == tuple:
# if list and not list of list, apply same for all
my_figure['layout'][ xaxis_key ].update(range=mz_range[i])
elif mz_range[0] == int or mz_range[0] == float:
my_figure['layout'][ xaxis_key ]['range'] = mz_range
my_figure['layout'][ xaxis_key ]['autorange'] = False
my_figure['layout'][ xaxis_key ].update(title='m/z ')
my_figure['layout']['yaxis' + str(i + 1)].update(title='Intensity')
my_figure['layout'][ xaxis_key ].update(
titlefont=
{
'color': '#000000',
'family': 'Helvetica',
'size': '18'
}
)
my_figure['layout']['yaxis'+str(i+1)].update(
titlefont=
{
'color': '#000000',
'family': 'Helvetica',
'size': '18'
}
)
my_figure['layout']['legend'].update(
font={
'size': 10,
'color': '#FF0000'
}
)
if layout:
my_figure['layout'].update(layout)
# my_figure['layout']['title'].update(title=self.header[-1])
if self.filename is None:
_filename = "spectrum_plot.html"
else:
_filename = self.filename
if filename is not None:
# save fkt name definition overrules original filename
_filename = filename
plt.plot(
my_figure,
filename = _filename,
auto_open = False
)
return
[docs] def get_data(self):
"""
Return data and layout in JSON format.
Returns:
plots (dict): JSON compatible python dict
"""
for i, plot in enumerate(self.plots):
for j, trace in enumerate(plot):
self.plots[i][j]['y'] = [
self.function_mapper[x](i) if x in self.function_mapper else x for x in trace['y']
]
return self.plots
if __name__ == '__main__':
print(__doc__)