ViewVC Help
View File | Revision Log | Show Annotations | View Changeset | Root Listing
root/osprai/osprai/trunk/vu_module.py
Revision: 65
Committed: Fri May 20 16:33:02 2011 UTC (7 years, 5 months ago) by clausted
File size: 10070 byte(s)
Log Message:
Added much testing to all modules using docstrings and doctest.  To help this, I also added two optional parameters to mclma(), verbose and maxiter.  For example, use "mclma(rois, verbose=False, maxiter=99)" to run the regression up to 99 iterations without echoing progress to the standard output.

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__ = "110215"
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 import Tkinter as Tk
33 import tkSimpleDialog as dialog
34 import matplotlib as mpl
35 mpl.use('TkAgg')
36 from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
37 from matplotlib.figure import Figure
38
39
40 def linegraph(baLine, title=""):
41 """
42 Display signal vs time using continuous lines.
43
44 :param baLine: Object containing the data.
45 :type baLine: BiosensorArray
46 :param title: Title to place above the graph.
47 :type title: str
48 :returns: nothing
49 """
50 global root, fig, ax, canvas ## Tk/mpl globals.
51 global ba0, ba1, ba2 ## Ref to ba for __roiList, dotgraph, linegraph
52 global gTitle ## Title for graph.
53 ba0, ba1, ba2 = baLine, 0, baLine
54 gTitle = title
55 __createSensorgramTkWindow()
56 __show()
57 root.mainloop()
58 return
59 """
60 How does linegraph() work? It sets some global values, then calls __show().
61 """
62
63 def dotgraph(baDot, title=""):
64 """
65 Display signal vs time using dotted lines.
66
67 :param baDot: Object containing the data.
68 :type baDot: BiosensorArray
69 :param title: Title to place above the graph.
70 :type title: str
71 :returns: nothing
72 """
73 global root, fig, ax, canvas ## Tk/mpl globals..
74 global ba0, ba1, ba2 ## Ref to ba for __roiList, dotgraph, linegraph
75 global gTitle ## Title for graph.
76 ba0, ba1, ba2 = baDot, baDot, 0
77 gTitle = title
78 __createSensorgramTkWindow()
79 __show()
80 root.mainloop()
81 return
82 ## End of dotgraph().
83 """
84 How does dotgraph() work? It sets some global values, then calls __show().
85 """
86
87 def dualgraph(baDot, baLine, title=""):
88 """
89 Display signal vs time using dotted AND continuous lines.
90
91 :param baDot: Object containing the dotted-line data.
92 :type baDot: BiosensorArray
93 :param baLine: Object containing the continuous-line data.
94 :type baLine: BiosensorArray
95 :param title: Title to place above the graph.
96 :type title: str
97 :returns: nothing
98 """
99 global root, fig, ax, canvas ## Tk/mpl globals.
100 global ba0, ba1, ba2 ## Ref to ba for __roiList, dotgraph, linegraph
101 global gTitle ## Title for graph.
102 ba0, ba1, ba2 = baDot, baDot, baLine
103 gTitle = title
104 __createSensorgramTkWindow()
105 __show()
106 root.mainloop()
107 return
108 """
109 How does dualgraph() work? It sets some global values, then calls __show().
110 """
111
112 def __show():
113 """
114 Graph data of ba using Tk window.
115 """
116 global root, fig, ax, canvas
117 global ba1, ba2
118 global gTitle
119
120 ## Prepare graph labels.
121 ax.clear()
122 if (gTitle==""): gTitle='SPR Data plotted %s' % date.today().isoformat()
123 ax.set_title(gTitle)
124 ax.set_xlabel('Time (s)')
125 ax.set_ylabel('SPR Response')
126 ax.grid(True)
127
128 ## Plot traces of real data.
129 if (ba1 != 0):
130 ## Dotted traces.
131 marker = ['r,', 'g,', 'b,', 'c,', 'm,', 'y,'] + ['k,'] * 100
132 for i,j in enumerate(__roiList()):
133 txt = str(j) + ':' + ba1.roi[j].name
134 t = ba1.roi[j].time
135 y = ba1.roi[j].value
136 ax.plot(t, y, marker[i], label=txt)
137 if (ba2 != 0):
138 ## Line traces.
139 marker = ['r', 'g', 'b', 'c', 'm', 'y'] + ['k'] * 100
140 for i,j in enumerate(__roiList()):
141 txt = str(j) + ':' + ba2.roi[j].name
142 t = ba2.roi[j].time
143 y = ba2.roi[j].value
144 ax.plot(t, y, marker[i], label=txt)
145
146 ## Format legend.
147 leg = ax.legend(loc='upper right')
148 for t in leg.get_texts(): t.set_fontsize('x-small')
149 #for t in leg.get_lines(): t.set_linestyle('None')
150 #labels = [line.get_label() for line in ax.lines]
151 #fig.legend(ax.lines, labels, 'right')
152
153 canvas.draw()
154 return
155 """
156 End of __show().
157 """
158
159 def __btnNext():
160 """
161 Show next six traces on the graph.
162 """
163 global ba0
164 lo = max(__roiList()) + 1
165 if (lo == len(ba0.roi)): return
166 lo = max(lo,0)
167 hi = lo + 6
168 hi = min(hi, len(ba0.roi))
169 ba0.set_plot_list(range(lo, hi))
170 __show()
171 return
172
173 def __btnPrev():
174 """
175 Show the previous six traces on the graph.
176 """
177 global ba0
178 lo = min(__roiList()) - 6
179 lo = max(lo,0)
180 hi = lo + 6
181 hi = min(hi, len(ba0.roi))
182 ba0.set_plot_list(range(lo, hi))
183 __show()
184 return
185
186 def __btnTraces():
187 """
188 Ask for list of traces to show on graph.
189 """
190 global ba0
191 txt = "Which ROIs would you like to see? (e.g. 19,20,21)"
192 txt = dialog.askstring(title="Input",prompt=txt)
193 txt = txt + "," ## Be sure eval() produces a list.
194 ba0.set_plot_list(eval(txt))
195 __show()
196 return
197
198
199 def __roiList():
200 """
201 List of first six plottable ROIs.
202 """
203 global ba0
204 #x = [i for i in range(len(ba.roi)) if ba0.roi[i].plottable]
205 x = [i.index for i in ba0.roi if i.plottable]
206 return x[:6]
207
208
209 def __createSensorgramTkWindow():
210 """
211 Create a Tk window for the Matplotlib graph.
212 This window has three buttons which will allow the user to browse through many traces.
213 """
214 global root, fig, ax, canvas
215 root = Tk.Tk()
216 root.wm_title("TK matplotlib Osprai Sensorgram")
217 ## Prepare a matplotlib Figure/Axes.
218 fig = Figure(figsize=(6,4), dpi=100)
219 ax = fig.add_subplot(111)
220 ax.hold(True) # Hold data until ax.clear().
221 #ax.set_position([0.1, 0.1, 0.6, 0.8]) # Fraction of frame [left,bot,w,h]
222 ## Define tk.DrawingArea
223 canvas = FigureCanvasTkAgg(fig, master=root)
224 #canvas.__show()
225 canvas.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)
226 ## Add a pylab-style toolbar.
227 toolbar = NavigationToolbar2TkAgg( canvas, root )
228 toolbar.update()
229 canvas._tkcanvas.pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)
230 ## Add buttons.
231 button1 = Tk.Button(master=root, text='Next6', command=__btnNext)
232 button1.pack(side=Tk.RIGHT)
233 button2 = Tk.Button(master=root, text='Choose..', command=__btnTraces)
234 button2.pack(side=Tk.RIGHT)
235 button3 = Tk.Button(master=root, text='Prev6', command=__btnPrev)
236 button3.pack(side=Tk.RIGHT)
237 return
238 """
239 End of __createSensorgramTkWindow().
240 """
241
242 ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ##
243
244
245 def scatterplot(ba0, t1, t2, t3, t4, title):
246 """
247 Plot binding changes between (t4-t3) versus (t2-t1).
248 Also print the results to the standard output.
249
250 :param ba0: Object containing the data.
251 :type ba0: BiosensorArray
252 :param t1: Timepoint before binding, first axis.
253 :type t1: float
254 :param t2: Timepoint after binding, first axis.
255 :type t2: float
256 :param t3: Timepoint before binding, second axis.
257 :type t3: float
258 :param t4: Timepoint after binding, second axis.
259 :type t4: float
260 :param title: Title to place above the graph.
261 :type title: str
262 :returns: nothing
263 """
264 root = Tk.Tk()
265 root.wm_title("TK matplotlib Osprai Sensorgram")
266 ## Prepare a matplotlib Figure/Axes.
267 fig = Figure(figsize=(6,4), dpi=100)
268 ax = fig.add_subplot(111)
269 ax.hold(True) # Hold data until ax.clear().
270 ## Define tk.DrawingArea
271 canvas = FigureCanvasTkAgg(fig, master=root)
272 canvas.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)
273 ## Add a pylab-style toolbar.
274 toolbar = NavigationToolbar2TkAgg( canvas, root )
275 toolbar.update()
276 canvas._tkcanvas.pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)
277
278 ## Prepare graph labels.
279 ax.clear()
280 if (title==""): title='Scatterplot of %s' % date.today().isoformat()
281 ax.set_title(title)
282 ax.set_xlabel('Binding12')
283 ax.set_ylabel('Binding34')
284 ax.grid(True)
285
286 ## Get array of values at each of the four time points.
287 y1 = np.array([np.average(iroi.time2val(t1-15, t1+15)) for iroi in ba0.roi])
288 y2 = np.array([np.average(iroi.time2val(t2-15, t2+15)) for iroi in ba0.roi])
289 y3 = np.array([np.average(iroi.time2val(t3-15, t3+15)) for iroi in ba0.roi])
290 y4 = np.array([np.average(iroi.time2val(t4-15, t4+15)) for iroi in ba0.roi])
291 dx, dy = (y2-y1), (y4-y3)
292
293 ## Print to stdout
294 print "Name", "Binding12", "Binding34"
295 for i in range(len(dx)): print ba0.roi[i].name, dx[i], dy[i]
296
297 ## Plot
298 ax.plot(dx, dy, 'bo') ## Blue circles with 'bo'.
299 canvas.draw()
300 root.mainloop()
301 return
302 """
303 How does scatterplot() work?
304 First create a Tk window for the scatterplot graph.
305 Variables root, fig, ax, canvas are local here, not global.
306 Use list comprehensions to get list of average signal 30 sec around t1, t2, t3, t4.
307 Plot signal change between t1-t2 against t3-t4. Also print to std output.
308 """
309
310
311 ## Print a message to the users so they see this module is loaded.
312 #print "Loaded vu_module.py version ", __version__
313
314 ################################# End of module #################################