Exemple #1
0
    def __init__(self, name, registeredclass, subclass, ordering,
                 params=[], secret=0, tip=None, discussion=None, **kwargs):

        self._name = name
        self.subclass = subclass
        if type(registeredclass) in (ListType, TupleType):
            self.registeredclasses = tuple(registeredclass[:])
        else:
            self.registeredclasses = (registeredclass,)
        self.ordering = ordering
        self.params = params
        self.secret = secret
        self.tip = tip
        self.discussion = discussion
        # Registered subclasses must have unique names in the main OOF
        # namespace:
        try:
            scls = utils.OOFeval(subclass.__name__)
        except NameError:
            # ok, name isn't already defined.
            self.exportToOOF()
        else:
            raise NameError("RegisteredClass subclass '%s' is already defined."
                            % subclass.__name__)

        self.__dict__.update(kwargs)
        # Store the registration.  Extract it first, so that it also
        # works for the RegisteredCClasses.
        for registeredclass in self.registeredclasses:
            registeredclass.registry.append(self)
            # Sorting each time is inefficient, but doesn't happen often.
            registeredclass.registry.sort()
            switchboard.notify(registeredclass)
Exemple #2
0
    def new_material(self, name,
                     materialtype=material.MATERIALTYPE_BULK,
                     *props):
        # If a Material already exists with the same name, just
        # redefine it by deleting its old Properties and adding the
        # new ones.  *Don't* try deleting the Material entirely and
        # recreating it from scratch, which seems like the easy way to
        # go. Deleting the Material would delete it from any
        # Microstructures and Meshes that use it.
        try:
            matprop = self.materials[name]
        except KeyError:
            matprop = MaterialProps(name, materialtype)
            self.materials[name] = matprop
        else:
            matprop.delete_all_props()

        mat = matprop.actual
        for p in props:
            mat.addProperty(p)
            reg = p.registration()
            path = AllProperties.data.reverse_dict[reg].path()
            matprop.add_prop_ref(path, reg)
            reg.materials[name]=(matprop, p)

        switchboard.notify("new_material", name)
        for ms in microStructures.actualMembers():
            if mat in material.getMaterials(ms.getObject()):
                switchboard.notify("materials changed in microstructure",
                                   ms.getObject())
Exemple #3
0
def _defineField(menuitem, subproblem, field):
    if parallel_enable.enabled():
        ipcsubpmenu.Field.Define(subproblem=subproblem, field=field)
    else:
        # 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.getParent().getObject(),
                                      field, singleFieldDef=True)
                meshctxt.update_fields()
                didsomething = True
        finally:
            subpcontext.end_writing()
            subpcontext.cancel_reservation()
        if didsomething:
            subpcontext.autoenableBCs()
            subpcontext.changed("Field defined.")
            switchboard.notify("field defined", subproblem, field.name(), 1)
            switchboard.notify("redraw")
Exemple #4
0
    def bdyPropagate(self, name, contextbdy):
        # Replace the boundaries up and down the stack with a suitably
        # mapped version of the modified boundary.  Operate only
        # on sheriffs, and don't re-operate on the original object.

        # Then, ensure that the modifications get to the meshes --
        # in this case, we need to run over the whole stack, because
        # although deputy skeletons don't have boundaries, their
        # meshes nevertheless do.

        start = self.getObject().sheriffSkeleton() # Current sheriff
        children = self.undobuffer.getToTop()

        current = start
        for c in withoutDeputies(children[1:]):
            if not c is start:
                contextbdy.remove(c)
                contextbdy.map(current, c,
                               direction=skeletonboundary.MAP_DOWN)
                current = c

        current = start
        parents = self.undobuffer.getToBottom()
        for p in withoutDeputies(parents[1:]):
            if not p is start:
                contextbdy.remove(p)
                contextbdy.map(current, p, direction=skeletonboundary.MAP_UP)
                current = p

        # Update the boundaries in the Meshes to match the boundaries
        # in the Skeleton.
        for mesh in self.getMeshes():
            mesh.getObject().skeleton.pushBoundaryToMesh(mesh, name)

        switchboard.notify("new boundary configuration", self)
Exemple #5
0
    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)
Exemple #6
0
    def createPointBoundary(self, name, node_set,
                            exterior=None, autoselect=1):
        bdy = self.getObject().makePointBoundary(name, node_set, exterior)

        for mesh in self.getMeshes():
            mesh.newPointBoundary(name, bdy)

        context_bdy = bdy.makeContextBoundary(self, name, self.getObject())
        self.pointboundaries[name] = context_bdy
        
        # Propagation up and down.
        # See routine above for nomenclature lament.
        # DeputySkeleton.mapBoundary is a no-op.
        current = self.getObject()
        children = self.undobuffer.getToTop()
        for c in withoutDeputies(children[1:]):
            c.mapBoundary(context_bdy, current,
                          direction=skeletonboundary.MAP_DOWN)
            current = c

        current = self.getObject()
        parents = self.undobuffer.getToBottom()
        for p in withoutDeputies(parents[1:]):
            p.mapBoundary(context_bdy, current,
                          direction=skeletonboundary.MAP_UP)
            current = p

        switchboard.notify("new boundary created", self)
        if autoselect:
            self.selectBoundary(name)
        self.bdytimestamp.increment()
Exemple #7
0
    def postProcess(self, context):
        ## global Pcount
        ## Pcount += 1
        ## random.seed(1)
        skeleton = context.getObject()
        prog = self.makeProgress()
        self.count = 0
        prog.setMessage(self.header)
        before = skeleton.energyTotal(self.criterion.alpha)

        while self.iteration.goodToGo():
            self.count += 1
            # the context acquires the writing permissions inside
            # coreProcess.
            self.coreProcess(context)
            self.updateIteration(prog)

            if prog.stopped():
                break

        switchboard.notify("skeleton nodes moved", context)
        if prog.stopped():
            self.targets.cleanUp()
            return

        after = skeleton.energyTotal(self.criterion.alpha)
        if before:
            rate = 100.0*(before-after)/before
        else:
            rate = 0.0
        diffE = after - before
        reporter.report("%s deltaE = %10.4e (%6.3f%%)"
                        % (self.outro, diffE, rate))
        self.targets.cleanUp()
        prog.finish()
