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 (8 years, 6 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 User Rev File contents
1 clausted 11 """
2 clausted 44 vu_module
3     ---------
4 clausted 11
5 clausted 44 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 clausted 54
15 clausted 47 Examples::
16 clausted 44
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 clausted 11 """
25 clausted 67 __version__ = "120425"
26 clausted 11
27    
28     ## Import libraries
29     import ba_class as ba ## Our Biosensor Array class.
30 clausted 14 import numpy as np
31 clausted 11 from datetime import date
32 clausted 67 from copy import deepcopy
33 clausted 11 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 clausted 14 def linegraph(baLine, title=""):
42 clausted 44 """
43     Display signal vs time using continuous lines.
44    
45     :param baLine: Object containing the data.
46 clausted 54 :type baLine: BiosensorArray
47 clausted 44 :param title: Title to place above the graph.
48     :type title: str
49     :returns: nothing
50     """
51 clausted 11 global root, fig, ax, canvas ## Tk/mpl globals.
52 clausted 67 global ba0, ba1, ba2 ## Ref to ba for _roiList, dotgraph, linegraph
53 clausted 14 global gTitle ## Title for graph.
54 clausted 11 ba0, ba1, ba2 = baLine, 0, baLine
55 clausted 14 gTitle = title
56 clausted 67 _createSensorgramTkWindow()
57     _show()
58 clausted 11 root.mainloop()
59     return
60 clausted 44 """
61 clausted 67 How does linegraph() work? It sets some global values, then calls _show().
62 clausted 44 """
63 clausted 11
64 clausted 14 def dotgraph(baDot, title=""):
65 clausted 44 """
66     Display signal vs time using dotted lines.
67    
68     :param baDot: Object containing the data.
69 clausted 54 :type baDot: BiosensorArray
70 clausted 44 :param title: Title to place above the graph.
71     :type title: str
72     :returns: nothing
73     """
74 clausted 11 global root, fig, ax, canvas ## Tk/mpl globals..
75 clausted 67 global ba0, ba1, ba2 ## Ref to ba for _roiList, dotgraph, linegraph
76 clausted 14 global gTitle ## Title for graph.
77 clausted 11 ba0, ba1, ba2 = baDot, baDot, 0
78 clausted 14 gTitle = title
79 clausted 67 _createSensorgramTkWindow()
80     _show()
81 clausted 11 root.mainloop()
82     return
83     ## End of dotgraph().
84 clausted 44 """
85 clausted 67 How does dotgraph() work? It sets some global values, then calls _show().
86 clausted 44 """
87 clausted 11
88 clausted 14 def dualgraph(baDot, baLine, title=""):
89 clausted 44 """
90     Display signal vs time using dotted AND continuous lines.
91 clausted 67 To graph measured and fitted data together, specify the same
92     object for baDot and baLine.
93 clausted 44
94     :param baDot: Object containing the dotted-line data.
95 clausted 54 :type baDot: BiosensorArray
96 clausted 44 :param baLine: Object containing the continuous-line data.
97 clausted 54 :type baLine: BiosensorArray
98 clausted 44 :param title: Title to place above the graph.
99     :type title: str
100     :returns: nothing
101     """
102 clausted 11 global root, fig, ax, canvas ## Tk/mpl globals.
103 clausted 67 global ba0, ba1, ba2 ## Ref to ba for _roiList, dotgraph, linegraph
104 clausted 14 global gTitle ## Title for graph.
105 clausted 11 ba0, ba1, ba2 = baDot, baDot, baLine
106 clausted 14 gTitle = title
107 clausted 67 _createSensorgramTkWindow()
108     _show()
109 clausted 11 root.mainloop()
110     return
111 clausted 44 """
112 clausted 67 How does dualgraph() work? It sets some global values, then calls _show().
113 clausted 44 """
114 clausted 11
115 clausted 67 def _show():
116 clausted 44 """
117 clausted 67 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 clausted 44 """
121 clausted 11 global root, fig, ax, canvas
122     global ba1, ba2
123 clausted 14 global gTitle
124 clausted 11
125 clausted 67 ## 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 clausted 11 ## Prepare graph labels.
137     ax.clear()
138 clausted 14 if (gTitle==""): gTitle='SPR Data plotted %s' % date.today().isoformat()
139     ax.set_title(gTitle)
140 clausted 11 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 clausted 67 for i,j in enumerate(_roiList()):
149 clausted 11 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 clausted 67 for i,j in enumerate(_roiList()):
157 clausted 11 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 clausted 44 """
172 clausted 67 End of _show().
173 clausted 44 """
174 clausted 11
175 clausted 67 def _btnNext():
176 clausted 44 """
177     Show next six traces on the graph.
178     """
179 clausted 11 global ba0
180 clausted 67 lo = max(_roiList()) + 1
181 clausted 16 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 clausted 67 _show()
187 clausted 11 return
188    
189 clausted 67 def _btnPrev():
190 clausted 44 """
191     Show the previous six traces on the graph.
192     """
193 clausted 11 global ba0
194 clausted 67 lo = min(_roiList()) - 6
195 clausted 16 lo = max(lo,0)
196     hi = lo + 6
197     hi = min(hi, len(ba0.roi))
198     ba0.set_plot_list(range(lo, hi))
199 clausted 67 _show()
200 clausted 11 return
201    
202 clausted 67 def _btnTraces():
203 clausted 44 """
204     Ask for list of traces to show on graph.
205     """
206 clausted 11 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 clausted 67 _show()
212 clausted 11 return
213    
214    
215 clausted 67 def _roiList():
216 clausted 44 """
217     List of first six plottable ROIs.
218     """
219 clausted 11 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 clausted 67 def _createSensorgramTkWindow():
226 clausted 14 """
227     Create a Tk window for the Matplotlib graph.
228 clausted 44 This window has three buttons which will allow the user to browse through many traces.
229 clausted 14 """
230 clausted 11 global root, fig, ax, canvas
231     root = Tk.Tk()
232 clausted 14 root.wm_title("TK matplotlib Osprai Sensorgram")
233 clausted 11 ## 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 clausted 67 #canvas._show()
241 clausted 11 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 clausted 67 button1 = Tk.Button(master=root, text='Next6', command=_btnNext)
248 clausted 11 button1.pack(side=Tk.RIGHT)
249 clausted 67 button2 = Tk.Button(master=root, text='Choose..', command=_btnTraces)
250 clausted 11 button2.pack(side=Tk.RIGHT)
251 clausted 67 button3 = Tk.Button(master=root, text='Prev6', command=_btnPrev)
252 clausted 11 button3.pack(side=Tk.RIGHT)
253     return
254 clausted 44 """
255 clausted 67 End of _createSensorgramTkWindow().
256 clausted 44 """
257 clausted 14
258     ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ##
259 clausted 11
260    
261 clausted 14 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 clausted 44
266     :param ba0: Object containing the data.
267 clausted 54 :type ba0: BiosensorArray
268 clausted 44 :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 clausted 14 """
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 clausted 44 """
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 clausted 14
326    
327 clausted 11 ## Print a message to the users so they see this module is loaded.
328 clausted 65 #print "Loaded vu_module.py version ", __version__
329 clausted 11
330 clausted 44 ################################# End of module #################################