예제 #1
0
파일: reporter.py 프로젝트: santiama/OOF3D
    def __init__(self):
        # Set flags.  For each type of message, if the flag is set,
        # then the messages of that type should be displayed to the
        # user.
        self.gui_mode = False
        self.flag_dict = {}
        for f in messageclasses:
            self.flag_dict[f] = True

        # Message list is a list of tuples, of the form (message, category).
        self.message_list = []
        self._pop_up_warnings = True
        self._warnings_are_errors = False
        
         # bar_text is the current contents of the progress bar.  It's
         # initialized to "" instead of None so that its len is always
         # computable.
        self.bar_text = ""
        # thread_bars contains the progress bar text from each thread,
        # keyed by thread number.  It's an ordered dict so that the
        # bars for the oldest threads are displayed first.
        self.thread_bars = utils.OrderedDict()

        self.lock = ooflib.SWIG.common.lock.SLock()    # locks message_list
        self.outlock = ooflib.SWIG.common.lock.SLock() # locks bars and output
예제 #2
0
 def reset(self, time0, continuing):
     # Reset all output schedules, and advance them to the first
     # time after time0 (which is the earliest time in the current
     # evolution).
     self.finished.clear()
     self.nexttimes = utils.OrderedDict()
     self.nexttime = None
     self.nextoutputs.clear()
     self.conditionalOutputs.clear()
     for output in self.outputs:
         if (output.active and output.fullyDefined()):
             output.schedule.reset(continuing)
             output.start(self.meshcontext, time0, continuing)
             if output.schedule.conditional:
                 self.conditionalOutputs.add(output)
             else:
                 try:
                     t = roundOffCheck(output.schedule.next(), time0)
                     if continuing:
                         while t <= time0:
                             t = output.schedule.next()
                     else:
                         while t < time0:
                             t = output.schedule.next()
                 except StopIteration:
                     # The schedule has no times in it later than time0.
                     # Just ignore it.
                     pass
                 else:
                     self.nexttimes[output] = t
                     if self.nexttime is None or t < self.nexttime:
                         self.nexttime = t
     self.nextoutputs = utils.OrderedSet(
         [o for (o,t) in self.nexttimes.items() if t == self.nexttime])
예제 #3
0
 def removeAll(self):
     self.outputs = [] # list, so GUI can present them in creation order
     ## Use OrderedSets and OrderedDicts instead of sets and dicts
     ## so that the order of outputs is repeatable, which makes
     ## testing much easier.
     self.nexttimes = utils.OrderedDict() # next time to perform each output
     self.nextoutputs = utils.OrderedSet() # outputs to perform at next time
     self.conditionalOutputs = utils.OrderedSet()
     self.nexttime = None
     self.finished = set()
예제 #4
0
 def exteriorSegmentsOfFaceSet(self, faces):  # Used in boundarybuilder.py
     # A segment is on the exterior of the face set if only one of
     # the segment's faces is in the set.
     skel = self.getObject()
     segcounts = utils.OrderedDict()
     for face in faces:
         for seg in skel.getFaceSegments(face):
             segcounts[seg] = segcounts.get(seg, 0) + 1
     return utils.OrderedSet(seg for seg, count in segcounts.items()
                             if count == 1)
