Exemplo n.º 1
0
    def runClicked(self):
        """
        Run button clicked.
        """
        input_file = self._tempInputFile()
        self.cleanup()
        self.needInputFile.emit(input_file)
        if not os.path.exists(input_file):
            mooseutils.mooseError("Input file didn't get written", dialog=True)
            return
        self.needCommand.emit()
        if self.runner.isRunning():
            self.runner.kill()
        self.kill_button.setDisabled(False)
        self._showProgressBar(True)
        self.progress_bar.setMaximum(11)
        self.progress_bar.setValue(0)

        if self._preferences.value("execute/clearLog"):
            self.clearLog.emit()

        start_time = math.floor(
            time.time()) if sys.platform == 'darwin' else time.time()
        self.startJob.emit(self.has_csv, input_file, start_time)
        self.runner.run(self.exe_path, self.exe_args +
                        ["-i", os.path.relpath(input_file)])
    def _callbackDiffToggle(self, value):
        """
        Callback for DiffToggle widget.

        Args:
            value[bool]: True/False indicating the toggle state of the widget.
        """
        self.store(self._filename, 'Filename')

        if value:
            goldname = mooseutils.gold(self._filename)
            diffname = 'peacock_tmp_diff.exo'

            if not os.path.exists(goldname):
                mooseutils.mooseError('The gold file was not located: {}'.format(goldname))

            cmd = [self._exodiff, '-map', '-F', '1e-10', '-t', '5.5e-06', os.path.abspath(self._filename), os.path.abspath(goldname), os.path.abspath(diffname)]
            subprocess.call(cmd)

            if os.path.exists(diffname):
                self.DiffVTKWindow.blockSignals(True)
                self.DiffVTKWindow.setVisible(True)
                self.DiffVTKWindow.onFileChanged(diffname)
                self.DiffVTKWindow.onCameraChanged(self._result.getVTKRenderer().GetActiveCamera())
                self.DiffVTKWindow.blockSignals(False)
                self.onWindowUpdated()
            else:
                mooseutils.mooseError('Failed to generate Exodiff file with command:\n{}'.format(' '.join(cmd)))

        else:
            self.DiffVTKWindow.setVisible(False)
Exemplo n.º 3
0
    def _callbackDiffToggle(self, value):
        """
        Callback for DiffToggle widget.

        Args:
            value[bool]: True/False indicating the toggle state of the widget.
        """
        self.store(self._filename, 'Filename')

        if value:
            goldname = mooseutils.gold(self._filename)
            diffname = 'peacock_tmp_diff.exo'

            if not os.path.exists(goldname):
                mooseutils.mooseError('The gold file was not located: {}'.format(goldname))

            cmd = [self._exodiff, '-map', '-F', '1e-10', '-t', '5.5e-06', os.path.abspath(self._filename), os.path.abspath(goldname), os.path.abspath(diffname)]
            subprocess.call(cmd)

            if os.path.exists(diffname):
                self.DiffVTKWindow.blockSignals(True)
                self.DiffVTKWindow.setVisible(True)
                self.DiffVTKWindow.onFileChanged(diffname)
                self.DiffVTKWindow.onCameraChanged(self._result.getVTKRenderer().GetActiveCamera())
                self.DiffVTKWindow.blockSignals(False)
                self.onWindowUpdated()
            else:
                mooseutils.mooseError('Failed to generate Exodiff file with command:\n{}'.format(' '.join(cmd)))

        else:
            self.DiffVTKWindow.setVisible(False)
Exemplo n.º 4
0
    def update(self, *args, **kwargs):
        """
        Update method for the graph axes.
        """
        super(Graph, self).update(*args, **kwargs)

        # Update Axis options
        self._setAxisOptions(self._vtkchart.GetAxis(vtk.vtkAxis.BOTTOM), self.getOption('xaxis'))
        self._setAxisOptions(self._vtkchart.GetAxis(vtk.vtkAxis.LEFT), self.getOption('yaxis'))
        self._setAxisOptions(self._vtkchart.GetAxis(vtk.vtkAxis.TOP), self.getOption('x2axis'))
        self._setAxisOptions(self._vtkchart.GetAxis(vtk.vtkAxis.RIGHT), self.getOption('y2axis'))

        # Legend
        utils.LegendOptions.set_options(self._vtkchart, self._vtkrenderer, self.getOption('legend'))

        # Line objects
        if self.isOptionValid('lines'):
            for line in self._options.pop('lines'):
                self._addPlotObject(line)

        # Current vtkPlot objects to display
        current = set()
        for line in self._plots:
            current.update(line.getVTKPlotObjects())

        # Error if no line objects exists
        if len(self._plots) == 0:
            mooseutils.mooseError("No line objects exists, thus no graph axes was created.")
            return

        # vtkPlot objects that are being replaced
        old = set()
        for i in range(self._vtkchart.GetNumberOfPlots()):
            old.add(self._vtkchart.GetPlot(i))

        # Remove vtkPlot objects that are in old, but not in current
        for plot in old.difference(current):
            idx = self._vtkchart.GetPlotIndex(plot)
            self._vtkchart.RemovePlot(idx)

        # Add the new plots
        for plot in current.difference(old):
            self._vtkchart.AddPlot(plot)

        # Set plot corners
        for line in self._plots:
            corner = line.options().raw('corner').allow.index(line.getOption('corner'))
            for plot in line.getVTKPlotObjects():
                self._vtkchart.SetPlotCorner(plot, corner)

            if line.needsUpdate():
                line.update()

        # Adjust hidden borders
        if self.isOptionValid('hidden_border'):
            self._vtkchart.SetHiddenAxisBorder(self.getOption('hidden_border'))
