Example #1
0
    def __init__(self, vtkactor_type=None, vtkmapper_type=None, **kwargs):
        super(ChiggerSourceBase, self).__init__(**kwargs)

        self._vtkactor = vtkactor_type()
        if not isinstance(self._vtkactor, self.VTKACTOR_TYPE):
            n = type(self._vtkactor).__name__
            t = self.VTKACTOR_TYPE.__name__
            raise mooseutils.MooseException(
                'The supplied actor is a {} but must be a {} '
                'type.'.format(n, t))

        if vtkmapper_type:
            self._vtkmapper = vtkmapper_type()
            if not isinstance(self._vtkmapper, self.VTKMAPPER_TYPE):
                n = type(self._vtkmapper).__name__
                t = self.VTKMAPPER_TYPE.__name__
                raise mooseutils.MooseException(
                    'The supplied mapper is a {} but must be a {} '
                    'type.'.format(n, t))
        else:
            self._vtkmapper = None

        if self._vtkmapper:
            self._vtkactor.SetMapper(self._vtkmapper)

        self._vtkrenderer = None  # This is set automatically by ChiggerResult object.
        self._parent = None  # Set by ChiggerResult
Example #2
0
    def update(self, **kwargs):
        """
        Computes the contour levels for the vtkContourFilter.
        """
        super(ContourFilter, self).update(**kwargs)

        varinfo = self._source.getCurrentVariableInformation()
        if varinfo.object_type != chigger.exodus.ExodusReader.NODAL:
            raise mooseutils.MooseException(
                'ContourFilter currently only works with nodal '
                'variables.')

        self._vtkfilter.SetInputArrayToProcess(
            0, 0, 0, vtk.vtkDataObject.FIELD_ASSOCIATION_POINTS, varinfo.name)

        if self.isOptionValid('levels'):
            levels = self.getOption('levels')
            n = len(levels)
            self._vtkfilter.SetNumberOfContours(n)
            for i in range(n):
                self._vtkfilter.SetValue(i, levels[i])
        elif self.isOptionValid('count'):
            rng = self._source.getVTKMapper().GetScalarRange()
            self._vtkfilter.GenerateValues(self.getOption('count'), rng)
        else:
            mooseutils.MooseException(
                'Either the "levels" or the "count" options must be used.')
Example #3
0
    def __init__(self, plugins=[], plugin_base=Plugin):
        super(PluginManager, self).__init__()

        # Check that self is a QWidget
        if not isinstance(self, QtWidgets.QWidget):
            mooseutils.MooseException(
                "{} objects must also be a QWidget.".format(
                    self.__class__.__name__))

        # A list of plugin classes (see setup()), this is private because child classes
        # shouldn't be messing with the classes.
        self._plugin_classes = plugins

        # The base class that this manager is allowed to manage
        self._plugin_base = plugin_base

        # An OrderedDict (to maintain the order plugins are added) for storing plugin objects
        self._plugins = collections.OrderedDict()

        # The tab index for this plugin
        self._index = None

        # List of all plugins for connecting signal
        self._all_plugins = []
        self._pref_widget = None
Example #4
0
    def start(self, timer=None):
        """
        Begin the interactive VTK session.
        """
        mooseutils.mooseDebug("{}.start()".format(self.__class__.__name__),
                              color='MAGENTA')

        if self.needsUpdate():
            self.update()

        if self.__vtkinteractor:
            self.__vtkinteractor.Initialize()

            if timer:
                if not isinstance(timer, base.ChiggerTimer):
                    n = type(timer).__name__
                    msg = "The supplied timer of type {} must be a ChiggerTimer object.".format(
                        n)
                    raise mooseutils.MooseException(msg)
                self.__vtkinteractor.AddObserver('TimerEvent', timer.callback)
                self.__vtkinteractor.CreateRepeatingTimer(timer.duration())

            self.__vtkinteractor.Start()

        if self.getOption('style') == 'test':
            self.__vtkwindow.Finalize()
