Пример #1
0
 def makeMenu(self, menu):
     self.menu = menu
     menu.addItem(oofmenu.OOFMenuItem(
         'MoveNode',
         threadable=oofmenu.THREADABLE,
         callback = self.moveNode,
         params=[primitives.PointParameter('origin',
                                           tip=parameter.emptyTipString),
                 primitives.PointParameter('destination',
                                           tip=parameter.emptyTipString)],
         help="Move a node to another positon.",
         discussion=xmlmenudump.loadFile('DISCUSSIONS/engine/menu/move_node.xml')
         ))
     menu.addItem(oofmenu.OOFMenuItem(
         'SelectNode',
         callback = self.selectNode,
         params=[primitives.PointParameter('position',
                                           tip=parameter.emptyTipString)],
         help="Select a node to move.",
         discussion=xmlmenudump.loadFile('DISCUSSIONS/engine/menu/select_move_node.xml')
         ))
     menu.addItem(oofmenu.OOFMenuItem(
         'AllowIllegal',
         callback = self.allowIllegal,
         params=[parameter.BooleanParameter('allowed', 0,
                                            tip=parameter.emptyTipString)],
         help="Are illegal elements allowed?",
         discussion=xmlmenudump.loadFile('DISCUSSIONS/engine/menu/allow_illegal.xml')
         ))
Пример #2
0
def buildSelectionModMenu():
    selmodmenu.clearMenu()
    selmodmenu.addItem(oofmenu.OOFMenuItem(
        'Undo',
        params=[whoville.WhoParameter('microstructure',
                                      microstructure.microStructures,
                                      tip=parameter.emptyTipString)],
        callback=pixelselectionmod.undo,
        help="Undo the latest selection.",
        discussion=xmlmenudump.loadFile('DISCUSSIONS/common/menu/undo_pixsel.xml')
        ))
    
    selmodmenu.addItem(oofmenu.OOFMenuItem(
        'Redo',
        params=[whoville.WhoParameter('microstructure',
                                      microstructure.microStructures,
                                      tip=parameter.emptyTipString)],
        callback=pixelselectionmod.redo,
        help="Redo the latest undone selection.",
        discussion=xmlmenudump.loadFile('DISCUSSIONS/common/menu/redo_pixsel.xml')
        ))

    selmodmenu.addItem(oofmenu.OOFMenuItem(
        'Clear',
        params=[whoville.WhoParameter('microstructure',
                                      microstructure.microStructures,
                                      tip=parameter.emptyTipString)],
        callback=pixelselectionmod.clear,
        help="Clear the current selection.",
        discussion="<para>Clear the current selection.</para>"))
    
    for registration in pixelselectionmod.SelectionModifier.registry:
        # Help string
        try:
            help = registration.tip
        except AttributeError:
            help = None
        # Discussion
        try:
            discussion = registration.discussion
        except AttributeError:
            discussion = None
        menuitem = selmodmenu.addItem(
            oofmenu.OOFMenuItem(utils.space2underscore(registration.name()),
                                callback=pixelselectionmod.doSelectionMod,
                                threadable=oofmenu.THREADABLE,
                                params=[
            whoville.WhoParameter('microstructure',
                                  microstructure.microStructures,
                                  tip=parameter.emptyTipString)
            ]+registration.params,
                                help=help,
                                discussion=discussion))
        menuitem.data = registration
Пример #3
0
 def makeMenu(self, menu):
     self.menu = menu
     menu.addItem(oofmenu.OOFMenuItem(
         'QueryElement',
         callback=self.queryElem,
         params=[primitives.PointParameter('position', tip='Target point.')],
         help="Query an FE element at a given point.",
         discussion=xmlmenudump.loadFile('DISCUSSIONS/engine/menu/query_mesh_elem.xml')
         ))
     menu.addItem(oofmenu.OOFMenuItem(
         'QueryNode',
         callback=self.queryNode,
         params=[primitives.PointParameter('position', tip='Target point.')],
         help="Query an FE node at a given point.",
         discussion=xmlmenudump.loadFile('DISCUSSIONS/engine/menu/query_mesh_node.xml')
         ))
Пример #4
0
def addToGfxSettings(gfxwindow):
    item = gfxwindow.menu.Settings.addItem(oofmenu.CheckOOFMenuItem(
        'Hide_Empty_Mesh_Elements',
        callback=toggleEmptyDrawing,
        value=gfxwindow.settings.hideEmptyElements,
        help="Toggle the display of elements with no Material.",
        discussion=xmlmenudump.loadFile('DISCUSSIONS/common/menu/hideempty.xml')))
    item.data = gfxwindow
Пример #5
0
class RefinementDegree(registeredclass.RegisteredClass):
    registry = []

    def markExtras(self, skeleton, markedEdges):
        pass

    tip = "Number of subdivisions per segment."
    discussion = xmlmenudump.loadFile(
        'DISCUSSIONS/engine/reg/refinementdegree.xml')
Пример #6
0
class ErrorNorm(registeredclass.RegisteredClass):
    registry = []

    #AMR subproblem, pass subproblem
    def preprocess(self, subproblem, flux):  # to be overridden by child class.
        pass

    tip = "How to measure error?"
    discussion = xmlmenudump.loadFile('DISCUSSIONS/engine/reg/errornorm.xml')
Пример #7
0
class ErrorEstimator(registeredclass.RegisteredClass):
    registry = []
    # If an ErrorEstimator needs a preprocess, it should be added.
    #AMR subproblem, pass subproblem
    def preprocess(self, subproblem):
        pass
    tip = "Error estimators."
    discussion = xmlmenudump.loadFile(
        'DISCUSSIONS/engine/reg/errorestimator.xml')
Пример #8
0
class Rationalizer(registeredclass.RegisteredClass):
    registry = []

    def __call__(self, skel, context, targets, criterion, fixer):
        prog = progress.findProgress("Rationalize")
        # Copy the element list from skeleton.element before
        # rationalizing. This is necessary because rationalizing
        # modifies the Skeleton's element list. 
        elements = targets(skel, context, copy=1)
        random.shuffle(elements)
        executed_action = self.getRegistration().gerund
        processed = {}
        count = 0
        done = 0  # No. of rationalized elements
        nel = len(elements)  # No. of elements in the list
        for element in elements:
            count += 1  # The i-th element being processed ... for progress bar
            if element not in processed and element.active(skel):
                # fixer is either self.findAndFix or self.fixAll. They
                # return a list of ProvisionalChanges objects, from
                # which we pick the best one.
                changes = fixer(skel, element)
                bestchange = criterion(changes, skel)
                if bestchange is not None:
                    done += bestchange.nRemoved()
                    # Accepting the change converts provisional
                    # elements to actual elements.
                    bestchange.accept(skel)
                    for elephant in bestchange.removed:
                        processed[elephant] = 1
                    for oldel, newel in bestchange.substitutions:
                        # If an unprocessed element has been replaced,
                        # its replacement still has to be processed.
                        # The element being replaced should *not* be
                        # processed, in any case, since it's no longer
                        # in the skeleton.
                        # If the criterion is "Unconditional" or
                        # "Limited Unconditional", it doesn't add subs to
                        # the list.
                        if oldel not in processed:
                            processed[oldel] = 1
                            if criterion.addSubstitute(elements, newel):
                                nel += 1

            if prog.stopped():
                break
            else:
                prog.setFraction(1.0*count/nel)
                prog.setMessage(executed_action + " %d/%d" % (count, nel))
        skel.cleanUp()
        
        reporter.report("%d elements rationalized : %s."
                        % (done, self.getRegistration().name()))

    tip = "Specific tools to remove badly shaped Elements from Skeletons."
    discussion = xmlmenudump.loadFile('DISCUSSIONS/engine/reg/rationalizer.xml')
Пример #9
0
class SubProblemType(registeredclass.RegisteredClass):
    registry = []
    tip = "Different varieties of Subproblems."
    discussion = xmlmenudump.loadFile(
        'DISCUSSIONS/engine/reg/subproblemtype.xml')

    def get_dependencies(self):
        # Return the paths (colon separated strings) to the other
        # subproblems on which this one depends.
        return []
Пример #10
0
def addToGfxSettings(gfxwindow):
    item = gfxwindow.menu.Settings.addItem(
        oofmenu.CheckOOFMenuItem(
            'Hide_Empty_Mesh_Elements',
            callback=toggleEmptyDrawing,
            value=gfxwindow.settings.hideEmptyElements,
            help="Toggle the display of elements with no Material.",
            discussion=xmlmenudump.loadFile(
                'DISCUSSIONS/common/menu/hideempty.xml')))
    item.data = gfxwindow
