def sanity_check(menuitem, skeleton, quick): skel = skeletoncontext.skeletonContexts[skeleton].getObject() if quick: sane = skel.quick_sanity_check() else: sane = skel.sanity_check() if not sane: raise ooferror.ErrPyProgrammingError("Skeleton sanity check failed!")
def __pow__(self, other): if other != 2: raise ooferror.ErrPyProgrammingError( "Power operation only defined for exponent equal to 2.") if config.dimension() == 2: return self.x * self.x + self.y * self.y elif config.dimension() == 3: return self.x * self.x + self.y * self.y + self.z * self.z
def __init__(self, comment, font=None): self.font = font self.commentList = [] self.fontList = [] self.pixList = [] # Split comment into paragraphs at blank lines. paragraphs = parasplit.split(comment) for para in paragraphs: # Replace newlines with spaces within paragraphs, and get # rid of excess white space. para = endline.sub(' ', para).strip() # Separate paragraph into strings so that each string has # a single font, by looking for BOLD(...). while para: index_bold = string.find(para, boldtag) # index_image = string.find(para, imagetag) if index_bold != -1: self.commentList.append(para[:index_bold]) self.fontList.append(0) self.pixList.append(0) para = para[index_bold + lenboldtag:] # look for closing ')' endmatch = delimexpr.search(para) if not endmatch: raise ooferror.ErrPyProgrammingError( "Missing delimeter for BOLD tag in tutorial!") boldtext = para[:endmatch.start() + 1] # replace all occurences of '\)' with ')' self.commentList.append(nondelimexpr.sub(')', boldtext)) self.fontList.append('bold') self.pixList.append(0) para = para[endmatch.end():] # elif index_image != -1: # self.commentList.append(para[:index_image]) # self.pixList.append(0) # self.fontList.append(0) # para = para[index_image + lenimagetag:] # # look for closing ')' # endmatch = delimexpr.search(para) # if not endmatch: # raise ooferror.ErrPyProgrammingError( # "Missing delimeter for IMAGE tag in tutorial!") # imagename = para[:endmatch.start()+1] # # replace all occurences of '\)' with ')' # self.commentList.append(nondelimexpr.sub(')', imagename)) # self.pixList.append('image') # self.fontList.append(0) # para = para[endmatch.end():] else: self.commentList.append(para) self.fontList.append(0) self.pixList.append(0) break self.commentList.append('\n\n') self.fontList.append(0) self.pixList.append(0)
def __init__(self, *parameters, **kwargs): debug.mainthreadTest() # A title for the dialog box can be specified by a REQUIRED # 'title' keyword argument. A WidgetScope can be specified # with a 'scope' keyword. If a parent window is specified # with the 'parentwindow' argument, the dialog will be brought # up as a transient window for it. try: scope = kwargs['scope'] except KeyError: scope = None widgetscope.WidgetScope.__init__(self, scope) try: data_dict = kwargs['dialog_data'] except KeyError: pass else: self.__dict__.update(data_dict) try: parentwindow = kwargs['parentwindow'] except KeyError: parentwindow = None try: scopedata = kwargs['data'] except KeyError: pass else: for key, value in scopedata.items(): self.setData(key, value) self.parameters = parameters self.dialog = gtklogger.Dialog(parent=parentwindow, flags=gtk.DIALOG_MODAL) try: title = kwargs['title'] except KeyError: raise ooferror.ErrPyProgrammingError("Untitled dialog!") gtklogger.newTopLevelWidget(self.dialog, 'Dialog-' + kwargs['title']) self.dialog.set_title(title) hbox = gtk.HBox() self.dialog.vbox.pack_start(hbox, expand=0, fill=0, padding=5) hbox.pack_start(gtk.Label(title), expand=1, fill=1, padding=10) self._button_hook() self.table = ParameterTable(parameters, scope=self) self.sbcallback = switchboard.requestCallbackMain( ('validity', self.table), self.validityCB) self.dialog.vbox.pack_start(self.table.gtk, expand=self.table.expandable, fill=True) self.response = None self.sensitize()
def __init__(self, param, scope=None, name=None): parameterwidgets.BooleanWidget.__init__(self, param, scope, name) self.fileSelector = self.scope.findWidget(lambda x: (isinstance( x, (WriteFileSelectorWidget, FakeFileSelectorWidget)))) if self.fileSelector is None: raise ooferror.ErrPyProgrammingError("Can't find file selector") self.set_validity() self.sbcallback = switchboard.requestCallbackMain( self.fileSelector, self.fileSelectorCB)
def sanity_check(menuitem, skeleton, quick): skelctxt = skeletoncontext.skeletonContexts[skeleton] if quick: sane = skelctxt.getObject().quick_sanity_check() else: sane = skelctxt.sanity_check() skelctxt.sane = sane # used by skeleton_modification_test.py if not sane: raise ooferror.ErrPyProgrammingError("Skeleton sanity check failed!")
def parameterTableXRef(self, ptable, widgets): for widget in widgets: if isinstance(widget, FileSelectorWidget): self.fileselector = widget switchboard.requestCallbackMain(self.fileselector, self.fsCB) # self.widgetChanged(self.checkValidity(), interactive=False) return raise ooferror.ErrPyProgrammingError( "ImpliedDirectorySelectorWidget has no FileSelectorWidget.")
def get_other_node(self, node): for n in self._nodes: if n != node and (node not in n.getPartners() or \ node in self._nodes): return n # if we get this far, it's because we've passed an invalid node for this segment. raise ooferror.ErrPyProgrammingError( "Cannot determine which node is the 'other node' for this segment!" )
def set_direction(self, n1, n2): nodes = self.segment.nodes() if nodes[0]==n1 and nodes[1]==n2: self.direction = 1 elif nodes[0]==n2 and nodes[1]==n1: self.direction = -1 else: raise ooferror.ErrPyProgrammingError( "Incorrect node set in SkeletonEdge.")
def __init__( self, name, subclass, modulename, ordering, params=[], propertyType=None, outputs=[], secret=0, interfaceCompatibility=interfaceparameters.COMPATIBILITY_BULK_ONLY, interfaceDiscontinuousFields=[], tip=None, discussion=None): PropertyRegistrationParent.__init__(self, subclass, modulename, ordering, secret) # Save the fully-qualified name for error reporting. This # datum should not be confused with the parameter "name", # which contains only the leaf part of the FQN. self._name = name # Keep a copy of the local parameters. self.params = params # Equations to which this property makes *direct* # contributions (ie, not via a flux). This is a basically a # dictionary of _PSInfo objects, keyed by Equation. self._equations = _PropertyStructureInfo() # Ditto, for Fluxes instead of Equations self._fluxes = _PropertyStructureInfo() self._constraints = _PropertyStructureInfo() self._outputs = outputs # names of PropOutputs it contributes to self.tip = tip self.discussion = discussion # discussion string or loadFile if propertyType is None: raise ooferror.ErrPyProgrammingError( "Missing propertyType in PropertyRegistration %s" % name) self._propertyType = propertyType #Interface branch self._interfaceCompatibility = interfaceCompatibility self._interfaceDiscontinuities = interfaceDiscontinuousFields # name-indexed dictionary of materials in which this property # occurs -- it is managed by the MaterialProps objects, except # in the new_params call, where it is local. self.materials = {} # At creation time, all parameters are new. self.new_params() # Add yourself to the AllProperties data object. "name" # must be the fully qualified name of the property. AllProperties[name] = self
def set_defaults(self): # For the regular RegisteredClassFactory, this copies the # values out of the gui and into the Parameters in the # Registrations (which are the same as the Parameters in the # menus) so that calling menuitem.callWithDefaults() does the # right thing. This doesn't make sense for the # RegisteredClassListFactory, since the menu Parameter is a # list of RegisteredClass objects, not the parameters of the # objects themselves. So don't use this, use get_value() instead. raise ooferror.ErrPyProgrammingError( "Don't use RegisteredClassListFactory.set_defaults()!")
def __init__(self, param, scope=None, name=None): parameterwidgets.BooleanWidget.__init__(self, param, scope, name) self.skelwidget = scope.findWidget( lambda w: isinstance(w, whowidget.WhoWidget) and w.whoclass is skeletoncontext.skeletonContexts) if self.skelwidget is None: raise ooferror.ErrPyProgrammingError( "Can't find WhoWidget for Skeleton") self.sbcallback = switchboard.requestCallbackMain( self.skelwidget, self.sensitize) self.sensitize()
def _polygonize3(self, points, norm, ipts): # There are only two possible orderings, and only one of # them creates a polygon with positive area. for ordering in [(0, 1, 2), (0, 2, 1)]: area = 0.0 for i in range(3): crossprod = ipts[ordering[i]].cross(ipts[ordering[(i + 1) % 3]]) area += crossprod.dot(norm) if area > 0: return SpaceCurve(points[i] for i in ordering) raise ooferror.ErrPyProgrammingError("Plane._polygonize3 failed.")
def advertise(obj): # This code is ugly, but at least it's compact. It's not much # uglier than the previous version, which required other code to # call advertiseField, et al, directly. if isinstance(obj, field.FieldPtr): return advertiseField(obj) if isinstance(obj, flux.FluxPtr): return advertiseFlux(obj) if isinstance(obj, equation.EquationPtr): return advertiseEquation(obj) raise ooferror.ErrPyProgrammingError("Don't know what to do with %s!" % obj)
def conjugatePair(name, equation, eqncomp, field, fieldcomp): # eqncomp and fieldcomp can either be a single FieldIndex object, # or a list of them. The lists must have the same length. if isinstance(eqncomp, FieldIndexPtr): eqncomp = [eqncomp] if isinstance(fieldcomp, FieldIndexPtr): fieldcomp = [fieldcomp] if len(eqncomp) != len(fieldcomp): raise ooferror.ErrPyProgrammingError( "Bad index specification in conjugatePair") for (ecomp, fcomp) in zip(eqncomp, fieldcomp): listofconjugatepairs.add( ConjugatePairObj(name, equation, ecomp, field, fcomp))
def __call__(self, skeleton, selection): skel = skeleton.getObject() interfacemsplugin = skel.MS.getPlugIn("Interfaces") try: interfacedef = interfacemsplugin.namedinterfaces[self.interface] except KeyError: #Should not happen raise ooferror.ErrPyProgrammingError("Interface not found!") seglist = [] for segment in skel.segments.values(): yes, side1elem = interfacedef.isInterfaceSegment(segment, skel) if yes: seglist.append(segment) selection.start() selection.clear() selection.select(seglist)
def socketWrite(data): if type(data)==types.StringType: global socketInput if socketInput is not None: # rank != 0, real socket exists, use it. socketInput.putData(data) else: # rank==0, use the buffer. global _buffer_lock, _buffer if len(data)>0: _buffer += data _buffer_lock.release() # Buffer is not empty, so leave lock in "released" state. else: raise ooferror.ErrPyProgrammingError( "Non-string data passed to socketWrite.")
def integrate(self, domain, output, order, power=1): femesh = domain.meshctxt.getObject() gauss_pts = self.element.integration_points(order) pts = [x.mastercoord() for x in gauss_pts] wgts = [x.weight() for x in gauss_pts] if power == 0: val = output.instancefn(output) return reduce(lambda x, y: x + y, wgts) * val.one() else: # power > 0 vals = output.evaluate(femesh, [self.element], [pts]) if power == 1: return reduce(lambda x, y: x + y[0] * y[1], zip(wgts, vals), vals[0].zero()) if power > 1: return reduce(lambda x, y: x + y[0] * (y[1]**power), zip(wgts, vals), vals[0].zero()) raise ooferror.ErrPyProgrammingError("Impossible situation arose")
def __init__(self, param, scope=None, name=None, verbose=False): self.state = None self.widget = chooser.ChooserWidget([], self.chooserCB, name=name) parameterwidgets.ParameterWidget.__init__(self, self.widget.gtk, scope=scope, verbose=verbose) if not (guilogger.recording() or guilogger.replaying()): self.fileSelector = self.scope.findWidget( lambda x: (isinstance(x, WriteFileSelectorWidget))) else: self.fileSelector = self.scope.findWidget( lambda x: (isinstance(x, FakeFileSelectorWidget))) if self.fileSelector is None: raise ooferror.ErrPyProgrammingError("Can't find file selector") self.set_options() self.widgetChanged(True, True) self.sbcallback = switchboard.requestCallbackMain(self.fileSelector, self.fileSelectorCB)
def __init__(self, param, scope=None, name=None): if scope is None: raise ooferror.ErrPyProgrammingError( "FluxProfileSetWidget instanced with no scope.") self.scope=scope self.fluxwidget = scope.findWidget( lambda x: x.__class__==meshparamwidgets.FluxParameterWidget) self.sbcb = switchboard.requestCallbackMain(self.fluxwidget, self.checkFlux) gtk_obj = gtk.VBox() parameterwidgets.ParameterWidget.__init__(self, gtk_obj, scope, name) self.profileset = [] # Profiles themselves. self.widgetset = [] # LabelledProfileRCF objects self.set_value(param.value) # TODO LATER: The real right way to handle validity is to behave # as a proper container, and catch the validity changes of the # enclosed RCFs. However, we happen to know that we are always # valid, so we do it the simple way. self.widgetChanged(1, interactive=0)
def remove_option(item, argument=None): # item is the *full* name of an option, but it may not be spelled # out in full in sys.argv. It also may have =argument appended to it # in sys.argv. Look for the possible matches. for i in range(len(sys.argv)): if item.startswith(sys.argv[i].split('=')[0]): if argument is None: del sys.argv[i] return if '=' in sys.argv[i] and sys.argv[i].split('=', 1)[1] == argument: del sys.argv[i] return if i + 1 < len(sys.argv) and sys.argv[i + 1] == argument: del sys.argv[i] del sys.argv[i] return # This should never happen. getopt has already checked that the # options are well formed, so there should be nothing # unrecognizable in the list. raise ooferror.ErrPyProgrammingError("Failed to remove option: %s %s" % (item, argument))
def renameBoundary(self, oldname, newname): if oldname == newname: return if newname in self.allBoundaryNames(): raise ooferror.ErrSetupError("Name %s already in use." % newname) if config.dimension() == 2 and runtimeflags.surface_mode: if newname in self.allInterfaceNames(): raise ooferror.ErrSetupError( "Name %s is already in use as an interface name." % newname) ## TODO 3.1: Use virtual methods in the boundary classes instead ## of this ugly if/elif. There should be just one dict for ## the name lookup. if oldname in self.faceboundaries: bdydict = self.faceboundaries elif oldname in self.edgeboundaries: bdydict = self.edgeboundaries elif oldname in self.pointboundaries: bdydict = self.pointboundaries else: raise ooferror.ErrPyProgrammingError( "Boundary name %s not found." % oldname) bdydict[newname] = bdydict[oldname] del bdydict[oldname] # SkelContextBoundary.rename calls Skeleton.renameBoundary bdydict[newname].rename(newname) # Maintain consistency in Meshes for mesh in self.getMeshes(): mesh.renameBoundary(oldname, newname) switchboard.notify("boundary renamed", self) # self.bdytimestamp.increment() self.selectBoundary(newname) switchboard.notify("new boundary configuration", self)
def __init__(self, name, regclass, ordering, params=[], secret=0, tip=None, **kwargs): registeredclass.Registration.__init__(self, name, BoundaryModifier, regclass, ordering, params=params, secret=secret, tip=tip, **kwargs) if issubclass(regclass, PointBoundaryModifier): self.modifiertype = PointBoundaryModifier elif issubclass(regclass, EdgeBoundaryModifier): self.modifiertype = EdgeBoundaryModifier else: raise ooferror.ErrPyProgrammingError( "Attempt to register unknown type of boundary modifier.")
def renameBoundary(self, oldname, newname): if oldname == newname: return if newname in self.allBoundaryNames(): raise ooferror.ErrSetupError("Name %s is already in use." % newname) #Interface branch if config.dimension() == 2 and runtimeflags.surface_mode: if newname in self.allInterfaceNames(): raise ooferror.ErrSetupError( "Name %s is already in use as an interface name." % newname) if oldname in self.edgeboundaries: dict = self.edgeboundaries elif oldname in self.pointboundaries: dict = self.pointboundaries else: raise ooferror.ErrPyProgrammingError( "Boundary name %s not found." % oldname) dict[newname] = dict[oldname] del dict[oldname] # SkelContextBoundary.rename calls Skeleton.renameBoundary dict[newname].rename(newname) # Maintain consistency in Meshes for mesh in self.getMeshes(): mesh.renameBoundary(oldname, newname) switchboard.notify("boundary renamed", self) self.bdytimestamp.increment() self.selectBoundary(newname)
def start(self): raise ooferror.ErrPyProgrammingError("Worker.start must be redefined.")
def addEdge(self, edge): if config.dimension() == 2 and edge.segment.nElements() != 1: raise ooferror.ErrPyProgrammingError( "Attempt to insert interior segment in exterior boundary.") self.edges.append(edge)
def getSelectionContext(self, skeletoncontext): raise ooferror.ErrPyProgrammingError( "SkeletonSelectionMode.getSelectionContext() needs to be redefined" " in class " + self.__class__.__name__)
def getGroupMenu(self): raise ooferror.ErrPyProgrammingError( "SkeletonSelectionMode.getGroupMenu() needs to be redefined" " in class " + self.__class__.__name__)
def newLayer(self): raise ooferror.ErrPyProgrammingError("%s.newLayer is not defined!" % self.__class__.__name__)
def animationTimes(self): # Return a list of available times. raise ooferror.ErrPyProgrammingError( "Someone forgot to redefine animationTimes for", self.__class__.__name__)