Exemplo n.º 5
0
    def setActive(self, result):
        """
        Set the active result object for interaction.
        """
        if result not in self._results:
            mooseutils.mooseError("The active result must be added to the RendererWindow prior to "
                                  "setting it as active.")
            return

        self.__active = result
        if self.__vtkinteractor:
            self.__vtkinteractor.GetInteractorStyle().SetDefaultRenderer(result.getVTKRenderer())
Exemplo n.º 6
0
    def setActive(self, result):
        """
        Set the active result object for interaction.
        """
        if result not in self._results:
            mooseutils.mooseError("The active result must be added to the RendererWindow prior to "
                                  "setting it as active.")
            return

        self.__active = result
        if self.__vtkinteractor:
            self.__vtkinteractor.GetInteractorStyle().SetDefaultRenderer(result.getVTKRenderer())
Exemplo n.º 7
0
 def save(self):
     """
     Save the contents into a file.
     """
     fname, other = QFileDialog.getSaveFileName(self, "Choose output", "", "Output file (*.log *.txt)")
     if fname:
         try:
             with open(fname, "w") as f:
                 f.write(self.toPlainText())
             mooseutils.mooseMessage("Saved content to %s" % fname)
         except Exception as e:
             mooseutils.mooseError("Failed to save file: %s" % e, dialog=True)
 def save(self):
     """
     Save the contents into a file.
     """
     fname, other = QFileDialog.getSaveFileName(self, "Choose output", "", "Output file (*.log *.txt)")
     if fname:
         try:
             with open(fname, "w") as f:
                 f.write(self.toPlainText())
             mooseutils.mooseMessage("Saved content to %s" % fname)
         except Exception as e:
             mooseutils.mooseError("Failed to save file: %s" % e, dialog=True)
Exemplo n.º 9
0
    def __getTimeInformation(self):
        """
        Helper for getting the current TimeData object using the 'time' and 'timestep' options.
        (private)

        Returns:
            TimeData: The current TimeData object.
        """

        # Time/timestep both set, unset 'time' and use 'timestep'
        if self.isOptionValid('timestep') and self.isOptionValid('time'):
            time = self.getOption('time')
            timestep = self.getOption('timestep')
            self._options.raw('time').unset()
            msg = "Both 'time' ({}) and 'timestep' ({}) are set, 'timestep' is being used."
            mooseutils.mooseWarning(msg.format(time, timestep))

        # Timestep
        timestep = -1
        n = len(self.__timedata) - 1
        if self.isOptionValid('timestep'):
            timestep = self.getOption('timestep')

            # Account for out-of-range timesteps
            if (timestep < 0) and (timestep != -1):
                mooseutils.mooseWarning("Timestep out of range:", timestep,
                                        'not in', repr([0, n]))
                self.setOption('timestep', 0)
                timestep = 0
            elif timestep > n:
                mooseutils.mooseWarning("Timestep out of range:", timestep,
                                        'not in', repr([0, n]))
                self.setOption('timestep', n)
                timestep = n

        # Time
        elif self.isOptionValid('time'):
            times = [t.time for t in self.__timedata]
            idx = bisect.bisect_right(times, self.getOption('time')) - 1
            if idx < 0:
                idx = 0
            elif idx > n:
                idx = -1
            timestep = idx

        else:
            t = self.getOption('time')
            ts = self.getOption('timestep')
            mooseutils.mooseError(
                'Invalid time ({}) and timestep({}) options.'.format(t, ts))

        return self.__timedata[timestep]
Exemplo n.º 10
0
    def contour(self):
        """
        Called when contours are toggled or the count or levels are changed.
        """
        # Disable for non-nodal variables
        active = self.setActive()
        if not active:
            return

        # Set the visibility of the contours
        checked = self.ContourToggle.isChecked()
        self.ContourLevels.setEnabled(checked)
        self.ContourCount.setEnabled(checked)
        filters = self._result.getOption('filters')

        # If visible setup the contour interval/count
        if checked:
            options = dict()
            text = self.ContourLevels.text()
            if len(text) > 0:
                try:
                    options['levels'] = [
                        float(item) for item in re.split('[;,\s]', str(text))
                    ]
                    self.ContourCount.setEnabled(False)
                except:
                    mooseutils.mooseError(
                        "Failed to convert supplied data to valid numeric contour levels."
                    )
                    self.ContourCount.setEnabled(True)
            else:
                self.ContourCount.setEnabled(True)
                options['levels'] = None
                options['count'] = int(self.ContourCount.value())

            self._contour.setOptions(**options)

            if self._contour not in filters:
                filters.append(self._contour)

        else:
            if self._contour in filters:
                filters.remove(self._contour)

        # Emit the changes
        if self._variable:
            self.store(self.stateKey(self._variable), 'Variable')
        self.resultOptionsChanged.emit({'filters': filters})
        self.windowRequiresUpdate.emit()
        self.contourClicked.emit(checked)
Exemplo n.º 11
0
    def addObject(self, widget):
        """
        Method for adding a widget to a layout.

        Args:
            widget[QWidget]: The widget to add.

        NOTE: This method exists so that derived classes can customize how items are added.
        """
        if not hasattr(self, widget.mainLayoutName()):
            mooseutils.mooseError("Unknown layout name '{}' returned when adding plugin '{}', the plugin is being skipped.".format(widget.mainLayoutName(), widget.__class__.__name__))
        else:
            layout = getattr(self, widget.mainLayoutName())
            layout.addWidget(widget)