Пример #11
0
    def __init__(self, name, methodclass, modifierclass, newselectionsignal,
                 modifierappliedsignal, changedselectionsignal, groupmenu,
                 materialsallowed=None):
        self.name = name

        # methodclass is the RegisteredClass of routines for creating
        # new selections.  These appear in the
        # SkeletonSelectionToolbox.
        self.methodclass = methodclass

        # modifierclass is the RegisteredClass of routines for
        # modifying existing selections.  These appear in the
        # SkeletonSelectionPage.
        self.modifierclass = modifierclass

        # newselectionsignal is sent along with a selection method and
        # pointlist when a new selection is made.
        # changedselectionsignal is sent when any change is made in
        # the selection at all.
        # modifierappliedsignal is sent along with a selection
        # modifier when the selection is modified.
        self.modifierappliedsignal = modifierappliedsignal
        self.newselectionsignal = newselectionsignal
        self.changedselectionsignal = changedselectionsignal

        # groupmenu is the menu of commands for manipulating groups of
        # the object.
        self.groupmenu = groupmenu

        # materialsallowed is either None or a MaterialType instance.
        # If not None, it indicates what kinds of material may be
        # explicitly assigned to groups of this type of selectable
        # object.
        self.materialsallowed = materialsallowed

        self.stacksize = 50

        # Create a menuitem for changing the stack size.  The
        # parameter is shared among the menuitems for all
        # SkeletonSelectionModes as well as the menuitem that sets all
        # of the buffer sizes at once.
        self.stacksize_menuitem = bufsizmenu.addItem(oofmenu.OOFMenuItem(
            name,
            callback=self.setUndoBufferSize,
            params=_stacksize_params, # global, see below
            help="Set the history buffer size for Skeleton %s selections" % name,
            discussion=xmlmenudump.loadFile(
                'DISCUSSIONS/engine/menu/skelbufsize.xml',
                lambda text,obj: text.replace('CLASS', name))
            ))
        

        SkeletonSelectionMode.modes.append(self)
        switchboard.notify(SkeletonSelectionMode, self)
Пример #12
0
class IsotropicRank4Tensor(registeredclass.ConvertibleRegisteredClass):
    registry = []
    tip = "Representations of an isotropic 4th rank tensor."
    discussion = xmlmenudump.loadFile('DISCUSSIONS/engine/reg/isotropic_rank4.xml')
    def tensorForm(self):
        modulus = cijkl.Cijkl()
        ibase = self.to_base()
        modulus[0,0] = modulus[1,1] = modulus[2,2] = ibase.c11
        modulus[0,1] = modulus[0,2] = modulus[1,2] = ibase.c12
        modulus[3,3] = modulus[4,4] = modulus[5,5] = 0.5*(ibase.c11-ibase.c12)
        return modulus
Пример #13
0
class MatrixMethod(registeredclass.RegisteredClass):
    registry = []

    def shortrepr(self):
        return self.__class__.__name__

    def solve(self, matrix, rhs, solution):
        return self.solveMatrix(matrix, rhs, solution)

    tip = "Ways to solve a matrix equation."
    discussion = xmlmenudump.loadFile(
        'DISCUSSIONS/engine/reg/matrixmethod.xml')
Пример #14
0
 def makeMenu(self, menu):
     self.menu = menu
     menu.addItem(
         oofmenu.OOFMenuItem('MoveNode',
                             callback=self.moveNode,
                             params=[
                                 parameter.IntParameter(
                                     'node',
                                     tip='Index of the node to be moved.'),
                                 pointparameter.PointParameter(
                                     'destination',
                                     tip=parameter.emptyTipString)
                             ],
                             help="Move a node to another positon.",
                             discussion=xmlmenudump.loadFile(
                                 'DISCUSSIONS/engine/menu/move_node.xml')))
     menu.addItem(
         oofmenu.OOFMenuItem(
             'SelectNode',
             callback=self.selectNode,
             params=[
                 pointparameter.PointParameter(
                     'position', tip=parameter.emptyTipString),
                 view.ViewParameter('view')
             ],
             help="Select a node to move.",
             discussion=xmlmenudump.loadFile(
                 'DISCUSSIONS/engine/menu/select_move_node.xml')))
     menu.addItem(
         oofmenu.OOFMenuItem(
             'AllowIllegal',
             callback=self.allowIllegal,
             params=[
                 parameter.BooleanParameter('allowed',
                                            0,
                                            tip=parameter.emptyTipString)
             ],
             help="Are illegal elements allowed?",
             discussion=xmlmenudump.loadFile(
                 'DISCUSSIONS/engine/menu/allow_illegal.xml')))
Пример #15
0
    def makeMenu(self, menu):
        self.menu = menu
        menu.addItem(oofmenu.OOFMenuItem(
            'Pin',
            callback = self.pin,
            params=[self.skeleton_param,
                    primitives.PointParameter('point', tip='Target point.')],
            help="Pin the node closest to the given point.",
            discussion=xmlmenudump.loadFile('DISCUSSIONS/engine/menu/pin.xml')
            ))
        menu.addItem(oofmenu.OOFMenuItem(
            'UnPin',
            callback = self.unpin,
            params=[self.skeleton_param,
                    primitives.PointParameter('point', tip='Target point.')],
            help="Unpin the node closest to the given point.",
            discussion=xmlmenudump.loadFile('DISCUSSIONS/engine/menu/unpin.xml')
            ))
        menu.addItem(oofmenu.OOFMenuItem(
            'TogglePin',
            callback=self.togglepin,
            params=[self.skeleton_param,
                    primitives.PointParameter('point', tip='Target point.')],
            help="Toggle the pinnedness of the node closest to the given point.",
            discussion=xmlmenudump.loadFile('DISCUSSIONS/engine/menu/toggle_pin.xml')
            ))
        menu.addItem(oofmenu.OOFMenuItem(
            'UnPinAll',
            callback = self.unpinall,
            params=[self.skeleton_param],
            help="Unpin all nodes.",
            discussion=xmlmenudump.loadFile('DISCUSSIONS/engine/menu/unpin_all.xml')
            ))
        menu.addItem(oofmenu.OOFMenuItem(
            'Invert',
            callback = self.invert,
            params=[self.skeleton_param],
            help="Invert pinned nodes.",
            discussion=xmlmenudump.loadFile('DISCUSSIONS/engine/menu/invert_pin.xml')
            ))

        menu.addItem(oofmenu.OOFMenuItem(
            'Undo',
            callback=self.undoPin,
            params=[self.skeleton_param],
            help="Undo the latest pin.",
            discussion=xmlmenudump.loadFile('DISCUSSIONS/engine/menu/undo_pin.xml')
            ))
        menu.addItem(oofmenu.OOFMenuItem(
            'Redo',
            callback=self.redoPin,
            params=[self.skeleton_param],
            help="Redo the latest undone pin.",
            discussion=xmlmenudump.loadFile('DISCUSSIONS/engine/menu/redo_pin.xml')
            ))
Пример #16
0
 def makeMenu(self, menu):
     self.menu = menu
     menu.addItem(
         oofmenu.OOFMenuItem(
             'QueryElement',
             callback=self.queryElem,
             params=[
                 primitives.PointParameter('position', tip='Target point.')
             ],
             help="Query an FE element at a given point.",
             discussion=xmlmenudump.loadFile(
                 'DISCUSSIONS/engine/menu/query_mesh_elem.xml')))
     menu.addItem(
         oofmenu.OOFMenuItem(
             'QueryNode',
             callback=self.queryNode,
             params=[
                 primitives.PointParameter('position', tip='Target point.')
             ],
             help="Query an FE node at a given point.",
             discussion=xmlmenudump.loadFile(
                 'DISCUSSIONS/engine/menu/query_mesh_node.xml')))
