source: trunk/src/testing/bin/performance_server.py @ 4

Revision 4, 15.8 KB checked in by ajaworski, 13 years ago (diff)

Added modified SAGE sources

  • Property svn:executable set to *
Line 
1#!/usr/bin/env python
2
3############################################################################
4#
5# SAGE LAUNCHER - A GUI for launching SAGE and all related components
6#
7# Copyright (C) 2007 Electronic Visualization Laboratory,
8# University of Illinois at Chicago
9#
10# All rights reserved.
11#
12# Redistribution and use in source and binary forms, with or without
13# modification, are permitted provided that the following conditions are met:
14#
15#  * Redistributions of source code must retain the above copyright
16#    notice, this list of conditions and the following disclaimer.
17#  * Redistributions in binary form must reproduce the above
18#    copyright notice, this list of conditions and the following disclaimer
19#    in the documentation and/or other materials provided with the distribution.
20#  * Neither the name of the University of Illinois at Chicago nor
21#    the names of its contributors may be used to endorse or promote
22#    products derived from this software without specific prior written permission.
23#
24# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
25# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
26# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
27# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
28# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
29# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
30# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
31# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
32# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
33# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
34# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
35#
36# Direct questions, comments etc about SAGE UI to www.evl.uic.edu/cavern/forum
37#
38#
39############################################################################
40
41import Numeric, random
42import socket, sys, os
43from wx.lib.plot import *
44
45ARRAY_SIZE=100
46
47class LineFrame(wx.Dialog):
48    def _createObjects(self):
49        print "create ", self.numgraphs, "graphs"
50        self.current = {}
51        self.datasets = {}
52        for i in range(self.numgraphs):
53            self.current[i] = 0
54            self.datasets[i] = Numeric.arange(ARRAY_SIZE*2)/float(ARRAY_SIZE*2)
55            self.datasets[i].shape = (ARRAY_SIZE, 2)
56            self.datasets[i][:,1] = 0
57       
58    def _addPoint(self,values):
59        x = float(values[0])
60        for j in range(self.numgraphs):
61            ar = [x, float(values[j+1])]
62            if self.current[j] < ARRAY_SIZE:
63                for i in range(self.current[j],ARRAY_SIZE):
64                    self.datasets[j][i] = ar
65                self.current[j] = self.current[j] + 1
66            else:
67                for i in range(1,ARRAY_SIZE):
68                    self.datasets[j][i-1] = self.datasets[j][i]
69                self.datasets[j][ARRAY_SIZE-1] = ar
70        self.client.Draw(self._drawObjects())
71       
72    def _drawObjects(self):
73        # ARRAY_SIZE points, plotted as red line
74        lines = []
75        for i in range(self.numgraphs):
76            lines.append( PolyLine(self.datasets[i], legend=self.ytitle[i], width=3,
77                                   colour=self.colors[i%6]) )
78        return PlotGraphics(lines, self.title, self.xtitle, "")
79
80    def __init__(self, parent, id, title):
81        wx.Dialog.__init__(self, parent, id, title,
82                          wx.DefaultPosition, (600, 400),style=wx.DEFAULT_FRAME_STYLE)
83        self.frame = parent
84
85        # Network connection
86        self.conn = None
87       
88        # self.timer = wx.Timer(self)
89        # self.timer.Start(10)
90        # self.Bind(wx.EVT_TIMER, self.OnTimer)
91        self.Bind(wx.EVT_IDLE, self.OnTimer)
92       
93        self.client = PlotCanvas(self)
94        # Create mouse event for showing cursor coords in status bar
95        self.client.Bind(wx.EVT_LEFT_DOWN, self.OnMouseLeftDown)
96        self.Show(True)
97
98        self.colors = ['red', 'blue', 'black', 'green', 'yellow', 'cyan', 'magenta' ]
99       
100        # settings
101        self.title  = title
102        self.xtitle = "X Title"
103        self.ytitle = {}
104        self.ytitle[0] = "Y Title"
105        self.numgraphs = 1
106        self.client.SetEnableLegend(0)
107        self.client.SetEnableGrid(1)
108
109        # draw
110        self.resetDefaults()
111
112    def SetClient(self, conn):
113        self.conn = conn
114
115    def SetNumGraphs(self, n):
116        self.numgraphs = n
117        self._createObjects()
118    def SetTitle(self, t):
119        self.title = t
120    def SetXtitle(self, t):
121        self.xtitle = t
122    def SetYtitle(self, ind, t):
123        self.ytitle[ind] = t
124        self.numgraphs = ind+1
125
126    def OnTimer(self, event):
127        if self.conn:
128            data = 1
129            it = 0
130            while data and (it<5):
131                try:
132                    msglen = 12*(self.numgraphs+1) + self.numgraphs
133                    data = self.conn.recv(msglen)
134                    if data:
135                        values = data.split()
136                        self._addPoint(values)
137                        it = it + 1
138                    else:
139                        return
140                except:
141                    return
142        self.client.Draw(self._drawObjects())
143        #event.RequestMore(True)
144       
145    def OnMouseLeftDown(self,event):
146        s= "Left Mouse Down at Point: (%.4f, %.4f)" % self.client.GetXY(event)
147        self.frame.SetStatusText(s)
148        event.Skip()
149
150    def OnFilePageSetup(self, event):
151        self.client.PageSetup()
152       
153    def OnFilePrintPreview(self, event):
154        self.client.PrintPreview()
155       
156    def OnFilePrint(self, event):
157        self.client.Printout()
158       
159    def OnSaveFile(self, event):
160        self.client.SaveFile()
161
162    def OnFileExit(self, event):
163        self.Close()
164
165    def OnPlotRedraw(self,event):
166        self.client.Redraw()
167
168    def OnPlotClear(self,event):
169        self.client.Clear()
170       
171    def OnPlotScale(self, event):
172        if self.client.last_draw != None:
173            graphics, xAxis, yAxis= self.client.last_draw
174            self.client.Draw(graphics,(1,3.05),(0,1))
175
176    def OnEnableZoom(self, event):
177        self.client.SetEnableZoom(event.IsChecked())
178       
179    def OnEnableGrid(self, event):
180        self.client.SetEnableGrid(event.IsChecked())
181       
182    def OnEnableLegend(self, event):
183        self.client.SetEnableLegend(event.IsChecked())
184
185    def OnScrUp(self, event):
186        self.client.ScrollUp(1)
187       
188    def OnScrRt(self,event):
189        self.client.ScrollRight(2)
190
191    def OnReset(self,event):
192        self.client.Reset()
193
194    def OnHelpAbout(self, event):
195        from wx.lib.dialogs import ScrolledMessageDialog
196        about = ScrolledMessageDialog(self, __doc__, "About...")
197        about.ShowModal()
198
199    def resetDefaults(self):
200        """Just to reset the fonts back to the PlotCanvas defaults"""
201        self.client.SetFont(wx.Font(12,wx.SWISS,wx.NORMAL,wx.NORMAL))
202        self.client.SetFontSizeAxis(12)
203        self.client.SetFontSizeLegend(12)
204        self.client.SetXSpec('auto')
205        self.client.SetYSpec('auto')
206       
207
208class MatrixCanvas(wx.Window):
209    def __init__(self, parent, id = -1, pos=wx.DefaultPosition,
210            size=wx.DefaultSize, style= wx.DEFAULT_FRAME_STYLE, name= ""):
211        wx.Window.__init__(self, parent, id, pos, size, style, name)
212        self.border = (1,1)
213
214        self.SetBackgroundColour("black")
215       
216        self.Bind(wx.EVT_PAINT, self.OnPaint)
217        self.Bind(wx.EVT_SIZE, self.OnSize)
218       
219        self.parent= parent
220
221        self.last_draw = None
222
223        # now on Mac, this seems to be a problem
224        #self.OnSize(None) # sets the initial size based on client size
225
226       
227    def Draw(self, graphics):
228        # allows using floats for certain functions
229        dc = wx.BufferedDC(wx.ClientDC(self), self._Buffer)
230           
231        dc.BeginDrawing()
232        dc.Clear()
233
234        Size  = self.GetClientSize()
235        width, height, colors =  graphics
236        stepw = (Size[0] - 60) / width
237        steph = (Size[1] - 60) / height
238        dc.SetPen(wx.Pen(wx.BLUE,1))
239        k = 0
240        for i in range(width):
241            for j in range(height):
242                dc.SetBrush(wx.Brush(colors[k]))
243                #if os.uname()[0] == 'Darwin':
244                #    dc.DrawRectangle( (30+i*stepw,30+j*steph), (stepw,steph))
245                #else:
246                dc.DrawRectangle( 30+i*stepw,30+j*steph, stepw,steph)
247                k = k + 1
248        self.last_draw = graphics
249
250        dc.EndDrawing()
251       
252    def Redraw(self, dc= None):
253        """Redraw the existing plot."""
254        if self.last_draw:
255            self.Draw(last_draw)
256
257    def Clear(self):
258        """Erase the window."""
259        dc = wx.BufferedDC(wx.ClientDC(self), self._Buffer)
260        dc.Clear()
261        self.last_draw = None
262
263    def OnPaint(self, event):
264        # All that is needed here is to draw the buffer to screen
265        dc = wx.BufferedPaintDC(self, self._Buffer)       
266       
267    def OnSize(self,event):
268        # The Buffer init is done here, to make sure the buffer is always
269        # the same size as the Window
270        Size = self.GetClientSize()
271        self._Buffer = wx.EmptyBitmap(Size[0],Size[1])
272        if self.last_draw is None:
273            self.Clear()
274        else:
275            self.Draw(self.last_draw)
276
277       
278class MatrixFrame(wx.Dialog):
279    def _createObjects(self):
280        print "create matrix"
281        self.data = Numeric.arange(self.w*self.h)/3.0
282        self.data.shape = (self.w,self.h)
283        self.data[:] = 0.0
284
285    def _drawObjects(self):       
286        ar = []
287        for i in range(self.w):
288            for j in range(self.h):
289                val = self.data[i][j]
290                col = wx.Color( int(val*255.),
291                                int(val*255.),
292                                int(val*255.))
293                ar.append( col )
294        return (self.w, self.h, ar)
295
296    def _addPoint(self,values):
297        x   = int(values[0])
298        y   = int(values[1])
299        val = float(values[2])
300        self.data[x][y] = val
301        self.client.Draw(self._drawObjects())
302       
303    def __init__(self, parent, id, title, xs, ys):
304        wx.Dialog.__init__(self, parent, id, title,
305                          wx.DefaultPosition, (500, 400),style=wx.DEFAULT_FRAME_STYLE)
306        self.frame = parent
307
308        # Network connection
309        self.conn = None
310
311        # Drawing object
312        self.client = MatrixCanvas(self)       
313       
314        self.Bind(wx.EVT_IDLE, self.OnTimer)
315        self.Show(True)
316
317        self.w = xs
318        self.h = ys
319        print "Matrix size", xs, ys
320
321        self._createObjects()
322       
323        # settings
324        self.title  = title
325        self.xtitle = "X Title"
326        self.ytitle = "Y Title"
327
328    def SetClient(self, conn):
329        self.conn = conn
330    def SetTitle(self, t):
331        self.title = t
332    def SetXtitle(self, t):
333        self.xtitle = t
334    def SetYtitle(self, t):
335        self.ytitle = t
336
337    def OnTimer(self, event):
338        if self.conn:
339            data = 1
340            it = 0
341            while data and (it<5):
342                try:
343                    msglen = 6 + 1 + 6 + 1 + 12  # x y value
344                    data = self.conn.recv(msglen)
345                    if data:
346                        values = data.split()
347                        self._addPoint(values)
348                        it = it + 1
349                    else:
350                        return
351                except:
352                    return
353        self.client.Draw(self._drawObjects())
354        #event.RequestMore(True)
355
356class MyApp(wx.App):
357
358    def OnIdle(self, event):
359        try:
360            conn, addr = self.s.accept()
361            conn.setblocking(1)
362            print 'Connected by', addr
363            type = conn.recv(64)
364            type = type.strip()
365            print "\t type[", type, "]"
366            if type == "lines":
367                title = conn.recv(64)
368                title = title.strip()
369                print "\t title[", title, "]"
370                xtitle = conn.recv(64)
371                xtitle = xtitle.strip()
372                print "\t xtitle[", xtitle, "]"
373                numgraphs = int( conn.recv(6) )
374                print "\t numgraphs", numgraphs
375                ytitle = {}
376                for i in range(numgraphs):
377                    ytitle[i] = conn.recv(64)
378                    ytitle[i] = ytitle[i].strip()
379                    print "\t\t graph", i, " name[", ytitle[i], "]"
380                frame = LineFrame(self.myframe, -1, title)
381                frame.SetNumGraphs(numgraphs)
382                frame.SetXtitle(xtitle)
383                for i in range(numgraphs):
384                    frame.SetYtitle(i, ytitle[i])
385                frame.SetClient(conn)
386                conn.send("1")
387                conn.setblocking(0)
388            if type == "matrix":
389                title = conn.recv(64)
390                title = title.strip()
391                print "\t title[", title, "]"
392                xtitle = conn.recv(64)
393                xtitle = xtitle.strip()
394                print "\t xtitle[", xtitle, "]"
395                sizes = conn.recv(13)
396                sizes = sizes.strip()
397                xs,ys = sizes.split()
398                xs = int(xs)
399                ys = int(ys)
400                numgraphs = 2
401                print "\t numgraphs", numgraphs
402                ytitle = {}
403                for i in range(numgraphs):
404                    ytitle[i] = conn.recv(64)
405                    ytitle[i] = ytitle[i].strip()
406                    print "\t\t graph", i, " name[", ytitle[i], "]"
407                frame = MatrixFrame(self.myframe, -1, title, xs, ys)
408                #frame.SetXtitle(xtitle)
409                #for i in range(numgraphs):
410                #    frame.SetYtitle(i, ytitle[i])
411                frame.SetClient(conn)
412                conn.send("1")
413                conn.setblocking(0)
414        except:
415            pass
416        event.RequestMore(True)
417
418    def OnInit(self):
419        wx.InitAllImageHandlers()
420        self.myframe= wx.Frame(None, -1, "MainFrame")
421
422        self.Bind(wx.EVT_IDLE, self.OnIdle)
423       
424        # Now Create the menu bar and items
425        self.myframe.mainmenu = wx.MenuBar()
426
427        menu = wx.Menu()
428        menu.Append(200, 'Page Setup...', 'Setup the printer page')       
429        menu.Append(201, 'Print Preview...', 'Show the current plot on page')
430        menu.Append(202, 'Print...', 'Print the current plot')
431        menu.Append(203, 'Save Plot...', 'Save current plot')
432        menu.Append(205, 'E&xit', 'Enough of this already!')
433        self.myframe.mainmenu.Append(menu, '&File')
434
435        menu = wx.Menu()
436
437        menu.Append(211, '&Redraw', 'Redraw plots')
438        menu.Append(212, '&Clear', 'Clear canvas')
439        menu.Append(213, '&Scale', 'Scale canvas')
440        menu.Append(214, 'Enable &Zoom', 'Enable Mouse Zoom', kind=wx.ITEM_CHECK)
441        menu.Append(215, 'Enable &Grid', 'Turn on Grid', kind=wx.ITEM_CHECK)
442        menu.Append(220, 'Enable &Legend', 'Turn on Legend', kind=wx.ITEM_CHECK)
443        menu.Append(225, 'Scroll Up 1', 'Move View Up 1 Unit')
444        menu.Append(230, 'Scroll Rt 2', 'Move View Right 2 Units')
445        menu.Append(235, '&Plot Reset', 'Reset to original plot')
446
447        self.myframe.mainmenu.Append(menu, '&Plot')
448
449        menu = wx.Menu()
450        menu.Append(300, '&About', 'About this thing...')
451        self.myframe.mainmenu.Append(menu, '&Help')
452
453        self.myframe.SetMenuBar(self.myframe.mainmenu)
454
455        # A status bar to tell people what's happening
456        self.myframe.CreateStatusBar(1)
457        self.myframe.Show(True)
458
459        HOST = ''                 # Symbolic name meaning the local host
460        PORT = 50008              # Arbitrary non-privileged port
461        self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
462        self.s.bind((HOST, PORT))
463        self.s.listen(5)
464        self.s.setblocking(0)
465                   
466        self.SetTopWindow(self.myframe)
467       
468        return True
469
470           
471app = MyApp(0)
472app.MainLoop()
473
Note: See TracBrowser for help on using the repository browser.