Exemplo n.º 12
0
 def _callbackScale(self, value):
     """
     Callback for scale toggle.
     """
     if value:
         try:
             self.set('set_{}scale', 'log')
         except:
             mooseutils.mooseError('Failed to set log axis limits, your data likely crosses zero.')
             self.Scale.setCheckState(QtCore.Qt.Unchecked)
             self.set('set_{}scale', 'linear')
     else:
         self.set('set_{}scale', 'linear')
     self.axesModified.emit()
Exemplo n.º 13
0
    def axis(self, name):
        """
        Return the pyplot.Axis object.

        Args:
            name[str]: 'x', 'y', or 'y2'.
        """
        if name == 'x':
            return self.axes(0).get_xaxis()
        elif name == 'y':
            return self.axes(0).get_yaxis()
        elif name == 'y2':
            return self.axes(1).get_yaxis()
        mooseutils.mooseError("Unknown axis name, must use: 'x', 'y', or 'y2'.")
Exemplo n.º 14
0
    def __getTimeInformation(self):
        """
        Helper for getting the current TimeData object using the 'time' and 'timestep' options.
        (private)

        Returns:
            TimeData: The current TimeData object.
        """

        # Time/timestep both set, unset 'time' and use 'timestep'
        if self.isOptionValid('timestep') and self.isOptionValid('time'):
            time = self.getOption('time')
            timestep = self.getOption('timestep')
            self._options.raw('time').unset()
            msg = "Both 'time' ({}) and 'timestep' ({}) are set, 'timestep' is being used."
            mooseutils.mooseWarning(msg.format(time, timestep))

        # Timestep
        timestep = -1
        n = len(self.__timedata)-1
        if self.isOptionValid('timestep'):
            timestep = self.getOption('timestep')

            # Account for out-of-range timesteps
            if (timestep < 0) and (timestep != -1):
                mooseutils.mooseWarning("Timestep out of range:", timestep, 'not in', repr([0, n]))
                self.setOption('timestep', 0)
                timestep = 0
            elif timestep > n:
                mooseutils.mooseWarning("Timestep out of range:", timestep, 'not in', repr([0, n]))
                self.setOption('timestep', n)
                timestep = n

        # Time
        elif self.isOptionValid('time'):
            times = [t.time for t in self.__timedata]
            idx = bisect.bisect_right(times, self.getOption('time')) - 1
            if idx < 0:
                idx = 0
            elif idx > n:
                idx = -1
            timestep = idx

        else:
            t = self.getOption('time')
            ts = self.getOption('timestep')
            mooseutils.mooseError('Invalid time ({}) and timestep({}) options.'.format(t, ts))

        return self.__timedata[timestep]
Exemplo n.º 15
0
    def getSample(self, variable):
        """
        Return the sampled data for the given variable.
        """
        self.checkUpdateState()
        self._probe.Update()

        # Return data
        if self._probe.GetOutput().GetPointData().HasArray(variable):
            y = self._probe.GetOutput().GetPointData().GetArray(variable)
        else:
            mooseutils.mooseError('Unable to locate the variable, ' + variable + \
                                  ', in the supplied source data.')
            return []
        return [y.GetValue(i) for i in range(y.GetNumberOfTuples()+1)]
    def getSample(self, variable):
        """
        Return the sampled data for the given variable.
        """
        self.checkUpdateState()
        self._probe.Update()

        # Return data
        if self._probe.GetOutput().GetPointData().HasArray(variable):
            y = self._probe.GetOutput().GetPointData().GetArray(variable)
        else:
            mooseutils.mooseError('Unable to locate the variable, ' + variable + \
                                  ', in the supplied source data.')
            return []
        return [y.GetValue(i) for i in range(y.GetNumberOfTuples() + 1)]
Exemplo n.º 17
0
 def _callbackScale(self, value):
     """
     Callback for scale toggle.
     """
     if value:
         try:
             self.set('set_{}scale', 'log')
         except:
             mooseutils.mooseError(
                 'Failed to set log axis limits, your data likely crosses zero.'
             )
             self.Scale.setCheckState(QtCore.Qt.Unchecked)
             self.set('set_{}scale', 'linear')
     else:
         self.set('set_{}scale', 'linear')
     self.axesModified.emit()
Exemplo n.º 18
0
    def __init__(self, layout='MainLayout'):
        super(Plugin, self).__init__()

        # Name of layout that this plugin should be added (see PluginManager.py)
        self._main_layout_name = layout

        # The default size policy
        self.setSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed)

        # Must be a QtWidget
        if not isinstance(self, QtWidgets.QWidget):
            mooseutils.mooseError("A Plugin must also be a QWidget.")
            return

        # The Peacock tab index
        self._index = None
        self._plugin_manager = None
Exemplo n.º 19
0
 def testMooseMessageError(self):
     """
     Test the error dialog message.
     """
     box = mooseutils.mooseError("A message", dialog = True, test = True)
     self.assertIn("A message", box.text())
     self.assertIn("ERROR", box.text())
     self.assertTrue(box.icon() == QtWidgets.QMessageBox.Critical)