예제 #5
0
def segments_from_node_aggregate(skelcontext, group):
    nodes = skelcontext.nodes_from_node_aggregate(group)

    seg_counts = utils.OrderedDict()
    node_counts = utils.OrderedDict()
    skel = skelcontext.getObject()

    # Look at all the segments connected to the nodes, and count how
    # many times each segment is found.
    for n in nodes:
        node_counts[n] = 0  # used later when checking for isolated nodes
        for s in skel.getNodeSegments(n):
            try:
                seg_counts[s] += 1
            except KeyError:
                seg_counts[s] = 1

    # Keep the segments that have two nodes in the node set.
    good_segs = [s for (s, count) in seg_counts.items() if count == 2]

    if len(good_segs) == 0:
        return []

    # Double-check that set of good segments includes all the nodes.
    # An isolated node won't be in good_segs, and means that the nodes
    # don't form a connected boundary.
    for s in good_segs:
        for n in s.getNodes():
            node_counts[n] += 1
    for count in node_counts.values():
        if count == 0:
            return []

    # The segments in good_segs may form loops, which is not
    # necessarily an error.  What we really want is the unique path
    # that uses all the nodes, if there is one.
    if config.dimension() == 2:
        return _prune_segments(good_segs)
    else:
        # _really_good_segs is a very robust but combinatorially
        # badly-scaling algorithm, but it works in 3D.
        return _really_good_segs(good_segs)
예제 #6
0
    def __init__(self, ms):
        microstructure.MicrostructurePlugIn.__init__(self, ms)
        self.namedinterfaces = utils.OrderedDict()
        self._materialassignments = {}
        self._selectedInterfaceName = None

        self.sbcallbacks = [
            ##            switchboard.requestCallback("materials changed in microstructure",
            ##                                        self.matChanged),
            ##            switchboard.requestCallback('destroy pixel group',
            ##                                        self.destpixgrp),
            ##            switchboard.requestCallback('changed pixel group', self.changedpixgrp)
            #TODO: Figure this out?
            #switchboard.requestCallback('changed pixel groups', self.chngdgrps)
        ]
예제 #7
0
 def __init__(self, segments=None):
     self.finished = False
     self.loop = False  # Paths can be loops, or not.
     if segments:
         self.seg_list = segments[:]
         self.path = []  # List of segments used so far.
         self.last_node = None  # Trailing node of the path so far.
         self.node_dict = utils.OrderedDict()
         for i in range(len(segments)):
             # Build a node-indexed dictionary of indices into the
             # segments list. node_dict[n] is a list of indices,
             # indicating which segments in the segments list
             # connect to node n.
             seg_nodes = self.seg_list[i].getNodes()
             for n in seg_nodes:
                 self.node_dict.setdefault(n, []).append(i)
예제 #8
0
파일: output.py 프로젝트: song2001/OOF2
    def getSettableParams(self):
        # Get names of the settable parameters from the prototype
        def valueless(p):
            return p.value is None

        pnames = self.getPrototype().listAllParameterNames(valueless)

        # Using the names, make a dict of clones of our *own* parameters
        pdict = utils.OrderedDict()
        for name in pnames:
            param = self.findParam(name)
            try:
                alias = self.getAliasForParam(param)
            except KeyError:
                pdict[name] = param.clone()
            else:
                pdict[alias] = param.clone()
        return pdict
예제 #9
0
    def __init__(self):
        # Set flags.  For each type of message, if the flag is set,
        # then the messages of that type should be displayed to the
        # user.
        self.gui_mode = False
        self.flag_dict = {}
        for f in messageclasses:
            self.flag_dict[f] = True

        # Message list is a list of tuples, of the form (message, category).
        self.message_list = []
        self._pop_up_warnings = True
        self._warnings_are_errors = False

        # bar_text is the current contents of the progress bar.  It's
        # initialized to "" instead of None so that its len is always
        # computable.
        self.bar_text = ""
        self.thread_bars = utils.OrderedDict()
예제 #10
0
from ooflib.engine.IO import meshinfo
from ooflib.engine.IO.GUI import meshdataGUI
from ooflib.engine.IO.GUI import genericinfoGUI

import gtk

## TODO: Add SegmentMode (and FaceMode, in 3D) to display interface
## materials.

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

# _modes stores the MeshInfoMode subclasses for each info mode.  The
# keys are the mode names: "Element", "Node", etc.  It's an OrderedDict
# to ensure that the initially selected mode is always the same.

_modes = utils.OrderedDict()