Пример #17
0
 def makeMenu(self, menu):
     self.menu = menu
     menu.addItem(
         oofmenu.OOFMenuItem(
             'QueryElement',
             callback=self.queryElem,
             params=[
                 primitives.PointParameter('position', tip='Target point.')
             ],
             help="Query the element closest to the given point.",
             discussion=xmlmenudump.loadFile(
                 'DISCUSSIONS/engine/menu/query_skel_elem.xml')))
     menu.addItem(
         oofmenu.OOFMenuItem(
             'QueryElementByID',
             callback=self.queryElemByID,
             params=[parameter.IntParameter('index', tip="Element index.")],
             help="Query the element with the given index.",
             discussion=xmlmenudump.loadFile(
                 'DISCUSSIONS/engine/menu/query_skel_elem_id.xml')))
     menu.addItem(
         oofmenu.OOFMenuItem(
             'QuerySegment',
             callback=self.querySgmt,
             params=[
                 primitives.PointParameter('position', tip='Target point.')
             ],
             help="Query the segment closest to the given point.",
             discussion=xmlmenudump.loadFile(
                 'DISCUSSIONS/engine/menu/query_skel_sgmt.xml')))
     menu.addItem(
         oofmenu.OOFMenuItem(
             'QuerySegmentByID',
             callback=self.querySgmtByID,
             params=[parameter.IntParameter('index', tip="Segment index.")],
             help="Query the segment with the given index.",
             discussion=xmlmenudump.loadFile(
                 'DISCUSSIONS/engine/menu/query_skel_sgmt_id.xml')))
     menu.addItem(
         oofmenu.OOFMenuItem(
             'QueryNode',
             callback=self.queryNode,
             params=[
                 primitives.PointParameter('position', tip='Target point.')
             ],
             help="Query the node closest to the given point.",
             discussion=xmlmenudump.loadFile(
                 'DISCUSSIONS/engine/menu/query_skel_node.xml')))
     menu.addItem(
         oofmenu.OOFMenuItem(
             'QueryNodeByID',
             callback=self.queryNodeByID,
             params=[parameter.IntParameter(
                 'index',
                 tip="Node index.",
             )],
             help="Query the node with the given index.",
             discussion=xmlmenudump.loadFile(
                 'DISCUSSIONS/engine/menu/query_skel_node_id.xml')))
Пример #18
0
 def makeMenu(self, menu):
     self.menu = menu
     menu.addItem(
         oofmenu.OOFMenuItem(
             'MoveNode',
             threadable=oofmenu.THREADABLE,
             callback=self.moveNode,
             params=[
                 primitives.PointParameter('origin',
                                           tip=parameter.emptyTipString),
                 primitives.PointParameter('destination',
                                           tip=parameter.emptyTipString)
             ],
             help="Move a node to another positon.",
             discussion=xmlmenudump.loadFile(
                 'DISCUSSIONS/engine/menu/move_node.xml')))
     menu.addItem(
         oofmenu.OOFMenuItem(
             'SelectNode',
             callback=self.selectNode,
             params=[
                 primitives.PointParameter('position',
                                           tip=parameter.emptyTipString)
             ],
             help="Select a node to move.",
             discussion=xmlmenudump.loadFile(
                 'DISCUSSIONS/engine/menu/select_move_node.xml')))
     menu.addItem(
         oofmenu.OOFMenuItem(
             'AllowIllegal',
             callback=self.allowIllegal,
             params=[
                 parameter.BooleanParameter('allowed',
                                            0,
                                            tip=parameter.emptyTipString)
             ],
             help="Are illegal elements allowed?",
             discussion=xmlmenudump.loadFile(
                 'DISCUSSIONS/engine/menu/allow_illegal.xml')))
Пример #19
0
class OutputDestination(registeredclass.RegisteredClass):
    registry = []
    tip="What to do with Scheduled Output data."
    discussion=xmlmenudump.loadFile('DISCUSSIONS/engine/reg/outputdest.xml')
    def open(self):
        pass
    # def open_append(self):
    #     pass
    def flush(self):
        pass
    def rewind(self):
        pass
    def close(self):
        pass
Пример #20
0
class SampleSet(registeredclass.RegisteredClass):
    registry = []

    def __init__(self):
        self.sample_list = []

    def get_col_names():
        return []

    def clearSamples(self):
        self.sample_list = []

    tip = "Container for samples.  Outputs are evaluated at samples."
    discussion = xmlmenudump.loadFile('DISCUSSIONS/engine/reg/sampleset.xml')
Пример #21
0
class SkelModCriterion(registeredclass.RegisteredClass):
    registry = []

    def __call__(self, changes, skel):
        # Child classes must provide __call__ method with
        # ProvisionalChanges, Skeleton as arguments
        pass

    def hopeless(self):
        return 0

    tip = "Acceptance criteria for skeleton modifications."
    discussion = xmlmenudump.loadFile(
        'DISCUSSIONS/engine/reg/skelmodcriterion.xml')
Пример #22
0
 def makeMenu(self, menu):
     self.menu = menu
     menu.addItem(
         oofmenu.OOFMenuItem(
             "QueryElement",
             callback=self.queryElem,
             params=[primitives.PointParameter("position", tip="Target point.")],
             help="Query the element closest to the given point.",
             discussion=xmlmenudump.loadFile("DISCUSSIONS/engine/menu/query_skel_elem.xml"),
         )
     )
     menu.addItem(
         oofmenu.OOFMenuItem(
             "QueryElementByID",
             callback=self.queryElemByID,
             params=[parameter.IntParameter("index", tip="Element index.")],
             help="Query the element with the given index.",
             discussion=xmlmenudump.loadFile("DISCUSSIONS/engine/menu/query_skel_elem_id.xml"),
         )
     )
     menu.addItem(
         oofmenu.OOFMenuItem(
             "QuerySegment",
             callback=self.querySgmt,
             params=[primitives.PointParameter("position", tip="Target point.")],
             help="Query the segment closest to the given point.",
             discussion=xmlmenudump.loadFile("DISCUSSIONS/engine/menu/query_skel_sgmt.xml"),
         )
     )
     menu.addItem(
         oofmenu.OOFMenuItem(
             "QuerySegmentByID",
             callback=self.querySgmtByID,
             params=[parameter.IntParameter("index", tip="Segment index.")],
             help="Query the segment with the given index.",
             discussion=xmlmenudump.loadFile("DISCUSSIONS/engine/menu/query_skel_sgmt_id.xml"),
         )
     )
     menu.addItem(
         oofmenu.OOFMenuItem(
             "QueryNode",
             callback=self.queryNode,
             params=[primitives.PointParameter("position", tip="Target point.")],
             help="Query the node closest to the given point.",
             discussion=xmlmenudump.loadFile("DISCUSSIONS/engine/menu/query_skel_node.xml"),
         )
     )
     menu.addItem(
         oofmenu.OOFMenuItem(
             "QueryNodeByID",
             callback=self.queryNodeByID,
             params=[parameter.IntParameter("index", tip="Node index.")],
             help="Query the node with the given index.",
             discussion=xmlmenudump.loadFile("DISCUSSIONS/engine/menu/query_skel_node_id.xml"),
         )
     )
Пример #23
0
 def __init__(self, name, ordering, parentClass=None,
              instanceClass=WhoDoUndo, proxyClasses=[], secret=0):
     WhoClass.__init__(self, name, ordering, parentClass=parentClass,
                       instanceClass=instanceClass,
                       proxyClasses=proxyClasses, secret=secret)
     self.historysize = historysize
     mainmenu.bufsizemenu.addItem(oofmenu.OOFMenuItem(
         utils.space2underscore(name),
         callback=self.setUndoBufferSize,
         # TODO: Disallow size=0.
         params=[parameter.IntParameter('size', historysize,
                                        tip='number of previous versions to preserve')],
         help="Set the history buffer size for %ss" % name,
         discussion=xmlmenudump.loadFile(
            'DISCUSSIONS/common/menu/bufsize.xml',
            lambda text,obj: text.replace('CLASS', name))
         ))
Пример #24
0
class Schedule(registeredclass.RegisteredClass):
    registry = []
    tip="Ways to specify when Scheduled Output will be produced."
    discussion=xmlmenudump.loadFile('DISCUSSIONS/engine/reg/schedule.xml')
    def __init__(self):
        self.time0 = 0.0
    def reset(self, continuing):
        pass
    def singleTime(self):
        # In subclasses this should return the time if the Schedule
        # contains only a single time, or None if the Schedule
        # contains multiple times.  If it contains a single unknown
        # time (which probably doesn't make sense) it should return
        # None.  This is used to distinguish between static and
        # quasistatic evolutions.
        return None
    def setOffset(self, time0): # adjust for relative vs absolute scheduletypes
        self.time0 = time0
Пример #25
0
def makemenu(menu_base):
    menu_base.clearSubMenu()
    for r in analyze.DataOperation.registry:
        help = getattr(r, "tip", None)
        new_item = oofmenu.OOFMenuItem(
            utils.space2underscore(r.name()),
            callback = _ops_callback,
            params = common_analysis_params + r.params,
            help=help,
            discussion=r.discussion)
        new_item.data = r
        menu_base.addItem(new_item)
    ops_menu.addItem(oofmenu.OOFMenuItem(
        'Rewind',
        callback=_rewind,
        params=[filenameparam.FileNameParameter(
                'filename',
                tip='The name of the output file.')],
        help="Overwrite the data currently in an output file.",
        discussion=xmlmenudump.loadFile('DISCUSSIONS/engine/menu/rewind.xml')
        ))