Exemplo n.º 20
0
    def contour(self):
        """
        Called when contours are toggled or the count or levels are changed.
        """
        # Disable for non-nodal variables
        active = self.setActive()
        if not active:
            return

        # Set the visibility of the contours
        checked = self.ContourToggle.isChecked()
        self.ContourLevels.setEnabled(checked)
        self.ContourCount.setEnabled(checked)
        filters = self._result.getOption('filters')

        # If visible setup the contour interval/count
        if checked:
            options = dict()
            text = self.ContourLevels.text()
            if len(text) > 0:
                try:
                    options['levels'] = [float(item) for item in re.split('[;,\s]', str(text))]
                    self.ContourCount.setEnabled(False)
                except:
                    mooseutils.mooseError("Failed to convert supplied data to valid numeric contour levels.")
                    self.ContourCount.setEnabled(True)
            else:
                self.ContourCount.setEnabled(True)
                options['levels'] = None
                options['count'] = int(self.ContourCount.value())

            self._contour.setOptions(**options)

            if self._contour not in filters:
                filters.append(self._contour)

        else:
            if self._contour in filters:
                filters.remove(self._contour)

        # Emit the changes
        if self._variable:
            self.store(self.stateKey(self._variable), 'Variable')
        self.resultOptionsChanged.emit({'filters':filters})
        self.windowRequiresUpdate.emit()
        self.contourClicked.emit(checked)
Exemplo n.º 21
0
 def setWorkingDir(self, dir_name):
     """
     Sets the working directory.
     Input:
         dir_name: The path of the working directory.
     """
     if not dir_name:
         return
     old_dirname = str(self.working_line.text())
     try:
         os.chdir(dir_name)
         self.working_line.setText(dir_name)
         if old_dirname != dir_name:
             self.workingDirChanged.emit(dir_name)
         self._updateRecentWorkingDir(dir_name)
     except OSError:
         mooseutils.mooseError("Invalid directory %s" % dir_name, dialog=True)
         self._updateRecentWorkingDir(dir_name, True)
Exemplo n.º 22
0
    def __init__(self, layout='MainLayout', settings_key="", **kwargs):
        super(Plugin, self).__init__()

        # Name of layout that this plugin should be added (see PluginManager.py)
        self._main_layout_name = layout

        # The default size policy
        self.setSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed)

        # Must be a QtWidget
        if not isinstance(self, QtWidgets.QWidget):
            mooseutils.mooseError("A Plugin must also be a QWidget.")
            return

        # The Peacock tab index
        self._index = None
        self._plugin_manager = None
        self._preferences = Preferences(settings_key)
Exemplo n.º 23
0
 def setWorkingDir(self, dir_name):
     """
     Sets the working directory.
     Input:
         dir_name: The path of the working directory.
     """
     if not dir_name:
         return
     old_dirname = str(self.working_line.text())
     try:
         os.chdir(dir_name)
         self.working_line.setText(dir_name)
         if old_dirname != dir_name:
             self.workingDirChanged.emit(dir_name)
         self._updateRecentWorkingDir(dir_name)
     except OSError:
         mooseutils.mooseError("Invalid directory %s" % dir_name, dialog=True)
         self._updateRecentWorkingDir(dir_name, True)
Exemplo n.º 24
0
    def __updateAxisOptions(self, axis):
        """
        Helper for updating Axis level settings.
        """
        if axis not in ['x', 'y', 'z']:
            mooseutils.mooseError("Must provide 'x', 'y', or 'z'.")
            return

        opt = self.getOption(axis + 'axis')
        color = opt['color']
        comp = ['x', 'y', 'z'].index(axis)
        self._vtkactor.GetTitleTextProperty(comp).SetColor(*color)
        self._vtkactor.GetLabelTextProperty(comp).SetColor(*color)

        func = getattr(self._vtkactor, 'Set{}AxisMinorTickVisibility'.format(axis.upper()))
        func(opt['minor_ticks'])

        func = getattr(self._vtkactor, 'Get{}AxesLinesProperty'.format(axis.upper()))
        func().SetColor(*color)
Exemplo n.º 25
0
    def setInputFile(self, input_file):
        """
        The input file has changed.
        Input:
            input_file[str]: The new input file
        """
        self._closeBlockEditor()

        if self.tree.app_info.valid():
            input_file = os.path.abspath(input_file)
            if self.tree.setInputFile(input_file):
                self.block_tree.setInputTree(self.tree)
                self.inputFileChanged.emit(input_file)
                return True
            elif input_file:
                mooseutils.mooseError("Failed to read input file", dialog=True)
        else:
            self.tree.input_filename = input_file
        return False
Exemplo n.º 26
0
    def write(self, filename, dialog=False, **kwargs):
        """
        Writes the VTKWindow to an image.
        """
        mooseutils.mooseDebug('RenderWindow.write()', color='MAGENTA')

        if self.needsUpdate() or kwargs:
            self.update(**kwargs)

        # Allowed extensions and the associated readers
        writers = dict()
        writers['.png'] = vtk.vtkPNGWriter
        writers['.ps'] = vtk.vtkPostScriptWriter
        writers['.tiff'] = vtk.vtkTIFFWriter
        writers['.bmp'] = vtk.vtkBMPWriter
        writers['.jpg'] = vtk.vtkJPEGWriter

        # Extract the extensionq
        _, ext = os.path.splitext(filename)
        if ext not in writers:
            w = ', '.join(writers.keys())
            msg = "The filename must end with one of the following extensions: {}.".format(
                w)
            mooseutils.mooseError(msg, dialog=dialog)
            return

        # Check that the directory exists
        dirname = os.path.dirname(filename)
        if (len(dirname) > 0) and (not os.path.isdir(dirname)):
            msg = "The directory does not exist: {}".format(dirname)
            mooseutils.mooseError(msg, dialog=dialog)
            return

        # Build a filter for writing an image
        window_filter = vtk.vtkWindowToImageFilter()
        window_filter.SetInput(self.__vtkwindow)
        window_filter.Update()

        # Write it
        writer = writers[ext]()
        writer.SetFileName(filename)
        writer.SetInputData(window_filter.GetOutput())
        writer.Write()