class MeshInfoModeMetaClass(type):
    def __init__(cls, name, bases, dct):
        super(MeshInfoModeMetaClass, cls).__init__(name, bases, dct)
        try:
            targetName = dct['targetName']
        except KeyError:
            pass
        else:
            _modes[targetName] = cls


#=--=##=--=##=--=##=--=##=--=##=--=##=--=##=--=##=--=##=--=##=--=##=--=#
예제 #11
0
    def __init__(self, name, classname, skel, parent):
        # All of the args have to be given, although not all are used.
        # This is because the constructor is called by WhoClass.add,
        # which assumes that the arguments are the same as those of
        # Who.__init__.  Probably a better solution using
        # RegisteredClasses could be found.

        # Keep track of node/segment/element index data (in that
        # order), so selectables can be uniquely identified within
        # this context, independently of which skeleton they're in.
        # This used to be done in the individual selectable classes,
        # but for repeatability reasons, it's desirable to restart the
        # indices in each context, ensuring that skeleton copies
        # really are absolutely identical in every respect.
        self.next_indices = (0, 0, 0)

        self.edgeboundaries = utils.OrderedDict()
        self.pointboundaries = utils.OrderedDict()
        self.selectedBdyName = None
        # There are two boundary timestamps, one for keeping track of
        # changes in the currently selected boundary, and another for
        # keeping track of changes to the configuration of boundaries
        # in any of these skeletons.  They are queried by their
        # respective displays in skeletonbdydisplay.py.
        self.bdyselected = timestamp.TimeStamp()
        self.bdytimestamp = timestamp.TimeStamp()

        # Various selection objects live here.  Instance the
        # selections from their constructors.  To get the current
        # selection, do "context.elementselection.retrieve()".
        self.nodeselection = skeletonselectable.NodeSelection(self)
        self.segmentselection = skeletonselectable.SegmentSelection(self)
        self.elementselection = skeletonselectable.ElementSelection(self)
        self.pinnednodes = skeletonnode.PinnedNodeSelection(self)

        # These attribute names (nodegroups, segmentgroups,
        # elementgroups) are used in the generic menu callback in
        # IO/skeletongroupmenu.py.  Also in skeletonselectionmod.py.
        # Change them in all places (or none, of course.)
        self.nodegroups = skeletongroups.NodeGroupSet(self)
        self.segmentgroups = skeletongroups.SegmentGroupSet(self)
        self.elementgroups = skeletongroups.ElementGroupSet(self)

        # WhoDoUndo.__init__ calls pushModification, so timing is
        # important.  pushModification calls implied_select for all
        # the selections, so the selection objects have to exist at
        # this point.
        whoville.WhoDoUndo.__init__(self, name, 'Skeleton', skel, parent)

        # Overwrite function, gets called when an item in the stack is
        # about to be overwritten.  This assignment replaces  the default
        # overwrite function set by the parent class initializer.
        self.undobuffer.overwrite = self.skeletonDestroy

        # Ensure that the passed-in obj really does start a new "family."
        skel.disconnect()

        # Ask the initial skel about any pre-existing boundaries.
        for (name, bdy) in skel.edgeboundaries.items():
            self.edgeboundaries[name] = \
              bdy.makeContextBoundary(self, name, skel)

        for (name, bdy) in skel.pointboundaries.items():
            self.pointboundaries[name] = \
              bdy.makeContextBoundary(self, name, skel)

        self.requestCallback("destroy pixel group", self.ms_grp_changed)
        self.requestCallback("changed pixel group", self.ms_grp_changed)
        self.requestCallback("changed pixel groups", self.ms_grps_changed)
        self.requestCallback('materials changed in microstructure',
                             self.materialsChanged)
예제 #12
0
    def __repr__(self):
        return self.__class__.__name__ + "('" + self.findName() + "')"


class UserDefinedView:
    deletable = True

    def __init__(self, view):
        self.view = view

    def resolve(self, gfxwindow):
        return self.view