def copyMicrostructure(menuitem, microstructure, name):
    if parallel_enable.enabled():
        microstructureIPC.msmenu.Copy(microstructure=microstructure,name=name)
        return

    ms = ooflib.common.microstructure.microStructures[microstructure]
    ms.begin_reading()
    grouplist = []
    try:
        sourceMS = ms.getObject()
        newMS = sourceMS.nominalCopy(name)
        newMScontext = ooflib.common.microstructure.microStructures[name]
        # First, copy images and load them to copied MS.
        for imagectxt in sourceMS.getImageContexts():
            sourceimage = imagectxt.getObject()
            immidge = sourceimage.clone(sourceimage.name())
            imagecontext.imageContexts.add([newMS.name(),immidge.name()],
                                           immidge,
                                           parent=newMScontext)
        # Copy pixel groups
        for grpname in sourceMS.groupNames():
            sourcegrp = sourceMS.findGroup(grpname)
            # Ignore "newness", all groups will be new.
            (newgrp, newness) = newMS.getGroup(grpname)
            newgrp.add(sourcegrp.members())
            newgrp.set_meshable(sourcegrp.is_meshable())
            grouplist.append(newgrp)
    finally:
        ms.end_reading()
        
    for g in grouplist:
        switchboard.notify("new pixel group", g)
Exemple #9
0
 def selectNode(self, menuitem, position):
     context = apply(self.gfxwindow().topwho, self.whoset)
     if context:
         skeleton = context.getObject()
         self.selectednode.set(skeleton.nearestNode(position))
         switchboard.notify('redraw')
         switchboard.notify(("node selected", self))
Exemple #10
0
def createMSFromImageFile(menuitem, filename, microstructure_name,
                          height, width, depth=0):
       
 
    if (height!=automatic and height<=0) or \
           (width!=automatic and width<=0) or \
           (config.dimension()==3 and depth!=automatic and depth<=0):
        raise ooferror.ErrUserError(
            "Negative microstructure sizes are not allowed.")

    image = autoReadImage(filename, height, width, depth)
    ms = ooflib.common.microstructure.Microstructure(microstructure_name,
                                              image.sizeInPixels(),
                                              image.size())

    immidgecontext = imagecontext.imageContexts.add(
        [ms.name(), image.name()], image,
        parent=ooflib.common.microstructure.microStructures[ms.name()])
 
    if parallel_enable.enabled():
        # For the rear-end guys
        from ooflib.image.IO import oofimageIPC
        oofimageIPC.imenu.Create_From_Imagefile_Parallel(
            msname=microstructure_name,
            imagename=image.name())

    switchboard.notify("redraw")
Exemple #11
0
def forgetTextOutputStreams():
    _streamsLock.acquire()
    try:
        _allStreams.clear()
    finally:
        _streamsLock.release()
    switchboard.notify("output destinations changed")
Exemple #12
0
def createMSFromImage(menuitem, name, width, height, image):
    if parallel_enable.enabled():
        # For the back-end processes
        from ooflib.image.IO import oofimageIPC
        oofimageIPC.imenu.Create_From_Image_Parallel(
            msname=name, image=image)

    # For serial mode #0 in parallel mode
    imagepath = labeltree.makePath(image)
    immidgecontext = imagecontext.imageContexts[image]
    immidge = immidgecontext.getObject().clone(imagepath[-1])

    size = immidge.size() # Point object.
    if width!=automatic.automatic:
        size[0]=width
    if height!=automatic.automatic:
        size[1]=height
        
    ms = ooflib.common.microstructure.Microstructure(name,
                                                   immidge.sizeInPixels(),
                                                   size)
    newimagecontext = imagecontext.imageContexts.add(
        [name, immidge.name()],
        immidge,
        parent=ooflib.common.microstructure.microStructures[name])
    switchboard.notify("redraw")
Exemple #13
0
 def removeSelectionFromGroup(self, name):
     if name in self.groups:
         clist, plist = self.trackerlist()
         for o in self.get_selection():
             o.remove_from_group(name, clist, plist)
         switchboard.notify("groupset member resized",
                            self.skeletoncontext, self)
Exemple #14
0
 def _skeleton_from_mstructure(menuitem, name, microstructure, x_elements, y_elements, skeleton_geometry):
     if parallel_enable.enabled():  # PARALLEL
         skeleton.initialSkeletonParallel(name, microstructure, x_elements, y_elements, skeleton_geometry)
     else:
         ms = microStructures[microstructure].getObject()
         skel = skeleton.initialSkeleton(name, ms, x_elements, y_elements, skeleton_geometry)
     switchboard.notify("redraw")
    def creatorcallback(self, menuitem, **kwargs):
        treepath = string.split(menuitem.path(),".")[3:]
        reg = self.data[treepath].object
        name = menuitem.params[0].value

        # Collision looks for the name under this tree, and if it
        # finds it, checks if the parameter values are all equal.  If
        # a collision occurs and the parameters conflict, an exception
        # is raised.  If collision returns "true", that means a
        # collision occurred but the parameters matched.  If collision
        # returns "false", a collision did not occur.
        namecollision, parametercollision = reg.collision(name,
                                                          menuitem.params[1:])
        if namecollision:               # name is a duplicate
            if parametercollision:      # parameters disagree
                if name != "":
                    raise ooferror.ErrSetupError("Named property in datafile conflicts with existing property '%s'" % name)
                # reparametrization of unnamed property
                if reg.materials:
                    raise ooferror.ErrSetupError("Unnamed property in datafile conflicts with existing property '%s'" % name)
                # Unnamed property is being reparametrized, but it's
                # not used in any materials, so it's ok.
                reg.new_params(**kwargs)
                switchboard.notify("redraw")
            # A name collision with no parameter collision doesn't
            # require any action.  The data file contained a property
            # identical to an existing property.
        else:
            # No collision, we must create a new NamedRegistration.
            # We know it's a NamedRegistration because unnamed
            # property registrations *always* produce a name conflict.
            fullname = string.join( treepath + [name], ":")
            newreg = reg.named_copy(fullname, menuitem.params[1:])
            switchboard.notify("redraw")
