ViewVC Help
View File | Revision Log | Show Annotations | View Changeset | Root Listing
root/osprai/osprai/trunk/vu_module.py
Revision: 67
Committed: Thu Apr 26 00:15:50 2012 UTC (7 years, 3 months ago) by clausted
File size: 10786 byte(s)
Log Message:
Fix bug in numbering ROIs in io_module.readicmtext().
Enhance vu_module.dualgraph() to automatically show modeled data along with read data.
Increase running average length in mdl_module; this isn't a good solution.
Change private function names from double-undescore to single-underscore prefixes.
Line File contents
1 """
2 vu_module
3 ---------
4
5 This is the viewer module for SPR data in a ba_class.
6 Traces can be displayed as dotted lines, continuous lines, or combinations.
7 Typically, up to six traces are displayed at a time.
8 Features include zooming, measurements, and save-to-PNG.
9 Graphics utilize the old Tk GUI toolkit.
10
11 .. moduleauthor:: Christopher Lausted,
12 Institute for Systems Biology,
13 OSPRAI developers.
14
15 Examples::
16
17 >>> import vu_module as vu
18 >>> import io_module as io
19 >>> ba1 = io.readsprit("spritdata.txt")
20 >>> vu.dotgraph(ba1, "Title")
21 >>> vu.linegraph(ba1, "Title")
22 >>> vu.dualgraph(ba1, ba2, "Title")
23 >>> vu.scatterplot(ba1, t1, t2, t3, t4, title)
24 """
25 __version__ = "120425"
26
27
28 ## Import libraries
29 import ba_class as ba ## Our Biosensor Array class.
30 import numpy as np
31 from datetime import date
32 from copy import deepcopy
33 import Tkinter as Tk
34 import tkSimpleDialog as dialog
35 import matplotlib as mpl
36 mpl.use('TkAgg')
37 from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
38 from matplotlib.figure import Figure
39
40
41 def linegraph(baLine, title=""):
42 """
43 Display signal vs time using continuous lines.
44
45 :param baLine: Object containing the data.
46 :type baLine: BiosensorArray
47 :param title: Title to place above the graph.
48 :type title: str
49 :returns: nothing
50 """
51 global root, fig, ax, canvas ## Tk/mpl globals.
52 global ba0, ba1, ba2 ## Ref to ba for _roiList, dotgraph, linegraph
53 global gTitle ## Title for graph.
54 ba0, ba1, ba2 = baLine, 0, baLine
55 gTitle = title
56 _createSensorgramTkWindow()
57 _show()
58 root.mainloop()
59 return
60 """
61 How does linegraph() work? It sets some global values, then calls _show().
62 """
63
64 def dotgraph(baDot, title=""):
65 """
66 Display signal vs time using dotted lines.
67
68 :param baDot: Object containing the data.
69 :type baDot: BiosensorArray
70 :param title: Title to place above the graph.
71 :type title: str
72 :returns: nothing
73 """
74 global root, fig, ax, canvas ## Tk/mpl globals..
75 global ba0, ba1, ba2 ## Ref to ba for _roiList, dotgraph, linegraph
76 global gTitle ## Title for graph.
77 ba0, ba1, ba2 = baDot, baDot, 0
78 gTitle = title
79 _createSensorgramTkWindow()
80 _show()
81 root.mainloop()
82 return
83 ## End of dotgraph().
84 """
85 How does dotgraph() work? It sets some global values, then calls _show().
86 """
87
88 def dualgraph(baDot, baLine, title=""):
89 """
90 Display signal vs time using dotted AND continuous lines.
91 To graph measured and fitted data together, specify the same
92 object for baDot and baLine.
93
94 :param baDot: Object containing the dotted-line data.
95 :type baDot: BiosensorArray
96 :param baLine: Object containing the continuous-line data.
97 :type baLine: BiosensorArray
98 :param title: Title to place above the graph.
99 :type title: str
100 :returns: nothing
101 """
102 global root, fig, ax, canvas ## Tk/mpl globals.
103 global ba0, ba1, ba2 ## Ref to ba for _roiList, dotgraph, linegraph
104 global gTitle ## Title for graph.
105 ba0, ba1, ba2 = baDot, baDot, baLine
106 gTitle = title
107 _createSensorgramTkWindow()
108 _show()
109 root.mainloop()
110 return
111 """
112 How does dualgraph() work? It sets some global values, then calls _show().
113 """
114
115 def _show():
116 """
117 Graph data of BiosensorArray objects using Tk window.
118 BiosensorArrays graphed are the globals ba1 and ba2.
119 If ba1 and ba2 are the same object, replace ba2 with modeled data.
120 """
121 global root, fig, ax, canvas
122 global ba1, ba2
123 global gTitle
124
125 ## Apply the model with a new ba object, if necessary.
126 if (ba1 is ba2):
127 ba2 = deepcopy(ba1)
128 for i,roi in enumerate(ba1.roi):
129 if (roi.model is None):
130 ## Use zeros (flatline) if not model is specified.
131 ba2.roi[i].value = 0 * roi.value
132 else:
133 ## Plug params into the specified model.
134 ba2.roi[i].value = roi.model(roi.time, roi.value, roi.params)
135
136 ## Prepare graph labels.
137 ax.clear()
138 if (gTitle==""): gTitle='SPR Data plotted %s' % date.today().isoformat()
139 ax.set_title(gTitle)
140 ax.set_xlabel('Time (s)')
141 ax.set_ylabel('SPR Response')
142 ax.grid(True)
143
144 ## Plot traces of real data.
145 if (ba1 != 0):
146 ## Dotted traces.
147 marker = ['r,', 'g,', 'b,', 'c,', 'm,', 'y,'] + ['k,'] * 100
148 for i,j in enumerate(_roiList()):
149 txt = str(j) + ':' + ba1.roi[j].name
150 t = ba1.roi[j].time
151 y = ba1.roi[j].value
152 ax.plot(t, y, marker[i], label=txt)
153 if (ba2 != 0):
154 ## Line traces.
155 marker = ['r', 'g', 'b', 'c', 'm', 'y'] + ['k'] * 100
156 for i,j in enumerate(_roiList()):
157 txt = str(j) + ':' + ba2.roi[j].name
158 t = ba2.roi[j].time
159 y = ba2.roi[j].value
160 ax.plot(t, y, marker[i], label=txt)
161
162 ## Format legend.
163 leg = ax.legend(loc='upper right')
164 for t in leg.get_texts(): t.set_fontsize('x-small')
165 #for t in leg.get_lines(): t.set_linestyle('None')
166 #labels = [line.get_label() for line in ax.lines]
167 #fig.legend(ax.lines, labels, 'right')
168
169 canvas.draw()
170 return
171 """
172 End of _show().
173 """
174
175 def _btnNext():
176 """
177 Show next six traces on the graph.
178 """
179 global ba0
180 lo = max(_roiList()) + 1
181 if (lo == len(ba0.roi)): return
182 lo = max(lo,0)
183 hi = lo + 6
184 hi = min(hi, len(ba0.roi))
185 ba0.set_plot_list(range(lo, hi))
186 _show()
187 return
188
189 def _btnPrev():
190 """
191 Show the previous six traces on the graph.
192 """
193 global ba0
194 lo = min(_roiList()) - 6
195 lo = max(lo,0)
196 hi = lo + 6
197 hi = min(hi, len(ba0.roi))
198 ba0.set_plot_list(range(lo, hi))
199 _show()
200 return
201
202 def _btnTraces():
203 """
204 Ask for list of traces to show on graph.
205 """
206 global ba0
207 txt = "Which ROIs would you like to see? (e.g. 19,20,21)"
208 txt = dialog.askstring(title="Input",prompt=txt)
209 txt = txt + "," ## Be sure eval() produces a list.
210 ba0.set_plot_list(eval(txt))
211 _show()
212 return
213
214
215 def _roiList():
216 """
217 List of first six plottable ROIs.
218 """
219 global ba0
220 #x = [i for i in range(len(ba.roi)) if ba0.roi[i].plottable]
221 x = [i.index for i in ba0.roi if i.plottable]
222 return x[:6]
223
224
225 def _createSensorgramTkWindow():
226 """
227 Create a Tk window for the Matplotlib graph.
228 This window has three buttons which will allow the user to browse through many traces.
229 """
230 global root, fig, ax, canvas
231 root = Tk.Tk()
232 root.wm_title("TK matplotlib Osprai Sensorgram")
233 ## Prepare a matplotlib Figure/Axes.
234 fig = Figure(figsize=(6,4), dpi=100)
235 ax = fig.add_subplot(111)
236 ax.hold(True) # Hold data until ax.clear().
237 #ax.set_position([0.1, 0.1, 0.6, 0.8]) # Fraction of frame [left,bot,w,h]
238 ## Define tk.DrawingArea
239 canvas = FigureCanvasTkAgg(fig, master=root)
240 #canvas._show()
241 canvas.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)
242 ## Add a pylab-style toolbar.
243 toolbar = NavigationToolbar2TkAgg( canvas, root )
244 toolbar.update()
245 canvas._tkcanvas.pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)
246 ## Add buttons.
247 button1 = Tk.Button(master=root, text='Next6', command=_btnNext)
248 button1.pack(side=Tk.RIGHT)
249 button2 = Tk.Button(master=root, text='Choose..', command=_btnTraces)
250 button2.pack(side=Tk.RIGHT)
251 button3 = Tk.Button(master=root, text='Prev6', command=_btnPrev)
252 button3.pack(side=Tk.RIGHT)
253 return
254 """
255 End of _createSensorgramTkWindow().
256 """
257
258 ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ##
259
260
261 def scatterplot(ba0, t1, t2, t3, t4, title):
262 """
263 Plot binding changes between (t4-t3) versus (t2-t1).
264 Also print the results to the standard output.
265
266 :param ba0: Object containing the data.
267 :type ba0: BiosensorArray
268 :param t1: Timepoint before binding, first axis.
269 :type t1: float
270 :param t2: Timepoint after binding, first axis.
271 :type t2: float
272 :param t3: Timepoint before binding, second axis.
273 :type t3: float
274 :param t4: Timepoint after binding, second axis.
275 :type t4: float
276 :param title: Title to place above the graph.
277 :type title: str
278 :returns: nothing
279 """
280 root = Tk.Tk()
281 root.wm_title("TK matplotlib Osprai Sensorgram")
282 ## Prepare a matplotlib Figure/Axes.
283 fig = Figure(figsize=(6,4), dpi=100)
284 ax = fig.add_subplot(111)
285 ax.hold(True) # Hold data until ax.clear().
286 ## Define tk.DrawingArea
287 canvas = FigureCanvasTkAgg(fig, master=root)
288 canvas.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)
289 ## Add a pylab-style toolbar.
290 toolbar = NavigationToolbar2TkAgg( canvas, root )
291 toolbar.update()
292 canvas._tkcanvas.pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)
293
294 ## Prepare graph labels.
295 ax.clear()
296 if (title==""): title='Scatterplot of %s' % date.today().isoformat()
297 ax.set_title(title)
298 ax.set_xlabel('Binding12')
299 ax.set_ylabel('Binding34')
300 ax.grid(True)
301
302 ## Get array of values at each of the four time points.
303 y1 = np.array([np.average(iroi.time2val(t1-15, t1+15)) for iroi in ba0.roi])
304 y2 = np.array([np.average(iroi.time2val(t2-15, t2+15)) for iroi in ba0.roi])
305 y3 = np.array([np.average(iroi.time2val(t3-15, t3+15)) for iroi in ba0.roi])
306 y4 = np.array([np.average(iroi.time2val(t4-15, t4+15)) for iroi in ba0.roi])
307 dx, dy = (y2-y1), (y4-y3)
308
309 ## Print to stdout
310 print "Name", "Binding12", "Binding34"
311 for i in range(len(dx)): print ba0.roi[i].name, dx[i], dy[i]
312
313 ## Plot
314 ax.plot(dx, dy, 'bo') ## Blue circles with 'bo'.
315 canvas.draw()
316 root.mainloop()
317 return
318 """
319 How does scatterplot() work?
320 First create a Tk window for the scatterplot graph.
321 Variables root, fig, ax, canvas are local here, not global.
322 Use list comprehensions to get list of average signal 30 sec around t1, t2, t3, t4.
323 Plot signal change between t1-t2 against t3-t4. Also print to std output.
324 """
325
326
327 ## Print a message to the users so they see this module is loaded.
328 #print "Loaded vu_module.py version ", __version__
329
330 ################################# End of module #################################