/[ascend]/trunk/pygtk/gtkbrowser.py
ViewVC logotype

Contents of /trunk/pygtk/gtkbrowser.py

Parent Directory Parent Directory | Revision Log Revision Log


Revision 915 - (show annotations) (download) (as text)
Sat Oct 28 07:06:22 2006 UTC (15 years, 8 months ago) by johnpye
File MIME type: text/x-python
File size: 34447 byte(s)
Working on what the problem is with 'on_load' methods in the C++/Python code.
Seems that 'EXTERNAL solve(SELF);' puts the model into a state which 'works' but if that's
not done first, then that set values in the model don't work correctly...
1 #!/usr/bin/env python
2
3 import sys
4 def print_loading_status(status,msg=None):
5 sys.stderr.write("\r \r")
6 if msg!=None:
7 sys.stderr.write(msg+"\n")
8 sys.stderr.write(status+"...\r")
9 sys.stderr.flush()
10
11 try:
12 #print_loading_status("Loading PSYCO")
13 #try:
14 # import psyco
15 # psyco.full()
16 # print "Running with PSYCO optimisation..."
17 #except ImportError:
18 # pass
19
20
21 print_loading_status("Loading python standard libraries")
22
23 import re
24 import urlparse
25 import optparse
26 import platform
27 import sys
28 import os.path
29
30 if platform.system() != "Windows":
31 import dl
32 # This sets the flags for dlopen used by python so that the symbols in the
33 # ascend library are made available to libraries dlopened within ASCEND:
34 sys.setdlopenflags(dl.RTLD_GLOBAL|dl.RTLD_NOW)
35
36 print_loading_status("Loading LIBASCEND/ascpy")
37 import ascpy
38
39 print_loading_status("Loading PyGTK, glade, pango")
40
41 import pygtk
42 pygtk.require('2.0')
43 import gtk
44 import gtk.glade
45 import pango
46
47 print_loading_status("Loading python matplotlib")
48 try:
49 import matplotlib
50 matplotlib.use('GTKAgg')
51
52 try:
53 print_loading_status("Trying python numarray")
54 import numarray
55 matplotlib.rcParams['numerix'] = 'numarray'
56 print_loading_status("","Using python module numarray")
57 except ImportError:
58 try:
59 print_loading_status("Trying python numpy")
60 import numpy
61 matplotlib.rcParams['numerix'] = 'numpy'
62 print_loading_status("","Using python module numpy")
63 except ImportError:
64 try:
65 print_loading_status("Trying python Numeric")
66 import Numeric
67 matplotlib.rcParams['numerix'] = 'Numeric'
68 print_loading_status("","Using python module Numeric")
69 except ImportError:
70 print_loading_status("","FAILED TO LOAD A NUMERIC MODULE FOR PYTHON")
71
72 except ImportError,e:
73 print_loading_status("","FAILED TO LOAD MATPLOTLIB")
74 raise RuntimeError("Failed to load MATPLOTLIB (is it installed?). Details:"+str(e))
75
76 print_loading_status("Loading IPython")
77 import console;
78 if not console.have_ipython:
79 print_loading_status("","IPython couldn't be loaded")
80
81 print_loading_status("Loading ASCEND python modules")
82 from preferences import * # loading/saving of .ini options
83 from solverparameters import * # 'solver parameters' window
84 from help import * # viewing help files
85 from incidencematrix import * # incidence/sparsity matrix matplotlib window
86 from observer import * # observer tab support
87 from properties import * # solver_var properties dialog
88 from varentry import * # for inputting of variables with units
89 from diagnose import * # for diagnosing block non-convergence
90 from solverreporter import * # solver status reporting
91 from modelview import * # model browser
92 from integrator import * # integrator dialog
93 from infodialog import * # general-purpose textual information dialog
94 from versioncheck import * # version check (contacts ascend.cruncher2.dyndns.org)
95 import config
96
97 except RuntimeError, e:
98 print "ASCEND had problems starting up. Please report the following"
99 print "error message at http://mantis.cruncher2.dyndns.org/."
100 print "\n\nFull error message:",str(e)
101 print "\n\nPress ENTER to close this window."
102 sys.stdout.flush()
103 sys.stdin.readline();
104 sys.exit();
105
106 except ImportError, e:
107 print "\n\n------------------ ERROR ---------------------"
108 print "ASCEND had problems importing required models."
109 print "\nPlease ensure you have all the runtime prerequisites installed."
110 print "Please then report a bug if you continue to have problems."
111 print "\nFull error message:",str(e)
112 if platform.system()=="Windows":
113 print "\nYou will also need to report the contents of any popup error"
114 print "messages from Windows if any were shown."
115 print "\n\nPress ENTER to close this window."
116 sys.stdout.flush()
117 sys.stdin.readline();
118 sys.exit();
119
120 print_loading_status("Starting GUI")
121
122 # This is my first ever GUI code so please be nice :)
123 # But I *have* at least read
124 # http://www.joelonsoftware.com/uibook/chapters/fog0000000057.html
125 # and leafed through
126 # http://developer.gnome.org/projects/gup/hig/
127
128 # The fancy tree-view gizmo is the GtkTreeView object. See the article
129 # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/300304
130 # for the original source code on which my implementation was based.
131
132 ESCAPE_KEY = 65307
133
134 HELP_ROOT = None
135
136 #======================================
137 # Browser is the main ASCEND library/model browser window
138
139 class Browser:
140
141 # ---------------------------------
142 # SETUP
143
144 def __init__(self,librarypath=None,assetspath=None):
145
146 if assetspath==None:
147 assetspath=config.PYGTK_ASSETS
148
149 #--------
150 # load the file referenced in the command line, if any
151
152 print_loading_status("Parsing options","CONFIG = %s"%config.VERSION)
153
154 parser = optparse.OptionParser(usage="%prog [[-m typename] file]", version="gtkbrowser $rev$" )
155 # add options here if we want
156
157 parser.add_option("-m", "--model"
158 ,action="store", type="string", dest="model"
159 ,help="specify the model to instantiate upon loading modules")
160
161 parser.add_option("--pygtk-assets"
162 ,action="store", type="string", dest="assets_dir"
163 ,help="override the configuration value for the location of assets"\
164 +" required by PyGTK for the ASCEND GUI, optional"
165 ,default=assetspath
166 )
167
168 parser.add_option("--library"
169 ,action="store", type="string", dest="library_path"
170 ,help="override the configuration value for the library path"
171 ,default=librarypath
172 )
173
174 parser.add_option("--no-auto-sim"
175 ,action="store_false", dest="auto_sim"
176 ,help="disable auto-instantiation of MODEL named as the file stem"
177 ,default=True
178 )
179
180 (self.options, args) = parser.parse_args()
181
182 #print "OPTIONS_______________:",self.options
183
184 self.assets_dir = self.options.assets_dir
185
186 self.observers = []
187 self.clip = None
188
189 #--------
190 # load up the preferences ini file
191
192 print_loading_status("Loading preferences")
193
194 self.prefs = Preferences()
195
196 _prefpath = self.prefs.getStringPref("Directories","librarypath",None)
197 _preffileopenpath = self.prefs.getStringPref("Directories","fileopenpath",None)
198
199 #--------
200 # set up library path and the path to use for File->Open dialogs
201
202 if self.options.library_path != None:
203 _path = os.path.abspath(self.options.library_path)
204 _pathsrc = "command line options"
205 # when a special path is specified, use that as the file-open location
206 self.fileopenpath = _path
207 else:
208 if _prefpath:
209 _path = _prefpath
210 _pathsrc = "user preferences"
211 else:
212 _path = config.LIBRARY_PATH
213 _pathsrc = "default (config.py)"
214
215 if _preffileopenpath:
216 self.fileopenpath = _preffileopenpath
217 else:
218 self.fileopenpath = _path
219
220 #--------
221 # Create the ASCXX 'Library' object
222
223 print_loading_status("Creating ASCEND 'Library' object","PATH = "+_path+" FROM "+_pathsrc)
224 self.library = ascpy.Library(_path)
225
226 self.sim = None
227
228 #-------------------
229 # Set up the window and main widget actions
230
231 self.glade_file = os.path.join(self.assets_dir,config.GLADE_FILE)
232
233 print_loading_status("Setting up windows") #,"GLADE_FILE = %s" % self.glade_file)
234
235 glade = gtk.glade.XML(self.glade_file,"browserwin")
236
237 self.window = glade.get_widget("browserwin")
238
239
240 if not self.window:
241 raise RuntimeError("Couldn't load window from glade file")
242
243 _display = self.window.get_screen().get_display().get_name()
244 _geom=self.prefs.getGeometrySizePosition(_display,"browserwin")
245 if _geom:
246 self.window.resize(_geom[0],_geom[1])
247 self.window.move(_geom[2],_geom[3])
248
249 self.window.connect("delete_event", self.delete_event)
250
251 self.browserpaned=glade.get_widget("browserpaned")
252 _geom2=self.prefs.getGeometryValue(_display,"browserpaned")
253 if _geom2:
254 self.browserpaned.set_position(_geom2)
255
256 self.openbutton=glade.get_widget("openbutton")
257 self.openbutton.connect("clicked",self.open_click)
258
259 self.reloadbutton=glade.get_widget("reloadbutton")
260 self.reloadbutton.connect("clicked",self.reload_click)
261
262 self.solvebutton=glade.get_widget("solvebutton")
263 self.solvebutton.connect("clicked",self.solve_click)
264
265 self.integratebutton=glade.get_widget("integratebutton")
266 self.integratebutton.connect("clicked",self.integrate_click)
267
268 self.checkbutton=glade.get_widget("checkbutton")
269 self.checkbutton.connect("clicked",self.check_click)
270
271 self.autotoggle=glade.get_widget("autotoggle")
272 self.automenu = glade.get_widget("automenu")
273 self.autotoggle.connect("toggled",self.auto_toggle)
274
275 self.methodrunbutton=glade.get_widget("methodrunbutton")
276 self.methodrunbutton.connect("clicked",self.methodrun_click)
277
278 self.methodsel=glade.get_widget("methodsel")
279
280 self.maintabs = glade.get_widget("maintabs")
281
282 self.statusbar = glade.get_widget("statusbar")
283
284 self.menu = glade.get_widget("browsermenu")
285
286 self.show_solving_popup=glade.get_widget("show_solving_popup")
287 self.show_solving_popup.set_active(self.prefs.getBoolPref("SolverReporter","show_popup",True))
288 self.close_on_converged=glade.get_widget("close_on_converged")
289 self.close_on_converged.set_active(self.prefs.getBoolPref("SolverReporter","close_on_converged",True))
290 self.close_on_nonconverged=glade.get_widget("close_on_nonconverged")
291 self.close_on_nonconverged.set_active(self.prefs.getBoolPref("SolverReporter","close_on_nonconverged",True))
292 self.solver_engine=glade.get_widget("solver_engine")
293
294 self.use_relation_sharing=glade.get_widget("use_relation_sharing")
295 self.use_relation_sharing.set_active(self.prefs.getBoolPref("Compiler","use_relation_sharing",True))
296
297 glade.signal_autoconnect(self)
298
299 #-------
300 # Status icons
301
302 self.fixedimg = gtk.Image()
303 self.fixedimg.set_from_file(os.path.join(self.options.assets_dir,'locked.png'))
304
305 self.iconstatusunknown = None
306 self.iconfixed = self.fixedimg.get_pixbuf()
307 self.iconsolved = self.window.render_icon(gtk.STOCK_YES,gtk.ICON_SIZE_MENU)
308 self.iconactive = self.window.render_icon(gtk.STOCK_NO,gtk.ICON_SIZE_MENU)
309 self.iconunsolved = None
310
311 self.statusicons={
312 ascpy.ASCXX_VAR_STATUS_UNKNOWN: self.iconstatusunknown
313 ,ascpy.ASCXX_VAR_FIXED: self.iconfixed
314 ,ascpy.ASCXX_VAR_SOLVED: self.iconsolved
315 ,ascpy.ASCXX_VAR_ACTIVE: self.iconactive
316 ,ascpy.ASCXX_VAR_UNSOLVED: self.iconunsolved
317 }
318
319
320 self.statusmessages={
321 ascpy.ASCXX_VAR_STATUS_UNKNOWN: "Status unknown"
322 ,ascpy.ASCXX_VAR_FIXED: "Fixed"
323 ,ascpy.ASCXX_VAR_SOLVED: "Converged"
324 ,ascpy.ASCXX_VAR_ACTIVE: "Active (unconverged)"
325 ,ascpy.ASCXX_VAR_UNSOLVED: "Not yet visited"
326 }
327
328 #-------------------
329 # waitwin
330
331 self.waitwin = gtk.gdk.Window(self.window.window,
332 gtk.gdk.screen_width(),
333 gtk.gdk.screen_height(),
334 gtk.gdk.WINDOW_CHILD,
335 0,
336 gtk.gdk.INPUT_ONLY)
337
338 _cursor = gtk.gdk.Cursor(gtk.gdk.WATCH)
339 self.waitwin.set_cursor(_cursor)
340
341 #-------------------
342 # pixbufs to be used in the error listing
343
344 self.iconok = self.window.render_icon(gtk.STOCK_YES,gtk.ICON_SIZE_MENU)
345 self.iconinfo = self.window.render_icon(gtk.STOCK_DIALOG_INFO,gtk.ICON_SIZE_MENU)
346 self.iconwarning = self.window.render_icon(gtk.STOCK_DIALOG_WARNING,gtk.ICON_SIZE_MENU)
347 self.iconerror = self.window.render_icon(gtk.STOCK_DIALOG_ERROR,gtk.ICON_SIZE_MENU)
348
349 #--------------------
350 # pixbufs for solver_var status
351
352 #--------------------
353 # set up the error view
354
355 self.errorview = glade.get_widget("errorview")
356 errstorecolstypes = [gtk.gdk.Pixbuf,str,str,str,int]
357 self.errorstore = gtk.TreeStore(*errstorecolstypes)
358 errtitles = ["","Location","Message"];
359 self.errorview.set_model(self.errorstore)
360 self.errcols = [ gtk.TreeViewColumn() for _type in errstorecolstypes]
361
362 i = 0
363 for tvcolumn in self.errcols[:len(errtitles)]:
364 tvcolumn.set_title(errtitles[i])
365 self.errorview.append_column(tvcolumn)
366
367 if i>0:
368 _renderer = gtk.CellRendererText()
369 tvcolumn.pack_start(_renderer, True)
370 tvcolumn.add_attribute(_renderer, 'text', i)
371 if(i==2):
372 tvcolumn.add_attribute(_renderer, 'foreground', 3)
373 tvcolumn.add_attribute(_renderer, 'weight', 4)
374 else:
375 _renderer1 = gtk.CellRendererPixbuf()
376 tvcolumn.pack_start(_renderer1, False)
377 tvcolumn.add_attribute(_renderer1, 'pixbuf', int(0))
378
379 i = i + 1
380
381
382 #--------------------
383 # set up the error reporter callback
384 self.reporter = ascpy.getReporter()
385 self.reporter.setPythonErrorCallback(self.error_callback)
386
387
388 #-------
389 # Solver engine list
390
391 _slvlist = ascpy.getSolvers()
392 self.solver_engine_menu = gtk.Menu()
393 self.solver_engine_menu.show()
394 self.solver_engine.set_submenu(self.solver_engine_menu)
395 self.solver_engine_menu_dict = {}
396 _fmi = None
397 for _s in _slvlist:
398 _mi = gtk.RadioMenuItem(_fmi,_s.getName(),False)
399 if _fmi==None:
400 _fmi = _mi
401 _mi.show()
402 _mi.connect('toggled',self.on_select_solver_toggled,_s.getName())
403 self.solver_engine_menu.append(_mi)
404 self.solver_engine_menu_dict[_s.getName()]=_mi
405
406 _pref_solver = self.prefs.getStringPref("Solver","engine","QRSlv")
407 _mi = self.solver_engine_menu_dict.get(_pref_solver)
408 if _mi:
409 _mi.set_active(1)
410
411 #--------
412 # Assign an icon to the main window
413
414 self.icon = None
415 if config.ICON_EXTENSION:
416 _iconpath = ""
417 try:
418 _icon = gtk.Image()
419 _iconpath = os.path.join(self.assets_dir,'ascend'+config.ICON_EXTENSION)
420 _icon.set_from_file(_iconpath)
421 _iconpbuf = _icon.get_pixbuf()
422 self.window.set_icon(_iconpbuf)
423 self.icon = _iconpbuf
424 except Exception, e:
425 print "FAILED TO SET APPLICATION ICON PATH '%s': %s" % (_iconpath,str(e))
426 self.reporter.reportError("FAILED to set application icon '%s': %s"
427 % (_iconpath,str(e))
428 )
429
430 #-------------------
431 # set up the module view
432
433 self.modtank = {}
434 self.moduleview = glade.get_widget("moduleview")
435 modulestorecoltypes = [str, str, int] # bool=can-be-instantiated
436 self.modulestore = gtk.TreeStore(*modulestorecoltypes)
437 moduleviewtitles = ["Module name", "Filename"]
438 self.moduleview.set_model(self.modulestore)
439 self.modcols = [ gtk.TreeViewColumn() for _type in modulestorecoltypes]
440 i = 0
441 for modcol in self.modcols[:len(moduleviewtitles)]:
442 modcol.set_title(moduleviewtitles[i])
443 self.moduleview.append_column(modcol)
444 _renderer = gtk.CellRendererText()
445 modcol.pack_start(_renderer, True)
446 modcol.add_attribute(_renderer, 'text', i)
447 modcol.add_attribute(_renderer,'weight',2)
448 i = i + 1
449 self.moduleview.connect("row-activated", self.module_activated )
450
451 #--------------------
452 # set up the methods combobox
453
454 self.methodstore = gtk.ListStore(str)
455 self.methodsel.set_model(self.methodstore)
456 _methodrenderer = gtk.CellRendererText()
457 self.methodsel.pack_start(_methodrenderer, True)
458 self.methodsel.add_attribute(_methodrenderer, 'text',0)
459
460 #--------
461 # set up the instance browser view
462
463 self.modelview = ModelView(self, glade)
464
465 #--------
466 # set up the tabs
467 self.tabs = {}
468 self.activetab = None # most recent observer tab
469
470 #--------
471 # set the state of the 'auto' toggle
472
473 self.is_auto = self.prefs.getBoolPref("Browser","auto_solve",True)
474 self.autotoggle.set_active(self.is_auto)
475 self.automenu.set_active(self.is_auto)
476
477 #--------
478 # tell libascend about this 'browser' object
479
480 print dir(ascpy.Registry())
481 ascpy.Registry().set("browser",self)
482
483 #--------
484 # options
485
486 if(len(args)==1):
487 self.do_open(args[0])
488
489 print "Options: ",self.options
490
491 _model = None
492 if self.options.model:
493 _model = self.options.model
494 print "MODEL: '%s'" % _model
495 elif self.options.auto_sim:
496 _head, _tail = os.path.split(args[0])
497 if(_tail):
498 _model, _ext = os.path.splitext(_tail)
499
500 if _model:
501 try:
502 _t=self.library.findType(_model)
503 try:
504 self.do_sim(_t)
505 if not self.options.model:
506 self.reporter.reportNote("Instantiated self-titled model '%s'" %_model)
507 except RuntimeError, e:
508 self.reporter.reportError("Failed to create instance of '%s': %s"
509 %(_model, str(e))
510 );
511 except RuntimeError, e:
512 if self.options.model:
513 self.reporter.reportError("Unknown model type '%s': %s"
514 %(_model, str(e))
515 );
516
517 def run(self):
518 self.window.show()
519 print_loading_status("ASCEND is now running")
520 gtk.main()
521
522 # ------------------
523 # SOLVER LIST
524
525 def set_solver(self,solvername):
526 """ this sets the active solver in the GUI, which is the default applied to newly instantiated models """
527 self.solver = ascpy.Solver(solvername)
528 self.prefs.setStringPref("Solver","engine",solvername)
529 self.reporter.reportNote("Set solver engine to '%s'" % solvername)
530
531 # --------------------------------------------
532 # MAJOR GUI COMMANDS
533
534 def on_fix_variable_activate(self,*args):
535 self.modelview.on_fix_variable_activate(*args)
536
537 def on_free_variable_activate(self,*args):
538 self.modelview.on_free_variable_activate(*args)
539
540 def on_select_solver_toggled(self,widget,solvername):
541 if widget.get_active():
542 self.set_solver(solvername)
543
544 def do_open(self,filename):
545 # TODO does the user want to lose their work?
546 # TODO do we need to chdir?
547
548 _context = self.statusbar.get_context_id("do_open")
549
550 self.errorstore.clear()
551 self.modelview.clear()
552
553 # self.library.clear()
554
555 print "Filename =",filename
556 self.statusbar.push(_context,"Loading '"+filename+"'")
557 self.library.load(filename)
558 print "Statusbar =",self.statusbar
559 try:
560 self.statusbar.pop(_context)
561 except TypeError,e:
562 print "For some reason, a type error (context=%s,filename=%s): %s" % (_context,filename,e)
563
564 self.filename = filename
565
566 # Load the current list of modules into self.modules
567 self.modtank = {}
568 self.modulestore.clear()
569 modules = self.library.getModules()
570 #self.library.listModules()
571 try:
572 _lll=len(modules)
573 except:
574 _msg = "UNABLE TO ACCESS MODULES LIST. This is bad.\n"+\
575 "Check your SWIG configuration (check for warnings during build)."
576
577 self.reporter.reportError(_msg)
578 raise RuntimeError(_msg)
579
580 for m in reversed(modules):
581 _n = str( m.getName() )
582 _f = str( m.getFilename() )
583 #print "ADDING ROW name %s, file = %s" % (_n, _f)
584 _r = self.modulestore.append(None, [ _n, _f, pango.WEIGHT_NORMAL ])
585 for t in self.library.getModuleTypes(m):
586 _n = t.getName()
587 _hasparams = t.hasParameters()
588 if _hasparams:
589 _w = pango.WEIGHT_NORMAL
590 else:
591 _w = pango.WEIGHT_BOLD
592
593 #print "ADDING TYPE %s" % _n
594 _piter = self.modulestore.append(_r , [ _n, "", _w ])
595 _path = self.modulestore.get_path(_piter)
596 self.modtank[_path]=t
597
598 #print "DONE ADDING MODULES"
599
600 self.sim = None;
601 self.maintabs.set_current_page(0);
602
603 # See http://www.daa.com.au/pipermail/pygtk/2005-October/011303.html
604 # for details on how the 'wait cursor' is done.
605 def start_waiting(self, message):
606 self.waitcontext = self.statusbar.get_context_id("waiting")
607 self.statusbar.push(self.waitcontext,message)
608
609 if self.waitwin:
610 self.waitwin.show()
611
612 while gtk.events_pending():
613 gtk.main_iteration()
614
615 def stop_waiting(self):
616 if self.waitwin:
617 self.statusbar.pop(self.waitcontext)
618 self.waitwin.hide()
619
620 def do_sim(self, type_object):
621 self.sim = None;
622 # TODO: clear out old simulation first!
623
624 print "DO_SIM(%s)" % str(type_object.getName())
625 self.start_waiting("Compiling...")
626
627 try:
628 _v = self.prefs.getBoolPref("Compiler","use_relation_sharing",True)
629 ascpy.getCompiler().setUseRelationSharing(_v)
630
631 self.sim = type_object.getSimulation(str(type_object.getName())+"_sim")
632
633 self.reporter.reportNote("SIMULATION ASSIGNED")
634 except RuntimeError, e:
635 self.stop_waiting()
636 self.reporter.reportError(str(e))
637 return
638
639 print "...DONE 'getSimulation'"
640 self.stop_waiting()
641
642 self.start_waiting("Building simulation...")
643 print "BUILDING SIMULATION"
644
645 try:
646 self.sim.build()
647 except RuntimeError, e:
648 self.stop_waiting()
649 self.reporter.reportError(str(e))
650 return
651
652 print "DONE BUILDING"
653 self.stop_waiting()
654
655 # get method names and load them into the GUI
656 self.methodstore.clear()
657 _methods = self.sim.getType().getMethods()
658 _activemethod = None;
659 for _m in _methods:
660 _i = self.methodstore.append([_m.getName()])
661 if _m.getName()=="on_load":
662 self.methodsel.set_active_iter(_i)
663
664 self.modelview.setSimulation(self.sim)
665
666 # set the active solver on the simulation
667 self.sim.setSolver(self.solver)
668
669 # run the 'on_load' method
670 self.start_waiting("Running default method...")
671 try:
672 self.reporter.reportNote("SIMULATION CREATED, RUNNING DEFAULT METHOD NOW...")
673 self.sim.runDefaultMethod()
674 except RuntimeError, e:
675 self.stop_waiting()
676 self.reporter.reportError(str(e))
677 return
678 self.stop_waiting()
679
680 self.modelview.refreshtree()
681
682 def do_solve_if_auto(self):
683 if self.is_auto:
684 self.sim.checkInstance()
685 self.do_solve()
686 else:
687 self.sim.processVarStatus()
688 self.modelview.refreshtree()
689
690 self.sync_observers()
691
692 def do_solve(self):
693 if not self.sim:
694 self.reporter.reportError("No model selected yet")
695 return
696
697 self.start_waiting("Solving with %s..." % self.solver.getName())
698
699 if self.prefs.getBoolPref("SolverReporter","show_popup",True):
700 reporter = PopupSolverReporter(self,self.sim.getNumVars())
701 else:
702 reporter = SimpleSolverReporter(self)
703
704 self.sim.solve(self.solver,reporter)
705
706 self.stop_waiting()
707
708 self.modelview.refreshtree()
709
710 def do_integrate(self):
711 if not self.sim:
712 self.reporter.reportError("No model selected yet")
713 return
714 integwin = IntegratorWindow(self,self.sim)
715 _integratorreporter = integwin.run()
716 if _integratorreporter!=None:
717 _integratorreporter.run()
718 self.sim.processVarStatus()
719 self.modelview.refreshtree()
720
721
722 def do_check(self):
723 if not self.sim:
724 self.reporter.reportError("No simulation yet")
725 return
726
727 self.start_waiting("Checking system...")
728
729 try:
730 self.sim.checkInstance()
731 self.reporter.reportWarning("System instance check run, check above for error (if any).")
732 # the above gives output but doesn't throw errors or return a status.
733 # ... this is a problem (at the C level)
734
735 status = self.sim.checkDoF()
736 if status==ascpy.ASCXX_DOF_UNDERSPECIFIED:
737 self.on_show_fixable_variables_activate(None)
738 elif status==ascpy.ASCXX_DOF_OVERSPECIFIED:
739 self.on_show_freeable_variables_activate(None)
740 elif status==ascpy.ASCXX_DOF_STRUCT_SINGULAR:
741 if not self.sim.checkStructuralSingularity():
742 sing = self.sim.getSingularityInfo()
743 title = "Structural singularity"
744 text = title
745 text += "\n\nThe singularity can be reduced by freeing the following variables:"
746 msgs = {
747 "The singularity can be reduced by freeing the following variables" : sing.freeablevars
748 ,"Relations involved in the structural singularity" : sing.rels
749 ,"Variables involved in the structural singularity" : sing.vars
750 }
751 for k,v in msgs.iteritems():
752 text+="\n\n%s:" % k
753 if len(v):
754 _l = [j.getName() for j in v]
755 _l.sort()
756 text+= "\n\t" + "\n\t".join(_l)
757 else:
758 text += "\nnone"
759
760 _dialog = InfoDialog(self,self.window,text,title)
761 _dialog.run()
762
763 self.reporter.reportNote("System DoF check OK")
764
765 except RuntimeError, e:
766 self.stop_waiting()
767 self.reporter.reportError(str(e))
768 return
769
770 self.stop_waiting()
771
772 self.modelview.refreshtree()
773
774 def do_method(self,method):
775 if not self.sim:
776 self.reporter.reportError("No model selected yet")
777
778 self.sim.run(method)
779 self.modelview.refreshtree()
780
781 def do_quit(self):
782 print_loading_status("Saving window location")
783 self.reporter.clearPythonErrorCallback()
784
785 _w,_h = self.window.get_size()
786 _t,_l = self.window.get_position()
787 _display = self.window.get_screen().get_display().get_name()
788 self.prefs.setGeometrySizePosition(_display,"browserwin",_w,_h,_t,_l );
789
790 _p = self.browserpaned.get_position()
791 self.prefs.setGeometryValue(_display,"browserpaned",_p);
792
793 print_loading_status("Saving current directory")
794 self.prefs.setStringPref("Directories","fileopenpath",self.fileopenpath)
795
796 self.prefs.setBoolPref("Browser","auto_solve",self.is_auto)
797
798 print_loading_status("Saving preferences")
799 # causes prefs to be saved unless they are still being used elsewher
800 del(self.prefs)
801
802 print_loading_status("Closing down GTK")
803 gtk.main_quit()
804
805 print_loading_status("Clearing error callback")
806 self.reporter.clearPythonErrorCallback()
807
808 print_loading_status("Quitting")
809 return False
810
811 def on_tools_sparsity_click(self,*args):
812
813 self.reporter.reportNote("Preparing incidence matrix...")
814 _im = self.sim.getIncidenceMatrix();
815
816 self.reporter.reportNote("Plotting incidence matrix...")
817
818 _sp = IncidenceMatrixWindow(_im);
819 _sp.run();
820
821 def on_tools_repaint_tree_activate(self,*args):
822 self.reporter.reportNote("Repainting model view...")
823 self.modelview.refreshtree()
824
825 def on_diagnose_blocks_click(self,*args):
826 try:
827 _bl = self.sim.getActiveBlock()
828 except RuntimeError, e:
829 self.reporter.reportError(str(e))
830 return
831 _db = DiagnoseWindow(self,_bl)
832 _db.run();
833
834 def on_add_observer_click(self,*args):
835 self.create_observer()
836
837 def on_keep_observed_click(self,*args):
838 print "KEEPING..."
839 if len(self.observers) <= 0:
840 self.reporter.reportError("No observer defined!")
841 return
842 self.tabs[self.currentobservertab].do_add_row()
843
844 def on_copy_observer_matrix_click(self,*args):
845 if self.clip == None:
846 self.clip = gtk.Clipboard()
847
848 if len(self.observers) <= 0:
849 self.reporter.reportError("No observer defined!")
850 return
851 self.tabs[self.currentobservertab].copy_to_clipboard(self.clip)
852
853 def on_use_relation_sharing_toggle(self,checkmenuitem,*args):
854 _v = checkmenuitem.get_active()
855 self.prefs.setBoolPref("Compiler","use_relation_sharing",_v)
856 self.reporter.reportNote("Relation sharing set to "+str(_v))
857
858 def on_show_solving_popup_toggle(self,checkmenuitem,*args):
859 _v = checkmenuitem.get_active()
860 self.prefs.setBoolPref("SolverReporter","show_popup",_v)
861 print "SET TO",_v
862
863 def on_close_on_converged_toggle(self,checkmenuitem,*args):
864 _v = checkmenuitem.get_active()
865 self.prefs.setBoolPref("SolverReporter","close_on_converged",_v)
866
867 def on_close_on_nonconverged_toggle(self,checkmenuitem,*args):
868 _v = checkmenuitem.get_active()
869 self.prefs.setBoolPref("SolverReporter","close_on_nonconverged",_v)
870
871 def on_show_variables_near_bounds_activate(self,*args):
872 _epsilon = 1e-4;
873 text = "Variables Near Bounds"
874 title=text;
875 text += "\n"
876 _vars = self.sim.getVariablesNearBounds(_epsilon)
877 if len(_vars):
878 for _v in _vars:
879 text += "\n%s"%_v.getName()
880 else:
881 text +="\nnone"
882 _dialog = InfoDialog(self,self.window,text,title)
883 _dialog.run()
884
885 # --------------------------------------------
886 # MODULE LIST
887
888 def module_activated(self, treeview, path, column, *args):
889 modules = self.library.getModules()
890 print "PATH",path
891 if len(path)==1:
892 self.reporter.reportNote("Launching of external editor not yet implemented")
893 elif len(path)==2:
894 if(self.modtank.has_key(path)):
895 _type = self.modtank[path];
896 self.reporter.reportNote("Creating simulation for type %s" % str(_type.getName()) )
897 self.do_sim(_type)
898 else:
899 self.reporter.reportError("Didn't find type corresponding to row")
900
901 # ----------------------------------
902 # ERROR PANEL
903
904 def get_error_row_data(self,sev,filename,line,msg):
905 _sevicon = {
906 0: self.iconok
907 ,1: self.iconinfo
908 ,2: self.iconwarning
909 ,3: self.iconerror
910 ,4: self.iconinfo
911 ,5: self.iconwarning
912 ,6: self.iconerror
913 }[sev]
914
915 _fontweight = pango.WEIGHT_NORMAL
916 if sev==6:
917 _fontweight = pango.WEIGHT_BOLD
918
919 _fgcolor = "black"
920 if sev==4:
921 _fgcolor = "#888800"
922 elif sev==5:
923 _fgcolor = "#884400"
924 elif sev==6:
925 _fgcolor = "#880000"
926 elif sev==0:
927 _fgcolor = BROWSER_FIXED_COLOR
928
929 if not filename and not line:
930 _fileline = ""
931 else:
932 if(len(filename) > 25):
933 filename = "..."+filename[-22:]
934 _fileline = filename + ":" + str(line)
935
936 _res = [_sevicon,_fileline,msg.rstrip(),_fgcolor,_fontweight]
937 #print _res
938 return _res
939
940 def error_callback(self,sev,filename,line,msg):
941 try:
942 pos = self.errorstore.append(None, self.get_error_row_data(sev, filename,line,msg))
943 path = self.errorstore.get_path(pos)
944 col = self.errorview.get_column(3)
945 self.errorview.scroll_to_cell(path,col)
946 except Exception,e:
947 print "UNABLE TO DISPLAY ERROR MESSAGE '%s'"%msg
948
949 return 0;
950
951 # --------------------------------
952 # BUTTON METHODS
953
954 def open_click(self,*args):
955 #print_loading_status("CURRENT FILEOPENPATH is",self.fileopenpath)
956 dialog = gtk.FileChooserDialog("Open ASCEND model...",
957 self.window,
958 gtk.FILE_CHOOSER_ACTION_OPEN,
959 (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OPEN, gtk.RESPONSE_OK)
960 )
961 dialog.set_current_folder(self.fileopenpath)
962 dialog.set_default_response(gtk.RESPONSE_OK)
963 dialog.set_transient_for(self.window)
964 dialog.set_modal(True)
965
966 filter = gtk.FileFilter()
967 filter.set_name("*.a4c, *.a4l")
968 filter.add_pattern("*.[Aa]4[Cc]")
969 filter.add_pattern("*.[Aa]4[Ll]")
970 dialog.add_filter(filter)
971
972 filter = gtk.FileFilter()
973 filter.set_name("All files")
974 filter.add_pattern("*")
975 dialog.add_filter(filter)
976
977 response = dialog.run()
978 _filename = dialog.get_filename()
979 print "\nFILENAME SELECTED:",_filename
980
981 _path = dialog.get_current_folder()
982 if _path:
983 self.fileopenpath = _path
984
985 dialog.hide()
986
987 if response == gtk.RESPONSE_OK:
988 self.reporter.reportNote("File %s selected." % dialog.get_filename() )
989 self.library.clear()
990 self.do_open( _filename)
991
992 def reload_click(self,*args):
993 _type = None
994 if(self.sim):
995 _type = self.sim.getType().getName().toString();
996
997 self.library.clear()
998 self.do_open(self.filename)
999
1000 if _type:
1001 _t = self.library.findType(_type)
1002 self.do_sim(_t)
1003
1004 def props_activate(self,widget,*args):
1005 return self.modelview.props_activate(self,widget,*args)
1006
1007 def observe_activate(self,widget,*args):
1008 return self.modelview.observe_activate(self,widget,*args)
1009
1010 def solve_click(self,*args):
1011 #self.reporter.reportError("Solving simulation '" + self.sim.getName().toString() +"'...")
1012 self.do_solve()
1013
1014 def console_click(self,*args):
1015 try:
1016 console.start(self)
1017 except RuntimeError,e:
1018 self.reporter.reportError("Unable to start console: "+str(e));
1019
1020 def integrate_click(self,*args):
1021 self.do_integrate()
1022
1023 def check_click(self,*args):
1024 self.do_check()
1025 #self.reporter.reportError("CHECK clicked")
1026
1027 def preferences_click(self,*args):
1028 if not self.sim:
1029 self.reporter.reportError("No simulation created yet!");
1030
1031 _paramswin = SolverParametersWindow(self)
1032 _paramswin.show()
1033
1034 def methodrun_click(self,*args):
1035 _sel = self.methodsel.get_active_text()
1036 if _sel:
1037 _method = None
1038 _methods = self.sim.getType().getMethods()
1039 for _m in _methods:
1040 if _m.getName()==_sel:
1041 _method = _m
1042 if not _method:
1043 self.reporter.reportError("Method is not valid")
1044 return
1045 self.do_method(_method)
1046 else:
1047 self.reporter.reportError("No method selected")
1048
1049 def auto_toggle(self,button,*args):
1050 self.is_auto = button.get_active()
1051 if hasattr(self,'automenu'):
1052 self.automenu.set_active(self.is_auto)
1053 else:
1054 raise RuntimeError("no automenu")
1055
1056 #if self.is_auto:
1057 # self.reporter.reportSuccess("Auto mode is now ON")
1058 #else:
1059 # self.reporter.reportSuccess("Auto mode is now OFF")
1060
1061 def on_file_quit_click(self,*args):
1062 self.do_quit()
1063
1064 def on_tools_auto_toggle(self,checkmenuitem,*args):
1065 self.is_auto = checkmenuitem.get_active()
1066 self.autotoggle.set_active(self.is_auto)
1067
1068 def on_help_about_click(self,*args):
1069 _xml = gtk.glade.XML(self.glade_file,"aboutdialog")
1070 _about = _xml.get_widget("aboutdialog")
1071 _about.set_position(gtk.WIN_POS_CENTER_ON_PARENT)
1072 _about.set_transient_for(self.window);
1073 _about.set_version(config.VERSION)
1074 _about.run()
1075 _about.destroy()
1076
1077 def on_help_contents_click(self,*args):
1078 _help = Help(HELP_ROOT)
1079 _help.run()
1080
1081 def on_help_check_for_updates_click(self,*args):
1082 v = VersionCheck()
1083 title = "Check for updates"
1084 text = "Your version is %s\n" % config.VERSION
1085 try:
1086 v.check()
1087 text += "Latest version is %s\n" % v.latest
1088 if v.info:
1089 text += "Get more info at %s\n" % v.info
1090 if v.download:
1091 text += "Download from %s\n" % v.download
1092 except Exception, e:
1093 text += "\nUnable to check version\n"
1094 text += str(e)
1095
1096 _dialog = InfoDialog(self,self.window,text,title)
1097 _dialog.run()
1098
1099 def on_show_fixable_variables_activate(self,*args):
1100 v = self.sim.getFixableVariables()
1101 text = "Fixable Variables"
1102 title = text
1103 text += "\n"
1104 if len(v):
1105 for var in v:
1106 text += "\n%s"%var
1107 else:
1108 text += "\nnone"
1109 _dialog = InfoDialog(self,self.window,text,title)
1110 _dialog.run()
1111
1112 def on_show_freeable_variables_activate(self,*args):
1113 v = self.sim.getFreeableVariables()
1114
1115 text = "Freeable Variables"
1116 title = text
1117 text += "\n"
1118 if len(v):
1119 for var in v:
1120 text += "\n%s" % var
1121 else:
1122 text += "\nnone"
1123 _dialog = InfoDialog(self,self.window,text,title)
1124 _dialog.run()
1125
1126 def on_show_external_functions_activate(self,*args):
1127 v = self.library.getExtMethods()
1128 text = "External Functions"
1129 title = text
1130 text +="\nHere is the list of external functions currently present in"
1131 text +=" the Library:"
1132
1133 if len(v):
1134 for ext in v:
1135 text += "\n\n%s (%d inputs, %d outputs):" % \
1136 (ext.getName(), ext.getNumInputs(), ext.getNumOutputs())
1137 text += "\n%s" % ext.getHelp()
1138 else:
1139 text +="\n\nNone"
1140 _dialog = InfoDialog(self,self.window,text,title)
1141 _dialog.run()
1142
1143 def on_maintabs_switch_page(self,notebook,page,pagenum):
1144 print("Page switched to %d" % pagenum)
1145 if pagenum in self.tabs.keys():
1146 self.currentobservertab = pagenum
1147
1148 def create_observer(self,name=None):
1149 _xml = gtk.glade.XML(self.glade_file,"observervbox");
1150 _label = gtk.Label();
1151 _tab = self.maintabs.append_page(_xml.get_widget("observervbox"),_label);
1152 _obs = ObserverTab(xml=_xml, name=name, browser=self, tab=_tab)
1153 _label.set_text(_obs.name)
1154 self.observers.append(_obs)
1155 self.tabs[_tab] = _obs
1156 self.currentobservertab = _tab
1157 return _obs
1158
1159 def sync_observers(self):
1160 for _o in self.observers:
1161 _o.sync()
1162
1163 def delete_event(self, widget, event):
1164 self.do_quit()
1165 return False
1166
1167 def observe(self,instance):
1168 if len(self.observers) ==0:
1169 self.create_observer()
1170 _observer = self.tabs[self.currentobservertab]
1171 _observer.add_instance(instance)
1172
1173 if __name__ == "__main__":
1174 b = Browser();
1175 b.run()

john.pye@anu.edu.au
ViewVC Help
Powered by ViewVC 1.1.22