Пример #26
0
def makemenu(menu_base):
    menu_base.clearSubMenu()
    for r in analyze.DataOperation.registry:
        help = getattr(r, "tip", None)
        new_item = oofmenu.OOFMenuItem(
            utils.space2underscore(r.name()),
            callback = _ops_callback,
            params = common_analysis_params + r.params,
            help=help,
            discussion=r.discussion)
        new_item.data = r
        menu_base.addItem(new_item)
    ops_menu.addItem(oofmenu.OOFMenuItem(
        'Rewind',
        callback=_rewind,
        params=[filenameparam.FileNameParameter(
                'filename',
                tip='The name of the output file.')],
        help="Overwrite the data currently in an output file.",
        discussion=xmlmenudump.loadFile('DISCUSSIONS/engine/menu/rewind.xml')
        ))
Пример #27
0
    help="Set default parameters for displaying selected skeleton nodes.",
    discussion="""<para>

    Set default parameters for the
    <xref linkend="RegisteredClass-SkeletonNodeSelectionDisplay"/>,
    which displays the currently selected &skel; &nodes; in the graphics
    window.  See
    <xref linkend="RegisteredClass-SkeletonNodeSelectionDisplay"/>
    for a discussion of the parameters. This command may be put in the
    &oof2rc; file to set defaults for all &oof2; sessions.
    
    </para>"""))

nodeSelectDisplay = registeredclass.Registration(
    'Selected Nodes',
    display.DisplayMethod,
    SkeletonNodeSelectionDisplay,
    params=nodeselparams,
    ordering=2.2,
    layerordering= display.PointLike(3),
    whoclasses=('Skeleton',),
    tip="Display the currently selected nodes.",
    discussion=xmlmenudump.loadFile('DISCUSSIONS/engine/reg/nodeselectdisplay.xml')
    )

def defaultNodeSelectDisplay():
    return nodeSelectDisplay(color=defaultNodeSelColor, size=defaultNodeSelSize)

ghostgfxwindow.PredefinedLayer('Skeleton', '<topmost>',
                               defaultNodeSelectDisplay)
Пример #28
0
import atexit
import os
import os.path

# Parameter = parameter.Parameter
StringParameter = parameter.StringParameter
IntParameter = parameter.IntParameter
FloatParameter = parameter.FloatParameter

OOFMenuItem = oofmenu.OOFMenuItem
OOFRootMenu = oofmenu.OOFRootMenu
CheckOOFMenuItem = oofmenu.CheckOOFMenuItem

OOF = OOFRootMenu(
    'OOF',
    discussion=xmlmenudump.loadFile('DISCUSSIONS/common/menu/oof.xml'))

################

# Automatically log all menu commands to a temp file. The location of
# the temp file is taken from the OOFTMP environment variable, if it's
# defined.  Otherwise it's determined by the tempfile.mkstemp
# function, which looks in the environment variables TMPDIR, TEMP, and
# TMP, followed by the directories /tmp, /var/tmp, and /usr/tmp.

ooftmpdir = os.getenv('OOFTMP')
if ooftmpdir is not None:
    fd, logpath = tempfile.mkstemp(prefix='oof2-', suffix='.py', dir=ooftmpdir)
else:
    fd, logpath = tempfile.mkstemp(prefix='oof2-', suffix='.py')
tmplogfile = os.fdopen(fd, 'w')
Пример #29
0
    # be using C.  M's symstate will be INCONSISTENT and C21 will be
    # empty.

    return (subproblem.matrix_symmetry_M == symstate.ASYMMETRIC
            or subproblem.matrix_symmetry_C == symstate.ASYMMETRIC
            or linsys.C21_nonempty())


registeredclass.Registration(
    'Forward Euler',
    timestepper.TimeStepper,
    ForwardEuler,
    ordering=0,
    explicit=True,
    tip="Fully explicit first order time stepping.",
    discussion=xmlmenudump.loadFile('DISCUSSIONS/engine/reg/euler.xml'))

#=--=##=--=##=--=##=--=##=--=##=--=##=--=##=--=##=--=##=--=##=--=##=--=#

# Generalized Euler: everything between Forward Euler and Backward
# Euler.  self.theta is defined in subclasses.


class NLDataGE(timestepper.NLData):
    def __init__(self, subproblem, linsys0, endtime, dt, unknowns, theta):
        self.dt = dt
        self.C = linsys0.C_MCKa()
        # resid0 is the part of the residual that can be computed at
        # startTime, with the linsys0 that's passed into this function.
        # resid0 = -C u_n + (1-theta) dt F(u_n, t)
        self.resid0 = self.C * unknowns
Пример #30
0
    oofmenu.OOFMenuItem(
        'Skeleton_Selection',
        help=
        "Set the size of history buffers for Skeleton selection operations",
        ordering=1))

_stacksize = 50


def _allBufSizesCB(menuitem, size):
    _stacksize = size
    for mode in SkeletonSelectionMode.modes:
        mode.setUndoBufferSize(menuitem, size)


_stacksize_params = [
    parameter.IntParameter('size',
                           _stacksize,
                           tip='number of previous selections to retain')
]

_all_stacksize_menuitem = bufsizmenu.addItem(
    oofmenu.OOFMenuItem(
        'All',
        callback=_allBufSizesCB,
        ordering=-1,
        params=_stacksize_params,
        help="Set the history buffer size for all Skeleton selections",
        discussion=xmlmenudump.loadFile(
            'DISCUSSIONS/engine/menu/skelbufsizes.xml')))
Пример #31
0
            0.0,  ## 'c-axis tilt'
            tip='second rotation, about the y-axis, in degrees.'),
        FloatRangeParameter(
            'beta',
            (-180., 180., 0.1),
            0.0,  ##  c-axis rot.
            tip='first rotation, about the z-axis, in degrees.'),
        FloatRangeParameter(
            'gamma',
            (-180., 180., 0.1),
            0.0,  ## z-axis rot
            tip='third rotation, about the z-axis, in degrees.')
    ],
    tip=
    'Euler angles (alpha, beta, gamma) are applied: first beta about the z axis, then alpha about the y, and finally gamma about z. This operation brings the crystal axes into coincidence with the lab axes.',
    discussion=xmlmenudump.loadFile('DISCUSSIONS/engine/reg/abg.xml'))

#=--=##=--=##=--=##=--=##=--=##=--=##=--=##=--=##=--=##=--=##=--=##=--=#


# Goldstein's "X" convention.  This may have some other more
# descriptive name, but I don't know what it is.  Rotations are z,x,z.
class X(Orientation):
    def __init__(self, phi, theta, psi):
        self.phi = phi
        self.theta = theta
        self.psi = psi
        self.corient = corientation.COrientX(
            *map(math.radians, (phi, theta, psi)))

    @staticmethod
Пример #32
0
        # x and y are the current location and is guaranteed to be
        # provided. All others are provided if applicable.  nx and ny
        # are the unit-vector components of the boundary normal at
        # this location. i is the node index, s is the arc length,
        # alpha is the fractional arc length.
        strfunction.StrFunction.__init__(
            self, 'x, y, nx, ny, i, s, alpha', funcstr)
    def __repr__(self):
        # ProfileFunctions only have to write their values when they
        # are used in ProfileFunctionParameters, which can set
        # themselves from a string. So just write the string.
        return "'%s'" % self.funcstr

xmlmenudump.XMLObjectDoc(
    'ProfileFunction',
    xmlmenudump.loadFile('DISCUSSIONS/engine/object/profilefunction.xml'))

# The ProfileFunctionParameter can accept either a string or a
# ProfileFunction object, but it only stores a ProfileFunction object.
# Like XYStrFunctionParameter, it needs a special "set" function.

class ProfileFunctionParameterBase(parameter.Parameter):
    def __init__(self, name, value=None, default=None, tip=None):
        parameter.Parameter.__init__(self, name,
                                         value=value,
                                         default=default, tip=tip)
    def set(self, value):
        if type(value) is types.StringType:
            self._value = self.profileClass(value)
        elif isinstance(value, self.profileClass):
            self._value = value
Пример #33
0
    ordering=1,
    help="Set default parameters for Mesh Info displays.",
    discussion="""<para>

    Set default parameters for
    <link linkend="RegisteredClass-MeshInfoDisplay"><classname>MeshInfoDisplays</classname></link>.
    See <xref linkend="RegisteredClass-MeshInfoDisplay"/> for the details.
    This command may be placed in the &oof2rc; file to set a default value
    for all &oof2; sessions.
    
    </para>"""))