Example #5
0
 def requireExtension(self, required):
     """
     Raise an exception of the supplied extension type is not registered.
     """
     if not self.getExtension(required):
         raise mooseutils.MooseException("The {} extension is required." \
                                         .format(required.__name__))
Example #6
0
    def __call__(self):
        """
        Operator() returns the vtkLookupTable for use as a colormap.
        """
        # Use peacock style
        name = self.getOption('cmap')
        if name == 'default':
            vtktable = self.__default()

        # Matplotlib
        elif USE_MATPLOTLIB and (name in dir(cm)):
            vtktable = self.__matplotlib()

        # Read from Paraview XML files
        elif name in self._data:
            vtktable = self.__xml()

        else:
            raise mooseutils.MooseException("Unknown colormap:", name)

        if self.isOptionValid('cmap_range'):
            vtktable.SetRange(*self.getOption('cmap_range'))

        if self.isOptionValid('cmap_nan'):
            vtktable.SetNanColor(*self.getOption('cmap_nan'))
        vtktable.Build()
        return vtktable
Example #7
0
def check(config_file=None, locations=None, generate=None):
    """
    Performs checks and optionally generates stub pages for missing documentation.
    """
    # Read the configuration
    app_ext = 'MooseDocs.extensions.app_syntax'
    config = MooseDocs.load_config(config_file)
    if app_ext not in config:
        mooseutils.MooseException("The 'check' utility requires the 'app_syntax' extension.")
    ext_config = config[app_ext]

    # Run the executable
    exe = MooseDocs.abspath(ext_config['executable'])
    if not os.path.exists(exe):
        raise IOError('The executable does not exist: {}'.format(exe))
    else:
        LOG.debug("Executing %s to extract syntax.", exe)
        raw = mooseutils.runExe(exe, '--yaml')
        yaml = mooseutils.MooseYaml(raw)

    # Populate the syntax
    for loc in ext_config['locations']:
        for key, value in loc.iteritems():
            if (locations is None) or (key in locations):
                value['group'] = key
                syntax = common.MooseApplicationSyntax(yaml, generate=generate,
                                                       install=ext_config['install'], **value)
                LOG.info("Checking documentation for '%s'.", key)
                syntax.check()

    return None
Example #8
0
    def getGlobalData(self, variable):
        """
        Access the global (i.e., Postprocessor) data contained in the Exodus file. (public)

        Inputs: variable[str]: An available and active (in 'variables' setting) GLOBAL variable
        name.

        Returns: float: The global data (Postprocessor value) for the current timestep and defined
        variable.

        Note: This function can also return the "Info_Records", which in MOOSE contains input file
        and other information from MOOSE, in this case a list of strings is returned.
        reader.GetFieldData('Info_Records') """
        self.checkUpdateState()

        field_data = self.__vtkreader.GetOutput().GetBlock(0).GetBlock(
            0).GetFieldData()
        varinfo = self.__variableinfo[variable]

        if varinfo.object_type != self.GLOBAL:
            msg = 'The variable "{}" must be a global variable.'.format(
                variable)
            raise mooseutils.MooseException(msg)

        vtk_array = field_data.GetAbstractArray(variable)
        return vtk_array.GetComponent(self.__current.index, 0)
    def add(self, key, obj, location='_end'):
        """
        Adds the 'obj' class with the given name to the storage container.

        Args:
          key[str]: The name of the object being added
          obj[Element]: The class (not isinstance) of the Element object to store
          location[str]: The name of the key where this should be inserted, it is possible to pass
                  special locations:
                    '_end': Insert the key being added to the end of the container
                    '_begin': Insert the key being added to the beginning of the container
                    '<key': Insert the new key before the key given with the '<' prefix
                    '>key': Insert the new key after the key given with the '<' prefix
                    'key': Insert the new key after the key (same as '<' prefix)
        """

        if not isinstance(obj, self._type):
            msg = 'Incorrect object provide, expected %s but received %s'
            raise mooseutils.MooseException(msg, self._type, obj)

        index = None
        if location == '_end':
            index = len(self._keys)
        elif location == '_begin':
            index = 0
        elif location.startswith('<'):
            index = self._keys.index(location[1:])
        elif location.startswith('>'):
            index = self._keys.index(location[1:]) + 1
        else:
            index = self._keys.index(location)

        self._keys.insert(index, key)
        self._objects.insert(index, obj)