namedViews = utils.OrderedDict()


def storeView(name, view):
    if name in namedViews and not namedViews[name].deletable:
        raise ooferror.ErrUserError("Attempt to overwrite a predefined View.")
    namedViews[name] = view


def retrieveView(name, gfxwindow):
    view = namedViews[name]
    # For UserDefinedViews, resolve() just returns the View.  For
    # PredefinedViews, resolve() makes sure that the whole
    # Microstructure is visible.
    return view.resolve(gfxwindow)
예제 #13
0
 def __init__(self, interfaces):
     self.interfaces = interfaces
     self.namedinterfaces = utils.OrderedDict()
예제 #14
0
    def __init__(self, name, classname, skel, parent):
        # All of the args have to be given, although not all are used.
        # This is because the constructor is called by WhoClass.add,
        # which assumes that the arguments are the same as those of
        # Who.__init__.  Probably a better solution using
        # RegisteredClasses could be found.

        if config.dimension() == 3:
            self.faceboundaries = utils.OrderedDict()
        self.edgeboundaries = utils.OrderedDict()
        self.pointboundaries = utils.OrderedDict()
        self.selectedBdyName = None
        # There are two boundary timestamps, one for keeping track of
        # changes in the currently selected boundary, and another for
        # keeping track of changes to the configuration of boundaries
        # in any of these skeletons.  They are queried by their
        # respective displays in skeletonbdydisplay.py.
        ## TODO 3.1: The second of these timestamps (bdytimestamp) is
        ## obsolete and has been removed.  Is the first also obsolete?
        self.bdyselected = timestamp.TimeStamp()

        # Various selection objects live here.  Instance the
        # selections from their constructors.  To get the current
        # selection, do "context.elementselection.retrieve()".
        self.nodeselection = skeletonselectable.NodeSelection(self)
        self.segmentselection = skeletonselectable.SegmentSelection(self)
        if config.dimension() == 3:
            self.faceselection = skeletonselectable.FaceSelection(self)
        self.elementselection = skeletonselectable.ElementSelection(self)
        self.pinnednodes = skeletonselectable.PinnedNodeSelection(self)

        # These attribute names (nodegroups, segmentgroups,
        # elementgroups) are used in the generic menu callback in
        # IO/skeletongroupmenu.py.  Also in skeletonselectionmod.py.
        # Change them in all places (or none, of course.)
        self.nodegroups = skeletongroups.NodeGroupSet(self)
        self.segmentgroups = skeletongroups.SegmentGroupSet(self)
        self.facegroups = skeletongroups.FaceGroupSet(self)
        self.elementgroups = skeletongroups.ElementGroupSet(self)

        # WhoDoUndo.__init__ calls pushModification, so timing is
        # important.  pushModification calls implied_select for all
        # the selections, so the selection objects have to exist at
        # this point.
        whoville.WhoDoUndo.__init__(self,
                                    name,
                                    'Skeleton',
                                    skel,
                                    parent,
                                    overwritefn=self.skeletonStackOverwrite)

        # When a skeleton with deputies is overwritten, a reference to
        # it must be kept as long any deputies exist.
        self.zombieSheriff = None

        # Ensure that the passed-in obj really does start a new "family."
        ## TODO OPT: Restore this, or delete this block if it's
        ## unnecessary.  In 2D, skel.disconnect() calls
        ## SkeletonSelectable.disconnect() for all selectables, which
        ## severs their parent/child relationships.  This is probably
        ## only necessary when copying a SkeletonContext.
        #skel.disconnect()

        # Ask the initial skel about any pre-existing boundaries.
        fbs = skel.getFaceBoundaries()
        for (name, bdy) in fbs.items():
            self.faceboundaries[name] = \
                bdy.makeContextBoundary(self, name, skel)

        ebs = skel.getEdgeBoundaries()
        for (name, bdy) in ebs.items():
            self.edgeboundaries[name] = \
                bdy.makeContextBoundary(self, name, skel)

        pbs = skel.getPointBoundaries()
        for name in pbs:
            self.pointboundaries[name] = \
              pbs[name].makeContextBoundary(self, name, skel)

        self.requestCallback("destroy pixel group", self.ms_grp_changed)
        self.requestCallback("changed pixel group", self.ms_grp_changed)
        self.requestCallback("changed pixel groups", self.ms_grps_changed)
        self.requestCallback('materials changed in microstructure',
                             self.materialsChanged)