Exemplo n.º 27
0
        def update(self, **kwargs):
            """
            Set the options for this cube. (public)
            """
            super(PlaneSourceMeta, self).update(**kwargs)

            if self.isOptionValid('origin'):
                self._vtksource.SetOrigin(*self.getOption('origin'))

            if self.isOptionValid('point1'):
                self._vtksource.SetPoint1(*self.getOption('point1'))

            if self.isOptionValid('point2'):
                self._vtksource.SetPoint2(*self.getOption('point2'))

            if self.isOptionValid('resolution'):
                self._vtksource.SetResolution(*self.getOption('resolution'))

            if self.isOptionValid('cmap'):
                if self.isOptionValid('color'):
                    mooseutils.mooseWarning(
                        'The "color" and "cmap" options are both being set, '
                        'the "color" will be ignored.')

                if not self.isOptionValid('data'):
                    mooseutils.mooseError(
                        'The "cmap" option requires that "data" option also '
                        'be supplied.')

                if self.isOptionValid('data'):
                    self._vtksource.Update()
                    data = self.getOption('data')
                    self._vtksource.GetOutput().GetCellData().SetScalars(data)
                    cmap_options = {
                        key: self.getOption(key)
                        for key in [
                            'cmap', 'cmap_reverse', 'cmap_num_colors',
                            'cmap_range'
                        ]
                    }
                    self._colormap.setOptions(**cmap_options)
                    self._vtkmapper.SetScalarRange(data.GetRange(0))
                    self._vtkmapper.SetLookupTable(self._colormap())
Exemplo n.º 28
0
    def write(self, filename, dialog=False, **kwargs):
        """
        Writes the VTKWindow to an image.
        """
        mooseutils.mooseDebug('RenderWindow.write()', color='MAGENTA')

        if self.needsUpdate() or kwargs:
            self.update(**kwargs)

        # Allowed extensions and the associated readers
        writers = dict()
        writers['.png'] = vtk.vtkPNGWriter
        writers['.ps'] = vtk.vtkPostScriptWriter
        writers['.tiff'] = vtk.vtkTIFFWriter
        writers['.bmp'] = vtk.vtkBMPWriter
        writers['.jpg'] = vtk.vtkJPEGWriter

        # Extract the extensionq
        _, ext = os.path.splitext(filename)
        if ext not in writers:
            w = ', '.join(writers.keys())
            msg = "The filename must end with one of the following extensions: {}.".format(w)
            mooseutils.mooseError(msg, dialog=dialog)
            return

        # Check that the directory exists
        dirname = os.path.dirname(filename)
        if (len(dirname) > 0) and (not os.path.isdir(dirname)):
            msg = "The directory does not exist: {}".format(dirname)
            mooseutils.mooseError(msg, dialog=dialog)
            return

        # Build a filter for writing an image
        window_filter = vtk.vtkWindowToImageFilter()
        window_filter.SetInput(self.__vtkwindow)
        window_filter.Update()

        # Write it
        writer = writers[ext]()
        writer.SetFileName(filename)
        writer.SetInputData(window_filter.GetOutput())
        writer.Write()
Exemplo n.º 29
0
    def __init__(self):
        super(Plugin, self).__init__()

        # Name of layout that this plugin should be added (see PluginManager.py)
        self._main_layout_name = 'MainLayout'

        # Widget is disabled until initialize is called
        self.setEnabled(False)

        # The default size policy
        self.setSizePolicy(QtWidgets.QSizePolicy.Preferred,
                           QtWidgets.QSizePolicy.Fixed)

        # Must be a QtWidget
        if not isinstance(self, QtWidgets.QWidget):
            mooseutils.mooseError("A Plugin must also be a QWidget.")
            return

        # The Peacock tab index
        self._index = None
Exemplo n.º 30
0
    def runClicked(self):
        """
        Run button clicked.
        """
        input_file = self._tempInputFile()
        self.cleanup()
        self.needInputFile.emit(input_file)
        if not os.path.exists(input_file):
            mooseutils.mooseError("Input file didn't get written", dialog=True)
            return
        self.needCommand.emit()
        if self.runner.isRunning():
            self.runner.kill()
        self.kill_button.setDisabled(False)
        self._showProgressBar(True)
        self.progress_bar.setMaximum(11)
        self.progress_bar.setValue(0)

        start_time = math.floor(time.time()) if sys.platform == 'darwin' else time.time()
        self.startJob.emit(self.has_csv, input_file, start_time)
        self.runner.run(self.exe_path, self.exe_args + ["-i", os.path.relpath(input_file)])
Exemplo n.º 31
0
    def __init__(self, manager=None, plugins=[]):
        super(ViewerBase, self).__init__()

        # Error checking
        if not plugins:
            mooseutils.mooseError("No plugins supplied.")
            return
        if not manager:
            mooseutils.mooseError("The type of manager to create must be supplied.")

        # Member variables and class settings
        self._manager = manager # the manager class to create
        self._plugins = plugins # the plugin classes (not instances) to created
        self._count = 0         # the number of tabs created
        self._data = None       # data to pass to PluginManager::initialize (see 'initialize')

        # Add the corner close/clone buttons
        self.setCornerWidget(ViewerCornerWidget())
        self.cornerWidget().close.connect(self.onClose)
        self.cornerWidget().clone.connect(self.onClone)
        self.setup()
        self.addManager()
