viewer modification: add start/stop time
authorMarius Sandu-Popa <sandupopamarius@gmail.com>
Fri, 20 Nov 2009 12:11:01 +0000 (14:11 +0200)
committerMarius Sandu-Popa <sandupopamarius@gmail.com>
Fri, 20 Nov 2009 12:11:30 +0000 (14:11 +0200)
viewer/config.py [new file with mode: 0644]
viewer/p2p-nexteditor.py
viewer/test3.py

diff --git a/viewer/config.py b/viewer/config.py
new file mode 100644 (file)
index 0000000..da5acfc
--- /dev/null
@@ -0,0 +1,2 @@
+dbpath='../auto/db/'
+dbextension='.db'
\ No newline at end of file
index 7fb716a..3833f85 100644 (file)
@@ -5,45 +5,69 @@ from enthought.traits.ui.api import *
 from enthought.traits.ui.menu import NoButtons
 from mpleditor import MPLFigureEditor
 from matplotlib.figure import Figure
+from matplotlib.dates import *
 from scipy import *
 from DbObjects import *
-from julian import julianToDatetime
+from datetime import datetime, timedelta
+from time import strptime
+from julian import *
+from config import *
 import sys
 import getopt
 import wx
 
-class AcquisitionThread(Thread):
-    def __init__ (self, dbname, plot_figure, cs_id, download_speed=None, upload_speed=None):
-       Thread.__init__(self)
-       self.dbname=dbname
-       self.plot_figure = plot_figure
-       self.cs_id = cs_id
-       self.download_speed = download_speed
-       self.upload_speed = upload_speed
+class PlotterThread(Thread):
+    def __init__ (self, dbname, cs_id, plot_figure, options):
+       Thread.__init__(self)
+       self.dbname = dbname
+        self.cs_id = cs_id
+       self.plot_figure = plot_figure
+        self.options = options
        
     def run(self):
-       cs = ClientSession(self.dbname, self.cs_id)
-       stmc = StatusMessageCollection(self.dbname, self.cs_id)
-       stmit = stmc.getIter()
-       x = []
-       y1 = []
-       y2 = []
-       while True:
-           try:
-               stm = next(stmit)
-           except StopIteration:
-               break
-           difftime =julianToDatetime(stm.timestamp)-julianToDatetime(cs.start_time)
-           x.append(difftime.seconds) 
-           if self.download_speed:
-               y1.append(stm.download_speed)
-           if self.upload_speed:
-               y2.append(stm.upload_speed)
-       self.plot_figure(x, y1, y2)
-       
+       cs = ClientSession(self.dbname, self.cs_id)
+        x = []; y1 = []; y2 = []
+        restrictions = []
+        date2 = julianToDatetime(cs.start_time)
+        td = timedelta(days=date2.day, \
+             seconds=date2.second, \
+             minutes=date2.minute, \
+             hours=date2.hour, \
+             microseconds=date2.microsecond)
+        
+        if self.options[2]:
+            date_start = self.time_from_date(date2, self.options[2])            
+            restrictions.append(('timestamp', float(datetimeToJulian(date_start)), 'gte'))
+        
+        if self.options[3]:
+            date_stop = self.time_from_date(date2, self.options[3])
+            restrictions.append(('timestamp', float(datetimeToJulian(date_stop)), 'lte'))
+           
+        stmc = StatusMessageCollection(self.dbname, self.cs_id, restrictions)
+       stmit = stmc.getIter()
+       while True:
+           try:
+                     stm = next(stmit)
+           except StopIteration:
+                 break
+            date1 = julianToDatetime(stm.timestamp)
+            difftime = date1 - td
+           x.append(date2num(difftime))
+           if self.options[0]:
+                 y1.append(stm.download_speed)
+           if self.options[1]:
+                 y2.append(stm.upload_speed)
+       self.plot_figure(x, y1, y2)
+
+    def time_from_date(self, date, tstr):
+        time = strptime(tstr, "%H:%M:%S")
+        td = timedelta(seconds=time.tm_sec, minutes=time.tm_min, hours=time.tm_hour)
+        return (date + td)
+
+
 class ControlPanel(HasTraits):
     #swarm widget