Example #10
0
    def build(self, num_threads=multiprocessing.cpu_count()):
        """
        Build all the pages in parallel.
        """
        if self._root is None:
            raise mooseutils.MooseException(
                "The 'init' method must be called prior to build.")

        # Build the complete markdown file tree from the configuration supplied at construction
        if not isinstance(self._root, anytree.NodeMixin):
            raise TypeError(
                "The 'buildNodes' method must return a anytree.NodeMixin object."
            )

        # Build the pages
        pages = list(self)
        jobs = []
        for chunk in mooseutils.make_chunks(pages, num_threads):
            p = multiprocessing.Process(target=self.buildPages, args=(chunk, ))
            p.start()
            jobs.append(p)

        for job in jobs:
            job.join()

        self.copyFiles()
Example #11
0
    def __init__(self, command=None, **kwargs):
        super(Command, self).__init__(**kwargs)

        self._command = command
        if self._command is None:
            raise mooseutils.MooseException("The 'command' argument variable must be set.")

        self._data['data-latex-begin'] = '\\{}'.format(self._command)
Example #12
0
    def __init__(self, *results, **kwargs):
        super(ExodusColorBar, self).__init__(**kwargs)

        self._results = results
        if len(results) not in [1, 2]:
            raise mooseutils.MooseException(
                'One or two ExodusResult objects must be supplied to '
                'the ExodusColorBar')
Example #13
0
 def getResult(self, index=0):
     """
     Return the associated ExodusResult object. The index must be 0 or 1.
     """
     if index not in [0, 1]:
         raise mooseutils.MooseException(
             "The supplied index must be 0 or 1.")
     return self._results[index]
    def __init__(self, exodus_source, **kwargs):
        super(LabelExodusSource, self).__init__(vtkmapper_type=vtk.vtkLabeledDataMapper, **kwargs)

        if not isinstance(exodus_source, ExodusSource):
            msg = 'The supplied object of type {} must be a ExodusSource object.'
            raise mooseutils.MooseException(msg.format(exodus_source.__class__.__name__))

        self._exodus_source = exodus_source
Example #15
0
    def __init__(self, vtkfilter_type=None, **kwargs):
        super(ChiggerFilterBase, self).__init__(**kwargs)

        self._source = None  # see initializeFilter
        self._vtkfilter = vtkfilter_type()
        if not isinstance(self._vtkfilter, self.VTKFILTER_TYPE):
            msg = 'The supplied filter is a {} but must be a {} type.'
            raise mooseutils.MooseException(
                msg.format(vtkfilter_type.__name__,
                           self.VTKFILTER_TYPE.__name__))
        def __init__(self, vtkgeometric_type=None, **kwargs):
            super(GeometricSource, self).__init__(**kwargs)

            if not vtkgeometric_type:
                raise mooseutils.MooseException(
                    'The vtk source object type must be supplied.')

            self._vtksource = vtkgeometric_type()

            self._colormap = base.ColorMap()
Example #17
0
    def __iter__(self):
        """
        Allow direct iteration over pages (MarkdownFileNodeBase nodes) contained in this object.
        """
        if self._root is None:
            raise mooseutils.MooseException("The 'init' method must be called prior to iterating "
                                            "over the 'nodes' objects")

        filter_ = lambda n: isinstance(n, nodes.MarkdownFileNodeBase)
        for node in anytree.iterators.PreOrderIter(self._root, filter_=filter_):
            yield node