Exemple #16
0
 def addSelectionToGroup(self, name):
     if name in self.groups:
         clist, plist = self.trackerlist()
         for o in self.get_selection():
             o.add_to_group(name, clist, plist)
         switchboard.notify("groupset member resized",
                            self.skeletoncontext, self)
Exemple #17
0
def parallel_copyEquationState(menuitem, source, target):
    notifications = []
    source_subp = ooflib.engine.mesh.meshes[source].get_default_subproblem()
    target_subp = ooflib.engine.mesh.meshes[target].get_default_subproblem()
    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_subp.path(), 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_subp.path(), 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 _bcremove(self, mesh, name):
    if parallel_enable.enabled():
        boundaryconditionIPC.ipcbcmenu.Delete(mesh=mesh,name=name)
    else:
        meshcontext = ooflib.engine.mesh.meshes[mesh]
        meshcontext.rmBdyConditionByName(name)
        switchboard.notify("mesh changed", ooflib.engine.mesh.meshes[mesh])
Exemple #19
0
def renamePixelGroup_parallel(menuitem, microstructure, group, new_name):
    # "group" arg is the old group name.
    mscontext = ooflib.common.microstructure.microStructures[microstructure]
    ms = mscontext.getObject()
    mscontext.begin_writing()
    renamed = False
    try:
        grp = ms.findGroup(group)
        # Don't just say "if grp" here.  PixelGroup has a __len__
        # function, so empty groups evaluate to "false".
        if grp is not None:
            ms.renameGroup(group, new_name)
            renamed = True
            #Interface branch (only implemented for 2D)
            if config.dimension() == 2:
                interfacemsplugin=ms.getPlugIn("Interfaces")
                interfacemsplugin.renameGroup(group, new_name)
        else:
            raise ooferror.ErrUserError("There is no pixel group named %s!"
                                        % group)
    finally:
        mscontext.end_writing()

    if renamed:
        switchboard.notify('renamed pixel group', grp, group, new_name)
Exemple #20
0
 def clearQuerier(self):
     self.last_position = None
     if self.querier:
         self.querier.set()
         self.peeker.reset()
         self.redraw()
     switchboard.notify((self, "clear"))
Exemple #21
0
    def pushModificationSignal(self):
        self.pause_writing()
        # Switchboard callbacks usually run on subthreads -- this
        # pause/resume pair might be useless, but it's harmless.
        switchboard.notify(('who changed', self.classname), self)
##        self.parallelPushModification(self._obj)
        self.resume_writing()
Exemple #22
0
 def redefined(self):
     # Called when the things affecting the subproblem definition
     # itself have changed.  For example, a MaterialSubProblem is
     # redefined when its Material is assigned to or removed from
     # pixels.
     self.getObject().redefined()
     switchboard.notify("subproblem redefined", self.path())
Exemple #23
0
 def removeInterface(self,name):
     try:
         del self.namedinterfaces[name]
         interfacenames=self.getInterfaceNames()
         doomedinterfaces=[name]
         #Because of the possibility of compound interfaces (e.g. union),
         #we must search the other interfaces for the presence
         #of the interface corresponding to name.
         for interfacename in interfacenames:
             interfaceobj=self.namedinterfaces[interfacename]
             if interfaceobj.hasInterface(name):
                 del self.namedinterfaces[interfacename]
                 doomedinterfaces.append(interfacename)
         self.removeMaterialFromInterfaces(doomedinterfaces)
         self.unselectInterface()
         #Remove boundary conditions that refer to the doomedinterfaces
         meshclass=ooflib.engine.mesh.meshes
         msname=self.microstructure.name()
         for meshkey in meshclass.keys(base=msname):
             meshctxt=meshclass[[msname]+meshkey]
             for doomedinterfacename in doomedinterfaces:
                 meshctxt.removeInterface(doomedinterfacename)
         self.rebuildMeshes()
         switchboard.notify("interface removed",self.microstructure)
     except KeyError:
         pass
Exemple #24
0
 def delete(self, name):
     path = makePath(name)
     if len(path) == 1:
         for i in range(len(self.nodes)): # Use index so "del" works.
             if self.nodes[i].name==path[0]:
                 # Think of the children.
                 if len(self.nodes[i].nodes)!=0:
                     raise ErrUserError(
                         "Attempt to delete non-leaf from labeltree.")
                 else:
                     # Then do the deletion, in the tree and
                     # in the menus and reverse dictionary.
                     oldnode = self.nodes[i]
                     if self.nodes[i].object is not None:
                         del self.root.reverse_dict[self.nodes[i].object]
                     del self.nodes[i]
                     for menu in self.menus.values():
                         menu.removeItem(path[0])
                     # Tell the switchboard...
                     switchboard.notify((self.root, "delete"), oldnode)
                 break 
                     
     # Otherwise, not at bottom. Recurse. 
     else:
         nodename = path[0]
         for node in self.nodes:
             if node.name == nodename:
                 node.delete(path[1:])
                 break
Exemple #25
0
 def moveNode(self, menuitem, origin, destination):
     skelcontext = self.gfxwindow().topwho('Skeleton')
     if skelcontext:
         #
         if parallel_enable.enabled():
             from ooflib.engine.IO import skeletonIPC
             skeletonIPC.smenu.Move_Node_Helper(origin=origin,
                                                destination=destination,
                                                allow_illegal=self.allow_illegal,
                                                skeletonpath=skelcontext.path())
             return
         #
         skeleton = skelcontext.getObject().deputyCopy()
         skeleton.activate()
         node = skeleton.nearestNode(origin)
         skelcontext.reserve()
         skelcontext.begin_writing()
         try:
             skeleton.moveNodeTo(node, destination)
             if node.illegal():
                 if self.allow_illegal==1:
                     skeleton.setIllegal()
                 else:
                     node.moveBack()
             elif skeleton.illegal(): # node motion may have rehabilitated
                 skeleton.checkIllegality()
             skelcontext.pushModification(skeleton)
         finally:
             skelcontext.end_writing()
             skelcontext.cancel_reservation()
         skeleton.needsHash()
         switchboard.notify('redraw')