Exemplo n.º 32
0
    def __init__(self, manager=None, plugins=[]):
        super(ViewerBase, self).__init__()

        # Error checking
        if not plugins:
            mooseutils.mooseError("No plugins supplied.")
            return
        if not manager:
            mooseutils.mooseError("The type of manager to create must be supplied.")

        # Member variables and class settings
        self._manager = manager # the manager class to create
        self._plugins = plugins # the plugin classes (not instances) to created
        self._count = 0         # the number of tabs created
        self._data = None       # data to pass to PluginManager::initialize (see 'initialize')

        # Add the corner close/clone buttons
        self.setCornerWidget(ViewerCornerWidget())
        self.cornerWidget().close.connect(self.onClose)
        self.cornerWidget().clone.connect(self.onClone)
        self.setup()
        self.addManager()
Exemplo n.º 33
0
        def update(self, **kwargs):
            """
            Set the options for this cube. (public)
            """
            super(PlaneSourceMeta, self).update(**kwargs)

            if self.isOptionValid('origin'):
                self._vtksource.SetOrigin(*self.getOption('origin'))

            if self.isOptionValid('point1'):
                self._vtksource.SetPoint1(*self.getOption('point1'))

            if self.isOptionValid('point2'):
                self._vtksource.SetPoint2(*self.getOption('point2'))

            if self.isOptionValid('resolution'):
                self._vtksource.SetResolution(*self.getOption('resolution'))

            if self.isOptionValid('cmap'):
                if self.isOptionValid('color'):
                    mooseutils.mooseWarning('The "color" and "cmap" options are both being set, '
                                            'the "color" will be ignored.')

                if not self.isOptionValid('data'):
                    mooseutils.mooseError('The "cmap" option requires that "data" option also '
                                          'be supplied.')

                if self.isOptionValid('data'):
                    self._vtksource.Update()
                    data = self.getOption('data')
                    self._vtksource.GetOutput().GetCellData().SetScalars(data)
                    cmap_options = {key:self.getOption(key) for key in ['cmap', 'cmap_reverse',
                                                                        'cmap_num_colors',
                                                                        'cmap_range']}
                    self._colormap.setOptions(**cmap_options)
                    self._vtkmapper.SetScalarRange(data.GetRange(0))
                    self._vtkmapper.SetLookupTable(self._colormap())
Exemplo n.º 34
0
    def openInputFile(self, filename):
        """
        Opens a file and parses it.
        Input:
            filename: file name of the input file
        Signals:
            input_file_changed: On success
        Raises:
            PeacockException: On invalid input file
        """
        filename = str(filename)
        self.filename = path.abspath(filename)
        self.changed = False
        self.root_node = GPNode("/", None)

        # Do some basic checks on the filename to make sure
        # it is probably a real input file since the GetPot
        # parser doesn't do any checks.
        if not path.exists(filename):
            msg = "Input file %s does not exist" % filename
            mooseutils.mooseError(msg)
            raise PeacockException(msg)

        if not path.isfile(filename):
            msg = "Input file %s is not a file" % filename
            mooseutils.mooseError(msg)
            raise PeacockException(msg)

        if not filename.endswith(".i"):
            msg = "Input file %s does not have the proper extension" % filename
            mooseutils.mooseError(msg)
            raise PeacockException(msg)

        try:
            self.root_node = readInputFile(filename)
            with open(filename, "r") as f:
                self.original_text = f.read()
            self.changed = False
        except ParseException as e:
            msg = "Failed to parse input file %s:\n%s\n" % (filename, e.msg)
            mooseutils.mooseWarning(msg)
            raise e
        except Exception as e:
            msg = "Error occurred while parsing input file %s:\n%s\n" % (
                filename, e)
            mooseutils.mooseWarning(msg)
            raise e
Exemplo n.º 35
0
    def openInputFile(self, filename):
        """
        Opens a file and parses it.
        Input:
            filename: file name of the input file
        Signals:
            input_file_changed: On success
        Raises:
            PeacockException: On invalid input file
        """
        filename = str(filename)
        self.filename = path.abspath(filename)
        self.changed = False
        self.root_node = GPNode("/", None)

        # Do some basic checks on the filename to make sure
        # it is probably a real input file since the GetPot
        # parser doesn't do any checks.
        if not path.exists(filename):
            msg = "Input file %s does not exist" % filename
            mooseutils.mooseError(msg)
            raise PeacockException(msg)

        if not path.isfile(filename):
            msg = "Input file %s is not a file" % filename
            mooseutils.mooseError(msg)
            raise PeacockException(msg)

        if not filename.endswith(".i"):
            msg = "Input file %s does not have the proper extension" % filename
            mooseutils.mooseError(msg)
            raise PeacockException(msg)

        try:
            self.root_node = readInputFile(filename)
            with open(filename, "r") as f:
                self.original_text = f.read()
            self.changed = False
        except ParseException as e:
            msg = "Failed to parse input file %s:\n%s\n" % (filename, e.msg)
            mooseutils.mooseWarning(msg)
            raise e
        except Exception as e:
            msg = "Error occurred while parsing input file %s:\n%s\n" % (filename, e)
            mooseutils.mooseWarning(msg)
            raise e
Exemplo n.º 36
0
    def openInputFile(self, filename):
        """
        Opens a file and parses it.
        Input:
            filename: file name of the input file
        Signals:
            input_file_changed: On success
        Raises:
            PeacockException: On invalid input file
        """
        filename = str(filename)
        self.filename = os.path.abspath(filename)
        self.changed = False
        self.root_node = None

        # Do some basic checks on the filename to make sure
        # it is probably a real input file since the GetPot
        # parser doesn't do any checks.
        if not os.path.exists(filename):
            msg = "Input file %s does not exist" % filename
            mooseutils.mooseError(msg)
            raise PeacockException(msg)

        if not os.path.isfile(filename):
            msg = "Input file %s is not a file" % filename
            mooseutils.mooseError(msg)
            raise PeacockException(msg)

        if not filename.endswith(".i"):
            msg = "Input file %s does not have the proper extension" % filename
            mooseutils.mooseError(msg)
            raise PeacockException(msg)

        with open(filename, 'r') as f:
            data = f.read()
        self.readInputData(data, filename)