Example #18
0
 def getVTKSource(self):
     """
     Return the "source" vtk object. (abstract)
     classes must override this method. The VTK object returned from this function will
     be connected to the first filter, if then exist, or the vtkAbstractMapper object. See the
     'update' method for this class for how the connections are made.
     """
     raise mooseutils.MooseException(
         'The {}."getSource()" method must be overridden by your '
         'mapper object and return the source vtk object to connect '
         'to the filers and mapper.'.format(self.__class__.__name__))
Example #19
0
 def count(self):
     """
     Return the number of pages.
     """
     if self._root is None:
         raise mooseutils.MooseException("The 'init' method must be called prior to count.")
     count = 0
     for node in self._root.descendants:
         if isinstance(node, nodes.CopyFileNode) and (node.name.endswith('.moose.svg')):
             continue
         count += 1
     return count
    def __init__(self, exodus_source, **kwargs):
        super(ExodusSourceLineSampler, self).__init__(**kwargs)

        if not isinstance(exodus_source, ExodusSource):
            msg = 'The supplied object of type {} must be a ExodusSource object.'
            raise mooseutils.MooseException(
                msg.format(exodus_source.__class__.__name__))

        self._distance = []
        self._exodus_source = exodus_source

        self._probe = vtk.vtkCompositeDataProbeFilter()
Example #21
0
 def initialize(self):
     """
     Initialize by adding actors to renderer.
     """
     super(ChiggerResult, self).initialize()
     for src in self._sources:
         if not isinstance(src, self.SOURCE_TYPE):
             n = src.__class__.__name__
             t = self.SOURCE_TYPE.__name__
             msg = 'The supplied source type of {} must be of type {}.'.format(n, t)
             raise mooseutils.MooseException(msg)
         src.setVTKRenderer(self._vtkrenderer)
         self._vtkrenderer.AddViewProp(src.getVTKActor())
Example #22
0
    def __init__(self,
                 name=None,
                 site_dir=os.path.relpath(os.getcwd()),
                 parent=None):

        if (name is None) or (not isinstance(name, str)):
            raise mooseutils.MooseException('The "name" string must be supplied to the ' \
                                            'MooseDocsNode object.')

        if (site_dir is None) or (not isinstance(
                site_dir, str)) or not os.path.isdir(site_dir):
            raise mooseutils.MooseException('The "site_dir" must be a string and a valid ' \
                                            'directory.')

        self.__name = name
        self.__site_dir = site_dir
        self.__parent = parent
        self.__children = []

        # Automatically add the child to parent
        if self.__parent:
            self.__parent.append(self)
Example #23
0
    def setup(self):
        """
        Call widget setup methods and connect signals and slots from plugins.
        """
        super(PluginManager, self).setup()

        # Create the plugins
        for plugin_class in self._plugin_classes:

            # Create the widget instance
            widget = plugin_class()

            # Check the type
            if not isinstance(widget, self._plugin_base):
                mooseutils.MooseException(
                    "The supplied widget is of type '{}' but must be a direct child of a '{}'"
                    .format(widget.__class__.__name__,
                            self._plugin_base.__name__))

            # Define the widget name
            name = widget.__class__.__name__

            # Store widget in a list if more than one exist
            if name in self._plugins:
                if not isinstance(self._plugins[name], list):
                    self._plugins[name] = [self._plugins[name]]
                self._plugins[name].append(widget)

            # Store widget directly if only one
            else:
                self._plugins[name] = widget

            # Set the parent
            widget.setParent(self)

            # Add the widget
            self.addObject(widget)

            # Set the class attribute base on plugin name
            setattr(self, name, self._plugins[name])
            mooseutils.mooseDebug('Adding plugin as member: {}'.format(name))

            # Store in the temporary flat list
            self._all_plugins.append(widget)

        # Connect signal/slots of plugins
        for plugin0 in self._all_plugins:
            plugin0._plugin_manager = self
            for plugin1 in self._all_plugins:
                plugin0.connect(plugin1)