예제 #15
0

def cleanUp():
    global shuttingdown
    shuttingdown = True


switchboard.requestCallbackMain("shutdown", cleanUp)

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

# BaseOutputStream does the work for OutputStream, which writes Output
# data to a file.  More than one OutputStream can write to the same
# file, which they do by sharing a single BaseOutputStream.

_allStreams = utils.OrderedDict()  # All BaseOutputStreams, keyed by filename
_streamsLock = lock.SLock()  # Controls access to _allStreams


class BaseOutputStream(object):
    def __init__(self, filename, mode, openfile):
        self.filename = filename
        self.file = None
        self.openfile = openfile  # fn that actually opens the file
        # _streamsLock has always been aquired before __init__ is called.
        _allStreams[filename] = self
        self.referents = []  # all OutputStreams using this BaseOutputStream
        # lastOutput and lastargs are used to decide whether or not to
        # write the header info in the data file.  It's not written if
        # the output and its args are the same as they were for the
        # previous write.
예제 #16
0
# versions of this software, you first contact the authors at
# [email protected].

## Store and retrieve named sets of analysis parameters

from ooflib.SWIG.common import lock
from ooflib.common import debug
from ooflib.common import registeredclass
from ooflib.common import utils
from ooflib.common.IO import parameter
from ooflib.common.IO import xmlmenudump
from ooflib.engine.IO import analyze
from ooflib.engine.IO import scheduledoutput
from ooflib.engine.IO import outputdestination

_namedAnalyses = utils.OrderedDict()
namelock = lock.SLock()


class _nameResolver(object):
    # Callable object for creating a unique name for a bulk or
    # boundary analysis.
    def __init__(self, defaultname):
        self.defaultname = defaultname

    def __call__(self, param, name):
        if param.automatic():
            basename = self.defaultname
        else:
            basename = name
        return utils.uniqueName(basename, _namedAnalyses.keys())
