| 1 |
|
| 2 |
|
| 3 |
""" |
| 4 |
Plotting functions for pymzML. |
| 5 |
The Factory object can hold several plots with several data traces each. |
| 6 |
The plot will be rendered as interactive plotly plots. |
| 7 |
""" |
| 8 |
|
| 9 |
|
| 10 |
n |
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
|
| 25 |
|
| 26 |
|
| 27 |
|
| 28 |
|
| 29 |
|
| 30 |
|
| 31 |
import math |
| 32 |
import plotly.offline as plt |
| 33 |
import plotly.graph_objs as go |
| 34 |
from plotly import tools |
| 35 |
|
| 36 |
|
| 37 |
class Factory(object): |
| 38 |
def __init__(self, filename="spectrum_plot.html"): |
| 39 |
""" |
| 40 |
Class to plot pymzml.spec.Spectrum using plotly. |
| 41 |
|
| 42 |
Args: |
| 43 |
filename (str): Name for the output file. Default = "spectrum_plot.html" |
| 44 |
|
| 45 |
Example: |
| 46 |
|
| 47 |
>>> import pymzml, get_example_file |
| 48 |
>>> mzMLFile = 'profile-mass-spectrum.mzml' |
| 49 |
>>> example_file = get_example_file.open_example(mzMLFile) |
| 50 |
>>> run = pymzml.run.Run("../mzML_example_files/"+mzMLFile, |
| 51 |
... precisionMSn = 250e-6 |
| 52 |
... ) |
| 53 |
>>> p = pymzml.plot.Factory() |
| 54 |
>>> for spec in run: |
| 55 |
>>> p.new_plot() |
| 56 |
>>> p.add(spec.peaks, color=(200,00,00), style='sticks') |
| 57 |
>>> p.add(spec.centroided_peaks, color=(00,00,00), style='sticks') |
| 58 |
>>> p.add(spec.reprofiled_peaks, color=(00,255,00), style='sticks') |
| 59 |
>>> p.save( |
| 60 |
... filename="output/plotAspect.xhtml", |
| 61 |
... mz_range = (745.2,745.6) |
| 62 |
... ) |
| 63 |
|
| 64 |
NOTE: |
| 65 |
This should go into example_script/plot_spectrum.py |
| 66 |
|
| 67 |
""" |
| 68 |
self.filename = filename |
| 69 |
self.plots = [] |
| 70 |
self.titles = [] |
| 71 |
self.lookup = dict() |
| 72 |
self.y_max = [] |
| 73 |
self.x_max = [] |
| 74 |
self.offset = 1 |
| 75 |
self.precisions = [] |
| 76 |
self.styles = ["sticks", "triangle", "spline", "linear"] |
| 77 |
self.widths = ["small", "medium", "big"] |
| 78 |
self.style_parameters = { |
| 79 |
"sticks": { |
| 80 |
"mode": "lines+text", |
| 81 |
"shape": "linear", |
| 82 |
"filling": "tozeroy", |
| 83 |
"width": lambda n: self.precisions[n], |
| 84 |
}, |
| 85 |
"triangle": { |
| 86 |
"mode": "lines+text", |
| 87 |
"shape": "linear", |
| 88 |
"filling": "tozeroy", |
| 89 |
"width": lambda n: self.scalings[n], |
| 90 |
}, |
| 91 |
"lines": {"mode": "lines+text", "shape": "spline", "filling": None}, |
| 92 |
"points": {"mode": "markers", "shape": "linear", "filling": None}, |
| 93 |
} |
| 94 |
|
| 95 |
def new_plot(self, precision="5e-6", title=None): |
| 96 |
""" |
| 97 |
Add new plot to the plotting Factory. |
| 98 |
|
| 99 |
Args: |
| 100 |
header (str): an optional title that will be printed above the plot |
| 101 |
mz_range (tuple): Boundaries of the new plot |
| 102 |
normalize (boolean): whether or not the individal data sets |
| 103 |
are normalized in the plot |
| 104 |
precision (float): measuring precision used in handler. |
| 105 |
Default 5e-6. |
| 106 |
""" |
| 107 |
self.precisions.append(precision) |
| 108 |
self.plots.append([]) |
| 109 |
return |
| 110 |
|
| 111 |
def add( |
| 112 |
self, |
| 113 |
data, |
| 114 |
color=(0, 0, 0), |
| 115 |
style="sticks", |
| 116 |
mz_range=None, |
| 117 |
opacity=0.8, |
| 118 |
name=None, |
| 119 |
plot_num=-1, |
| 120 |
title=None, |
| 121 |
): |
| 122 |
""" |
| 123 |
Add data to the graph. |
| 124 |
|
| 125 |
Arguments: |
| 126 |
data (list): The data added to the graph. Must be list of |
| 127 |
tuples, like (mz,i) or (mz1, mz2, i, string) |
| 128 |
style (str): plotting style. Default = "sticks".\n |
| 129 |
Currently supported styles are:\n |
| 130 |
* 'sticks'\n |
| 131 |
* 'triangle' (small, medium or big)\n |
| 132 |
* 'spline' (top, medium or bottom)\n |
| 133 |
* 'linear' (top, medium or bottom)\n |
| 134 |
color (tuple): color encoded in RGB. Default = (0,0,0) |
| 135 |
mz_range (tuple): Boundaries that should be added to the current |
| 136 |
plot |
| 137 |
opacity (float): opacity of the data points\n |
| 138 |
name (str): name of data in legend\n |
| 139 |
plot_num (int): Add data to plot[plot_num]\n |
| 140 |
|
| 141 |
""" |
| 142 |
style_attribs = style.split(".") |
| 143 |
assert ( |
| 144 |
len(style_attribs) == 3 |
| 145 |
), "Style must set datatype, plotting style and width:\n{0}".format( |
| 146 |
style_attribs |
| 147 |
) |
| 148 |
|
| 149 |
if len(self.plots) == 0: |
| 150 |
self.new_plot(title=title) |
| 151 |
|
| 152 |
precision = float(self.precisions[plot_num]) |
| 153 |
|
| 154 |
if style_attribs[0] == "label": |
| 155 |
as_anno = True |
| 156 |
elif style_attribs[0] == "data": |
| 157 |
as_anno = False |
| 158 |
else: |
| 159 |
raise Exception("Style must be declare trace as data or annotation") |
| 160 |
|
| 161 |
|
| 162 |
x_values = [] |
| 163 |
y_values = [] |
| 164 |
txt_values = [] |
| 165 |
|
| 166 |
if as_anno: |
| 167 |
for vars in data: |
| 168 |
mz, i = vars[0], vars[1] |
| 169 |
txt = vars[2] |
| 170 |
x_values.extend( |
| 171 |
[ |
| 172 |
mz |
| 173 |
- ( |
| 174 |
mz * precision |
| 175 |
), |
| 176 |
mz, |
| 177 |
mz |
| 178 |
+ ( |
| 179 |
mz * precision |
| 180 |
), |
| 181 |
None, |
| 182 |
] |
| 183 |
) |
| 184 |
y_values.extend( |
| 185 |
[ |
| 186 |
0, |
| 187 |
i, |
| 188 |
0, |
| 189 |
None, |
| 190 |
] |
| 191 |
) |
| 192 |
txt_values.extend([None, txt, None, None]) |
| 193 |
else: |
| 194 |
for mz, i in data: |
| 195 |
x_values.extend( |
| 196 |
[mz - (mz * precision), mz, mz + (mz * precision), None] |
| 197 |
) |
| 198 |
y_values.extend([0.0, i, 0.0, None]) |
| 199 |
|
| 200 |
data = go.Scatter( |
| 201 |
{ |
| 202 |
"x": x_values, |
| 203 |
"y": y_values, |
| 204 |
"text": txt_values, |
| 205 |
"textfont": {"family": "Helvetica", "size": 10, "color": "#000000"}, |
| 206 |
"textposition": "top center", |
| 207 |
"visible": "True", |
| 208 |
"marker": {"size": 10}, |
| 209 |
"mode": self.style_parameters[style_attribs[1]]["mode"], |
| 210 |
"name": name, |
| 211 |
"line": { |
| 212 |
"color": "rgb" + str(color), |
| 213 |
"width": 1, |
| 214 |
"shape": self.style_parameters[style_attribs[1]]["shape"], |
| 215 |
}, |
| 216 |
"fill": self.style_parameters[style_attribs[1]]["filling"], |
| 217 |
"fillcolor": { |
| 218 |
"color": "rgba" + str((color[0], color[1], color[2], opacity)) |
| 219 |
}, |
| 220 |
"opacity": opacity, |
| 221 |
} |
| 222 |
) |
| 223 |
|
| 224 |
self.plots[plot_num].append(data) |
| 225 |
return |
| 226 |
|
| 227 |
def info(self): |
| 228 |
""" |
| 229 |
Prints summary about the plotting factory, i.e.how many plots and how |
| 230 |
many datasets per plot. |
| 231 |
""" |
| 232 |
print( |
| 233 |
""" |
| 234 |
Factory holds {0} unique plots""".format( |
| 235 |
len(self.plots) |
| 236 |
) |
| 237 |
) |
| 238 |
for i, plot in enumerate(self.plots): |
| 239 |
print("\t\tPlot {0} holds {1} unique datasets".format(i, len(plot))) |
| 240 |
for j, dataset in enumerate(plot): |
| 241 |
print( |
| 242 |
"\t\t\tDataset {0} holds {1} datapoints".format( |
| 243 |
j, len(dataset["x"]) |
| 244 |
) |
| 245 |
) |
| 246 |
|
| 247 |
print() |
| 248 |
return |
| 249 |
|
| 250 |
def get_data(self): |
| 251 |
""" |
| 252 |
Return data and layout in JSON format. |
| 253 |
|
| 254 |
Returns: |
| 255 |
plots (dict): JSON compatible python dict |
| 256 |
""" |
| 257 |
for i, plot in enumerate(self.plots): |
| 258 |
for j, trace in enumerate(plot): |
| 259 |
self.plots[i][j]["y"] = [ |
| 260 |
self.function_mapper[x](i) if x in self.function_mapper else x |
| 261 |
for x in trace["y"] |
| 262 |
] |
| 263 |
return self.plots |
| 264 |
|
| 265 |
def save(self, filename=None, xLimits=None): |
| 266 |
""" |
| 267 |
Saves all plots and their data points that have been added to the |
| 268 |
plotFactory. |
| 269 |
|
| 270 |
Args: |
| 271 |
filename (str): Name for the output file. Default = "spectrum_plot.html" |
| 272 |
mz_range (tuple): m/z range which should be considered [start, end]. |
| 273 |
Default = None |
| 274 |
""" |
| 275 |
plot_number = len(self.plots) |
| 276 |
|
| 277 |
rows, cols = int(math.ceil(plot_number / float(2))), 2 |
| 278 |
|
| 279 |
if plot_number % 2 == 0: |
| 280 |
my_figure = tools.make_subplots( |
| 281 |
rows=rows, cols=cols, vertical_spacing=0.6 / rows |
| 282 |
) |
| 283 |
else: |
| 284 |
specs = [[{}, {}] for x in range(rows - 1)] |
| 285 |
specs.append([{"colspan": 2}, None]) |
| 286 |
my_figure = tools.make_subplots( |
| 287 |
rows=rows, |
| 288 |
cols=cols, |
| 289 |
vertical_spacing=0.6 / rows, |
| 290 |
specs=specs, |
| 291 |
subplot_titles=self.titles, |
| 292 |
) |
| 293 |
|
| 294 |
for i, plot in enumerate(self.plots): |
| 295 |
for j, trace in enumerate(plot): |
| 296 |
my_figure.append_trace(trace, int(math.floor((i / 2) + 1)), (i % 2) + 1) |
| 297 |
|
| 298 |
for i in range(plot_number): |
| 299 |
if xLimits: |
| 300 |
my_figure["layout"]["xaxis" + str(i + 1)].update(range=xLimits[i]) |
| 301 |
my_figure["layout"]["xaxis" + str(i + 1)].update(title="m/z ") |
| 302 |
my_figure["layout"]["yaxis" + str(i + 1)].update(title="Intensity") |
| 303 |
my_figure["layout"]["xaxis" + str(i + 1)].update( |
| 304 |
titlefont={"color": "#000000", "family": "Helvetica", "size": "18"} |
| 305 |
) |
| 306 |
my_figure["layout"]["yaxis" + str(i + 1)].update( |
| 307 |
titlefont={"color": "#000000", "family": "Helvetica", "size": "18"} |
| 308 |
) |
| 309 |
|
| 310 |
my_figure["layout"]["legend"].update(font={"size": 10, "color": "#FF0000"}) |
| 311 |
|
| 312 |
if self.filename is None: |
| 313 |
_filename = "spectrum_plot.html" |
| 314 |
else: |
| 315 |
_filename = self.filename |
| 316 |
|
| 317 |
if filename is not None: |
| 318 |
|
| 319 |
_filename = filename |
| 320 |
|
| 321 |
plt.plot(my_figure, filename=_filename, auto_open=False) |
| 322 |
return |
| 323 |
|
| 324 |
|
| 325 |
if __name__ == "__main__": |
| 326 |
data = [(1, 10), (2, 20)] |
| 327 |
anno = [(1, 10, "blub"), (2, 20, "bla")] |
| 328 |
Fac = Factory() |
| 329 |
|
| 330 |
print("'style='data.sticks.medium'") |
| 331 |
Fac.add(data, style="data.sticks.medium") |
| 332 |
print() |
| 333 |
print("style='data.triangle.small'") |
| 334 |
Fac.add(data, style="data.triangle.small") |
| 335 |
print() |
| 336 |
Fac.add(anno, style="label.sticks.medium") |
| 337 |
Fac.save(filename="tmp.html") |