Exemple #26
0
def copyPixelGroup(menuitem, microstructure, group, name):
    if parallel_enable.enabled():
        pixelgroupIPC.ipcpixgrpmenu.Copy(microstructure=microstructure,
                                         group=group,
                                         name=name)
        return
    if group != name:
        mscontext = ooflib.common.microstructure.microStructures[microstructure]
        ms = mscontext.getObject()
        mscontext.begin_writing()
        newness = False
        try:
            oldgroup = ms.findGroup(group)
            if oldgroup is not None:
                (newgroup, newness) = ms.getGroup(name)
                newgroup.addWithoutCheck(oldgroup.members())
            else:
                raise ooferror.ErrUserError("There is no pixel group named %s!"
                                            % group)
        finally:
            mscontext.end_writing()
            
        if newness:
            switchboard.notify("new pixel group", newgroup)
        switchboard.notify("changed pixel group", newgroup, microstructure)
Exemple #27
0
def renamePixelGroup(menuitem, microstructure, group, new_name):
    if parallel_enable.enabled():
        pixelgroupIPC.ipcpixgrpmenu.Rename(microstructure=microstructure,
                                           group=group,
                                           new_name=new_name)
        return

    # "group" arg is the old group name.
    mscontext = ooflib.common.microstructure.microStructures[microstructure]
    ms = mscontext.getObject()
    mscontext.begin_writing()
    renamed = False
    try:
        grp = ms.findGroup(group)
        # Don't just say "if grp" here.  PixelGroup has a __len__
        # function, so empty groups evaluate to "false".
        if grp is not None:
            ms.renameGroup(group, new_name)
            renamed = True
            if config.dimension() == 2 and runtimeflags.surface_mode:
                interfacemsplugin=ms.getPlugIn("Interfaces")
                interfacemsplugin.renameGroup(group, new_name)
        else:
            raise ooferror.ErrUserError("There is no pixel group named %s!"
                                        % group)
    finally:
        mscontext.end_writing()

    if renamed:
        switchboard.notify('renamed pixel group', grp, group, new_name)
Exemple #28
0
 def renameInterface(self,oldname,newname):
     if oldname==newname:
         return
     if newname in self.getCurrentReservedNames():
         raise ooferror.ErrSetupError("Name %s already in use." % newname)
     try:
         obj=self.namedinterfaces[oldname]
         del self.namedinterfaces[oldname]
         self.namedinterfaces[newname]=obj
         interfacenames=self.getInterfaceNames()
         #Because of the possibility of compound interfaces (e.g. union),
         #we must search the other interfaces for the presence
         #of the interface corresponding to oldname.
         for interfacename in interfacenames:
             interfaceobj=self.namedinterfaces[interfacename]
             interfaceobj.renameInterface(oldname,newname)
         #interface must also be renamed in the list of
         #material assignments
         matname=self.getInterfaceMaterialName(oldname)
         self.removeMaterialFromInterfaces([oldname])
         self.assignMaterialToInterfaces(matname,[newname])
         #Rename the interface in the boundary conditions
         #and in the edgements.
         meshclass=ooflib.engine.mesh.meshes
         msname=self.microstructure.name()
         for meshkey in meshclass.keys(base=msname):
             meshctxt=meshclass[[msname]+meshkey]
             meshctxt.renameInterface(oldname,newname)
         self.selectInterface(newname)
         switchboard.notify("interface renamed",self.microstructure)
     except KeyError:
         pass
Exemple #29
0
 def clearGroup(self, *names):
     if names:
         for name in names:
             if name in self.groups:
                 for t in self.tracker.values():
                     t.clear_group(name)
         switchboard.notify("groupset member resized",
                            self.skeletoncontext, self)
Exemple #30
0
 def assignMaterial(self, groupname, material):
     ts = timestamp.TimeStamp()
     ts.increment()
     self.materials[groupname] = (material, ts)
     switchboard.notify("materials changed in skeleton", self.skeletoncontext)
     for mesh in self.skeletoncontext.getMeshes():
         mesh.refreshMaterials(self.skeletoncontext)
     switchboard.notify("redraw")
Exemple #31
0
def _copyEquationState(menuitem, source, target):
    if source == target:
        raise ooferror.ErrUserError('Source and target must differ!')
    if parallel_enable.enabled():
        ipcsubpmenu.Copy_Equation_State(source=source, target=target)
        return

    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("Equations changed.")
Exemple #32
0
 def widgetChanged(self, validity, interactive):
     if self._valid and not validity:
         self._valid = 0
         switchboard.notify(('validity', self), 0)
     elif not self._valid and validity:
         self._valid = 1
         switchboard.notify(('validity', self), 1)
     switchboard.notify(self, interactive)
    def creatorcallback(self, menuitem, **kwargs):
        treepath = string.split(menuitem.path(), ".")[3:]
        reg = self.data[treepath].object
        name = menuitem.params[0].value

        # Collision looks for the name under this tree, and if it
        # finds it, checks if the parameter values are all equal.  If
        # a collision occurs and the parameters conflict, an exception
        # is raised.  If collision returns "true", that means a
        # collision occurred but the parameters matched.  If collision
        # returns "false", a collision did not occur.
        namecollision, parametercollision = reg.collision(
            name, menuitem.params[1:])
        if namecollision:  # name is a duplicate
            if parametercollision:  # parameters disagree
                if name != "":
                    raise ooferror.ErrSetupError(
                        "Named property in datafile conflicts with existing property '%s'"
                        % name)
                # reparametrization of unnamed property
                if reg.materials:
                    raise ooferror.ErrSetupError(
                        "Unnamed property in datafile conflicts with existing property '%s'"
                        % name)
                # Unnamed property is being reparametrized, but it's
                # not used in any materials, so it's ok.
                reg.new_params(**kwargs)
                switchboard.notify("redraw")
            # A name collision with no parameter collision doesn't
            # require any action.  The data file contained a property
            # identical to an existing property.
        else:
            # No collision, we must create a new NamedRegistration.
            # We know it's a NamedRegistration because unnamed
            # property registrations *always* produce a name conflict.
            fullname = string.join(treepath + [name], ":")
            newreg = reg.named_copy(fullname, menuitem.params[1:])
            switchboard.notify("redraw")