meshInfoDisplay = registeredclass.Registration(
    'Info',
    display.DisplayMethod,
    MeshInfoDisplay,
    params=meshinfoparams,
    ordering=4.0,
    layerordering=display.PointLike(100),
    whoclasses=('Mesh',),
    tip="Set display parameters for the decorations used by the Mesh Info toolbox.",
    discussion=xmlmenudump.loadFile('DISCUSSIONS/engine/reg/meshinfodisplay.xml')
    )

def defaultMeshInfoDisplay():
    return meshInfoDisplay(query_color=defaultQueryColor,
                           peek_color=defaultPeekColor,
                           node_size=defaultNodeSize,
                           element_width=defaultElementWidth)
ghostgfxwindow.PredefinedLayer('Mesh', '<topmost>', defaultMeshInfoDisplay)
Пример #34
0
        activearea = microstructure.activearea
        pixelselection = microstructure.pixelselection
        activearea.start()
        activearea.clear()              # everything is active
        activearea.invert()             # everything is inactive
        pixgrp = pixelselection.getSelectionAsGroup()
        courier = GroupSelection(microstructure, pixgrp)
        activearea.unselectWithoutCheck(courier)

registeredclass.Registration(
    'Activate Selection Only',
    ActiveAreaModifier,
    ActivateOnlySelection,
    ordering=0.1,
    tip="Activate the selected pixels, deactivating everything else.",
    discussion=xmlmenudump.loadFile('DISCUSSIONS/common/menu/activate_selection_only.xml')
    )

class ActivateSelection(ActiveAreaModifier):
    def __call__(self, microstructure):
        activearea = microstructure.activearea
        pixelselection = microstructure.pixelselection
        activearea.start()
        pixgrp = pixelselection.getSelectionAsGroup()
        activearea.unselectWithoutCheck(GroupSelection(microstructure, pixgrp))

