def __init__(self, obj=None, title=None, callback=None, fill=0, expand=0, scope=None, name=None, *args, **kwargs): meshwidget = scope.findWidget(lambda x: isinstance( x, whowidget.WhoWidget) and x.whoclass is mesh.meshes) meshctxt = mesh.meshes[meshwidget.get_value()] bcwidget = scope.findWidget(lambda x: isinstance(x, BCNameWidget)) bc = meshctxt.getBdyCondition(bcwidget.get_value()) self.time_derivs = (bc.field.time_derivative() in meshctxt.all_initializable_fields()) debug.fmsg("time_derivs=", self.time_derivs) regclassfactory.RegisteredClassFactory.__init__( self, bdycondition.FloatBCInitMethod.registry, obj=obj, title=title, callback=callback, fill=fill, expand=expand, scope=scope, name=name, *args, **kwargs)
def loadImageIntoMS(image, microstructure): # Used by loadImage() and copyImage() to install an image into a # microstructure. 'image' is an OOFImage object. # 'microstructure' is a Microstructure name. A new Microstructure # is created if necessary. # See if the Microstructure already exists msclass = whoville.getClass('Microstructure') try: # look for existing microstructure ms = msclass[microstructure] # Who object except KeyError: msobj = ooflib.SWIG.common.cmicrostructure.CMicrostructure( microstructure, image.sizeInPixels(), image.size()) ms = msclass.add(microstructure, msobj, parent=None) # Check size of microstructure if ms.getObject().sizeInPixels() != image.sizeInPixels(): debug.fmsg("ms=", ms.getObject().sizeInPixels(), "image=", image.sizeInPixels()) raise ooferror.ErrUserError("Cannot load an image into an existing" " Microstructure of a different size.") # See if the image name is unique in the Microstructure newname = imagecontext.imageContexts.uniqueName([ms.name(), image.name()]) image.rename(newname) # Create ImageContext object immidgecontext = imagecontext.imageContexts.add([ms.name(), newname], image, parent=ms)
def shutdown(exitstatus): # In GUI mode, this is called after the GUI exits. # Restore the default exception handler, in case something goes # wrong during shutdown, and the machinery to display OOF # exceptions has already been dismantled. This call must come # before mainthread_delete(). excepthook.assign_excepthook() # On some systems (at least OS X 10.5.7) it's important to delete # the main thread's ThreadState object explicitly before calling # sys.exit(). If called implicitly by sys.exit, the ThreadState # destructor crashes. This must come after the GUI has been # stopped, or else subthreads used in stopping the GUI will fail. threadstate.mainthread_delete() ## gc.garbage is a list of objects which couldn't be deleted, ## because they have circular references *and* __del__ methods. ## Python can't use garbage collection on such objects because it ## doesn't know the order in which to call the __del__ methods. if gc.garbage: debug.fmsg("garbage=", gc.garbage) # for g in gc.garbage: # from ooflib.SWIG.common import doublevec # if isinstance(g, doublevec.DoubleVecPtr): # debug.dumpReferrers(g, levels=2) sys.stdout.flush() sys.exit(exitstatus)
def loadLog(menuitem, filename, checkpoints): if gtklogger.replaying(): raise ooferror.ErrUserError( "Multiple GUI logs cannot be replayed simultaneously!") debug.fmsg("Loading gui script", filename) menuitem.root().setOption('post_hook', menucheckpoint) dblevel = 0 if debug.debug(): dblevel = 3 #dblevel = 4 global _replaying _replaying = True # When replaying, we have to make sure that progress bars *always* # appear, so we set the delay time to 0. If the delay time is # non-zero, then a script recorded on a slow machine would insert # a checkpoint for opening the activity viewer window, but a # faster machine might never open the window, and would wait # forever for the checkpoint when replaying the script. progressbar_delay.set_delay(None, 0) gtklogger.replay(filename, beginCB=activityViewer.openActivityViewer, finishCB=logFinished, debugLevel=dblevel, threaded=thread_enable.query(), exceptHook=loggererror, checkpoints=checkpoints)
def _quit(menuitem): global _rank if _rank != 0: ## print "quitting back-end" ## sys.stdout.flush() debug.fmsg() quit.quit()
def loadLog(menuitem, filename, checkpoints): if gtklogger.replaying(): raise ooferror.ErrUserError( "Multiple GUI logs cannot be replayed simultaneously!") debug.fmsg("Loading gui script", filename) menuitem.root().setOption('post_hook', menucheckpoint) dblevel = 0 if debug.debug(): dblevel = 3 #dblevel = 4 global _replaying _replaying = True # When replaying, we have to make sure that progress bars *always* # appear, so we set the delay time to 0. If the delay time is # non-zero, then a script recorded on a slow machine would insert # a checkpoint for opening the activity viewer window, but a # faster machine might never open the window, and would wait # forever for the checkpoint when replaying the script. progressbar_delay.set_delay(None, 0) gtklogger.replay( filename, beginCB=activityViewer.openActivityViewer, finishCB=logFinished, debugLevel=dblevel, threaded=thread_enable.query(), exceptHook=loggererror, checkpoints=checkpoints)
def loadscript(menuitem, filename): if filename is not None: debug.fmsg('reading', filename, 'in thread', threadstate.findThreadNumber()) kwargs = {} if subScriptErrorHandler: kwargs['errhandler'] = subScriptErrorHandler interp = PScriptLoader(filename, **kwargs) interp.run() if interp.error: # If the interpreter raised an exception and we're in # batch mode, the shell error status won't be set unless a # new exception is raised here. The old exception has # already been handled by the time we get to this point. # interp.error[0] is the class of the exception. # interp.error[1] is its value. errorname = interp.error[0].__name__ if errorname.lower()[0] in "aeiou": article = "an" else: article = "a" raise ooferror.ErrUserError( "Script '%s' raised %s %s exception" % (filename, article, interp.error[0].__name__) # "Script '%s' raised %s %s exception: %s" % # (filename, article, interp.error[0].__name__, interp.error[1]) ) debug.fmsg('finished reading', filename)
def readData(self, tslfile, prog): count = 1 lines = tslfile.readlines() nlines = len(lines) data = utils.ReservableList(nlines) hexgrid = False for line in lines: if line[0] == '#': # line is in the header if line.startswith('# GRID: HexGrid'): hexgrid = True else: # line is not a header line substrings = line.split() if len(substrings) < 5: raise ooferror.ErrUserError( "Not enough columns in line %d of %s" % (count, tslfile.name)) if len(substrings) >= 8: phase = substrings[7] else: phase = 'phase0' values = map(float, substrings[:5]) position = primitives.Point(values[3], values[4]) angles = values[:3] angles[0] = angles[0] - math.radians(self.angle_offset) data.append(DataPoint(position, angles, 'phase' + phase)) count += 1 prog.setMessage("read %d/%d lines" % (count, nlines)) prog.setFraction(float(count) / nlines) debug.fmsg("read %d lines, %d data points" % (count, len(data))) return data, hexgrid
def __call__(self, **kwargs): # Check for extra arguments paramnames = [p.name for p in self.params] for argname in kwargs.keys(): if argname not in paramnames: debug.fmsg("params=", self.params) debug.fmsg("paramnames=", paramnames) raise ooferror.ErrUserError( "Unexpected argument '%s' in %s constructor" % (argname, self.subclass.__name__)) pdict = {} for p in self.params: try: p.value = kwargs[p.name] except KeyError: pass pdict[p.name] = p.value try: object = self.subclass(**pdict) except TypeError: debug.fmsg("Error creating", self.subclass) debug.fmsg("got arguments=", pdict) debug.fmsg("expected arguments=", self.params) raise # if not hasattr(object, 'timestamp'): # object.timestamp = timestamp.TimeStamp() return object
def readData(self, tslfile, prog): count = 1 lines = tslfile.readlines() nlines = len(lines) data = utils.ReservableList(nlines) hexgrid = False for line in lines: if line[0] == '#': # line is in the header if line.startswith('# GRID: HexGrid'): hexgrid = True else: # line is not a header line substrings = line.split() if len(substrings) < 5: raise ooferror.ErrUserError( "Not enough columns in line %d of %s" % (count, tslfile.name)) if len(substrings) >= 8: phase = substrings[7] else: phase = 'phase0' values = map(float, substrings[:5]) position = primitives.Point(values[3], values[4]) angles = values[:3] angles[0] = angles[0] - math.radians(self.angle_offset) data.append(DataPoint(position, angles, 'phase'+phase)) count += 1 prog.setMessage("read %d/%d lines" % (count, nlines)) prog.setFraction(float(count)/nlines) debug.fmsg("read %d lines, %d data points" % (count, len(data))) return data, hexgrid
def resume_writing(self): # a useful skill for job applicants if _debuglocks: debug.dumpCaller() debug.fmsg('resuming writing', self, id(self)) self.rwLock.write_resume() if _debuglocks: debug.fmsg('resumed writing', self, id(self))
def end_writing(self): parent = self.getParent() # See comment above if parent: parent.end_reading() if _debuglocks: debug.dumpCaller() debug.fmsg('end writing', self, id(self)) self.rwLock.write_release()
def end_reading(self): parent = self.getParent() if parent: parent.end_reading() self.rwLock.read_release() if _debuglocks: debug.dumpCaller() debug.fmsg('ended reading', self, id(self), self.rwLock.nReaders())
def readfile(self, filename, prog, z=0): tslfile = file(filename, "r") prog.setMessage("Reading " + filename) count = 1 # line counter lines = tslfile.readlines() nlines = len(lines) data = utils.ReservableList(nlines) angletype = None for line in lines: if line[0] == '#': if line.startswith("Column 1-3", 2): if "radians" in line: angletype = "radians" else: angletype = "degrees" debug.fmsg("Angles are in %s." % angletype) else: # line[0] != '#' substrings = line.split() if len(substrings) < 5: raise ooferror.ErrUserError( "Too few numbers in line %d of %s" % (count, filename)) values = map(float, substrings[:5]) if angletype == "radians": angles = values[:3] elif angletype == "degrees": angles = map(math.radians, values[:3]) else: raise ooferror.ErrDataFileError( "Angle type not specified in TSL data file") orientation = corientation.COrientBunge(*angles) if config.dimension() == 2: point = primitives.Point(values[3], values[4]) elif config.dimension() == 3: point = primitives.Point(values[3], values[4], z) data.append(DataPoint(point, # position angles, ' '.join(substrings[10:]))) # phase name count += 1 # count actual file lines, comments and all prog.setMessage("read %d/%d lines" % (count, nlines)) prog.setFraction(float(count)/nlines) npts = len(data) debug.fmsg("read %d lines, %d data points" % (count, npts)) # We don't yet know if the points are on a rectangular or a # hexagonal lattice, so split the data up into rows. # getrows() is a generator, but we need an actual list so that # we can index into it. rows = list(getrows(data)) if len(rows) < 2: raise ooferror.ErrUserError( "Orientation map data has too few rows.") if rows[0][0].position[0] != rows[1][0].position[0]: # Must be a hexagonal lattice. Throw out every other row. reporter.warn("Converting hexagonal lattice to rectangular by discarding alternate rows.") rows = rows[::2] # discard odd numbered rows return rows, npts
def reserve(self): if _debuglocks: debug.dumpCaller() debug.fmsg('reserving', self) self.reservation_lock.acquire() if _debuglocks: debug.fmsg('reserved', self) self.have_reservation = 1 switchboard.notify("made reservation", self)
def __init__(self, namelist, callback=None, callbackargs=(), update_callback=None, update_callback_args=(), helpdict={}): debug.mainthreadTest() self.gtk = gtk.Label("Gen-u-wine Fake Widget") debug.fmsg(namelist)
def show_contourmap_info(self): # TODO MERGE: This is only used in 2D and will go away when 2D # uses vtk for contouring. debug.fmsg() if not self.gtk: return current_contourmethod = self.current_contourmap_method if current_contourmethod: current_contourmethod.draw_contourmap( self, self.oofcanvas)
def __init__(self, question, *answers, **kwargs): debug.mainthreadTest() if len(answers) == 0: raise ooferror.ErrSetupError( "Questioner must have at least one possible answer.") self.answers = answers self.gtk = gtklogger.Dialog() self.gtk.set_keep_above(True) gtklogger.newTopLevelWidget(self.gtk, "Questioner") hbox = gtk.HBox() self.gtk.vbox.pack_start(hbox, padding=15) hbox.pack_start(gtk.Label(question), padding=15) self.defaultbutton = None try: self.default = kwargs['default'] except KeyError: self.default = None else: if not self.default in answers: self.answers = (self.default, ) + answers self.answerdict = {} count = 1 for answer in self.answers: #TODO:Replace the try except block with this #stock = answer["stock"] #choice = answer["choice"] #icon = gtk.stock_lookup(stock) #if icon is None: # debug.fmsg('no gtk stock icon for id: ', stock) # self.gtk.add_button(choice, count) #else: # button = self.gtk.add_button(icon, count) # label = gtkutils.findChild(gtk.Label, button) # label.set_text(choice) #if answer["stock"] == self.default["stock"]: # self.gtk.set_default_response(count) try: stock = _stock[answer] button = self.gtk.add_button(stock, count) # Replace the label on the stock button with the answer text. label = gtkutils.findChild(gtk.Label, button) label.set_text(answer) except KeyError: debug.fmsg('no stock icon for', answer) self.gtk.add_button(answer, count) self.answerdict[count] = answer if answer == self.default: self.gtk.set_default_response(count) count += 1 hbox.show_all()
def begin_reading(self): if _debuglocks: debug.dumpCaller() debug.fmsg('acquiring read lock', self, id(self)) self.rwLock.read_acquire() parent = self.getParent() if parent: parent.begin_reading() if _debuglocks: debug.fmsg('acquired read lock', self, id(self), self.rwLock.nReaders())
def setLUT(self): # Subclasses must define getLUT(), which returns the color # lookup table, and getRange(), which returns the min and max # values to be plotted. ctxt = self.who() if ctxt is None: debug.fmsg("Failed to find who object") return themesh = ctxt.resolve(self.gfxwindow) dmin, dmax = self.getRange(themesh) mainthread.runBlock(self.canvaslayer.set_lookupTable, (self.getLUT(themesh), dmin, dmax))
def parallel_delete_subproblem(menuitem, subproblem): debug.fmsg() subpctxt = ooflib.engine.subproblemcontext.subproblems[subproblem] if subpctxt.name() == ooflib.engine.mesh.defaultSubProblemName: raise ooferror.ErrUserError("You can't delete the default Subproblem!") subpctxt.reserve() subpctxt.begin_writing() try: subpctxt.destroy() finally: subpctxt.end_writing() subpctxt.cancel_reservation()
def parallel_rename_subproblem(menuitem, subproblem, name): debug.fmsg() oldpath = labeltree.makePath(subproblem) subprob = ooflib.engine.subproblemcontext.subproblems[oldpath] if subprob.name() == ooflib.engine.mesh.defaultSubProblemName: raise ooferror.ErrUserError("You can't rename the default Subproblem!") subprob.reserve() subprob.begin_writing() try: subprob.rename(name, exclude=oldpath[-1]) finally: subprob.end_writing() subprob.cancel_reservation()
def _read(self): while 1: try: self.data += self.comm.recv(SocketInput.buffer_size) except socket.error, e: # If the socket error no. is EINTR (interrupted system call), # then just go around again. debug.fmsg(e) if e[0]!=errno.EINTR: break else: # If no exceptions of the socket.error instance, then exit. break
def begin_writing(self): if _debuglocks: debug.dumpCaller() debug.fmsg('acquiring write lock', self, id(self)) self.rwLock.write_acquire() # While changing an object, make sure that its parents don't # change as well, because that could effectively change the # object... Since we're not actually changing the parent, we # just acquire the read lock. parent = self.getParent() if parent: parent.begin_reading() if _debuglocks: debug.fmsg('acquired write lock', self, id(self))
def parallel_deactivateEquation(menuitem, subproblem, equation): debug.fmsg() subpcontext = ooflib.engine.subproblemcontext.subproblems[subproblem] subpcontext.reserve() subpcontext.begin_writing() try: subpcontext.getObject().deactivate_equation(equation) finally: subpcontext.end_writing() subpcontext.cancel_reservation() switchboard.notify('equation activated', subproblem, equation.name(), 0) subpcontext.autoenableBCs() subpcontext.changed()
def next(self): ## TODO: This doesn't quite do the right thing on the first ## step of a continued computation, if the previous step was ## truncated to hit the end time exactly. For example, with ## factor=2 and timestep=0.1, the times are 0.1, 0.3, 0.7, ## 1.5, etc. If the end time is 1, the output times will be ## 0.1, 0.3, 0.7, and 1.0. If the solution is continued, the ## next time will be 3.1, although it probably should be 1.5. if self.lasttime is None: self.lasttime = self.time0 self.lasttime += self.nextstep self.nextstep *= self.factor debug.fmsg("Geometric returning", self.lasttime) return self.lasttime
def report_skeleton(self): debug.fmsg("#NODES") for nd in self.skeleton.node_iterator(): debug.fmsg("Node #", nd.getIndex(), nd.position(), nd._remote_index) debug.fmsg("#ELEMENTS") for el in self.skeleton.element_iterator(): debug.fmsg("Element #", el.getIndex(), [n.getIndex() for n in el.nodes])
def next(self): ## TODO 3.1: This doesn't quite do the right thing on the first ## step of a continued computation, if the previous step was ## truncated to hit the end time exactly. For example, with ## factor=2 and timestep=0.1, the times are 0.1, 0.3, 0.7, ## 1.5, etc. If the end time is 1, the output times will be ## 0.1, 0.3, 0.7, and 1.0. If the solution is continued, the ## next time will be 3.1, although it probably should be 1.5. if self.lasttime is None: self.lasttime = self.time0 self.lasttime += self.nextstep self.nextstep *= self.factor debug.fmsg("Geometric returning", self.lasttime) return self.lasttime
def parallel_edit_subproblem(menuitem, name, subproblem): debug.fmsg() oldsubp = ooflib.engine.subproblemcontext.subproblems[name] if oldsubp.name() == ooflib.engine.mesh.defaultSubProblemName: raise ooferror.ErrUserError("You can't edit the default Subproblem!") meshctxt = oldsubp.getParent() oldsubp.reserve() oldsubp.begin_writing() try: oldsubpobj = oldsubp.getObject() # Save lists of fields, etc, so that they can be restored in # the new subproblem. oldfields = oldsubp.all_compound_fields( ) # should be only CompoundFields oldactivefields = [ field for field in oldfields if oldsubpobj.is_active_field(field) ] oldeqns = oldsubp.all_equations() oldsubp.destroy() finally: oldsubp.end_writing() oldsubp.cancel_reservation() # Create context for new subproblem. newsubp = meshctxt.newSubProblem(subproblem, name) meshctxt.reserve() meshctxt.begin_writing() # Gather switchboard messages and send them all after the lock has # been released. notifications = [] try: # Restore field and equation state saved from old subproblem. for field in oldfields: subproblem.define_field(field) notifications.append(("field defined", name, field.name(), 1)) for field in oldactivefields: subproblem.activate_field(field) notifications.append(("field activated", name, field.name(), 1)) for eqn in oldeqns: subproblem.activate_equation(eqn) notifications.append(("equation activated", name, eqn.name(), 1)) finally: meshctxt.end_writing() meshctxt.cancel_reservation() newsubp.autoenableBCs() for notice in notifications: switchboard.notify(*notice)
def parallel_undefineField(menuitem, subproblem, field): debug.fmsg() subpcontext = ooflib.engine.subproblemcontext.subproblems[subproblem] subpcontext.reserve() subpcontext.begin_writing() try: subpcontext.getObject().undefine_field(field) subpcontext.getParent().update_fields() finally: subpcontext.end_writing() subpcontext.cancel_reservation() subpcontext.autoenableBCs() subpcontext.changed() switchboard.notify("field defined", subproblem, field.name(), 0) switchboard.notify("redraw")
def parallel_copy_subproblem(menuitem, subproblem, mesh, name): debug.fmsg() sourcectxt = ooflib.engine.subproblemcontext.subproblems[subproblem] sourceobj = sourcectxt.getObject() # Make a copy of the CSubProblem object, using the clone function # (added to the class by registerCClass). copyobj = sourceobj.clone() # new CSubProblem sourcectxt.begin_reading() try: fields = sourcectxt.all_compound_fields() activefields = [ field for field in fields if sourcectxt.getObject().is_active_field(field) ] equations = sourceobj.all_equations() finally: sourcectxt.end_reading() meshctxt = ooflib.engine.mesh.meshes[mesh] copyctxt = meshctxt.newSubProblem(copyobj, mesh + ':' + name) # new context copyname = copyctxt.path() # Set Fields and Equations in the copy copyctxt.reserve() copyctxt.begin_writing() notifications = [] try: for field in fields: copyobj.define_field(field) notifications.append(("field defined", copyname, field.name(), 1)) for field in activefields: copyobj.activate_field(field) notifications.append( ("field activated", copyname, field.name(), 1)) for eqn in sourceobj.all_equations(): copyobj.activate_equation(eqn) notifications.append( ("equation activated", copyname, eqn.name(), 1)) finally: copyctxt.end_writing() copyctxt.cancel_reservation() copyctxt.autoenableBCs() for notice in notifications: switchboard.notify(*notice)
def __init__(self, obj=None, title=None, callback=None, fill=0, expand=0, scope=None, name=None, *args, **kwargs): meshwidget = scope.findWidget( lambda x: isinstance(x, whowidget.WhoWidget) and x.whoclass is mesh.meshes) meshctxt = mesh.meshes[meshwidget.get_value()] bcwidget = scope.findWidget( lambda x: isinstance(x, BCNameWidget)) bc = meshctxt.getBdyCondition(bcwidget.get_value()) self.time_derivs = (bc.field.time_derivative() in meshctxt.all_initializable_fields()) debug.fmsg("time_derivs=", self.time_derivs) regclassfactory.RegisteredClassFactory.__init__( self, bdycondition.FloatBCInitMethod.registry, obj=obj, title=title, callback=callback, fill=fill, expand=expand, scope=scope, name=name, *args, **kwargs)
def parallel_edit_subproblem(menuitem, name, subproblem): debug.fmsg() oldsubp = ooflib.engine.subproblemcontext.subproblems[name] if oldsubp.name() == ooflib.engine.mesh.defaultSubProblemName: raise ooferror.ErrUserError("You can't edit the default Subproblem!") meshctxt = oldsubp.getParent() oldsubp.reserve() oldsubp.begin_writing() try: oldsubpobj = oldsubp.getObject() # Save lists of fields, etc, so that they can be restored in # the new subproblem. oldfields = oldsubp.all_compound_fields() # should be only CompoundFields oldactivefields = [field for field in oldfields if oldsubpobj.is_active_field(field)] oldeqns = oldsubp.all_equations() oldsubp.destroy() finally: oldsubp.end_writing() oldsubp.cancel_reservation() # Create context for new subproblem. newsubp = meshctxt.newSubProblem(subproblem, name) meshctxt.reserve() meshctxt.begin_writing() # Gather switchboard messages and send them all after the lock has # been released. notifications = [] try: # Restore field and equation state saved from old subproblem. for field in oldfields: subproblem.define_field(field) notifications.append(("field defined", name, field.name(), 1)) for field in oldactivefields: subproblem.activate_field(field) notifications.append(("field activated", name, field.name(), 1)) for eqn in oldeqns: subproblem.activate_equation(eqn) notifications.append(("equation activated", name, eqn.name(), 1)) finally: meshctxt.end_writing() meshctxt.cancel_reservation() newsubp.autoenableBCs() for notice in notifications: switchboard.notify(*notice)
def __init__(self, val): self.gtk = gtk.VBox() debug.fmsg("val=", val) # Use makeWidget(v) instead of v.makeWidget() so that # GenericOVWidget will be used if needed for subwidgets. self.widgets = [makeWidget(v) for v in val.args] first = True self.sbcallbacks = [] for w in self.widgets: if not first: self.gtk.pack_start(gtk.HSeparator(), expand=0, fill=0, padding=0) first = False self.gtk.pack_start(w.gtk, expand=0, fill=1, padding=2) self.sbcallbacks.append( switchboard.requestCallbackMain(w.gtk, self.subWidgetChanged))
def read(self, filename): prog = progress.getProgress(os.path.basename(filename), progress.DEFINITE) rows, npts = self.readfile(filename, prog) try: nx = len(rows[0]) ny = len(rows) count = 0 for row in rows: count += 1 if len(row) != nx: raise ooferror.ErrUserError( "Orientation map data appears to be incomplete") # pixel size dx = rows[0][1].position[0] - rows[0][0].position[0] dy = rows[1][0].position[1] - rows[0][0].position[1] pxlsize = primitives.Point(dx, dy) # If we assume that the points are in the centers of the # pixels, then the actual physical size is one pixel bigger # than the range of the xy values. size = rows[-1][-1].position + pxlsize debug.fmsg("nx=", nx, "ny=", ny, "size=", size, "pxlsize=", pxlsize) if config.dimension() == 2: od = orientmapdata.OrientMap(primitives.iPoint(nx, ny), size) else: od = orientmapdata.OrientMap(primitives.iPoint(nx, ny, 1), size) count = 0 for row in rows: for datum in row: self.addDatum(od, datum, pxlsize, ny, count, npts, prog) finally: prog.finish() return od
def parallel_solve(menuitem, subproblem, solver): from ooflib.common import debug debug.fmsg() subpcontext = ooflib.engine.subproblemcontext.subproblems[subproblem] subpcontext.reserve() timedriver = timedrivers.Null() try: try: # null timedriver.apply just calls solverdriver.apply timedriver.apply(solver, subpcontext) except ooferror.ErrProcessAborted: pass ## solved flag is set even if solution did NOT ## converge in order to show how far the solution ## went. subpcontext.solved() finally: subpcontext.cancel_reservation()
def parallel_copy_subproblem(menuitem, subproblem, mesh, name): debug.fmsg() sourcectxt = ooflib.engine.subproblemcontext.subproblems[subproblem] sourceobj = sourcectxt.getObject() # Make a copy of the CSubProblem object, using the clone function # (added to the class by registerCClass). copyobj = sourceobj.clone() # new CSubProblem sourcectxt.begin_reading() try: fields = sourcectxt.all_compound_fields() activefields = [field for field in fields if sourcectxt.getObject().is_active_field(field)] equations = sourceobj.all_equations() finally: sourcectxt.end_reading() meshctxt = ooflib.engine.mesh.meshes[mesh] copyctxt = meshctxt.newSubProblem(copyobj, mesh+':'+name) # new context copyname = copyctxt.path() # Set Fields and Equations in the copy copyctxt.reserve() copyctxt.begin_writing() notifications = [] try: for field in fields: copyobj.define_field(field) notifications.append(("field defined", copyname, field.name(), 1)) for field in activefields: copyobj.activate_field(field) notifications.append(("field activated", copyname, field.name(), 1)) for eqn in sourceobj.all_equations(): copyobj.activate_equation(eqn) notifications.append(("equation activated", copyname, eqn.name(), 1)) finally: copyctxt.end_writing() copyctxt.cancel_reservation() copyctxt.autoenableBCs() for notice in notifications: switchboard.notify(*notice)
def __call__(self,**kwargs): # Check for extra arguments paramnames = [p.name for p in self.params] for argname in kwargs.keys(): if argname not in paramnames: raise ooferror.ErrUserError( "Unexpected argument '%s' in %s constructor" % (argname, self.subclass.__name__)) pdict = {} for p in self.params: try: p.value = kwargs[p.name] except KeyError: pass pdict[p.name] = p.value try: object = self.subclass(**pdict) except TypeError: debug.fmsg("Error creating", self.subclass) debug.fmsg("got arguments=", pdict) debug.fmsg("expected arguments=", self.params) raise if not hasattr(object, 'timestamp'): object.timestamp = timestamp.TimeStamp() return object
def __init__(self, question, *answers, **kwargs): debug.mainthreadTest() if len(answers)==0: raise ooferror.ErrSetupError( "Questioner must have at least one possible answer.") self.answers = answers self.gtk = gtklogger.Dialog(parent=guitop.top().gtk) gtklogger.newTopLevelWidget(self.gtk, "Questioner") hbox = gtk.HBox() self.gtk.vbox.pack_start(hbox, padding=15) hbox.pack_start(gtk.Label(question), padding=15) self.defaultbutton = None try: self.default = kwargs['default'] except KeyError: self.default=None else: if not self.default in answers: self.answers = (self.default,)+answers self.answerdict = {} count = 1 for answer in self.answers: try: stock = _stock[answer] button = self.gtk.add_button(stock, count) # Replace the label on the stock button with the answer text. label = gtkutils.findChild(gtk.Label, button) label.set_text(answer) except KeyError: debug.fmsg('no stock icon for', answer) self.gtk.add_button(answer, count) self.answerdict[count] = answer if answer == self.default: self.gtk.set_default_response(count) count += 1 hbox.show_all()
def rerecordLog(menuitem, filename, checkpoints, use_gui): if gtklogger.replaying(): raise ooferror.ErrUserError( "Multiple GUI logs cannot be replayed simultaneously!") menuitem.root().setOption('post_hook', menucheckpoint) dblevel = 0 if debug.debug(): dblevel = 3 #dblevel = 4 global _replaying, _recording _replaying = True _recording = True progressbar_delay.set_delay(None, 0) # Find a suitable new name for the backup copy of the old log # file. Just append ".bak", but if that file already exists, # append ".bakX", where X is an integer. if not os.path.exists(filename + '.bak'): backupname = filename + '.bak' else: backupname = None count = 2 while not backupname: trialname = "%s.bak%d" % (filename, count) if not os.path.exists(trialname): backupname = trialname count += 1 os.system('cp '+filename+' '+backupname) debug.fmsg("Loading gui script", backupname) gtklogger.replay( backupname, beginCB=activityViewer.openActivityViewer, finishCB=logFinished, debugLevel=dblevel, threaded=thread_enable.query(), exceptHook=loggererror, rerecord=filename, checkpoints=checkpoints, logger_comments=use_gui) #Passing the logger_comments parameter to show the loggergui
def parallel_deactivateField(menuitem, subproblem, field): debug.fmsg() deactivation = False subpcontext = ooflib.engine.subproblemcontext.subproblems[subproblem] subpcontext.reserve() subpcontext.begin_writing() try: subp = subpcontext.getObject() if subp.is_active_field(field): subp.deactivate_field(field) deactivation = True else: reporter.report( "You must define and activate a Field before you can deactivate it.") finally: subpcontext.end_writing() subpcontext.cancel_reservation() if deactivation: subpcontext.autoenableBCs() switchboard.notify("field activated", subproblem, field.name(), 0) subpcontext.changed()
def readData(self, tslfile, prog): count = 1 # line counter lines = tslfile.readlines() nlines = len(lines) data = utils.ReservableList(nlines) angletype = None for line in lines: if line[0] == '#': if line.startswith("Column 1-3", 2): if "radians" in line: angletype = "radians" else: angletype = "degrees" else: # line[0] != '#' substrings = line.split() if len(substrings) < 5: raise ooferror.ErrUserError( "Too few numbers in line %d of %s" % (count, tslfile.name)) values = map(float, substrings[:5]) if angletype == "radians": angles = values[:3] angles[0] = angles[0] - math.radians(self.angle_offset) elif angletype == "degrees": angles[0] = angles[0] - self.angle_offset angles = map(math.radians, values[:3]) else: raise ooferror.ErrDataFileError( "Angle type not specified in TSL data file") data.append(DataPoint( primitives.Point(values[3], values[4]), # position angles, ' '.join(substrings[10:]))) # phase name count += 1 # count actual file lines, comments and all prog.setMessage("read %d/%d lines" % (count, nlines)) prog.setFraction(float(count)/nlines) npts = len(data) debug.fmsg("read %d lines, %d data points" % (count, npts)) return data, None # None ==> hexgrid not detected yet
def parallel_copyEquationState(menuitem, source, target): debug.fmsg() # Let the front-end/pre-IPC call to check this #if source == target: # raise ooferror.ErrUserError('Source and target must differ!') notifications = [] source_subp = ooflib.engine.subproblemcontext.subproblems[source] target_subp = ooflib.engine.subproblemcontext.subproblems[target] source_subp.begin_reading() target_subp.reserve() target_subp.begin_writing() try: source_obj = source_subp.getObject() target_obj = target_subp.getObject() source_eqns = source_obj.all_equations() target_eqns = target_obj.all_equations() for e in target_eqns: if not source_obj.is_active_equation(e): target_obj.deactivate_equation(e) notifications.append( ("equation activated", target, e.name(), 0) ) for e in source_eqns: if not target_obj.is_active_equation(e): target_obj.activate_equation(e) notifications.append( ("equation activated", target, e.name(), 1) ) finally: source_subp.end_reading() target_subp.end_writing() target_subp.cancel_reservation() for n in notifications: switchboard.notify(*n) target_subp.autoenableBCs() target_subp.changed()
def shutdown(exitstatus): # Restore the default exception handler, in case something goes # wrong during shutdown, and the machinery to display OOF # exceptions has already been dismantled. This call must come # before mainthread_delete(). excepthook.assign_excepthook() # On some systems (at least OS X 10.5.7) it's important to delete # the main thread's ThreadState object explicitly before calling # sys.exit(). If called implicitly by sys.exit, the ThreadState # destructor crashes. This must come after the GUI has been # stopped, or else subthreads used in stopping the GUI will fail. threadstate.mainthread_delete() ## gc.garbage is a list of objects which couldn't be deleted, ## because they have circular references *and* __del__ methods. ## Python can't use garbage collection on such objects because it ## doesn't know the order in which to call the __del__ methods. if gc.garbage: debug.fmsg("garbage=", gc.garbage) sys.stdout.flush() sys.exit(exitstatus)
def draw(self, gfxwindow, device): # High level drawing action is done here. Loop through the # layers and drawIfNecessary. Note that if the device is a # bufferedoutputdevice, the low level drawing calls will be # added to the buffer and excecuted after device.show is # called. self.lock.acquire() try: for layer in self.layers: reason = layer.incomputable(gfxwindow) if reason: # ignore incomputable display methods # debug.fmsg('ignoring layer:', layer, reason) layer.clear(device) else: try: layer.drawIfNecessary(gfxwindow, device) except subthread.StopThread: # print layer, "has a problem!" return # TODO SWIG1.3: After conversion to SWIG 1.3, OOF # exceptions will probably be subclasses of # Exception. except (Exception, ooferror.ErrErrorPtr), exc: # This should not happen for computable Outputs debug.fmsg('Exception while drawing!', exc) raise finally: self.lock.release() # If the device is a buffered output device, this flushes # the buffer and executes the low level drawing calls -- # ie actually draws something on the screen. device.show() # Finally, if it is 3D and some layers were actually # drawn, render the scene. We only want to call this at a # high level because 3D rendering is slow. if config.dimension() == 3: gfxwindow.oofcanvas.update_volume_and_render()
def parallel_defineField(menuitem, subproblem, field): debug.fmsg() # subproblem is a name, not an object subpcontext = ooflib.engine.subproblemcontext.subproblems[subproblem] subpcontext.reserve() subpcontext.begin_writing() didsomething = False try: if not subpcontext.is_defined_field(field): subpcontext.getObject().define_field(field) meshctxt = subpcontext.getParent() initializer = meshctxt.get_initializer(field) if initializer: initializer.apply(subpcontext.getObject(), field) meshctxt.update_fields() didsomething = True finally: subpcontext.end_writing() subpcontext.cancel_reservation() if didsomething: subpcontext.autoenableBCs() subpcontext.changed() switchboard.notify("field defined", subproblem, field.name(), 1) switchboard.notify("redraw")
def parallel_mesh_info_query(menuitem, targetname, position, mesh): debug.fmsg() meshcontext = ooflib.engine.mesh.meshes[mesh] skelobj = meshcontext.getSkeleton() femesh = meshcontext.getObject() if targetname=="Node": fnode = femesh.closestNode(position.x, position.y) reportstring="" distance2=-1 if fnode: distance2=(fnode.position()-position)**2 reportstring=""" index=%d type=%s position=(%g,%g) displaced_position=(%g,%g) fields=%s\n""" % (fnode.index(), fnode.classname(), fnode.position().x,fnode.position().y, fnode.displaced_position(femesh).x, fnode.displaced_position(femesh).y, ', '.join(fnode.fieldNames())) #Get the subproblems defined on the mesh that contains the node, #get the active fields in each subproblem, and find the values #of the fields at the node. reportsubpfields=[" subproblems and field values:"] for subpctxt in meshcontext.subproblems(): subp=subpctxt.getObject() if subp.containsNode(fnode): reportsubpfields.append(8*" "+subpctxt.name()) for field in subpctxt.all_compound_fields(): if subp.is_active_field(field): reportsubpfields.append(12*" "+`field`) #The hasField check is redundant because of containsNode above. if fnode.hasField(field): for i in range(field.ndof()): reportsubpfields.append(16*" "+("%g" % field.value(fnode,i))) reportstring+=string.join(reportsubpfields,"\n") if _rank==0: #Get list of squares of distance of node to the click point distance2list=[distance2] #Get list of reportstring(s) from each process reportstringlist=[reportstring] dmin=-1 dmin_proc=-1 msg="Mesh Info Query Node IPC/MPI:\n" #Get report from other processes for proc in range(_size): if proc!=0: reportstringlist.append(mpitools.Recv_String(proc)) distance2list.append(mpitools.Recv_Double(proc)) if distance2list[proc]>=0: dmin=distance2list[proc] dmin_proc=proc #Find closest node among those "nominated" by each process for proc in range(_size): if distance2list[proc]>=0: if distance2list[proc]<dmin: dmin=distance2list[proc] dmin_proc=proc if dmin_proc!=-1: msg+="The closest node to the point clicked at (%g,%g) is from process %d:%s\n" % \ (position.x,position.y,dmin_proc,reportstringlist[dmin_proc]) reporter.report(msg) else: #Backend sends report to front end mpitools.Send_String(reportstring,0) mpitools.Send_Double(distance2,0) ################################################################################ elif targetname=="Element": selem = skelobj.enclosingElement(position) reportstring="" distance2=-1 if selem: felem = femesh.getElement(selem.meshindex) if felem: distance2=(selem.center()-position)**2 mat = felem.material() if mat: matname = mat.name() else: matname = "<No material>" reportstring=""" index=%s type=%d nodes=%s material=%s\n""" % (felem.masterelement().name(), felem.get_index(), string.join(["%s %d at (%g, %g)" % (obj.classname(), obj.index(), obj.position().x, obj.position().y) for obj in felem.node_iterator()],","), matname) #Get the subproblems defined on the mesh, #get the active fields in each subproblem, and find the values #of the fields at the position inside the element. reportsubpfields=[" subproblems and field values:"] for subpctxt in meshcontext.subproblems(): subp=subpctxt.getObject() reportsubpfields.append(8*" "+subpctxt.name()) for field in subpctxt.all_compound_fields(): if subp.is_active_field(field): reportsubpfields.append(12*" "+`field`) masterpos=felem.to_master(position) o=felem.outputField(field,masterpos) valuelist=o.valuePtr().value_list() for val in valuelist: reportsubpfields.append(16*" "+`val`) reportstring+=string.join(reportsubpfields,"\n") if _rank==0: distance2list=[distance2] #Get list of reportstring(s) from each process reportstringlist=[reportstring] dmin=-1 dmin_proc=-1 msg="Mesh Info Query Element IPC/MPI:\n" #Get report from other processes for proc in range(_size): if proc!=0: reportstringlist.append(mpitools.Recv_String(proc)) distance2list.append(mpitools.Recv_Double(proc)) if distance2list[proc]>=0: dmin=distance2list[proc] dmin_proc=proc #Find closest element among those "nominated" by each process for proc in range(_size): if distance2list[proc]>=0: if distance2list[proc]<dmin: dmin=distance2list[proc] dmin_proc=proc if dmin_proc!=-1: msg+="From process %d:" % dmin_proc msg+=reportstringlist[dmin_proc] reporter.report(msg) else: reporter.report("No enclosing element found!\n") else: #Backend sends report to front end mpitools.Send_String(reportstring,0) mpitools.Send_Double(distance2,0)