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

Annotation of /trunk/pygtk/gtkbrowser.py

Parent Directory Parent Directory | Revision Log Revision Log


Revision 246 - (hide annotations) (download) (as text)
Tue Jan 31 16:24:27 2006 UTC (14 years, 7 months ago) by johnpye
Original Path: trunk/pygtk/interface/gtkbrowser.py
File MIME type: text/x-python
File size: 28701 byte(s)
Some more work on the 'Observer' feature
1 johnpye 132 #!/usr/bin/env python
2    
3     import pygtk
4     pygtk.require('2.0')
5     import gtk
6     import gtk.glade
7     import pango
8     import re
9 johnpye 230 import preferences # loading/saving of .ini options
10 johnpye 132 import urlparse
11     import optparse
12    
13 johnpye 230 from solverparameters import * # 'solver parameters' window
14     from help import * # viewing help files
15 johnpye 237 from incidencematrix import * # incidence/sparsity matrix matplotlib window
16 johnpye 246 from observer import * # observer tab support
17 johnpye 230
18 johnpye 132 import sys, dl
19     # This sets the flags for dlopen used by python so that the symbols in the
20     # ascend library are made available to libraries dlopened within ASCEND:
21     sys.setdlopenflags(dl.RTLD_GLOBAL|dl.RTLD_NOW)
22     import ascend
23    
24     # This is my first ever GUI code so please be nice :)
25    
26     # The fancy tree-view gizmo is the GtkTreeView object. See the article
27     # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/300304
28     # for the original source code on which my implementation was based.
29    
30     GLADE_FILE = "/home/john/src/ascend/trunk/pygtk/interface/ascend.glade"
31    
32 johnpye 227 ESCAPE_KEY = 65307
33    
34 johnpye 230 HELP_ROOT = None
35    
36 johnpye 223 #======================================
37     # Browser is the main ASCEND library/model browser window
38    
39 johnpye 132 class Browser:
40    
41     # ---------------------------------
42     # SETUP
43    
44     def __init__(self):
45     #--------
46     # load the file referenced in the command line, if any
47    
48     parser = optparse.OptionParser(usage="%prog [[-m typename] file]", version="gtkbrowser $rev$" )
49     # add options here if we want
50    
51 johnpye 160 parser.add_option("-m", "--model"
52     ,action="store", type="string", dest="model"
53     ,help="specify the model to instantiate upon loading modules")
54 johnpye 132 (options, args) = parser.parse_args()
55    
56     #print "OPTIONS_______________:",options
57    
58 johnpye 246 self.observers = []
59    
60 johnpye 132 #--------
61     # load up the preferences ini file
62    
63     self.prefs = preferences.Preferences()
64    
65     #--------
66     # initialise ASCEND
67    
68     self.library = ascend.Library()
69    
70     self.sim = None
71    
72     #-------------------
73     # Set up the window and main widget actions
74    
75     glade = gtk.glade.XML(GLADE_FILE,"browserwin")
76    
77     self.window = glade.get_widget("browserwin")
78 johnpye 208
79 johnpye 132 if not self.window:
80     raise RuntimeError("Couldn't load window from glade file")
81 johnpye 172
82 johnpye 173 _display = self.window.get_screen().get_display().get_name();
83     _geom=self.prefs.getGeometrySizePosition(_display,"browserwin")
84 johnpye 172 if _geom:
85     self.window.resize(_geom[0],_geom[1]);
86     self.window.move(_geom[2],_geom[3]);
87 johnpye 173
88 johnpye 132 self.window.connect("delete_event", self.delete_event)
89    
90 johnpye 173 self.browserpaned=glade.get_widget("browserpaned");
91     _geom2=self.prefs.getGeometryValue(_display,"browserpaned");
92     if _geom2:
93     self.browserpaned.set_position(_geom2);
94    
95 johnpye 132 self.openbutton=glade.get_widget("openbutton")
96     self.openbutton.connect("clicked",self.open_click)
97    
98     self.reloadbutton=glade.get_widget("reloadbutton")
99     self.reloadbutton.connect("clicked",self.reload_click)
100    
101     self.solvebutton=glade.get_widget("solvebutton")
102     self.solvebutton.connect("clicked",self.solve_click)
103    
104     self.checkbutton=glade.get_widget("checkbutton")
105     self.checkbutton.connect("clicked",self.check_click)
106    
107     self.autotoggle=glade.get_widget("autotoggle")
108     self.autotoggle.connect("toggled",self.auto_toggle)
109    
110 johnpye 230 self.is_auto = self.autotoggle.get_active()
111    
112 johnpye 132 self.methodrunbutton=glade.get_widget("methodrunbutton")
113     self.methodrunbutton.connect("clicked",self.methodrun_click)
114    
115     self.methodsel=glade.get_widget("methodsel")
116    
117     self.maintabs = glade.get_widget("maintabs")
118    
119 johnpye 164 self.statusbar = glade.get_widget("statusbar")
120    
121 johnpye 208 self.menu = glade.get_widget("browsermenu")
122     glade.signal_autoconnect(self)
123    
124 johnpye 230 self.automenu = glade.get_widget("automenu")
125     self.automenu.set_active(self.is_auto)
126     if self.automenu == None:
127     print "NO AUTOMENU FOUND"
128    
129 johnpye 132 #-------------------
130 johnpye 164 # waitwin
131    
132     self.waitwin = gtk.gdk.Window(self.window.window,
133     gtk.gdk.screen_width(),
134     gtk.gdk.screen_height(),
135     gtk.gdk.WINDOW_CHILD,
136     0,
137     gtk.gdk.INPUT_ONLY)
138    
139     _cursor = gtk.gdk.Cursor(gtk.gdk.WATCH)
140     self.waitwin.set_cursor(_cursor)
141    
142     #-------------------
143 johnpye 132 # pixbufs to be used in the error listing
144    
145     self.iconok = self.window.render_icon(gtk.STOCK_YES,gtk.ICON_SIZE_MENU)
146     self.iconinfo = self.window.render_icon(gtk.STOCK_DIALOG_INFO,gtk.ICON_SIZE_MENU)
147     self.iconwarning = self.window.render_icon(gtk.STOCK_DIALOG_WARNING,gtk.ICON_SIZE_MENU)
148     self.iconerror = self.window.render_icon(gtk.STOCK_DIALOG_ERROR,gtk.ICON_SIZE_MENU)
149    
150     #--------------------
151     # set up the context menu for fixing/freeing vars
152    
153 johnpye 226 # TODO import this menu from Glade (this code is a PITA)
154    
155 johnpye 132 self.treecontext = gtk.Menu();
156 johnpye 181 self.fixmenuitem = gtk.ImageMenuItem("_Fix",True);
157     _img = gtk.Image()
158     _img.set_from_file('icons/locked.png')
159     self.fixmenuitem.set_image(_img)
160    
161     self.freemenuitem = gtk.ImageMenuItem("F_ree",True);
162     _img = gtk.Image()
163     _img.set_from_file('icons/unlocked.png')
164     self.freemenuitem.set_image(_img)
165    
166     self.plotmenuitem = gtk.ImageMenuItem("P_lot",True);
167     _img = gtk.Image()
168     _img.set_from_file('icons/plot.png')
169     self.plotmenuitem.set_image(_img)
170    
171     self.propsmenuitem = gtk.ImageMenuItem("_Properties",True);
172     _img = gtk.Image()
173     _img.set_from_file('icons/properties.png')
174     self.propsmenuitem.set_image(_img)
175    
176 johnpye 246 self.observemenuitem = gtk.ImageMenuItem("_Observe",True);
177     _img = gtk.Image()
178     _img.set_from_file('icons/observe.png')
179     self.observemenuitem.set_image(_img)
180    
181 johnpye 207 self.fixmenuitem.show(); self.fixmenuitem.set_sensitive(False)
182     self.freemenuitem.show(); self.freemenuitem.set_sensitive(False)
183     self.plotmenuitem.show(); self.plotmenuitem.set_sensitive(False)
184 johnpye 246 self.observemenuitem.show(); self.observemenuitem.set_sensitive(False)
185 johnpye 181 self.propsmenuitem.show()
186 johnpye 246 self.treecontext.append(self.fixmenuitem)
187     self.treecontext.append(self.freemenuitem)
188 johnpye 181 _sep = gtk.SeparatorMenuItem(); _sep.show()
189     self.treecontext.append(_sep);
190 johnpye 246 self.treecontext.append(self.plotmenuitem)
191     self.treecontext.append(self.observemenuitem)
192 johnpye 181 _sep = gtk.SeparatorMenuItem(); _sep.show()
193 johnpye 246 self.treecontext.append(_sep)
194     self.treecontext.append(self.propsmenuitem)
195 johnpye 132 self.fixmenuitem.connect("activate",self.fix_activate)
196     self.freemenuitem.connect("activate",self.free_activate)
197 johnpye 175 self.plotmenuitem.connect("activate",self.plot_activate)
198 johnpye 181 self.propsmenuitem.connect("activate",self.props_activate)
199 johnpye 246 self.observemenuitem.connect("activate",self.observe_activate)
200    
201 johnpye 132 if not self.treecontext:
202     raise RuntimeError("Couldn't create browsercontext")
203     #--------------------
204     # set up the error view
205    
206 johnpye 168 self.errorview = glade.get_widget("errorview")
207 johnpye 132 errstorecolstypes = [gtk.gdk.Pixbuf,str,str,str,int]
208     self.errorstore = gtk.TreeStore(*errstorecolstypes)
209     errtitles = ["","Location","Message"];
210     self.errorview.set_model(self.errorstore)
211     self.errcols = [ gtk.TreeViewColumn() for _type in errstorecolstypes]
212    
213     i = 0
214     for tvcolumn in self.errcols[:len(errtitles)]:
215     tvcolumn.set_title(errtitles[i])
216     self.errorview.append_column(tvcolumn)
217    
218     if i>0:
219     _renderer = gtk.CellRendererText()
220     tvcolumn.pack_start(_renderer, True)
221     tvcolumn.add_attribute(_renderer, 'text', i)
222     if(i==2):
223     tvcolumn.add_attribute(_renderer, 'foreground', 3)
224     tvcolumn.add_attribute(_renderer, 'weight', 4)
225     else:
226     _renderer1 = gtk.CellRendererPixbuf()
227     tvcolumn.pack_start(_renderer1, False)
228     tvcolumn.add_attribute(_renderer1, 'pixbuf', int(0))
229    
230     i = i + 1
231    
232    
233     #--------------------
234     # set up the error reporter callback
235     self.reporter = ascend.getReporter()
236     self.reporter.setPythonErrorCallback(self.error_callback)
237    
238     #-------------------
239     # set up the module view
240    
241     self.modtank = {}
242     self.moduleview = glade.get_widget("moduleview")
243     modulestorecoltypes = [str, str]
244     self.modulestore = gtk.TreeStore(*modulestorecoltypes)
245     moduleviewtitles = ["Module name", "Filename"]
246     self.moduleview.set_model(self.modulestore)
247     self.modcols = [ gtk.TreeViewColumn() for _type in modulestorecoltypes]
248     i = 0
249     for modcol in self.modcols[:len(moduleviewtitles)]:
250     modcol.set_title(moduleviewtitles[i])
251     self.moduleview.append_column(modcol)
252     _renderer = gtk.CellRendererText()
253     modcol.pack_start(_renderer, True)
254     modcol.add_attribute(_renderer, 'text', i)
255     i = i + 1
256     self.moduleview.connect("row-activated", self.module_activated )
257    
258     #-------------------
259     # RE for units matching
260     self.units_re = re.compile("([-+]?(\d+(\.\d*)?|\d*\.d+)([eE][-+]?\d+)?)\s*(.*)");
261    
262     #--------------------
263     # set up the methods combobox
264    
265     self.methodstore = gtk.ListStore(str)
266     self.methodsel.set_model(self.methodstore)
267     _methodrenderer = gtk.CellRendererText()
268     self.methodsel.pack_start(_methodrenderer, True)
269     self.methodsel.add_attribute(_methodrenderer, 'text',0)
270    
271     #--------
272     # set up the instance browser view
273    
274     self.otank = {}
275     self.treeview = glade.get_widget("browserview")
276     columns = [str,str,str,str,int,bool]
277     self.treestore = gtk.TreeStore(*columns)
278     titles = ["Name","Type","Value"];
279     self.treeview.set_model(self.treestore)
280     self.tvcolumns = [ gtk.TreeViewColumn() for _type in columns[:len(titles)] ]
281    
282     self.treeview.connect("row-expanded", self.row_expanded )
283     self.treeview.connect("button-press-event", self.tree_click )
284    
285     # data columns are: name type value colour weight editable
286    
287     i = 0
288     for tvcolumn in self.tvcolumns[:len(titles)]:
289     tvcolumn.set_title(titles[i])
290     self.treeview.append_column(tvcolumn)
291    
292     renderer = gtk.CellRendererText()
293     tvcolumn.pack_start(renderer, True)
294     tvcolumn.add_attribute(renderer, 'text', i)
295     tvcolumn.add_attribute(renderer, 'foreground', 3)
296     tvcolumn.add_attribute(renderer, 'weight', 4)
297     if(i==2):
298     tvcolumn.add_attribute(renderer, 'editable', 5)
299     renderer.connect('edited',self.cell_edited_callback)
300     i = i + 1
301    
302    
303     if(len(args)==1):
304     self.do_open(args[0])
305    
306     print "Options: ",options
307    
308     if options.model:
309     try:
310     _t =self.library.findType(options.model);
311     self.do_sim(_t);
312     except RuntimeError, e:
313     self.reporter.reportError("Failed to create instance of '%s': %s" %(options.model, str(e)));
314    
315 johnpye 223
316 johnpye 132 def run(self):
317     self.window.show()
318     gtk.main()
319    
320     # --------------------------------------------
321     # MAJOR GUI COMMANDS
322    
323    
324     def do_open(self,filename):
325     # TODO does the user want to lose their work?
326     # TODO do we need to chdir?
327    
328 johnpye 164 _context = self.statusbar.get_context_id("do_open")
329    
330 johnpye 132 self.errorstore.clear()
331    
332     self.treestore.clear()
333     self.otank = {}
334    
335 johnpye 175 # self.library.clear()
336 johnpye 164
337     self.statusbar.push(_context,"Loading '"+filename+"'")
338 johnpye 132 self.library.load(filename)
339 johnpye 164 self.statusbar.pop(_context)
340 johnpye 132
341     self.filename = filename
342    
343     # Load the current list of modules into self.modules
344     self.modtank = {}
345     self.modulestore.clear()
346     modules = self.library.getModules()
347     for m in reversed(modules):
348     _n = str( m.getName() )
349     _f = str( m.getFilename() )
350     #print "ADDING ROW name %s, file = %s" % (_n, _f)
351     _r = self.modulestore.append(None, [ _n, _f ])
352     for t in self.library.getModuleTypes(m):
353     _n = t.getName()
354     #print "ADDING TYPE %s" % _n
355     _piter = self.modulestore.append(_r , [ _n, "" ])
356     _path = self.modulestore.get_path(_piter)
357     self.modtank[_path]=t
358    
359     #print "DONE ADDING MODULES"
360    
361     self.sim = None;
362     self.maintabs.set_current_page(0);
363 johnpye 164
364 johnpye 168 # See http://www.daa.com.au/pipermail/pygtk/2005-October/011303.html
365     # for details on how the 'wait cursor' is done.
366 johnpye 164 def start_waiting(self, message):
367     self.waitcontext = self.statusbar.get_context_id("waiting")
368     self.statusbar.push(self.waitcontext,message)
369    
370     if self.waitwin:
371     self.waitwin.show()
372    
373     while gtk.events_pending():
374     gtk.main_iteration()
375 johnpye 132
376 johnpye 164 def stop_waiting(self):
377     if self.waitwin:
378     self.statusbar.pop(self.waitcontext)
379     self.waitwin.hide()
380    
381 johnpye 132 def do_sim(self, type_object):
382     self.sim = None;
383     # TODO: clear out old simulation first!
384    
385     print "DO_SIM(%s)" % str(type_object.getName())
386 johnpye 164 self.start_waiting("Compiling...")
387    
388 johnpye 132 self.sim = type_object.getSimulation(str(type_object.getName())+"_sim")
389     print "...DONE 'getSimulation'"
390 johnpye 164 self.stop_waiting()
391 johnpye 132
392 johnpye 164 self.start_waiting("Building simulation...")
393 johnpye 132 print "BUILDING SIMULATION"
394 johnpye 164 self.sim.build()
395 johnpye 132 print "DONE BUILDING"
396 johnpye 164 self.stop_waiting()
397 johnpye 132
398 johnpye 223 self.sim.setSolver(ascend.Solver("QRSlv"))
399    
400 johnpye 132 # empty things out first
401     self.methodstore.clear()
402     self.treestore.clear()
403    
404     # methods
405     _methods = self.sim.getType().getMethods()
406 johnpye 160 _activemethod = None;
407 johnpye 132 for _m in _methods:
408 johnpye 160 _i = self.methodstore.append([_m.getName()])
409     if _m.getName()=="default_self":
410     self.methodsel.set_active_iter(_i)
411 johnpye 132
412     # instance hierarchy
413     self.otank = {} # map path -> (name,value)
414     self.make( self.sim.getName(),self.sim.getModel() )
415     self.maintabs.set_current_page(1);
416    
417     def do_solve(self):
418     if not self.sim:
419     self.reporter.reportError("No model selected yet")
420 johnpye 171 return;
421 johnpye 132
422 johnpye 168 self.start_waiting("Solving...")
423 johnpye 164
424 johnpye 154 self.sim.solve(ascend.Solver("QRSlv"))
425 johnpye 164
426 johnpye 168 self.stop_waiting()
427 johnpye 132 self.refreshtree()
428    
429     def do_check(self):
430     if not self.sim:
431     self.reporter.reportError("No model selected yet")
432    
433 johnpye 171 self.start_waiting("Checking system...")
434    
435 johnpye 132 if self.sim.check():
436     self.reporter.reportNote("System check OK")
437 johnpye 171
438 johnpye 132 self.sim.checkDoF()
439    
440 johnpye 171 self.stop_waiting()
441    
442 johnpye 132 self.refreshtree()
443    
444     def do_method(self,method):
445     if not self.sim:
446     self.reporter.reportError("No model selected yet")
447    
448     self.sim.run(method)
449     self.refreshtree()
450    
451 johnpye 230 def do_quit(self):
452     self.reporter.clearPythonErrorCallback()
453     _w,_h = self.window.get_size()
454     _t,_l = self.window.get_position()
455     _display = self.window.get_screen().get_display().get_name()
456     self.prefs.setGeometrySizePosition(_display,"browserwin",_w,_h,_t,_l );
457    
458     _p = self.browserpaned.get_position()
459     self.prefs.setGeometryValue(_display,"browserpaned",_p);
460    
461     # causes prefs to be saved unless they are still being used elsewher
462     del(self.prefs)
463    
464     gtk.main_quit()
465     print "GTK QUIT"
466     return False
467    
468 johnpye 231 def on_tools_sparsity_click(self,*args):
469 johnpye 237
470     self.reporter.reportNote("Preparing incidence matrix...")
471 johnpye 233 _im = self.sim.getIncidenceMatrix();
472 johnpye 231
473 johnpye 237 self.reporter.reportNote("Plotting incidence matrix...")
474 johnpye 234
475 johnpye 237 _sp = IncidenceMatrixWindow(_im);
476     _sp.run();
477    
478 johnpye 245 def on_add_observer_click(self,*args):
479 johnpye 246 if len(self.observers) >= 1:
480     self.reporter.reportError("Not supported: multiple observers")
481     return
482     self.observers.append(self.create_observer())
483 johnpye 245
484 johnpye 132 # --------------------------------------------
485     # MODULE LIST
486    
487     def module_activated(self, treeview, path, column, *args):
488     modules = self.library.getModules()
489     print "PATH",path
490     if len(path)==1:
491     self.reporter.reportNote("Launching of external editor not yet implemented")
492     elif len(path)==2:
493     if(self.modtank.has_key(path)):
494     _type = self.modtank[path];
495     self.reporter.reportNote("Creating simulation for type %s" % str(_type.getName()) )
496     self.do_sim(_type)
497     else:
498     self.reporter.reportError("Didn't find type corresponding to row")
499    
500     # --------------------------------------------
501     # INSTANCE TREE
502    
503     def get_tree_row_data(self,instance):
504     _value = str(instance.getValue())
505     _type = str(instance.getType())
506     _name = str(instance.getName())
507     _fgcolor = "black"
508     _fontweight = pango.WEIGHT_NORMAL
509     _editable = False
510     if instance.getType().isRefinedSolverVar():
511     _editable = True
512     if instance.isFixed():
513     _fgcolor = "#008800"
514     _fontweight = pango.WEIGHT_BOLD
515     else:
516     _fgcolor = "#000088"
517     _fontweight = pango.WEIGHT_BOLD
518     elif instance.isBool() or instance.isReal() or instance.isInt():
519     # TODO can't edit constants that have already been refined
520     _editable = True
521    
522     #if(len(_value) > 80):
523     # _value = _value[:80] + "..."
524    
525     return [_name, _type, _value, _fgcolor, _fontweight, _editable]
526    
527     def get_error_row_data(self,sev,filename,line,msg):
528     _sevicon = {
529     0: self.iconok
530     ,1: self.iconinfo
531     ,2: self.iconwarning
532     ,3: self.iconerror
533     ,4: self.iconinfo
534     ,5: self.iconwarning
535     ,6: self.iconerror
536     }[sev]
537    
538     _fontweight = pango.WEIGHT_NORMAL
539     if sev==6:
540     _fontweight = pango.WEIGHT_BOLD
541    
542     _fgcolor = "black"
543     if sev==4:
544     _fgcolor = "#888800"
545     elif sev==5:
546     _fgcolor = "#884400"
547     elif sev==6:
548     _fgcolor = "#880000"
549     elif sev==0:
550     _fgcolor = "#008800"
551    
552     if not filename and not line:
553     _fileline = ""
554     else:
555     if(len(filename) > 25):
556     filename = "..."+filename[-22:]
557     _fileline = filename + ":" + str(line)
558    
559     _res = [_sevicon,_fileline,msg.rstrip(),_fgcolor,_fontweight]
560     #print _res
561     return _res
562    
563     def make_row( self, piter, name, value ):
564    
565     _piter = self.treestore.append( piter, self.get_tree_row_data(value) )
566     return _piter
567    
568     def refreshtree(self):
569     # @TODO FIXME use a better system than colour literals!
570     for _path in self.otank: # { path : (name,value) }
571     _iter = self.treestore.get_iter(_path)
572     _name, _instance = self.otank[_path]
573     self.treestore.set_value(_iter, 2, _instance.getValue())
574     if _instance.getType().isRefinedSolverVar():
575     if _instance.isFixed() and self.treestore.get_value(_iter,3)=="#000088":
576     self.treestore.set_value(_iter,3,"#008800")
577     elif not _instance.isFixed() and self.treestore.get_value(_iter,3)=="#008800":
578     self.treestore.set_value(_iter,3,"#000088")
579    
580     def cell_edited_callback(self, renderer, path, newtext, **kwargs):
581     # get back the Instance object we just edited (having to use this seems like a bug)
582     path = tuple( map(int,path.split(":")) )
583    
584     if not self.otank.has_key(path):
585     raise RuntimeError("cell_edited_callback: invalid path '%s'" % path)
586     return
587    
588     _name, _instance = self.otank[path]
589    
590     if _instance.isReal():
591     # only real-valued things can have units
592    
593     try:
594     # match a float with option text afterwards, optionally separated by whitespace
595     _match = re.match(self.units_re,newtext)
596     if not _match:
597     self.reporter.reportError("Not a valid value-and-optional-units")
598     return
599    
600     _val = _match.group(1)
601     _units = _match.group(5)
602     #_val, _units = re.split("[ \t]+",newtext,2);
603     except RuntimeError:
604     self.reporter.reportError("Unable to split value and units")
605     return
606     print "val = ",_val
607     print "units = ",_units
608    
609     # parse the units, throw an error if no good
610     try:
611     _val = float(_val)
612     except RuntimeError:
613     self.reporter.reportError("Unable to convert number part '%s' to float" % _val)
614    
615     if _units.strip() == "":
616     _u = _instance.getType().getPreferredUnits()
617     if _u == None:
618     _u = _instance.getDimensions().getDefaultUnits()
619     self.reporter.reportNote("Assuming units '%s'" % _u.getName().toString() )
620     else:
621     try:
622     _u = ascend.Units(_units)
623     self.reporter.reportNote("Parsed units %s" % _units)
624     except RuntimeError:
625     self.reporter.reportError("Unrecognisable units '%s'" % _units)
626     return
627    
628     if _instance.getDimensions() != _u.getDimensions():
629    
630     if _u.getDimensions().isDimensionless():
631     _units = "[dimensionless]"
632    
633     _my_dims = _instance.getDimensions().getDefaultUnits()
634     if _instance.getDimensions().isDimensionless():
635     _my_dims = "[dimensionless]"
636    
637     self.reporter.reportError("Incompatible units '%s' (must fit with '%s')"
638     % (_units, _my_dims) )
639     return
640    
641     if _units.strip() != "" and not _instance.getDimensions().isDimensionless():
642     self.prefs.setPreferredUnits(str(_instance.getType().getName()), _units);
643    
644     _conv = float(_u.getConversion())
645     # self.reporter.reportNote("Converting: multiplying '%s %s' by factor %s to get SI units" % (_val, _units, _conv) )
646     _val = _val * _conv;
647    
648     self.reporter.reportNote("Setting '%s' to '%f'" % (_name, _val))
649    
650     if _instance.getType().isRefinedSolverVar():
651     # set the 'fixed' flag as well
652     _instance.setFixedValue(float(_val))
653     else:
654     _instance.setRealValue(float(_val))
655     else:
656     if _instance.isBool():
657     _lower = newtext.lower();
658     if _lower.startswith("t") or _lower.startswith("y") or _lower.strip()=="1":
659     newtext = 1
660     elif _lower.startswith("f") or _lower.startswith("n") or _lower.strip()=="0":
661     newtext = 0
662     else:
663     self.reporter.reportError("Invalid entry for a boolean variable: '%s'" % newtext)
664     return
665     _val = bool(newtext);
666     if _val == _instance.getValue():
667     self.reporter.reportNote("Boolean atom '%s' was not altered" % _instance.getName())
668     return
669     _instance.setBoolValue(_val)
670    
671     elif _instance.isInt():
672     _val = int(newtext)
673     if _val == _instance.getValue():
674     self.reporter.reportNote("Integer atom '%s' was not altered" % _instance.getName())
675     return
676     _instance.setIntValue(_val)
677     else:
678     self.reporter.reportError("Attempt to set a non-real, non-boolean, non-integer value!")
679     return
680    
681     # now that the variable is set, update the GUI and re-solve if desired
682     _iter = self.treestore.get_iter(path)
683     self.treestore.set_value(_iter,2,_instance.getValue())
684    
685     if _instance.getType().isRefinedSolverVar():
686     self.treestore.set_value(_iter,3,"#008800") # set the row green as fixed
687    
688 johnpye 230 if self.is_auto:
689 johnpye 132 self.sim.check()
690     self.do_solve()
691     #self.reporter.reportError("SOLVER completed")
692    
693    
694     def make_children(self, value, piter ):
695     if value.isCompound():
696     children=value.getChildren();
697     for child in children:
698     _name = child.getName();
699     _piter = self.make_row(piter,_name,child)
700     _path = self.treestore.get_path(_piter)
701     self.otank[_path]=(_name,child)
702     #self.reporter.reportError("2 Added %s at path %s" % (_name,repr(_path)))
703    
704     def make(self, name=None, value=None, path=None, depth=1):
705     if path is None:
706     # make root node
707     piter = self.make_row( None, name, value )
708     path = self.treestore.get_path( piter )
709     self.otank[ path ] = (name, value)
710     #self.reporter.reportError("4 Added %s at path %s" % (name, path))
711     else:
712     name, value = self.otank[ path ]
713    
714     piter = self.treestore.get_iter( path )
715     if not self.treestore.iter_has_child( piter ):
716     self.make_children(value,piter)
717    
718     if depth:
719     for i in range( self.treestore.iter_n_children( piter ) ):
720     self.make( path = path+(i,), depth = depth - 1 )
721 johnpye 160 else:
722     self.treeview.expand_row("0",False)
723 johnpye 132
724     def row_expanded( self, treeview, piter, path ):
725     self.make( path = path )
726    
727     # ----------------------------------
728     # ERROR PANEL
729    
730     def error_callback(self,sev,filename,line,msg):
731     pos = self.errorstore.append(None, self.get_error_row_data(sev, filename,line,msg))
732     path = self.errorstore.get_path(pos)
733     col = self.errorview.get_column(3)
734     self.errorview.scroll_to_cell(path,col)
735    
736     return 0;
737    
738     # --------------------------------
739     # BUTTON METHODS
740    
741     def open_click(self,*args):
742     dialog = gtk.FileChooserDialog("Open file...",
743 johnpye 160 None,
744     gtk.FILE_CHOOSER_ACTION_OPEN,
745     (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL,
746     gtk.STOCK_OPEN, gtk.RESPONSE_OK))
747 johnpye 132 dialog.set_default_response(gtk.RESPONSE_OK)
748    
749     filter = gtk.FileFilter()
750     filter.set_name("*.a4c, *.a4l")
751     filter.add_pattern("*.[Aa]4[Cc]")
752     filter.add_pattern("*.[Aa]4[Ll]")
753     dialog.add_filter(filter)
754    
755     filter = gtk.FileFilter()
756     filter.set_name("All files")
757     filter.add_pattern("*")
758     dialog.add_filter(filter)
759    
760     response = dialog.run()
761     _filename = dialog.get_filename()
762     dialog.destroy()
763    
764     if response == gtk.RESPONSE_OK:
765     self.reporter.reportNote("File %s selected." % dialog.get_filename() )
766 johnpye 185 self.library.clear()
767 johnpye 132 self.do_open( _filename)
768    
769    
770     def reload_click(self,*args):
771     _type = None
772     if(self.sim):
773     _type = self.sim.getType().getName().toString();
774    
775 johnpye 185 self.library.clear()
776 johnpye 132 self.do_open(self.filename)
777    
778     if _type:
779     _t = self.library.findType(_type)
780     self.do_sim(_t)
781    
782     def solve_click(self,*args):
783     #self.reporter.reportError("Solving simulation '" + self.sim.getName().toString() +"'...")
784     self.do_solve()
785    
786     def check_click(self,*args):
787     self.do_check()
788     #self.reporter.reportError("CHECK clicked")
789    
790 johnpye 208 def preferences_click(self,*args):
791     if not self.sim:
792     self.reporter.reportError("No simulation created yet!");
793    
794 johnpye 235 _paramswin = SolverParametersWindow(self.sim, self.reporter, GLADE_FILE)
795 johnpye 223 _paramswin.show()
796 johnpye 221
797 johnpye 132 def methodrun_click(self,*args):
798     _sel = self.methodsel.get_active_text()
799     if _sel:
800     _method = None
801     _methods = self.sim.getType().getMethods()
802     for _m in _methods:
803     if _m.getName()==_sel:
804     _method = _m
805     if not _method:
806     self.reporter.reportError("Method is not valid")
807     return
808     self.do_method(_method)
809     else:
810     self.reporter.reportError("No method selected")
811    
812     def auto_toggle(self,button,*args):
813 johnpye 230 self.is_auto = button.get_active()
814     self.automenu.set_active(self.is_auto)
815    
816     if self.is_auto:
817 johnpye 168 self.reporter.reportSuccess("Auto mode is now ON")
818 johnpye 132 else:
819 johnpye 168 self.reporter.reportSuccess("Auto mode is now OFF")
820 johnpye 132
821 johnpye 230 def on_file_quit_click(self,*args):
822     self.do_quit()
823    
824     def on_tools_auto_toggle(self,checkmenuitem,*args):
825     self.is_auto = checkmenuitem.get_active()
826     self.autotoggle.set_active(self.is_auto)
827    
828     def on_help_about_click(self,*args):
829     _xml = gtk.glade.XML(GLADE_FILE,"aboutdialog");
830     _dialog = _xml.get_widget("aboutdialog")
831     _dialog.run()
832     _dialog.destroy()
833    
834     def on_help_contents_click(self,*args):
835     _help = Help(HELP_ROOT)
836     _help.run()
837    
838 johnpye 245 def create_observer(self,name=None):
839     if name==None:
840     name="New Observer"
841    
842     _xml = gtk.glade.XML(GLADE_FILE,"observervbox");
843     _label = gtk.Label();
844     _label.set_text(name)
845     self.maintabs.append_page(_xml.get_widget("observervbox"),_label);
846 johnpye 246 self.observers.append(ObserverTab(_xml,name,self))
847 johnpye 245
848 johnpye 132 # ------------------------------
849     # CONTEXT MENU
850    
851     def tree_click(self,widget,event):
852     # which button was clicked?
853     if event.button == 3:
854     _x = int(event.x)
855     _y = int(event.y)
856     _time = event.time
857     _pthinfo = self.treeview.get_path_at_pos(_x, _y)
858     if _pthinfo != None:
859 johnpye 172 _canpop = False;
860 johnpye 132 _path, _col, _cellx, _celly = _pthinfo
861     # self.reporter.reportError("Right click on %s" % self.otank[_path][0])
862     _instance = self.otank[_path][1]
863     if _instance.getType().isRefinedSolverVar():
864 johnpye 172 _canpop = True;
865 johnpye 246 self.observemenuitem.set_sensitive(True)
866 johnpye 132 if _instance.isFixed():
867 johnpye 181 self.fixmenuitem.set_sensitive(False)
868     self.freemenuitem.set_sensitive(True)
869 johnpye 132 else:
870 johnpye 181 self.fixmenuitem.set_sensitive(True)
871     self.freemenuitem.set_sensitive(False)
872 johnpye 207 elif _instance.isRelation():
873     _canpop = True;
874     self.propsmenuitem.set_sensitive(True)
875 johnpye 172
876     if _instance.isPlottable():
877 johnpye 181 self.plotmenuitem.set_sensitive(True)
878 johnpye 172 _canpop = True;
879     else:
880 johnpye 181 self.plotmenuitem.set_sensitive(False)
881 johnpye 172
882     if _canpop:
883     self.treeview.grab_focus()
884     self.treeview.set_cursor( _path, _col, 0)
885 johnpye 132 self.treecontext.popup( None, None, None, event.button, _time)
886     return 1
887    
888     def fix_activate(self,widget):
889     _path,_col = self.treeview.get_cursor()
890     _name, _instance = self.otank[_path]
891     _instance.setFixed(True)
892     self.reporter.reportNote("Fixed variable %s" % _instance.getName().toString())
893 johnpye 230 if self.is_auto:
894 johnpye 132 self.sim.check()
895     self.do_solve()
896     else:
897     self.refreshtree()
898     return 1
899    
900     def free_activate(self,widget):
901     _path,_col = self.treeview.get_cursor()
902     _instance = self.otank[_path][1]
903     _instance.setFixed(False)
904     self.reporter.reportNote("Freed variable %s" % _instance.getName().toString())
905 johnpye 230 if self.is_auto:
906 johnpye 132 self.sim.check()
907     self.do_solve()
908     else:
909     self.refreshtree()
910     return 1
911    
912 johnpye 172 def plot_activate(self,widget):
913 johnpye 175 self.reporter.reportNote("plot_activate...");
914 johnpye 172 _path,_col = self.treeview.get_cursor()
915     _instance = self.otank[_path][1]
916     if not _instance.isPlottable():
917 johnpye 175 self.reporter.reportError("Can't plot instance %s" % _instance.getName().toString())
918 johnpye 172 return
919 johnpye 175 else:
920     self.reporter.reportNote("Instance %s about to be plotted..." % _instance.getName().toString())
921 johnpye 172
922 johnpye 175 print("Plotting instance '%s'..." % _instance.getName().toString())
923    
924 johnpye 176 _plot = _instance.getPlot()
925 johnpye 175
926 johnpye 176 print "Title: ", _plot.getTitle()
927 johnpye 180 _plot.show(True)
928 johnpye 176
929 johnpye 172 return 1
930    
931 johnpye 181 def props_activate(self,widget):
932 johnpye 207 _path,_col = self.treeview.get_cursor()
933     _instance = self.otank[_path][1]
934     if _instance.isRelation():
935 johnpye 215 print "Relation '"+_instance.getName().toString()+"':", \
936     _instance.getRelationAsString(self.sim.getModel())
937 johnpye 207 else:
938     self.reporter.reportWarning("props_activate not implemented")
939 johnpye 172
940 johnpye 246 def observe_activate(self,widget):
941     _path,_col = self.treeview.get_cursor()
942     _instance = self.otank[_path][1]
943     if _instance.getType().isRefinedSolverVar():
944     print "OBSERVING",_instance.getName().toString()
945     if len(self.observers) > 1:
946     self.reporter.reportError("Not implemented: multiple observers")
947     return
948     if len(self.observers) ==0:
949     self.create_observer()
950     _observer = self.observers[0]
951     _observer.add_instance(_instance)
952    
953 johnpye 132 # ---------------------------------
954     # WINDOW-LEVEL ACTIONS
955    
956     def delete_event(self, widget, event, data=None):
957 johnpye 230 self.do_quit()
958 johnpye 132 return False
959    
960     def test():
961     import ascend
962     b = Browser();
963     b.run()
964    
965     if __name__ == "__main__":
966     test()

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