registeredclass.Registration(
    'Activate Selection',
    ActiveAreaModifier,
    ActivateSelection,
    ordering=0.5,
Пример #35
0
class ContinuumProfile(ProfileX, _ContinuumProfileX):
    pass

registeredclass.Registration(
    "Continuum Profile",
    ProfileX,
    ContinuumProfile,
    ordering=2,
    params=[
        profilefunction.ProfileFunctionXParameter(
            "function",
            value=profilefunction.ProfileFunctionX("0.0"),
            tip="A function of x, y, nx, ny, i, s, and/or alpha.")
        ],
    tip="Boundary condition is an arbitrary function of position.",
    discussion=xmlmenudump.loadFile(
        'DISCUSSIONS/engine/reg/continuumprofilex.xml')
    )

class ContinuumProfileXT(ProfileXT, _ContinuumProfileXT):
    pass

registeredclass.Registration(
    "Continuum Profile",
    ProfileXT,
    ContinuumProfileXT,
    ordering=2,
    params=[
        profilefunction.ProfileFunctionXTParameter(
            "function",
            value=profilefunction.ProfileFunctionXT("0.0"),
            tip="A function of x, y, nx, ny, i, s, alpha, and/or t.")
Пример #36
0
    details.  This command may be put into your &oof2rc; file to set
    defaults for all &oof2; sessions.
    
    </para>"""))

meshCrossSectionDisplay = registeredclass.Registration(
    'Cross Section',
    display.DisplayMethod,
    MeshCrossSectionDisplay,
    params=[
        meshcsparams.MeshCrossSectionSetParameter(
            'cross_sections',
            placeholder.selection,
            tip="Which cross-section to display?")
    ] + meshcsdispparams,
    ordering=5.0,
    layerordering=display.SemiLinear,
    whoclasses=('Mesh', ),
    tip="Determine which cross sections are displayed, and how.",
    discussion=xmlmenudump.loadFile(
        'DISCUSSIONS/engine/reg/meshcsdisplay.xml', ))


def defaultMeshCrossSectionDisplay():
    return meshCrossSectionDisplay(color=defaultMeshCSColor,
                                   linewidth=defaultMeshCSLineWidth)


ghostgfxwindow.PredefinedLayer('Mesh', '<contourable>',
                               defaultMeshCrossSectionDisplay)
Пример #37
0

class PinInternalBoundaryNodes(PinNodesModifier):
    def __call__(self, skelcontext):
        skel = skelcontext.getObject()
        skelcontext.pinnednodes.start()
        skelcontext.pinnednodes.pinInternalBoundaryNodes(skel)


registeredclass.Registration(
    'Pin Internal Boundary Nodes',
    PinNodesModifier,
    PinInternalBoundaryNodes,
    ordering=2,
    tip="Pin all internal boundary nodes.",
    discussion=xmlmenudump.loadFile('DISCUSSIONS/engine/reg/pininternal.xml'))

#=--=##=--=##=--=##=--=##=--=##=--=##=--=##=--=##=--=##=--=##=--=##=--=#


class PinSelectedSegments(PinNodesModifier):
    def __call__(self, skelcontext):
        skelcontext.pinnednodes.start()
        skelcontext.pinnednodes.pinSelectedSegments(
            skelcontext.segmentselection.currentSelectionTracker())


registeredclass.Registration('Pin Selected Segments',
                             PinNodesModifier,
                             PinSelectedSegments,
                             ordering=4,
Пример #38
0
                sister in processed or
                element.dominantPixel(skel.MS)!=sister.dominantPixel(skel.MS)):
                continue
            j = sister.nodes.index(node0)
            nodeA = sister.nodes[(j+1)%3]
            nodeB = element.nodes[(i+2)%3]
            nlist = [node0, nodeA, node1, nodeB]
            parents = element.getParents() + sister.getParents()
            change = skeleton.ProvisionalChanges(skel)
            change.removeElements(element, sister)
            change.insertElements(ProvisionalQuad(nlist, parents=parents))
            changes.append(change)
        return changes

###################################################
    
registeredclass.Registration(
    'Merge Triangles',
    skeletonmodifier.SkeletonModifier,
    MergeTriangles, ordering = 5,
    params=[parameter.RegisteredParameter('targets',
                                          skeletonmodifier.SkelModTargets,
                                          tip = 'Which elements to modify.'),
            parameter.RegisteredParameter('criterion',
                                          skeletonmodifier.SkelModCriterion,
                                          tip='Acceptance criterion.')
    ],
    tip="Merge neighboring homogeneous triangles to form quadrilaterals.",
    discussion=xmlmenudump.loadFile('DISCUSSIONS/engine/reg/merge.xml')
    )
Пример #39
0
    SkeletonBoundaryDisplay,
    params=[SkeletonBoundaryListParameter('boundaries', [],
                                      tip="Boundaries to display."),
            color.ColorParameter('color', value=color.gray50,
                                 tip="Color for the displayed boundaries."),
            parameter.IntRangeParameter('linewidth', widthRange, 4,
                                        tip="Line width for edge boundaries."),
            parameter.IntRangeParameter('dotsize', widthRange, 4,
                                        tip="Dot radius for point boundaries."),
            parameter.IntRangeParameter('arrowsize', (0, 20), 10,
                                        tip="Arrow size for edge boundaries.")],
    ordering=1.0,
    layerordering=display.SemiLinear(2),
    whoclasses=('Skeleton',),
    tip="Display some or all of the boundaries of the Skeleton",
    discussion=xmlmenudump.loadFile('DISCUSSIONS/engine/reg/skeletonbdydisplay.xml')
    )

# Layer for showing the selected boundary (point and edge) of a skeleton.

class SelectedSkeletonBoundaryDisplay(display.DisplayMethod):
    def __init__(self, color, linewidth, dotsize, arrowsize):
        self.color = color
        self.linewidth = linewidth
        self.dotsize = dotsize
        self.arrowsize = arrowsize
        display.DisplayMethod.__init__(self)
        
    def draw(self, gfxwindow, device):
        skel = self.who().resolve(gfxwindow)
        skelobj = skel.getObject()
Пример #40
0
        self.analysisObj.perform(self, meshcontext, time, self.destination)
    def finish(self, meshcontext):
        self.analysisObj.finish(meshcontext)
        scheduledoutput.ScheduledOutput.finish(self, meshcontext)
    def defaultName(self):
        return self.analysis
    def printHeaders(self, destination):
        self.analysisObj.printHeaders(destination)
    def save(self, datafile, meshctxt):
        # Before saving the ScheduledOutput, make sure the named
        # analysis is in the data file.
        from ooflib.engine.IO import analyzemenu
        analyzemenu.saveAnalysisDef(datafile, self.analysis)
        scheduledoutput.ScheduledOutput.save(self, datafile, meshctxt)

registeredclass.Registration(
    "Named Analysis",
    scheduledoutput.ScheduledOutput,
    NamedAnalysisOutput,
    ordering=3,
    destinationClass=outputdestination.TextOutputDestination,
    params=[
        AnalysisNameParameter(
            "analysis", 
            tip="Name of the analysis operation to perform.  Named analyses can be created on the Analysis and Boundary Analysis Pages.")
        ],
    tip="Use a predefined bulk or boundary Analysis method.",
    discussion=xmlmenudump.loadFile('DISCUSSIONS/engine/reg/namedanalysis.xml')
)
        
Пример #41
0
registeredclass.Registration(
    'Material',
    display.DisplayMethod,
    MicrostructureMaterialDisplay,
    ordering=0,
    layerordering=display.Planar(0.4),
    params=[
    color.ColorParameter('no_material', color.black,
                         tip="Color to use if no material has been assigned to a pixel"),
    color.ColorParameter('no_color', color.blue,
                         tip="Color to use if the assigned material has no assigned color")
    ],
    whoclasses = ('Microstructure',),
    tip="Display the color of the Material assigned to each pixel.",
    discussion=xmlmenudump.loadFile('DISCUSSIONS/engine/reg/microstructuredisplay.xml')
    )

############################

if config.dimension() == 2:

    class OrientationDisplay(MSMaterialDisplay):
        def __init__(self, colorscheme, no_material=color.blue,
                     no_orientation=color.black):
            self.colorscheme = colorscheme
            self.no_orientation = no_orientation
            self.no_material = no_material
            MSMaterialDisplay.__init__(self)
        def draw(self, gfxwindow, device):
            msobj = self.who().getObject(gfxwindow)
Пример #42
0
            prog.setMessage("checked %d/%d segments" % (i + 1, n))


registeredclass.Registration(
    "Heterogeneous Segments",
    RefinementTarget,
    CheckHeterogeneousEdges,
    ordering=3,
    params=[
        parameter.FloatRangeParameter(
            "threshold", (0.0, 1.0, 0.05), value=0.9, tip="Refine segments whose homogeneity is less than this."
        ),
        parameter.RegisteredParameter("choose_from", SegmentChooser, tip="Segments to consider."),
    ],
    tip="Divide heterogeneous segments.",
    discussion=xmlmenudump.loadFile("DISCUSSIONS/engine/reg/check_hetero_segs.xml"),
)


class CheckSelectedEdges(RefinementTarget):
    def __call__(self, skeleton, context, divisions, markedEdges, criterion):
        prog = progress.findProgress("Refine")
        segments = context.segmentselection.retrieve()
        n = len(segments)
        for i, segment in enumerate(segments):
            if segment.active(skeleton):
                self.markSegment(segment, divisions, markedEdges)
            if prog.stopped():
                return
            prog.setFraction(1.0 * (i + 1) / n)
            prog.setMessage("checked %d/%d segments" % (i + 1, n))
Пример #43
0
# Node-specific menu items:

new = oofmenu.OOFMenuItem(
    "New_Group",
    cli_only=1,
    callback=_new_group,
    params=parameter.ParameterGroup(
    whoville.WhoParameter("skeleton", whoville.getClass('Skeleton'),
                          tip=parameter.emptyTipString),
    AutomaticNameParameter("name", value=automatic.automatic,
                           resolver=NewGroupNameResolver("nodegroup",
                                                         "nodegroups"),
                           tip="Name of the group to be created.")),
    help="Create a new node group.",
    discussion=xmlmenudump.loadFile('DISCUSSIONS/engine/menu/newnodegroup.xml')
    )
new.data = "nodegroups"
nodegroupmenu.addItem(new)


auto = oofmenu.OOFMenuItem(
    "Auto_Group",
    cli_only=1,
    callback=_auto_group,
    params=[whoville.WhoParameter("skeleton", whoville.getClass("Skeleton"),
                                  tip=parameter.emptyTipString)],
    help="Create node groups for each pixel group.",
    discussion=
"""<para>Automatically create a &nodegroup; in the &skel; for every
&pixelgroup; in the &micro;.  All &skel; &nodes; lying on a pixel in a
Пример #44
0
from ooflib.engine.IO import microstructuredisplay

class OrientationMapDisplay(display.DisplayMethod):
    def __init__(self, colorscheme):
        self.colorscheme = colorscheme
        display.DisplayMethod.__init__(self)
    def draw(self, gfxwindow, device):
        msobj = self.who().getObject(gfxwindow)
        data = orientmapdata.getOrientationMap(msobj)
        if data is not None:
            orientimage = orientmapdata.OrientMapImage(data, self.colorscheme)
            device.draw_image(orientimage, coord.Coord(0,0), msobj.size())
    def getTimeStamp(self, gfxwindow):
        msobj = self.who().getObject(gfxwindow)
        return max(display.DisplayMethod.getTimeStamp(self, gfxwindow),
                   orientmapdata.getOrientationMapTimestamp(msobj))

registeredclass.Registration(
    'Orientation Map',
    display.DisplayMethod,
    OrientationMapDisplay,
    ordering=2,
    params=[parameter.RegisteredParameter('colorscheme',
                                          angle2color.Angle2Color,
                                tip='Method for converting angles to colors.')
            ],
    layerordering=display.Planar(0.5),
    whoclasses = ('Microstructure',),
    tip="Display a Microstructure's Orientation Map, whether or not it's used by Material Properties.",
    discussion=xmlmenudump.loadFile('DISCUSSIONS/orientationmap/reg/orientationmapdisplay.xml'))
Пример #45
0
    def __init__(self,
                 name,
                 methodclass,
                 modifierclass,
                 changedselectionsignal,
                 modifierappliedsignal,
                 groupmenu,
                 allCourier,
                 materialsallowed=None):
        self.name = name

        # methodclass is the RegisteredClass of routines for creating
        # new selections.  These appear in the
        # SkeletonSelectionToolbox.
        self.methodclass = methodclass

        # modifierclass is the RegisteredClass of routines for
        # modifying existing selections.  These appear in the
        # SkeletonSelectionPage.
        self.modifierclass = modifierclass

        # changedselectionsignal is sent when any change is made in
        # a selection.  It indicates which selection was changed, but
        # not how.
        self.changedselectionsignal = changedselectionsignal
        # modifierappliedsignal is sent when a selection modifier is
        # uses.  The modifier is sent as an argument.
        self.modifierappliedsignal = modifierappliedsignal

        # groupmenu is the menu of commands for manipulating groups of
        # the object.
        self.groupmenu = groupmenu

        # allCourier is a SkeletonSelectionCourier class that can be
        # used to loop over all objects of this category in the
        # Skeleton.
        self.allCourier = allCourier

        # materialsallowed is either None or a MaterialType instance.
        # If not None, it indicates what kinds of material may be
        # explicitly assigned to groups of this type of selectable
        # object.
        self.materialsallowed = materialsallowed

        self.stacksize = 50

        # Create a menuitem for changing the stack size.  The
        # parameter is shared among the menuitems for all
        # SkeletonSelectionModes as well as the menuitem that sets all
        # of the buffer sizes at once.
        self.stacksize_menuitem = bufsizmenu.addItem(
            oofmenu.OOFMenuItem(
                name,
                callback=self.setUndoBufferSize,
                params=_stacksize_params,  # global, see below
                help="Set the history buffer size for Skeleton %s selections" %
                name,
                discussion=xmlmenudump.loadFile(
                    'DISCUSSIONS/engine/menu/skelbufsize.xml',
                    lambda text, obj: text.replace('CLASS', name))))

        SkeletonSelectionMode.modes.append(self)
Пример #46
0
class RGBData8(ImageData):
    def __init__(self, rgbvalues):
        self.rgbvalues = rgbvalues
    def values(self):
        return self.rgbvalues

registeredclass.Registration(
    'RGBData8',
    ImageData,
    RGBData8,
    ordering=0,
    params=[
    parameter.ListOfUnsignedShortsParameter('rgbvalues', tip="RGB values.")],
    tip="RGB image data.",
    discussion=xmlmenudump.loadFile('DISCUSSIONS/image/reg/rgbdata8.xml'))



class GrayData8(ImageData):
    def __init__(self, grayvalues):
        self.grayvalues = grayvalues
    def values(self):
        return self.grayvalues

registeredclass.Registration(
    'GrayData8',
    ImageData,
    GrayData8,
    ordering=1,
    params=[
Пример #47
0
    # use since they don't have any swig overhead.
    if config.dimension() == 2:
        if type(ptlist) == types.ListType:
            return [Point(pt[0], pt[1]) for pt in ptlist]
        return ptlist.__class__([Point(pt[0], pt[1]) for pt in ptlist])
    elif config.dimension() == 3:
        if type(ptlist) == types.ListType:
            return [Point(pt[0], pt[1], pt[2]) for pt in ptlist]
        return ptlist.__class__([Point(pt[0], pt[1], pt[2]) for pt in ptlist])


## Documentation for Point and iPoint classes

from ooflib.common.IO import xmlmenudump
xmlmenudump.XMLObjectDoc(
    'iPoint', xmlmenudump.loadFile('DISCUSSIONS/common/object/ipoint.xml'))

xmlmenudump.XMLObjectDoc(
    'Point', xmlmenudump.loadFile('DISCUSSIONS/common/object/point.xml'))

#=--=##=--=##=--=##=--=##=--=##=--=##=--=##=--=##=--=##=--=##=--=##=--=#


class Rectangle(object):
    # A Rectangle is a pair of points at diagonally opposite corners.
    def __init__(self, pt0, pt1):
        # Don't assume that args pt0 and pt1 have .x and .y data
        self.lowleft = Point(min(pt0[0], pt1[0]), min(pt0[1], pt1[1]))
        self.upright = Point(max(pt0[0], pt1[0]), max(pt0[1], pt1[1]))

    def enclosing_rectangle(self):
Пример #48
0
    
    ## TODO: This calculation more logically belongs in
    ## LinearizedSystem, but it doesn't know the matrix_symmetries.

    return (subproblem.matrix_symmetry_M == symstate.ASYMMETRIC or
            subproblem.matrix_symmetry_C == symstate.ASYMMETRIC or
            linsys.C21_nonempty())

registeredclass.Registration(
    '4th order Runge-Kutta',
    timestepper.TimeStepper,
    RK4,
    ordering=2.1,
    explicit=True,
    tip="Fourth order Runge-Kutta time stepping.",
    discussion=xmlmenudump.loadFile('DISCUSSIONS/engine/reg/rk4.xml')
    )

## Second order Runge-Kutta

## y_{n+1} = y_n + h k_2 + O(h^3)
## k_1 = g(t_n, y_n)
## k_2 = g(t_n + h/2, y_n + h/2 k_1)

## g(t, u) = C^{-1} (f - K u)


class RK2(RKBase):
    def errorOrder(self):
        return 3.0
    def shortrepr(self):
Пример #49
0
    def compute_jacobian(self, data, nlsolver):
        return data.linsys.J_MCK()

    def compute_linear_coef_mtx(self, data, nlsolver):
        return data.linsys.K_MCK()


####################################################################

registeredclass.Registration(
    'Static',
    timestepper.StepDriver,
    StaticDriver,
    ordering=0,
    tip="Solve a subproblem as a static or quasi-static system.",
    discussion=xmlmenudump.loadFile('DISCUSSIONS/engine/reg/staticdriver.xml'))

# _StaticStepper never appears in the user interface because there's
# only one kind of static stepper, so it doesn't really need a
# Registration.  However, if it doesn't have a Registration its
# __repr__ doesn't work, which hinders debugging.  So here it has a
# Registration, but it's secret.

registeredclass.Registration(
    'Static',
    timestepper.TimeStepper,
    _StaticStepper,
    tip="Used internally by the Static StepDriver",
    secret=True,
    ordering=10000)
Пример #50
0
from ooflib.SWIG.common import activearea
from ooflib.common import debug
from ooflib.common import primitives
from ooflib.common.IO import mainmenu
from ooflib.common.IO import oofmenu
from ooflib.common.IO import parameter
from ooflib.common.IO import whoville
from ooflib.common.IO import xmlmenudump
import ooflib.common.microstructure

OOF = mainmenu.OOF
micromenu = OOF.LoadData.addItem(
    oofmenu.OOFMenuItem(
        "Microstructure",
        help="Commands describing Microstructures in data files.",
        discussion=xmlmenudump.loadFile("DISCUSSIONS/common/menu/microstructureIO.xml"),
    )
)

#########

import sys


def _newMicrostructure(menuitem, name, isize, size):
    sys.stdout.flush()
    try:
        oldms = ooflib.common.microstructure.microStructures[name]
    except KeyError:
        pass
    else:
Пример #51
0
from ooflib.SWIG.common import config
from ooflib.common import registeredclass
##import weakref


class BitmapDisplayMethod(display.DisplayMethod):
    def __init__(self):
        self.bitmapobject = None
        display.DisplayMethod.__init__(self)

    def draw(self, gfxwindow, device):
        bitmapobj = self.who().getObject(gfxwindow)
        if config.dimension() == 2:
            device.draw_image(bitmapobj, coord.Coord(0, 0), bitmapobj.size())
        if config.dimension() == 3:
            device.draw_image(bitmapobj, coord.Coord(0, 0, 0),
                              bitmapobj.size())


bitmapDisplay = registeredclass.Registration(
    'Bitmap',
    display.DisplayMethod,
    BitmapDisplayMethod,
    ordering=-100,
    layerordering=display.Planar,
    params=[],
    whoclasses=('Image', ),
    tip="Display an Image as a bitmap.",
    discussion=xmlmenudump.loadFile(
        'DISCUSSIONS/common/reg/bitmapdisplay.xml'))
Пример #52
0
        C0.axpy(1-theta1, self.a0dot, self.resid0)    # ... + (1-theta)*C0*a0dot

        timestepper.NLData.__init__(self, subproblem, linsys, endtime)

def _asymmetric(subproblem):
    return ((subproblem.second_order_fields() and
            subproblem.matrix_symmetry_M == symstate.ASYMMETRIC)
            or
            subproblem.matrix_symmetry_C == symstate.ASYMMETRIC
            or
            subproblem.matrix_symmetry_K == symstate.ASYMMETRIC)

registeredclass.Registration(
    'SS22',
    timestepper.TimeStepper,
    SS22,
    params=[
        parameter.FloatRangeParameter(
            'theta1', (0.0, 1.0, 0.1), 0.5,
            tip='First moment of the weight function for time averages.'),
        parameter.FloatRangeParameter(
            'theta2', (0.0, 1.0, 0.1), 0.5,
            tip='Second moment of the weight function for time averages.')
        ],
    ordering=3.0,
    require_timederiv = True,
    tip="Zienkowicz and Taylor's SS22 algorithm for solving equations with second order time derivatives.",
    discussion=xmlmenudump.loadFile('DISCUSSIONS/engine/reg/ss22.xml'))


Пример #53
0
## refactor the classes like that, then the ErrorNorm classes must at
## least be renamed so that it's clear that they are only meant to be
## used with the ZZ estimator.
    
class L2ErrorNorm(ErrorNorm):
    #AMR subproblem, pass subproblem
    def __call__(self, element, subproblem, flux):
        return subproblem.zz_L2_estimate(element, flux)
    
registeredclass.Registration(
    'L2 Error Norm',
    ErrorNorm,
    L2ErrorNorm,
    ordering=0,
    tip="Use the root mean square of the components of the error.",
    discussion=xmlmenudump.loadFile('DISCUSSIONS/engine/reg/l2errornorm.xml'))

class WeightedL2ErrorNorm(ErrorNorm):
    def __init__(self):
        self.weights = None
    #AMR subproblem, pass subproblem
    def preprocess(self, subproblem, flux):
        bottom = 0.0  # [bottom, top] : the range normalized values
        top = 0.3     # to be weighted.
        self.weights = subproblem.zz_L2_weights(flux, bottom, top)
    #AMR subproblem, pass subproblem
    def __call__(self, element, subproblem, flux):
        index = element.get_index()
        return subproblem.zz_L2_estimate(element, flux)*self.weights[index]
    
registeredclass.Registration(
Пример #54
0
# # # # # # # # # # # # # # # #

# Should call the selector with the skeletoncontext and a list of
# nodes on which to operate.
class SingleNodeSelect(NodeSelectMethod):
    def select(self, skeletoncontext, pointlist, selector):
        closest = skeletoncontext.getObject().nearestNode(pointlist[0])
        selector([closest])
        
NodeSelectionRegistration(
    'Single_Node',
    SingleNodeSelect,
    ordering=0,
    events=['up'],
    tip="Select a single node.",
    discussion=xmlmenudump.loadFile('DISCUSSIONS/engine/reg/single_node.xml'))

if config.dimension() == 2:
    class RectangleNodeSelect(NodeSelectMethod):
        def select(self, skeletoncontext, pointlist, selector):
            reslist = []
            xmin = min(pointlist[0].x, pointlist[1].x)
            xmax = max(pointlist[0].x, pointlist[1].x)
            ymin = min(pointlist[0].y, pointlist[1].y)
            ymax = max(pointlist[0].y, pointlist[1].y)
            for n in skeletoncontext.getObject().nodes:
                if n.position().x < xmax and n.position().x > xmin and \
                       n.position().y < ymax and n.position().y > ymin:
                    reslist.append(n)
            selector(reslist)
Пример #55
0
    'Element Edges',
    display.DisplayMethod,
    MeshEdgeDisplay,
    ordering=0.0,
    layerordering=display.Linear,
    params=meshdispparams + [
        color.ColorParameter(
            'color', defaultMeshColor, tip="Color of the displayed edges."),
        IntRangeParameter('width',
                          widthRange,
                          defaultMeshWidth,
                          tip="Line thickness, in pixels.")
    ],
    whoclasses=('Mesh', ),
    tip="Draw the edges of Mesh Elements.",
    discussion=xmlmenudump.loadFile(
        'DISCUSSIONS/engine/reg/meshedgedisplay.xml'))

registeredclass.Registration(
    'Element Edges',
    display.DisplayMethod,
    SkeletonEdgeDisplay,
    ordering=0.0,
    layerordering=display.Linear,
    params=[
        color.ColorParameter('color',
                             defaultSkeletonColor,
                             tip="Color of the displayed edges."),
        IntRangeParameter('width',
                          widthRange,
                          defaultSkeletonWidth,
                          tip="Line thickness, in pixels.")
Пример #56
0
    ms.activearea.end_writing()
    switchboard.notify('active area modified', None)
    switchboard.notify('redraw')

def _delete(menuitem, microstructure, name):
    ms = ooflib.common.microstructure.getMicrostructure(microstructure)
    ms.deleteActiveArea(name)
    switchboard.notify('stored active areas changed', name)

# Build menu items for active area modifications

aamodmenu = mainmenu.OOF.addItem(oofmenu.OOFMenuItem(
    'ActiveArea',
    cli_only=1,
    help='Create and manipulate Active Areas.',
    discussion=xmlmenudump.loadFile('DISCUSSIONS/common/menu/activearea.xml')
    ))
                                                                                
def buildActiveAreaModMenu():
    aamodmenu.clearMenu()
                                                                                
    aamodmenu.addItem(oofmenu.OOFMenuItem(
        'Undo',
        callback=_undo,
        params=[whoville.WhoParameter('microstructure',
                                      ooflib.common.microstructure.microStructures,
                                      tip=parameter.emptyTipString)
                ],
        help="Undo the latest active area modification.",
        discussion="""<para>
        Revert to the previous &active; in the given
Пример #57
0
def _deleteCB(menuitem, skeleton, boundary):
    skelctxt = skeletoncontext.skeletonContexts[skeleton]
    skelctxt.removeBoundary(boundary)


boundarymenu.addItem(
    oofmenu.OOFMenuItem("Delete",
                        callback=_deleteCB,
                        help="Delete a boundary from a Skeleton.",
                        params=[
                            boundarybuilder.skeletonparam,
                            skeletongroupparams.SkeletonBoundaryParameter(
                                'boundary', tip="Boundary to be removed.")
                        ],
                        discussion=xmlmenudump.loadFile(
                            'DISCUSSIONS/engine/menu/boundary_delete.xml')))

### Boundary renaming


def _renameCB(menuitem, skeleton, boundary, name):
    skelctxt = skeletoncontext.skeletonContexts[skeleton]
    skelctxt.renameBoundary(boundary, name)


boundarymenu.addItem(
    oofmenu.OOFMenuItem("Rename",
                        callback=_renameCB,
                        help="Rename a Skeleton boundary.",
                        params=[
                            boundarybuilder.skeletonparam,
Пример #58
0
def buildActiveAreaModMenu():
    aamodmenu.clearMenu()
                                                                                
    aamodmenu.addItem(oofmenu.OOFMenuItem(
        'Undo',
        callback=_undo,
        params=[whoville.WhoParameter('microstructure',
                                      ooflib.common.microstructure.microStructures,
                                      tip=parameter.emptyTipString)
                ],
        help="Undo the latest active area modification.",
        discussion="""<para>
        Revert to the previous &active; in the given
        &micro;.</para>"""
        ))
                                                                                
    aamodmenu.addItem(oofmenu.OOFMenuItem(
        'Redo',
        callback=_redo,
        params=[whoville.WhoParameter('microstructure',
                                      ooflib.common.microstructure.microStructures,
                                      tip=parameter.emptyTipString)
                ],
        help="Redo the latest undone active area modification.",
        discussion="""<para>
        Undo the latest <xref linkend='MenuItem-OOF.ActiveArea.Undo'/>.
        </para>"""))

    aamodmenu.addItem(oofmenu.OOFMenuItem(
        'Override',
        params=[parameter.BooleanParameter('override', 0,
                                           tip="Whether to override or not."),
                whoville.WhoParameter('microstructure',
                                      ooflib.common.microstructure.microStructures,
                                      tip=parameter.emptyTipString)
                ],
        callback=_override,
        help="Temporarily activate the entire Microstructure.",
        discussion=xmlmenudump.loadFile('DISCUSSIONS/common/menu/activearea_override.xml')))

    aamodmenu.addItem(oofmenu.OOFMenuItem(
        'Store',
        callback=_store,
        params=parameter.ParameterGroup(
        whoville.WhoParameter('microstructure',
                              ooflib.common.microstructure.microStructures,
                              tip=parameter.emptyTipString),
        parameter.AutomaticNameParameter('name', value=automatic.automatic,
                                         resolver=activeAreaNameResolver,
                                         tip = "The name of the active are to be stored")),
        help="Store the current active area.",
        discussion="""<para>

        Give the current &active; a <varname>name</varname>, and store
        it for future use.  This makes it easy to switch between
        different active regions of a &micro;.  If the given
        <varname>name</varname> is already being used for another
        &active; in the same &micro;, then
        <userinput>&lt;x&gt;</userinput> will be appended to it, where
        <userinput>x</userinput> is an integer chosen to make the name
        unique.

        </para>"""))

    aamodmenu.addItem(oofmenu.OOFMenuItem(
        'Restore',
        callback=_restore,
        params=[whoville.WhoParameter('microstructure',
                                      ooflib.common.microstructure.microStructures,
                                      tip=parameter.emptyTipString),
                parameter.StringParameter('name', tip="The name of the active area to be restored.")],
        help="Restore a named active area.",
        discussion="""<para>
        Set the current &active; to the given <link
        linkend='MenuItem-OOF.ActiveArea.Store'>stored</link>
        &active;.
        </para>"""))
    
    aamodmenu.addItem(oofmenu.OOFMenuItem(
        'Rename',
        callback=_rename,
        params=[
        whoville.WhoParameter('microstructure',
                              ooflib.common.microstructure.microStructures,
                              tip=parameter.emptyTipString),
        parameter.StringParameter('oldname',
                                  tip="The name of a stored active area."),
        parameter.StringParameter('newname', '',
                                  tip='A new name for the active area.')
        ],
        help="Rename the stored active area.",
        discussion="<para>Assign a new name to a stored active area.</para>"))
    
    aamodmenu.addItem(oofmenu.OOFMenuItem(
        'Delete',
        callback=_delete,
        params=[
        whoville.WhoParameter('microstructure',
                              ooflib.common.microstructure.microStructures,
                              tip=parameter.emptyTipString),
        parameter.StringParameter('name', tip="The name of the active area to be deleted.")],
        help="Delete a stored active area.",
        discussion="""<para>
        Delete a <link
        linkend='MenuItem-OOF.ActiveArea.Store'>stored</link> active
        area.  This only deletes the stored copy of the active area.
        It does not affect the activity of any pixels.
        </para>"""))
    
                           
                                                                                
    for registration in activeareamod.ActiveAreaModifier.registry:
        # registration tip string => menuitem help string
        try:
            help = registration.tip
        except AttributeError:
            help = None
        # registration discussion => menuitem discussion
        try:
            discussion = registration.discussion
        except AttributeError:
            discussion = None
        menuitem = aamodmenu.addItem(
            oofmenu.OOFMenuItem(utils.space2underscore(registration.name()),
                                callback=activeareamod.modify,
                                params=[
            whoville.WhoParameter('microstructure',
                                  ooflib.common.microstructure.microStructures,
                                  tip=parameter.emptyTipString)
            ] + registration.params,
                                help=help,
                                discussion=discussion))
        menuitem.data = registration