Exemplo n.º 37
0
    def __updateVariable(self):
        """
        Method to update the active variable to display on the object. (private)
        """
        def get_available_variables():
            """
            Returns a sting listing the available nodal and elemental variable names.
            """
            nvars = self.__reader.getVariableInformation(
                var_types=[ExodusReader.NODAL]).keys()
            evars = self.__reader.getVariableInformation(
                var_types=[ExodusReader.ELEMENTAL]).keys()
            msg = ["Nodal:"]
            msg += [" " + var for var in nvars]
            msg += ["\nElemental:"]
            msg += [" " + var for var in evars]
            return ''.join(msg)

        # Define the active variable name
        available = self.__reader.getVariableInformation(
            var_types=[ExodusReader.NODAL, ExodusReader.ELEMENTAL])

        # Case when no variable exists
        if not available:
            return

        default = available[available.keys()[0]]
        if not self.isOptionValid('variable'):
            varinfo = default
        else:
            var_name = self.getOption('variable')
            if var_name not in available:
                msg = "The variable '{}' provided does not exist, using '{}', available " \
                      "variables include:\n{}"
                mooseutils.mooseError(
                    msg.format(var_name, default.name,
                               get_available_variables()))
                varinfo = default
            else:
                varinfo = available[var_name]

        # Update vtkMapper to the correct data mode
        if varinfo.object_type == ExodusReader.ELEMENTAL:
            self._vtkmapper.SetScalarModeToUseCellFieldData()
        elif varinfo.object_type == ExodusReader.NODAL:
            self._vtkmapper.SetScalarModeToUsePointFieldData()
        else:
            raise mooseutils.MooseException(
                'Unknown variable type, not sure how you made it here.')
        self.__current_variable = varinfo

        # Colormap
        if not self.isOptionValid('color'):
            self._colormap.setOptions(
                cmap=self.getOption('cmap'),
                cmap_reverse=self.getOption('cmap_reverse'),
                cmap_num_colors=self.getOption('cmap_num_colors'))
            self._vtkmapper.SelectColorArray(varinfo.name)
            self._vtkmapper.SetLookupTable(self._colormap())
            self._vtkmapper.UseLookupTableScalarRangeOff()

        # Component
        component = -1  # Default component to utilize if not valid
        if self.isOptionValid('component'):
            component = self.getOption('component')

        if component == -1:
            self._vtkmapper.GetLookupTable().SetVectorModeToMagnitude()
        else:
            if component > varinfo.num_components:
                msg = 'Invalid component number ({}), the variable "{}" has {} components.'
                mooseutils.mooseError(
                    msg.format(component, varinfo.name,
                               varinfo.num_components))
            self._vtkmapper.GetLookupTable().SetVectorModeToComponent()
            self._vtkmapper.GetLookupTable().SetVectorComponent(component)

        # Range
        if (self.isOptionValid('min')
                or self.isOptionValid('max')) and self.isOptionValid('range'):
            mooseutils.mooseError(
                'Both a "min" and/or "max" options has been set along with the '
                '"range" option, the "range" is being utilized, the others are '
                'ignored.')

        # Range
        rng = list(
            self.__getRange())  # Use range from all sources as the default
        if self.isOptionValid('range'):
            rng = self.getOption('range')
        else:
            if self.isOptionValid('min'):
                rng[0] = self.getOption('min')
            if self.isOptionValid('max'):
                rng[1] = self.getOption('max')

        if rng[0] > rng[1]:
            mooseutils.mooseDebug(
                "Minimum range greater than maximum:", rng[0], ">", rng[1],
                ", the range/min/max settings are being ignored.")
            rng = list(self.__getRange())

        self.getVTKMapper().SetScalarRange(rng)

        # Handle Elemental variables that are not everywhere on the domain
        varname = self.__current_variable.name
        block = self.getOption('block')
        if (self.__current_variable.object_type
                == ExodusReader.ELEMENTAL) and (block is not None):
            for i in range(
                    self.__vtkextractblock.GetOutput().GetNumberOfBlocks()):
                if not hasattr(self.__vtkextractblock.GetOutput().GetBlock(i),
                               'GetNumberOfBlocks'):
                    continue
                for j in range(self.__vtkextractblock.GetOutput().GetBlock(
                        i).GetNumberOfBlocks()):
                    blk = self.__vtkextractblock.GetOutput().GetBlock(
                        i).GetBlock(j)
                    if not blk.GetCellData().HasArray(varname):
                        data = vtk.vtkDoubleArray()
                        data.SetName(varname)
                        data.SetNumberOfTuples(
                            blk.GetCellData().GetArray(0).GetNumberOfTuples())
                        data.FillComponent(0, vtk.vtkMath.Nan())
                        blk.GetCellData().AddArray(data)