Exemple #34
0
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()
Exemple #35
0
    def createPointBoundary(self,
                            name,
                            node_set,
                            exterior=False,
                            autoselect=1):

        # TODO OPT: get rid of call to list, needs typemap for sets
        bdy = self.getObject().makePointBoundary(name, list(node_set),
                                                 exterior)

        context_bdy = bdy.makeContextBoundary(self, name, self.getObject())
        self.pointboundaries[name] = context_bdy

        # Propagation up and down.
        # See routine above for nomenclature lament.
        # DeputySkeleton.mapBoundary is a no-op.
        sheriff = self.resolveCSkeleton(self.getObject().sheriffSkeleton())
        current = sheriff
        children = self.undobuffer.getToTop(start=sheriff)
        for c in withoutDeputies(children[1:]):
            c.mapBoundary(context_bdy,
                          current,
                          direction=cskeletonselectable.MAP_DOWN)
            current = c

        current = sheriff
        parents = self.undobuffer.getToBottom(start=sheriff)
        for p in withoutDeputies(parents[1:]):
            p.mapBoundary(context_bdy,
                          current,
                          direction=cskeletonselectable.MAP_UP)
            current = p

        switchboard.notify("new boundary created", self)
        if autoselect:
            self.selectBoundary(name)
        # self.bdytimestamp.increment()
        switchboard.notify("new boundary configuration", self)
Exemple #36
0
def parallel_activateField(menuitem, mesh, field):
    activated = False
    meshcontext = ooflib.engine.mesh.meshes[mesh]
    subpcontext = meshcontext.get_default_subproblem()
    subpcontext.reserve()
    subpcontext.begin_writing()
    try:
        subp = subpcontext.getObject()
        if subp.is_defined_field(field):
            subp.activate_field(field)
            activation = True
        else:
            reporter.report(
                "You must define a Field before you can activate it.")
    finally:
        subpcontext.end_writing()
        subpcontext.cancel_reservation()

    if activation:
        subpcontext.autoenableBCs()
        switchboard.notify("field activated", subpcontext.path(), field.name(),
                           1)
        subpcontext.changed()
Exemple #37
0
    def createMSFromImageFile(menuitem,
                              filenames,
                              microstructure_name,
                              height,
                              width,
                              depth=0):

        if ((height != automatic and height <= 0)
                or (width != automatic and width <= 0)
                or (depth != automatic and depth <= 0)):
            raise ooferror.ErrUserError(
                "Negative microstructure sizes are not allowed.")

        image = autoReadImage(filenames, height, width, depth)
        ms = ooflib.SWIG.common.cmicrostructure.CMicrostructure(
            microstructure_name, image.sizeInPixels(), image.size())

        immidgecontext = imagecontext.imageContexts.add(
            [ms.name(), image.name()],
            image,
            parent=ooflib.common.microstructure.microStructures[ms.name()])

        switchboard.notify("redraw")
Exemple #38
0
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()
Exemple #39
0
 def clean(self, name):
     path = labeltree.makePath(name)
     try:
         obj = self[path]  # Who instance
     except KeyError:
         raise
     else:
         # Remove the leaf from the tree.  If it's the only leaf on
         # its branch, remove the branch.
         self.members.prune(path)
         obj.remove()
         self.nmembers -= 1
         # The order of these last two signals is important -- the
         # widgets catch the specific signal, and it's helpful to
         # the pages (which catch the generic signal) if the widget
         # is in the new state at page-update-time.
         obj.pause_writing()
         try:
             switchboard.notify(('remove who', self.name()),
                                path)  # specific
             switchboard.notify('remove who', self.name(), path)  # generic
         finally:
             obj.resume_writing()
Exemple #40
0
    def postProcess(self, context):
        ## global Pcount
        ## Pcount += 1
        ## random.seed(1)
        skeleton = context.getObject()
        prog = self.makeProgress()
        self.count = 0
        prog.setMessage(self.header)
        before = skeleton.energyTotal(self.criterion.alpha)

        while self.iteration.goodToGo():
            self.count += 1
            # the context acquires the writing permissions inside
            # coreProcess.
            self.coreProcess(context)
            self.updateIteration(prog)
            skeleton.updateGeometry()
            switchboard.notify("skeleton homogeneity changed", context.path())

            if prog.stopped():
                break

        switchboard.notify("skeleton nodes moved", context)
        if prog.stopped():
            self.targets.cleanUp()
            return

        after = skeleton.energyTotal(self.criterion.alpha)
        if before:
            rate = 100.0 * (before - after) / before
        else:
            rate = 0.0
        diffE = after - before
        reporter.report("%s deltaE = %10.4e (%6.3f%%)" %
                        (self.outro, diffE, rate))
        self.targets.cleanUp()
        prog.finish()
Exemple #41
0
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")
Exemple #42
0
def doSelectionMod(menuitem, microstructure, **params):
    registration = menuitem.data
    # create the SelectionModifier
    selectionModifier = registration(**params)
    # apply the SelectionModifier
    ms = ooflib.common.microstructure.microStructures[
        microstructure].getObject()
    selection = ms.pixelselection
    selection.begin_writing()
    try:
        selectionModifier(ms, selection)
    finally:
        selection.end_writing()
    switchboard.notify('pixel selection changed')
    switchboard.notify('modified pixel selection', selectionModifier)
    switchboard.notify('new pixel selection', None, None)
    switchboard.notify('redraw')