Example #24
0
    def __setOptionsHelper(self, chigger_object, options):
        """
        Private helper for setting chigger options.

        Inputs:
            chigger_object[ChiggerObject]: An object supporting setOptions calls.
            options[dict | chigger.utils.Options]: The options to set.
        """
        if chigger_object:
            if isinstance(options, dict):
                chigger_object.setOptions(**options)
            elif isinstance(options, chigger.utils.Options):
                chigger_object.setOptions(options)
            else:
                raise mooseutils.MooseException('Options supplied must be a dict or utils.Options class.')
Example #25
0
    def __init__(self, markdown=None, parser=None, **kwargs):
        super(MarkdownNode, self).__init__(**kwargs)

        if markdown is None:
            raise mooseutils.MooseException(
                'A markdown file or content must be supplied.')

        self.__parser = parser
        self.__content = None
        self.__md_file = None

        if os.path.isfile(markdown):
            self.__md_file = markdown
        else:
            self.__content = markdown
Example #26
0
    def __init__(self, name=None, attrs=None, strip=False, **kwargs):

        if name is None:
            raise mooseutils.MooseException("The 'name' argument variable must be set.")

        self._name = name
        self._attrs = attrs if attrs is not None else dict()
        self._strip = strip

        self._data = dict()
        keys = ['begin', 'begin_prefix', 'begin_suffix', 'end', 'end_prefix', 'end_suffix', 'open',
                'close', 'content', 'escape']
        for k in keys:
            self._data.setdefault('data-latex-{}'.format(k.replace('_', '-')), kwargs.get(k, None))
        self.__soup = None
Example #27
0
    def __init__(self, markdown_instance, **config):
        super(TemplatePostprocessorBase, self).__init__(markdown_instance)
        self._template = config.pop('template')
        self._template_args = config.pop('template_args', dict())
        self._environment_args = config.pop('environment_args', dict())

        # Storage for node property.
        self._node = None

        # The 'markdown.extensions.meta' extension is required, but the 'meta' extension doesn't get
        # registered so the list of preprocessors is checked.
        try:
            self.markdown.preprocessors.index('meta')
        except ValueError:
            raise mooseutils.MooseException("The 'meta' extension is required.")
Example #28
0
 def append(self, *args):
     """
     Append result object(s) to the window.
     """
     self.setNeedsUpdate(True)
     for result in args:
         mooseutils.mooseDebug('RenderWindow.append {}'.format(type(result).__name__))
         if isinstance(result, base.ResultGroup):
             self.append(*result.getResults())
         elif not isinstance(result, self.RESULT_TYPE):
             n = result.__class__.__name__
             t = self.RESULT_TYPE.__name__
             msg = 'The supplied result type of {} must be of type {}.'.format(n, t)
             raise mooseutils.MooseException(msg)
         self._results.append(result)
    def __init__(self, reader, **kwargs):

        # Build the ExodusSource objects
        if isinstance(reader, ExodusReader):
            sources = [ExodusSource(reader)]
        elif isinstance(reader, MultiAppExodusReader):
            sources = [ExodusSource(r) for r in reader]
        else:
            raise mooseutils.MooseException(
                'The supplied object of type {} is not supported, '
                'only ExodusReader and MultiAppExodusReader objects '
                'may be utilized.'.format(reader.__class__.__name__))

        # Supply the sources to the base class
        super(ExodusResult, self).__init__(*sources, **kwargs)
Example #30
0
    def update(self, **kwargs):
        """
        Updates the image reader. (override)
        """
        super(ImageAnnotationSource, self).update(**kwargs)

        if self.isOptionValid('filename'):
            filename = self.getOption('filename')
            if not os.path.exists(filename):
                filename = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'logos',
                                                        os.path.basename(filename)))
            if not os.path.exists(filename):
                raise mooseutils.MooseException('Unable to locate image file: {}'.format(filename))
            self.__reader.SetFileName(filename)
            self.__reader.Update()