Exemplo n.º 38
0
    def update(self, *args, **kwargs):
        """
        Update method for the graph axes.
        """
        super(Graph, self).update(*args, **kwargs)

        # Update Axis options
        self._setAxisOptions(self._vtkchart.GetAxis(vtk.vtkAxis.BOTTOM),
                             self.getOption('xaxis'))
        self._setAxisOptions(self._vtkchart.GetAxis(vtk.vtkAxis.LEFT),
                             self.getOption('yaxis'))
        self._setAxisOptions(self._vtkchart.GetAxis(vtk.vtkAxis.TOP),
                             self.getOption('x2axis'))
        self._setAxisOptions(self._vtkchart.GetAxis(vtk.vtkAxis.RIGHT),
                             self.getOption('y2axis'))

        # Legend
        utils.LegendOptions.set_options(self._vtkchart, self._vtkrenderer,
                                        self.getOption('legend'))

        # Line objects
        if self.isOptionValid('lines'):
            for line in self._options.pop('lines'):
                self._addPlotObject(line)

        # Current vtkPlot objects to display
        current = set()
        for line in self._plots:
            current.update(line.getVTKPlotObjects())

        # Error if no line objects exists
        if len(self._plots) == 0:
            mooseutils.mooseError(
                "No line objects exists, thus no graph axes was created.")
            return

        # vtkPlot objects that are being replaced
        old = set()
        for i in range(self._vtkchart.GetNumberOfPlots()):
            old.add(self._vtkchart.GetPlot(i))

        # Remove vtkPlot objects that are in old, but not in current
        for plot in old.difference(current):
            idx = self._vtkchart.GetPlotIndex(plot)
            self._vtkchart.RemovePlot(idx)

        # Add the new plots
        for plot in current.difference(old):
            self._vtkchart.AddPlot(plot)

        # Set plot corners
        for line in self._plots:
            corner = line.options().raw('corner').allow.index(
                line.getOption('corner'))
            for plot in line.getVTKPlotObjects():
                self._vtkchart.SetPlotCorner(plot, corner)

            if line.needsUpdate():
                line.update()

        # Adjust hidden borders
        if self.isOptionValid('hidden_border'):
            self._vtkchart.SetHiddenAxisBorder(self.getOption('hidden_border'))
Exemplo n.º 39
0
    def __updateVariable(self):
        """
        Method to update the active variable to display on the object. (private)
        """
        def get_available_variables():
            """
            Returns a sting listing the available nodal and elemental variable names.
            """
            nvars = self.__reader.getVariableInformation(var_types=[ExodusReader.NODAL]).keys()
            evars = self.__reader.getVariableInformation(var_types=[ExodusReader.ELEMENTAL]).keys()
            msg = ["Nodal:"]
            msg += [" " + var for var in nvars]
            msg += ["\nElemental:"]
            msg += [" " + var for var in evars]
            return ''.join(msg)

        # Define the active variable name
        available = self.__reader.getVariableInformation(var_types=[ExodusReader.NODAL,
                                                                    ExodusReader.ELEMENTAL])

        # Case when no variable exists
        if not available:
            return

        default = available[available.keys()[0]]
        if not self.isOptionValid('variable'):
            varinfo = default
        else:
            var_name = self.getOption('variable')
            if var_name not in available:
                msg = "The variable '{}' provided does not exist, using '{}', available " \
                      "variables include:\n{}"
                mooseutils.mooseError(msg.format(var_name, default.name, get_available_variables()))
                varinfo = default
            else:
                varinfo = available[var_name]

        # Update vtkMapper to the correct data mode
        if varinfo.object_type == ExodusReader.ELEMENTAL:
            self._vtkmapper.SetScalarModeToUseCellFieldData()
        elif varinfo.object_type == ExodusReader.NODAL:
            self._vtkmapper.SetScalarModeToUsePointFieldData()
        else:
            raise mooseutils.MooseException('Unknown variable type, not sure how you made it here.')
        self.__current_variable = varinfo

        # Colormap
        if not self.isOptionValid('color'):
            self._colormap.setOptions(cmap=self.getOption('cmap'),
                                      cmap_reverse=self.getOption('cmap_reverse'),
                                      cmap_num_colors=self.getOption('cmap_num_colors'))
            self._vtkmapper.SelectColorArray(varinfo.name)
            self._vtkmapper.SetLookupTable(self._colormap())
            self._vtkmapper.UseLookupTableScalarRangeOff()

        # Component
        component = -1 # Default component to utilize if not valid
        if self.isOptionValid('component'):
            component = self.getOption('component')

        if component == -1:
            self._vtkmapper.GetLookupTable().SetVectorModeToMagnitude()
        else:
            if component > varinfo.num_components:
                msg = 'Invalid component number ({}), the variable "{}" has {} components.'
                mooseutils.mooseError(msg.format(component, varinfo.name, varinfo.num_components))
            self._vtkmapper.GetLookupTable().SetVectorModeToComponent()
            self._vtkmapper.GetLookupTable().SetVectorComponent(component)

        # Range
        if (self.isOptionValid('min') or self.isOptionValid('max')) and self.isOptionValid('range'):
            mooseutils.mooseError('Both a "min" and/or "max" options has been set along with the '
                                  '"range" option, the "range" is being utilized, the others are '
                                  'ignored.')

        # Range
        rng = list(self.__getRange()) # Use range from all sources as the default
        if self.isOptionValid('range'):
            rng = self.getOption('range')
        else:
            if self.isOptionValid('min'):
                rng[0] = self.getOption('min')
            if self.isOptionValid('max'):
                rng[1] = self.getOption('max')

        if rng[0] > rng[1]:
            mooseutils.mooseDebug("Minimum range greater than maximum:", rng[0], ">", rng[1],
                                  ", the range/min/max settings are being ignored.")
            rng = list(self.__getRange())

        self.getVTKMapper().SetScalarRange(rng)