Exemple #43
0
def meshablePixelGroup(menuitem, microstructure, group, meshable):
    if parallel_enable.enabled():
        pixelgroupIPC.ipcpixgrpmenu.Meshable(microstructure=microstructure,
                                             group=group,
                                             meshable=meshable)
        return

    mscontext = ooflib.common.microstructure.microStructures[microstructure]
    ms = mscontext.getObject()
    mscontext.begin_writing()
    try:
        grp = ms.findGroup(group)
        if grp is not None:
            grp.set_meshable(meshable)
            ms.recategorize()
        else:
            raise ooferror.ErrUserError("There is no pixel group named %s!" %
                                        group)
    finally:
        mscontext.end_writing()

    switchboard.notify('redraw')
    if grp is not None:
        switchboard.notify("changed pixel group", grp, microstructure)
Exemple #44
0
def _undefineField(menuitem, subproblem, field):
    if parallel_enable.enabled():
        ipcsubpmenu.Field.Undefine(subproblem=subproblem, field=field)
    else:
        subpcontext = ooflib.engine.subproblemcontext.subproblems[subproblem]
        subpcontext.reserve()
        subpcontext.begin_writing()
        try:
            subpcontext.getObject().undefine_field(field)
            subpcontext.getParent().update_fields()
            # After undefining a Field, the data cache in the mesh has
            # the wrong number of dofs in it.  We could in principle
            # delete the correct dofs from each cache entry, but it
            # might be slow (especially for a disk cache).  The
            # simpler thing to do is to just delete the whole cache.
            subpcontext.getParent().clearDataCache()
        finally:
            subpcontext.end_writing()
            subpcontext.cancel_reservation()

        subpcontext.autoenableBCs()
        subpcontext.changed("Field undefined.")
        switchboard.notify("field defined", subproblem, field.name(), 0)
        switchboard.notify("redraw")
Exemple #45
0
 def deleteMaterial(self, matname, material_type):
     # if material_type==material.MATERIALTYPE_INTERFACE:
     if material_type == interface_mat_type:
         try:
             del self._materialassignments[matname]
         except KeyError:
             pass
         #Unassociate matname from skeleton boundaries
         msname = self.microstructure.name()
         skelclass = skeletoncontext.skeletonContexts
         for skelkey in skelclass.keys(base=msname):
             skelctxt = skelclass[[msname] + skelkey]
             for bname in skelctxt.allEdgeBoundaryNames():
                 bdyctxt = skelctxt.getBoundary(bname)
                 if bdyctxt._interfacematerial == matname:
                     bdyctxt._interfacematerial = None
     else:
         if len(self.namedinterfaces) == 0:
             return
         interfacenames = self.getInterfaceNames()
         doomedinterfaces = []
         for interfacename in interfacenames:
             interfaceobj = self.namedinterfaces[interfacename]
             if interfaceobj.hasBulkMaterial(matname):
                 del self.namedinterfaces[interfacename]
                 doomedinterfaces.append(interfacename)
         self.removeMaterialFromInterfaces(doomedinterfaces)
         #Remove boundary conditions that refer to the doomedinterfaces
         meshclass = ooflib.engine.mesh.meshes
         msname = self.microstructure.name()
         for meshkey in meshclass.keys(base=msname):
             meshctxt = meshclass[[msname] + meshkey]
             for doomedinterfacename in doomedinterfaces:
                 meshctxt.removeInterface(doomedinterfacename)
         self.rebuildMeshes()
         switchboard.notify("interface removed", self.microstructure)
Exemple #46
0
def _activateField(menuitem, subproblem, field):
    activation = False
    if parallel_enable.enabled():
        ipcsubpmenu.Field.Activate(subproblem=subproblem, field=field)
    else:
        subpcontext = ooflib.engine.subproblemcontext.subproblems[subproblem]
        subpcontext.reserve()
        subpcontext.begin_writing()
        try:
            subp = subpcontext.getObject()
            if subp.is_defined_field(field):
                subp.activate_field(field)
                activation = True
            else:
                reporter.report(
                    "You must define a Field before you can activate it.")
        finally:
            subpcontext.end_writing()
            subpcontext.cancel_reservation()

        if activation:
            subpcontext.autoenableBCs()
            switchboard.notify("field activated", subproblem, field.name(), 1)
            subpcontext.changed("Field activated.")
Exemple #47
0
    def coreProcess(self, context):
        skeleton = context.getObject()
        prog = self.makeProgress()
        self.totalEnergy = skeleton.energyTotal(self.criterion.alpha)
        self.nok = self.nbad = 0
        self.deltaE = 0.
        activenodes = self.targets(context)
        random.shuffle(activenodes)
        j = 0
        context.begin_writing()
        try:
            for node in activenodes:
                # obtain transition points
                tps = self.movedPosition(skeleton, node)
                changes = []
                for tp in tps:
                    if tp:
                        change = deputy.DeputyProvisionalChanges()
                        change.moveNode(node, tp, skeleton)
                        changes.append(change)

                bestchange = self.criterion(changes, skeleton)
                if bestchange is not None:
                    self.nok += 1
                    self.deltaE += bestchange.deltaE(skeleton,
                                                     self.criterion.alpha)
                    bestchange.accept(skeleton)
                else:
                    self.nbad += 1

                if prog.stopped():
                    return
            skeleton.timestamp.increment()
        finally:
            context.end_writing()
            switchboard.notify("redraw")
Exemple #48
0
def createMSFromImage(menuitem, name, width, height, image):
    if parallel_enable.enabled():
        # For the back-end processes
        from ooflib.image.IO import oofimageIPC
        oofimageIPC.imenu.Create_From_Image_Parallel(msname=name, image=image)

    # For serial mode #0 in parallel mode
    imagepath = labeltree.makePath(image)
    immidgecontext = imagecontext.imageContexts[image]
    immidge = immidgecontext.getObject().clone(imagepath[-1])

    size = immidge.size()  # Point object.
    if width != automatic.automatic:
        size[0] = width
    if height != automatic.automatic:
        size[1] = height

    ms = ooflib.SWIG.common.cmicrostructure.CMicrostructure(
        name, immidge.sizeInPixels(), size)
    newimagecontext = imagecontext.imageContexts.add(
        [name, immidge.name()],
        immidge,
        parent=ooflib.common.microstructure.microStructures[name])
    switchboard.notify("redraw")