-    sw_id = String(auto_set=False, enter_set=True)
+    dbname = String(auto_set=False, enter_set=True)
     sw_torrent = String()
     sw_filesize = String()
     sw_purpose = String ()
@@ -68,8 +92,10 @@ class ControlPanel(HasTraits):
     cs_ds_limit = String()
     cs_us_limit = String()
     cs_start_time = CStr()
-    
+
     #options widget
+    time_start = Str()
+    time_stop = Str()
     download_speed = Bool()
     upload_speed = Bool()
     plot = Button()
@@ -79,41 +105,44 @@ class ControlPanel(HasTraits):
                version 1.00
     ''')
     
-    def __init__(self, figure, dbname):
-       self.dbname=dbname;
-       self.figure = figure;
-       self.axes = self.figure.add_axes((0.04,0.06,0.93,0.91))
-       self.axes.grid(linestyle='dashed')
-       #self.line = None
+    def __init__(self, figure):
+       self.figure = figure;
+        self.axes = self.figure.add_axes((0.04, 0.06, 0.93, 0.91))
+       self.axes.grid(linestyle='dashed')
        
     view = View(Group(
-                    Group(Group(
-                           Item('sw_id', label='Id', style='text'),
-                           Item('10'),
-                           Item('sw_torrent', label='Torrent'),
-                           Item('sw_filesize', label='Filesize(Kb)'),
-                           Item('sw_purpose', label='Purpose'),
-                           Item('sw_source', label='Source'),
-                           show_border=True, label='Swarm', style = 'readonly'),
-                       Item('20'),
-                       Group(
-                           Item('cs_id', label='Id', style='text'),
-                           Item('10'),
-                           Item('cs_os', label='OS'),
-                           Item('cs_os_vs', label='OS Version'),
-                           Item('cs_os_cpu', label='System CPU'),
-                           Item('cs_os_ram', label='System RAM'),
-                           Item('cs_public_ip', label='Public IP'),
-                           Item('cs_public_port', label='Public PORT'),
-                           Item('cs_ds_limit', label='Download LMT'),
-                           Item('cs_us_limit', label='Upload LMT'),
-                           Item('cs_start_time', label='Start Time'),
-                           show_border=True, label='Client Session', style = 'readonly'),
-                       HGroup('download_speed', 'upload_speed',
-                           show_border=True, label='Options'),
-                       Item('20'),
-                       Item('plot', show_label=False),
-                       label="Control", dock='tab', style='simple'),
+                    Group(
+                        Item('dbname', label='Database File', style='text'),
+                               Item('20'),
+                        Group(
+                                   Item('sw_torrent', label='Torrent'),
+                                   Item('sw_filesize', label='Filesize(Kb)'),
+                                   Item('sw_purpose', label='Purpose'),
+                                   Item('sw_source', label='Source'),
+                                   show_border=True, label='Swarm', style='readonly'),
+                               Item('10'),
+                        Group(
+                                   Item('cs_id', label='Id', style='simple'),
+                                   Item('10'),
+                                   Item('cs_os', label='OS'),
+                                   Item('cs_os_vs', label='OS Version'),
+                                   Item('cs_os_cpu', label='System CPU'),
+                                   Item('cs_os_ram', label='System RAM'),
+                                   Item('cs_public_ip', label='Public IP'),
+                                   Item('cs_public_port', label='Public PORT'),
+                               Item('cs_ds_limit', label='Download LMT'),
+                                   Item('cs_us_limit', label='Upload LMT'),
+                                   Item('cs_start_time', label='Start Time'),
+                                   show_border=True, label='Client Session', style='readonly'),
+                               Group(
+                        HGroup(Item('time_start', label='Start'),
+                               Item('40'),
+                               Item('time_stop', label='Stop')),
+                        HGroup('download_speed',Item('30'), 'upload_speed'),
+                               show_border=True, label='Options'),
+                        Item('10'),
+                               Item('plot', show_label=False),
+                               label="Control", dock='tab', style='simple'),
                     #Group(
                         #Group(
                             #Item('experiment', style='custom', show_label=False),
@@ -122,59 +151,63 @@ class ControlPanel(HasTraits):
                             #Item('results', style='custom', show_label=False),
                             #label="Results",),
                     #label='Experiment', dock="tab"),
-                Item('help', style='readonly', show_label=False,  dock="tab"),
+                Item('help', style='readonly', show_label=False, dock="tab"),
                 layout='tabbed')
                 )
     
-    def _sw_id_fired(self):
-       sw = Swarm(self.dbname, self.sw_id);
-       self.sw_torrent = sw.torrent
-       self.sw_filesize = sw.filesize;
-       self.sw_purpose = sw.purpose;
-       self.sw_source = sw.source;
+    def _dbname_changed(self):
+       sw = Swarm(dbpath + self.dbname + dbextension, -1);
+       self.sw_id = sw.id;
+       self.sw_torrent = sw.torrent
+       self.sw_filesize = sw.filesize;
+       self.sw_purpose = sw.purpose;
+       self.sw_source = sw.source;
     
-    def _cs_id_fired(self):
-       cs = ClientSession(self.dbname, self.cs_id);
-       self.cs_os = cs.system_os
-       self.cs_os_vs = cs.system_os_version
-       self.cs_os_cpu = cs.system_cpu
-       self.cs_os_ram = cs.system_ram
-       self.cs_public_ip = cs.public_ip
-       self.cs_public_port = cs.public_port
-       self.cs_ds_limit = cs.ds_limit
-       self.cs_us_limit = cs.us_limit
-       self.cs_start_time = julianToDatetime(cs.start_time)
+    def _cs_id_changed(self, new):
+       cs = ClientSession(dbpath + self.dbname + dbextension, new);
+       self.cs_os = cs.system_os
+       self.cs_os_vs = cs.system_os_version
+       self.cs_os_cpu = cs.system_cpu
+       self.cs_os_ram = cs.system_ram
+       self.cs_public_ip = cs.public_ip
+       self.cs_public_port = cs.public_port
+       self.cs_ds_limit = cs.ds_limit
+       self.cs_us_limit = cs.us_limit
+       self.cs_start_time = julianToDatetime(cs.start_time)
        
     def _plot_fired(self):
-       if len(self.cs_id) and (self.download_speed or self.upload_speed):
-           self.axes.clear()
-           self.axes.grid(linestyle='dashed')
-           AcquisitionThread(self.dbname, self.plot_figure, self.cs_id, self.download_speed, self.upload_speed).start()
+       if len(self.cs_id) and (self.download_speed or self.upload_speed):
+           self.axes.clear()
+           self.axes.grid(linestyle='dashed')
+            dbfile = dbpath + self.dbname + dbextension
+            options = [self.download_speed, self.upload_speed, self.time_start, self.time_stop]
+           PlotterThread(dbfile, self.cs_id, self.plot_figure, options).start()
 
     def plot_figure(self, x, y1, y2):
-       if y1:
-           self.axes.plot(x, y1, label='download speed')
-       if y2:
-           self.axes.plot(x, y2, label='upload speed')
-       self.axes.legend(shadow=True, fancybox=True)
-       self.axes.set_xlabel("time (s)")
-       wx.CallAfter(self.figure.canvas.draw)
-       
+       if y1:
+           self.axes.plot_date(x, y1, 'b-', label='download speed')
+       if y2:
+           self.axes.plot_date(x, y2, 'r-', label='upload speed')
+        self.axes.xaxis.set_major_formatter(DateFormatter('%H:%M:%S'))
+       self.axes.set_xlabel("time (s)")
+        self.axes.legend(shadow=True, fancybox=True)
+        self.figure.autofmt_xdate(rotation=25)
+       wx.CallAfter(self.figure.canvas.draw)
+    
 class MainWindow(HasTraits):
     figure = Instance(Figure)
     panel = Instance(ControlPanel)
-    dbname = sys.argv[1];
     
     def _figure_default(self):
         figure = Figure()
         return figure
 
     def _panel_default(self):
-        return ControlPanel(figure=self.figure, dbname=self.dbname)
+        return ControlPanel(figure=self.figure)
 
     view = View(HSplit(Item('figure', editor=MPLFigureEditor(),
                             dock='vertical'),
-                       Item('panel', style="custom", springy=True, width=-100),
+                       Item('panel', style="custom", springy=True, width= -100),
                        show_labels=False,
                       ),
                title='Editor',
@@ -184,3 +217,4 @@ class MainWindow(HasTraits):
 
 if __name__ == '__main__':
     MainWindow().configure_traits()
+
index ae5faa1..7d8a28a 100755 (executable)
@@ -1,35 +1,54 @@
-#!/usr/bin/env python
-
-# For detailed comments on animation and the techniques used here, see
-# the wiki entry
-# http://www.scipy.org/wikis/topical_software/MatplotlibAnimation
-import time
-
-import gtk, gobject
-
+"""
+An example of how to use pylab to manage your figure windows, but
+modify the GUI by accessing the underlying gtk widgets
+"""
 import matplotlib
 matplotlib.use('GTKAgg')
-
-import numpy as np
-import matplotlib.pyplot as plt
-import pipong
-from numpy.random import randn, randint
-
-
-fig = plt.figure()
-ax = fig.add_subplot(111)
-canvas = ax.figure.canvas
-
-
-def start_anim(event):
-    gobject.idle_add(animation.draw,animation)
-    canvas.mpl_disconnect(start_anim.cid)
-
-animation = pipong.Game(ax)
-start_anim.cid = canvas.mpl_connect('draw_event', start_anim)
-
-
-tstart = time.time()
-plt.grid() # to ensure proper background restore
-plt.show()
-print 'FPS:' , animation.cnt/(time.time()-tstart)
\ No newline at end of file
+from pylab import get_current_fig_manager, subplot, plot, legend, connect, show
+
+ax = subplot(111)
+plot([1,2,3], 'ro-', label='easy as 1 2 3')
+plot([1,4,9], 'gs--', label='easy as 1 2 3 squared')
+legend()
+
+
+manager = get_current_fig_manager()
+# you can also access the window or vbox attributes this way
+toolbar = manager.toolbar
+
+# now let's add a button to the toolbar
+import gtk
+next = 8; #where to insert this in the mpl toolbar
+button = gtk.Button('Click me')
+button.show()
+
+def clicked(button):
+    print 'hi mom'
+button.connect('clicked', clicked)
+
+toolitem = gtk.ToolItem()
+toolitem.show()
+toolitem.set_tooltip(
+    toolbar.tooltips,
+    'Click me for fun and profit')
+
+toolitem.add(button)
+toolbar.insert(toolitem, next); next +=1
+
+# now let's add a widget to the vbox
+label = gtk.Label()
+label.set_markup('Drag mouse over axes for position')
+label.show()
+vbox = manager.vbox
+vbox.pack_start(label, False, False)
+vbox.reorder_child(manager.toolbar, -1)
+
+def update(event):
+    if event.xdata is None:
+        label.set_markup('Drag mouse over axes for position')
+    else:
+        label.set_markup('<span color="#ef0000">x,y=(%f, %f)</span>'%(event.xdata, event.ydata))
+
+connect('motion_notify_event', update)
+
+show()
\ No newline at end of file