예제 #17
0
파일: output.py 프로젝트: song2001/OOF2
    def __init__(self,
                 name,
                 otype,
                 callback,
                 inputs=[],
                 params=[],
                 tip=parameter.emptyTipString,
                 discussion=parameter.emptyTipString,
                 srepr=None,
                 instancefn=None,
                 column_names=None,
                 parent=None):
        # otype is the type of the output.

        # inputs is a list of Parameters specifying the names and
        # types of the inputs to this Output.

        # params is a list of Parameters governing the behavior of
        # this Output.

        # callback is a function or other callable object (see
        # engine/IO/outputClones.py).  The arguments to the callback
        # are (mesh, elements, coords) plus anything specified by the
        # Output constructor's inputs and params arguments.  Those
        # extra arguments are passed as keyword arguments, with the
        # keyword determined by the input or param's 'name'.

        # The 'elements' argument is a list of the Elements that the
        # Output is being evaluated in.  The 'coords' argument is a
        # list of lists of Coords.  coords[i] is a list of
        # MasterCoords within the Element elements[i].  The Output
        # must be evaluated at these positions.

        # callback arguments corresponding to items in the 'params'
        # list are simple values, whose type is determined by the
        # param's Parameter type.

        # callback arguments corresponding to items in the 'inputs'
        # list are lists of values, whose type is determined by the
        # input's Parameter type.  There's one entry in the list for
        # each coord in the 'coords' list.  The input list is a flat
        # list, for now.  This may change.

        # srepr is a function to be used as the shortrepr for the
        # Output.  srepr takes a single argument, self, and returns a
        # string.  It should use findParam, resolveAlias, and
        # findInput as necessary and evaluate their shortreprs.

        # column_names is a function that returns a list of the names
        # of the output columns.  If it's None, the parent's column
        # names function will be used.

        self.name = name
        self.callback = callback
        self.tip = tip
        self.discussion = discussion
        self.parent = parent
        self.prototype = (parent is None)

        if srepr is not None:
            self.srepr = srepr  # short repr

        # 'instancefn' is a function that returns an instance of the
        # OutputVal subclass that this Output will produce.  If it's
        # None, then self.instancefn won't be defined, and the
        # Output's parent's 'instancefn' method will be used.
        if instancefn is not None:
            self.instancefn = instancefn
        # Same for column_names, which returns a list of names of the
        # columns in the output.
        if column_names is not None:
            self.column_names = column_names

        # Check that all names in iparms and params are unique.
        names = set()
        for p in params:
            if p.name in names:
                raise KeyError("Parameter name '%s' is not unique" % p.name)
            names.add(p.name)
        for p in inputs:
            if p.name in names:
                raise KeyError("Input name '%s' is not unique" % p.name)
            names.add(p.name)
        del names

        # self.params and self.iparms are OrderedDicts so that the
        # parameters will appear in the UI in the same order in which
        # they were specified in the params list.  Both are
        # dictionaries of Parameters keyed by name.
        self.params = utils.OrderedDict()
        for p in params:
            self.params[p.name] = p
        self.iparms = utils.OrderedDict()
        for i in inputs:
            self.iparms[i.name] = i

        # TODO: This is a hack that will have to be cleaned up.  Most
        # Outputs have an otype that is a single class (most commonly
        # OutputValPtr).  Some are PosOutputs and have an otype that's
        # a tuple, (Point, Coord).  When Outputs are connected to one
        # another, the parameter.TypeChecker mechanism is used.  When
        # Outputs are used in analyze.py, it only checks the
        # class. For now, TypeChecker has been changed so that it
        # works correctly on a single class.  The correct solution is
        # for Outputs not to use TypeChecker at all, maybe.
        self.otype = otype
        if isinstance(otype, parameter.TypeChecker):
            self.otype = otype
        elif type(otype) in (types.ListType, types.TupleType):
            self.otype = parameter.TypeChecker(*otype)
        else:
            self.otype = otype

        # Dictionary of other Outputs that are connected to us
        self.inputs = utils.OrderedDict()  # keyed by name

        # Dictionaries of aliases for parameters
        self.aliases = {}  # key = param, value = alias
        self.sesaila = {}  # key = alias, value = param
예제 #18
0
from UTILS import file_utils
fp_file_compare = file_utils.fp_file_compare
reference_file = file_utils.reference_file
# Flag that says whether to generate missing reference data files.
# Should be false unless you really know what you're doing.
file_utils.generate = False

# These tests should be run *before* solver_test so that outputs can
# be used to verify solutions.  That means that these tests should use
# meshes with artificial data.

## TODO 3.1: Add tests for managing linear and planar cross sections.

from ooflib.common import utils
meshTestDict = utils.OrderedDict() # OutputTests keyed by Mesh path
outputTestDict = utils.OrderedDict() # OutputTests keyed by Output path

class OutputTest(object):
    def __init__(self, mesh, operation, output, oparams, domain, sampling,
                 referencefile, time=0.0, tolerance=1.e-8, skip=False,
                 commands=[]):
        self.mesh = mesh        # just the Mesh part of the path
        self.operation = operation
        self.output = output    # path
        self.oparams = oparams  # dict
        self.domain = domain
        self.sampling = sampling
        self.referencefile = referencefile
        self.tolerance = tolerance
        self.time = time