Exemple #49
0
 def renameMaterial(self, oldmatname, newmatname, material_type):
     # if material_type==material.MATERIALTYPE_INTERFACE:
     if material_type == interface_mat_type:
         try:
             interfacenamelist = self._materialassignments[oldmatname]
             del self._materialassignments[oldmatname]
             self._materialassignments[newmatname] = interfacenamelist
         except KeyError:
             pass
         #Rename materials associated with skeleton boundaries
         msname = self.microstructure.name()
         skelclass = skeletoncontext.skeletonContexts
         for skelkey in skelclass.keys(base=msname):
             skelctxt = skelclass[[msname] + skelkey]
             for bname in skelctxt.allEdgeBoundaryNames():
                 bdyctxt = skelctxt.getBoundary(bname)
                 if bdyctxt._interfacematerial == oldmatname:
                     bdyctxt._interfacematerial = newmatname
     else:
         for interfaceobj in self.namedinterfaces.values():
             interfaceobj.renameBulkMaterial(oldmatname, newmatname)
         #A material has been renamed, it is possible the details of
         #one or more interfaces have been changed.
         switchboard.notify("interface renamed", self.microstructure)
Exemple #50
0
def doImageMod(menuitem, image, **params):
    if parallel_enable.enabled():
        from ooflib.image.IO import oofimageIPC
        paramenu = oofimageIPC.modmenu.getItem(menuitem.name)
        paramenu(image=image, **params)

    # image is the image name, actually
    imagectxt = imagecontext.imageContexts[image]
    imagectxt.reserve()
    try:
        immidge = imagectxt.getObject()  # OOFImage object
        newimmidge = immidge.clone(immidge.name())
        registration = menuitem.data
        imageModifier = registration(**params)  # create ImageModifier obj
        imagectxt.begin_writing()
        try:
            imageModifier(newimmidge)  # call its __call__ method on the image
            oofimage.pushModification(image, newimmidge)
        finally:
            imagectxt.end_writing()
    finally:
        imagectxt.cancel_reservation()
    switchboard.notify('modified image', imageModifier, image)
    switchboard.notify('redraw')
Exemple #51
0
    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)
Exemple #52
0
def _modify(menuitem, skeleton, modifier):
    context = skeletoncontext.skeletonContexts[skeleton]
    context.reserve()
    start_nnodes = context.getObject().nnodes()
    start_nelems = context.getObject().nelements()
    try:
        context.begin_writing()
        cdebug.ProfilerStart("mod.prof")
        try:
            skel = modifier.apply(context.getObject())
            ## skel is None whenever the modifier fails
            ## or is interrupted from finishing its task
            if skel is None:
                reporter.warn("Modify Process Interrupted")
                return
            context.pushModification(skel)
            skel.needsHash()
        finally:
            context.end_writing()

        ## If the skeleton is modified in postProcess, use
        ## begin/end_writing inside the function call to guarantee
        ## that no dead-locking occurs because of possible switchboard
        ## calls that may make use of begin/end_reading(). See
        ## cfiddlenodes.spy for an example.
        modifier.postProcess(context)
        modifier.cleanUp()
        cdebug.ProfilerStop()
        skel.incrementTimestamp()

        end_nnodes = context.getObject().nnodes()
        end_nelems = context.getObject().nelements()
        if end_nnodes > start_nnodes:
            reporter.report(end_nnodes - start_nnodes, "more nodes.")
        elif end_nnodes < start_nnodes:
            reporter.report(start_nnodes - end_nnodes, "fewer nodes.")
        if end_nelems > start_nelems:
            reporter.report(end_nelems - start_nelems, "more elements.")
        elif end_nelems < start_nelems:
            reporter.report(start_nelems - end_nelems, "fewer elements.")
    finally:
        context.cancel_reservation()

    # "Skeleton modified" indicates that a specific modifier has been
    # applied.  "Skeleton changed" indicates that something has
    # changed, which might or might not have involved a
    # SkeletonModifier.  "Skeleton changed" is not redundant with "who
    # changed", because "who changed" is issued by pushModification
    # before postProcess is called, and postProcess might do most of
    # the work in a SkeletonModifier.
    ## TODO OPT: Some modifiers send these notifications in
    ## postProcess.  Don't send them again here.
    switchboard.notify('Skeleton modified', skeleton, modifier)
    switchboard.notify('Skeleton changed', skeleton)
    switchboard.notify('redraw')
Exemple #53
0
def _addprop(menuitem, name, property):
    matmanager.add_prop(name, property)
    switchboard.notify("material changed", name)
    switchboard.notify("prop_added_to_material", name, property)
    switchboard.notify("redraw")
    if parallel_enable.enabled() == 1:
        try:
            from ooflib.SWIG.common import mpitools
            if mpitools.Rank() == 0:
                materialmenuIPC.ipcmaterialmenu.Add_property(name=name,
                                                             property=property)
        except ImportError:
            pass
Exemple #54
0
def _meshFields(menuitem, mesh, defined, active, inplane):
    meshctxt = ooflib.engine.mesh.meshes[mesh]
    subpname = meshctxt.get_default_subproblem().path()

    for fname in defined:
        field = getFieldObj(fname)
        meshctxt.get_default_subproblem().getObject().define_field(field)
        switchboard.notify("field defined", subpname, field.name(), 1)

    for fname in active:
        field = getFieldObj(fname)
        meshctxt.get_default_subproblem().getObject().activate_field(field)
        switchboard.notify("field activated", subpname, field.name(), 1)

    for fname in inplane:
        field = getFieldObj(fname)
        meshctxt.set_in_plane_field(field, 1)
        switchboard.notify("field inplane", mesh, field.name(), 1)

    switchboard.notify("mesh changed", meshctxt)
Exemple #55
0
def _meshFields(menuitem, mesh, defined, active, inplane):
    meshctxt = ooflib.engine.mesh.meshes[mesh]
    subpname = meshctxt.get_default_subproblem().path()

    for fname in defined:
        field = getFieldObj(fname)
        meshctxt.get_default_subproblem().getObject().define_field(field)
        switchboard.notify("field defined", subpname, field.name(), 1)

    for fname in active:
        field = getFieldObj(fname)
        meshctxt.get_default_subproblem().getObject().activate_field(field)
        switchboard.notify("field activated", subpname, field.name(), 1)

    ## NO need to check for 2D here.  This is old code only for
    ## loading old OOF2 files.
    for fname in inplane:
        field = getFieldObj(fname)
        meshctxt.set_in_plane_field(field, 1)
        switchboard.notify("field inplane", mesh, field.name(), 1)

    switchboard.notify("mesh changed", meshctxt)
Exemple #56
0
    def changed(self, message):
        # Called when fields, equations, or materials have changed.
        self.defnChanged.increment()    # timestamp
        self.getObject().requirePrecompute()
        self.findTimeDependent()
        self.find_second_order_fields()
        switchboard.notify("subproblem changed", self)
        ## TODO: Get rid of "mesh changed", and just use
        ## Mesh.setStatus?  There seem to be a lot of nearly redundant
        ## signals.
        switchboard.notify("mesh changed", self.parent)

        fieldsdefined = self.define_timederiv_fields()
        for fld in fieldsdefined:
            switchboard.notify("field defined", self.path(), fld.name(), 1)

        self.getParent().setStatus(meshstatus.Unsolved(message))
Exemple #57
0
def autoPixelGroup(menuitem, grouper, delta, gamma, minsize, contiguous,
                   name_template, clear):
    ms = grouper.mscontext.getObject()
    if "%n" not in name_template:
        name_template = name_template + "%n"
    prog = progress.getProgress('AutoGroup', progress.DEFINITE)
    prog.setMessage('Grouping pixels...')
    grouper.mscontext.begin_writing()
    newgrpname = None
    try:
        newgrpname = statgroups.statgroups(ms, grouper.cobj, delta, gamma,
                                           minsize, contiguous, name_template,
                                           clear)
    finally:
        prog.finish()
        grouper.mscontext.end_writing()
    if newgrpname:
        switchboard.notify("new pixel group", ms.findGroup(newgrpname))
    switchboard.notify("changed pixel groups", ms.name())
    switchboard.notify("redraw")
Exemple #58
0
def _subpFields(menuitem, subproblem, defined, active, inplane):
    subpctxt = ooflib.engine.subproblemcontext.subproblems[subproblem]
    meshctxt = subpctxt.getParent()
    meshname = meshctxt.path()
    subpname = subpctxt.path()
    subp = subpctxt.getObject()

    for fname in defined:
        field = getFieldObj(fname)
        subp.define_field(field)
        switchboard.notify("field defined", subpname, field.name(), 1)

    for fname in active:
        field = getFieldObj(fname)
        subp.activate_field(field)
        switchboard.notify("field activated", subpname, field.name(), 1)

    for fname in inplane:
        field = getFieldObj(fname)
        meshctxt.set_in_plane_field(field, 1)
        switchboard.notify("field inplane", meshname, field.name(), 1)

    subpctxt.changed("Fields loaded.")
Exemple #59
0
def _modifyCB(self, skeleton, boundary, modifier):
    skelctxt = skeletoncontext.skeletonContexts[skeleton]
    modifier(skelctxt, boundary)
    switchboard.notify("redraw")
Exemple #60
0
def parallel_move_node(menuitem, origin, destination,
                       allow_illegal,
                       skeletonpath):
    skelcontext = skeletoncontext.skeletonContexts[skeletonpath]
    #skelcontext = self.gfxwindow().topwho('Skeleton')
    if skelcontext:
        skeleton = skelcontext.getObject().deputyCopy()
        skeleton.activate()
        #If one looks at moveNodeGUI.py, origin here is already
        #set to the position of the nearest node.
        node = skeleton.nearestNode(origin)
        nodeindex=node.getIndex()
        distance2=(node.position()-origin)**2
        ###############################################################
        # Get nearest node distances from all processes
        if _rank==0:
            #Get list of squares of distance of node to the click point
            distance2list=[distance2]
            dmin=-1
            dmin_proc_list=[]
            #Get distances from other processes
            for proc in range(_size):
                if proc!=0:
                    distance2list.append(mpitools.Recv_Double(proc))
                if distance2list[proc]>=0:
                    dmin=distance2list[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]
            for proc in range(_size):
                if distance2list[proc]==dmin:
                    dmin_proc_list.append(proc)
        else:
            #Backend sends report to front end
            mpitools.Send_Double(distance2,0)

        mpitools.Barrier()
        
        #Tell the processes in dmin_proc_list to try moving their nodes
        #and report back the result. Then really move the node if the
        #move is valid for all of them.
        if _rank==0:
            for proc in range(_size):
                if proc in dmin_proc_list:
                    if proc==0:
                        moveit=1
                    else:
                        mpitools.Send_Int(1,proc)
                else:
                    if proc==0:
                        moveit=0
                    else:
                        mpitools.Send_Int(0,proc)
        else:
            moveit=mpitools.Recv_Int(0)

        mpitools.Barrier()

        #
        ###############################################################
        skelcontext.reserve()
        skelcontext.begin_writing()
        try:
            if moveit:
                skeleton.moveNodeTo(node, destination)
                #TODO 3.1: If the node is shared, the move may be valid in one process
                #but invalid in another.
                if node.illegal():
                    if allow_illegal==1:
                        skeleton.setIllegal()
                    else:
                        node.moveBack()
                elif skeleton.illegal(): # node motion may have rehabilitated
                    skeleton.checkIllegality()
                skelcontext.pushModification(skeleton)
        finally:
            #
            collect_pieces(skeleton)
            #
            skelcontext.end_writing()
            skelcontext.cancel_reservation()
        skeleton.needsHash()
        switchboard.notify('redraw')