Beispiel #1
0
def estimateTimeSteps(executioner_node):
    """
    Gets the approximate number of steps from the Exectioner section of the input file
    Inputs:
        executioner_node[BlockInfo]: /Executioner
    """
    cur_steps = 0
    try:
        if executioner_node:
            num_steps = executioner_node.getParamInfo("num_steps")
            if num_steps and num_steps.value:
                cur_steps = int(num_steps.value)
            end_time = executioner_node.getParamInfo("end_time")
            dt = executioner_node.getParamInfo("dt")
            if end_time and end_time.value and dt and float(dt.value) > 0:
                steps = float(end_time.value) / float(dt.value)
                if cur_steps == 0 or steps < cur_steps:
                    cur_steps = steps
            adaptivity = executioner_node.children.get("Adaptivity")
            if adaptivity and adaptivity.included:
                steps = adaptivity.getParamInfo("steps")
                if steps and steps.value:
                    cur_steps += int(steps.value)

        return cur_steps + 2 + 1  # The +2 is for setup steps the +1 is so there is always a bit left...
    except Exception as e:
        mooseutils.mooseWarning("Problem calculating time steps: %s" % e)
        return 0
Beispiel #2
0
def estimateTimeSteps(executioner_node):
    """
    Gets the approximate number of steps from the Exectioner section of the input file
    Inputs:
        executioner_node[BlockInfo]: /Executioner
    """
    cur_steps = 0
    try:
        if executioner_node:
            num_steps = executioner_node.getParamInfo("num_steps")
            if num_steps and num_steps.value:
                cur_steps = int(num_steps.value)
            end_time = executioner_node.getParamInfo("end_time")
            dt = executioner_node.getParamInfo("dt")
            if end_time and end_time.value and dt and float(dt.value) > 0:
                steps = float(end_time.value) / float(dt.value)
                if cur_steps == 0 or steps < cur_steps:
                    cur_steps = steps
            adaptivity = executioner_node.children.get("Adaptivity")
            if adaptivity and adaptivity.included:
                steps = adaptivity.getParamInfo("steps")
                if steps and steps.value:
                    cur_steps += int(steps.value)

        return cur_steps + 2 + 1 # The +2 is for setup steps the +1 is so there is always a bit left...
    except Exception as e:
        mooseutils.mooseWarning("Problem calculating time steps: %s" % e)
        return 0
Beispiel #3
0
    def meshChanged(self, tree, reset=False):
        """
        The parameters of the mesh has changed.
        We need to update the view of the mesh by generating a new mesh file.
        """
        if reset:
            self._reset()

        self.meshEnabled.emit(False)
        if not tree.app_info.valid():
            return
        # if we aren't writing out the mesh node then don't show it
        mesh_node = tree.getBlockInfo("/Mesh")
        if not mesh_node or not mesh_node.included:
            self.onSetFilename(None)
            self.onWindowRequiresUpdate()
            self._setLoadingMessage("Mesh block not included")
            return

        exe_path = tree.app_info.path
        self._removeFileNoError(self.current_temp_mesh_file)
        input_filename = ""
        if tree.input_filename:
            input_filename = os.path.basename(
                os.path.splitext(tree.input_filename)[0])
        self.current_temp_mesh_file = os.path.abspath(
            self.temp_mesh_file.format(input_filename))
        input_file = os.path.abspath(self.temp_input_file)
        self._removeFileNoError(self.current_temp_mesh_file)
        self._removeFileNoError(input_file)
        self.needInputFile.emit(input_file)

        if not os.path.exists(input_file):
            self.meshEnabled.emit(False)
            self.onSetFilename(None)
            self.onWindowRequiresUpdate()
            self._setLoadingMessage("Error reading temporary input file")
            return
        try:
            args = [
                "-i", input_file, "--mesh-only", self.current_temp_mesh_file
            ]
            if self._use_test_objects:
                args.append("--allow-test-objects")
            ExeLauncher.runExe(exe_path, args, print_errors=False)
            self.meshEnabled.emit(True)
            self.onSetFilename(self.current_temp_mesh_file)
            self.onWindowRequiresUpdate()

        except Exception as e:
            self.meshEnabled.emit(False)
            self.onSetFilename(None)
            self.onWindowRequiresUpdate()
            mooseutils.mooseWarning("Error producing mesh: %s" % e)
            self._setLoadingMessage("Error producing mesh")
            self._removeFileNoError(self.current_temp_mesh_file)

        self._removeFileNoError(
            input_file
        )  # we need the mesh file since it is in use but not the input file
Beispiel #4
0
    def _addInputFileNode(self, input_node, included):
        """
        This adds a node from the input file.
        Input:
            input_node[hit.Node]: The node from the input file.
        """
        path = "/" + input_node.fullpath()
        entry = self.path_map.get(path)
        if not entry:
            parent_path = os.path.dirname(path)
            name = os.path.basename(path)
            entry = self.addUserBlock(parent_path, name)
            if not entry:
                mooseutils.mooseWarning("Could not create %s" % path)
                self.input_has_errors = True
                return

        entry.comments = self._getComments(input_node)
        entry.included = included
        entry.hard = True

        in_type = input_node.find("type")
        param_info = entry.parameters.get("type")
        if in_type and in_type.raw() and param_info:
            entry.setBlockType(in_type.raw())
            param_info.value = in_type.raw()
            if "type" not in entry.parameters_list:
                entry.parameters_list.insert(0, "type")

        active = self._readParameters(input_node, path)

        for child_node in input_node.children(node_type=hit.NodeType.Section):
            self._addInputFileNode(child_node, child_node.path() in active)
            if child_node.path() not in entry.children_write_first:
                entry.children_write_first.append(child_node.path())
Beispiel #5
0
    def _addInputFileNode(self, input_node, included):
        """
        This adds a node from the input file.
        Input:
            input_node[hit.Node]: The node from the input file.
        """
        path = "/" + input_node.fullpath()
        entry = self.path_map.get(path)
        if not entry:
            parent_path = os.path.dirname(path)
            name = os.path.basename(path)
            entry = self.addUserBlock(parent_path, name)
            if not entry:
                mooseutils.mooseWarning("Could not create %s" % path)
                self.input_has_errors = True
                return

        entry.comments = self._getComments(input_node)
        entry.included = included
        entry.hard = True

        in_type = input_node.find("type")
        param_info = entry.parameters.get("type")
        if in_type and in_type.raw() and param_info:
            entry.setBlockType(in_type.raw())
            param_info.value = in_type.raw()
            if "type" not in entry.parameters_list:
                entry.parameters_list.insert(0, "type")

        active = self._readParameters(input_node, path)

        for child_node in input_node.children(node_type=hit.NodeType.Section):
            self._addInputFileNode(child_node, child_node.path() in active)
            if child_node.path() not in entry.children_write_first:
                entry.children_write_first.append(child_node.path())
Beispiel #6
0
    def meshChanged(self, tree, reset=False):
        """
        The parameters of the mesh has changed.
        We need to update the view of the mesh by generating a new mesh file.
        """
        if reset:
            self._reset()

        self.meshEnabled.emit(False)
        if not tree.app_info.valid():
            return
        # if we aren't writing out the mesh node then don't show it
        mesh_node = tree.getBlockInfo("/Mesh")
        if not mesh_node or not mesh_node.included:
            self.onSetFilename(None)
            self.onWindowRequiresUpdate()
            self._setLoadingMessage("Mesh block not included")
            return

        exe_path = tree.app_info.path
        self._removeFileNoError(self.current_temp_mesh_file)
        input_filename = ""
        if tree.input_filename:
            input_filename = os.path.basename(os.path.splitext(tree.input_filename)[0])
        self.current_temp_mesh_file = os.path.abspath(self.temp_mesh_file.format(input_filename))
        input_file = os.path.abspath(self.temp_input_file)
        self._removeFileNoError(self.current_temp_mesh_file)
        self._removeFileNoError(input_file)
        self.needInputFile.emit(input_file)

        if not os.path.exists(input_file):
            self.meshEnabled.emit(False)
            self.onSetFilename(None)
            self.onWindowRequiresUpdate()
            self._setLoadingMessage("Error reading temporary input file")
            return
        try:
            args = ["-i", input_file, "--mesh-only", self.current_temp_mesh_file]
            if self._use_test_objects:
                args.append("--allow-test-objects")
            ExeLauncher.runExe(exe_path, args, print_errors=False)
            self.meshEnabled.emit(True)
            self.onSetFilename(self.current_temp_mesh_file)
            self.onSetColorbarVisible(False)
            self.onWindowRequiresUpdate()

        except Exception as e:
            self.meshEnabled.emit(False)
            self.onSetFilename(None)
            self.onWindowRequiresUpdate()
            mooseutils.mooseWarning("Error producing mesh: %s" % e)
            self._setLoadingMessage("Error producing mesh")
            self._removeFileNoError(self.current_temp_mesh_file)

        self._removeFileNoError(input_file) # we need the mesh file since it is in use but not the input file
Beispiel #7
0
 def appChanged(self, app_path):
     """
     Called when the executable changed.
     Input:
         app_path: New executable path
     """
     try:
         raw_data = self._getRawDump(app_path)
         self.json_data = json.loads(raw_data)
         self.app_path = app_path
     except Exception as e:
         mooseutils.mooseWarning("Failed to load json from '%s': %s" % (app_path, e))
Beispiel #8
0
 def setInputFile(self, input_filename):
     """
     Set a new input file
     Input:
         input_filename[str]: The name of the input file
     Return:
         bool: If it was a valid input file
     """
     try:
         new_input_file = InputFile(input_filename)
         return self._setInputFile(new_input_file)
     except Exception as e:
         mooseutils.mooseWarning("setInputFile exception: %s" % e)
         return False
Beispiel #9
0
 def setInputFile(self, input_filename):
     """
     Set a new input file
     Input:
         input_filename[str]: The name of the input file
     Return:
         bool: If it was a valid input file
     """
     try:
         new_input_file = InputFile(input_filename)
         return self._setInputFile(new_input_file)
     except Exception as e:
         mooseutils.mooseWarning("setInputFile exception: %s" % e)
         return False
Beispiel #10
0
 def writeInputFile(self, filename):
     """
     Write the input tree to a file.
     Input:
         filename: Where to write the file.
     """
     if not self.tree.app_info.valid() or not filename:
         return
     content = self.tree.getInputFileString()
     try:
         with open(filename, "w") as f:
             f.write(content)
     except IOError as e:
         mooseutils.mooseWarning("Failed to write input file %s: %s" % (filename, e))
Beispiel #11
0
    def __init__(self, *args, **kwargs):

        # Stored the supplied values
        # NOTE: The default and value are private to keep them from the type checking being
        # nullified if the values are just set directly.
        if len(args) == 2:
            self.name = args[0]
            self.__value = None
            self.doc = args[1]
            self.__default = None
        elif len(args) == 3:
            self.name = args[0]
            self.__value = args[1]
            self.doc = args[2]
            self.__default = self.__value
        else:
            raise Exception(
                "Wrong number of arguments, must supply 2 or 3 input arguments."
            )

        # Extract optional settings
        self.vtype = kwargs.pop('vtype', type(self.__value))
        self.allow = kwargs.pop('allow', [])

        # Check that allow is correct type
        if not isinstance(self.allow, list):
            mooseutils.mooseWarning(
                'The allow option must be supplied as a list.')

        # Check the allowed list contains the correct types
        else:
            for i in range(len(self.allow)):
                try:
                    if not isinstance(self.allow[i],
                                      self.vtype) and self.vtype != Option.ANY:
                        self.allow[i] = eval('{}({})'.format(
                            self.vtype.__name__, str(self.allow[i])))

                except:  #pylint: disable=bare-except
                    msg = 'The type provided, {}, does not match the type of the allowed ' + \
                          'values, {} for the {} option.'
                    mooseutils.mooseWarning(
                        msg.format(self.vtype.__name__,
                                   type(self.allow[i]).__name__, self.name))
                    return

        # Try to set the value using the set method to test the type and if it is allowed
        if (self.__value != None) and not isinstance(self.__value, Options):
            self.set(self.__value)
Beispiel #12
0
 def setInputFileData(self, input_str, filename="String"):
     """
     Set a new input file based on a existing string
     Input:
         input_str[str]: The input file data to parse
     Return:
         bool: If it was a valid input file
     """
     try:
         new_input_file = InputFile()
         new_input_file.readInputData(input_str, filename)
         return self._setInputFile(new_input_file)
     except Exception as e:
         mooseutils.mooseWarning("setInputFileData exception: %s" % e)
         return False
Beispiel #13
0
 def setInputFileData(self, input_str, filename="String"):
     """
     Set a new input file based on a existing string
     Input:
         input_str[str]: The input file data to parse
     Return:
         bool: If it was a valid input file
     """
     try:
         new_input_file = InputFile()
         new_input_file.readInputData(input_str, filename)
         return self._setInputFile(new_input_file)
     except Exception as e:
         mooseutils.mooseWarning("setInputFileData exception: %s" % e)
         return False
Beispiel #14
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
    def _addInputFileNode(self, input_node):
        """
        This adds a node from the input file.
        Input:
            input_node[GPNode]: The node from the input file.
        """
        path = input_node.fullName(no_root=True)
        entry = self.path_map.get(path)
        if not entry:
            parent_path = os.path.dirname(path)
            name = os.path.basename(path)
            entry = self.addUserBlock(parent_path, name)
            if not entry:
                mooseutils.mooseWarning("Could not create %s" % path)
                return

        entry.comments = "\n".join(input_node.comments)
        entry.included = True
        entry.hard = True

        in_type_name = input_node.params.get("type")
        param_info = entry.parameters.get("type")
        if in_type_name and param_info:
            entry.setBlockType(in_type_name)
            param_info.value = in_type_name
            if "type" not in entry.parameters_list:
                entry.parameters_list.insert(0, "type")

        for param_name in input_node.params_list:
            param_value = input_node.params[param_name]
            param_info = self.getParamInfo(path, param_name)
            if not param_info:
                # must be a user added param
                param_info = self.addUserParam(path, param_name, param_value)
            else:
                param_info.value = param_value
            param_info.set_in_input_file = True
            if param_info.name not in param_info.parent.parameters_write_first:
                param_info.parent.parameters_write_first.append(
                    param_info.name)
            param_info.comments = input_node.param_comments.get(param_name, "")

        for child_name in input_node.children_list:
            child_node = input_node.children[child_name]
            self._addInputFileNode(child_node)
            if child_name not in entry.children_write_first:
                entry.children_write_first.append(child_name)
Beispiel #16
0
    def _addInputFileNode(self, input_node):
        """
        This adds a node from the input file.
        Input:
            input_node[GPNode]: The node from the input file.
        """
        path = input_node.fullName(no_root=True)
        entry = self.path_map.get(path)
        if not entry:
            parent_path = os.path.dirname(path)
            name = os.path.basename(path)
            entry = self.addUserBlock(parent_path, name)
            if not entry:
                mooseutils.mooseWarning("Could not create %s" % path)
                return

        entry.comments = "\n".join(input_node.comments)
        entry.included = True
        entry.hard = True

        in_type_name = input_node.params.get("type")
        param_info = entry.parameters.get("type")
        if in_type_name and param_info:
            entry.setBlockType(in_type_name)
            param_info.value = in_type_name
            if "type" not in entry.parameters_list:
                entry.parameters_list.insert(0, "type")

        for param_name in input_node.params_list:
            param_value = input_node.params[param_name]
            param_info = self.getParamInfo(path, param_name)
            if not param_info:
                # must be a user added param
                param_info = self.addUserParam(path, param_name, param_value)
            else:
                param_info.value = param_value
            param_info.set_in_input_file = True
            if param_info.name not in param_info.parent.parameters_write_first:
                param_info.parent.parameters_write_first.append(param_info.name)
            param_info.comments = input_node.param_comments.get(param_name, "")

        for child_name in input_node.children_list:
            child_node = input_node.children[child_name]
            self._addInputFileNode(child_node)
            if child_name not in entry.children_write_first:
                entry.children_write_first.append(child_name)
Beispiel #17
0
    def __setitem__(self, name, value):
        """
        Overload for setting value of an option with [].

        Inputs:
            name[str]: The name of the Option to retrieve
            value: The value to set the option to
            **kwargs: Key, value pairs are passed to the Option object.
        """

        # Check that the option exists
        if not self.hasOption(name):
            mooseutils.mooseWarning('No option with the name:', name)

        # Set option to the given value, type checking occurs in the Option object
        else:
            self.__options[name].set(value)
Beispiel #18
0
    def __setitem__(self, name, value):
        """
        Overload for setting value of an option with [].

        Inputs:
            name[str]: The name of the Option to retrieve
            value: The value to set the option to
            **kwargs: Key, value pairs are passed to the Option object.
        """

        # Check that the option exists
        if not self.hasOption(name):
            mooseutils.mooseWarning('No option with the name:', name)

        # Set option to the given value, type checking occurs in the Option object
        else:
            self.__options[name].set(value)
Beispiel #19
0
 def testMooseMessageWarning(self):
     """
     Test the warning dialog message.
     """
     box = mooseutils.mooseWarning("A message", dialog = True, test = True)
     self.assertIn("A message", box.text())
     self.assertIn("WARNING", box.text())
     self.assertTrue(box.icon() == QtWidgets.QMessageBox.Warning)
Beispiel #20
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
Beispiel #21
0
    def add(self, *args, **kwargs):
        """
        Add a new option to the warehouse

        Inputs:
            name[str]: The name of the option, used to access and set its value
            value: The value to set the property too (i.e., the default value)
            doc[str]: The documentation string

        Optional Key, value Pairs
            vtype: The type of the value
            allowed[list]: The allowed values
        """
        if args[0] in self.__options:
            mooseutils.mooseWarning('A parameter with the name', args[0], 'already exists.')
            return

        self.__options[args[0]] = Option(*args, **kwargs)
Beispiel #22
0
    def add(self, *args, **kwargs):
        """
        Add a new option to the warehouse

        Inputs:
            name[str]: The name of the option, used to access and set its value
            value: The value to set the property too (i.e., the default value)
            doc[str]: The documentation string

        Optional Key, value Pairs
            vtype: The type of the value
            allowed[list]: The allowed values
        """
        if args[0] in self.__options:
            mooseutils.mooseWarning('A parameter with the name', args[0], 'already exists.')
            return

        self.__options[args[0]] = Option(*args, **kwargs)
Beispiel #23
0
 def addUserParam(self, param, value):
     """
     Adds a user parameter.
     Input:
         param[str]: Name of the parameter to add
         value[str]: Initial value of the parameter
     Return:
         ParameterInfo: The new parameter
     """
     pinfo = self.getParamInfo(param)
     if pinfo:
         mooseutils.mooseWarning("Tried to add a user parameter when that name already exists: %s:%s" % (self.path, param))
         return
     pinfo = ParameterInfo(self, param)
     pinfo.user_added = True
     pinfo.value = value
     self.addParameter(pinfo)
     return pinfo
Beispiel #24
0
 def readInputData(self, data, filename):
     try:
         self.filename = os.path.abspath(filename)
         root = hit.parse(os.path.abspath(filename), data)
         hit.explode(root)
         w = DupWalker(os.path.abspath(filename))
         root.walk(w, hit.NodeType.Field)
         if w.errors:
             for err in w.errors:
                 mooseutils.mooseWarning(err)
             raise PeacockException("Parser errors")
         self.original_text = data
         self.root_node = root
         self.changed = False
     except PeacockException as e:
         msg = "Failed to parse input file %s:\n%s\n" % (filename, e)
         mooseutils.mooseWarning(msg)
         raise e
Beispiel #25
0
    def __setValue(self, value, set_default=False):
        """
        Set the value of the option with type checking.

        Inputs:
            set_default[bool]: (default: False) When true the value passed in is also set to the
                               default.
        """

        # None is always allowed
        if value is None:
            self.unset()
            return

        # If the Option is storing another Set of options and is passed a dict(), then
        # loop through the dictionary and update each option in the set of options.
        if (self.vtype is Options) and isinstance(value, dict):
            for k, v in value.items():
                self.__value[k] = v

        else:
            if not isinstance(value, self.vtype):

                # Check if we can convert (e.g., int->float)
                try:
                    value = eval(self.vtype.__name__ + '(' + str(value) + ')')
                except:  #pylint: disable=bare-except
                    msg = '{} must be of type {} but {} provided.'
                    mooseutils.mooseWarning(
                        msg.format(self.name, self.vtype.__name__,
                                   type(value).__name__))
                    value = None

            # Check that the value is allowed
            if self.allow and (value != None) and (value not in self.allow):
                msg = 'Attempting to set {} to a value of {} but only the following are allowed: {}'
                mooseutils.mooseWarning(
                    msg.format(self.name, value, self.allow))
                value = None

            self.__value = value

            if set_default:
                self.__default = value
Beispiel #26
0
    def __init__(self, *args, **kwargs):

        # Stored the supplied values
        # NOTE: The default and value are private to keep them from the type checking being
        # nullified if the values are just set directly.
        if len(args) == 2:
            self.name = args[0]
            self.__value = None
            self.doc = args[1]
            self.__default = None
        elif len(args) == 3:
            self.name = args[0]
            self.__value = args[1]
            self.doc = args[2]
            self.__default = self.__value
        else:
            raise Exception("Wrong number of arguments, must supply 2 or 3 input arguments.")

        # Extract optional settings
        self.vtype = kwargs.pop('vtype', type(self.__value))
        self.allow = kwargs.pop('allow', [])

        # Check that allow is correct type
        if not isinstance(self.allow, list):
            mooseutils.mooseWarning('The allow option must be supplied as a list.')

        # Check the allowed list contains the correct types
        else:
            for i in range(len(self.allow)):
                try:
                    if not isinstance(self.allow[i], self.vtype) and self.vtype != Option.ANY:
                        self.allow[i] = eval('{}({})'.format(self.vtype.__name__,
                                                             str(self.allow[i])))

                except: #pylint: disable=bare-except
                    msg = 'The type provided, {}, does not match the type of the allowed ' + \
                          'values, {} for the {} option.'
                    mooseutils.mooseWarning(msg.format(self.vtype.__name__,
                                                       type(self.allow[i]).__name__, self.name))
                    return

        # Try to set the value using the set method to test the type and if it is allowed
        if (self.__value != None) and not isinstance(self.__value, Options):
            self.set(self.__value)
Beispiel #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())
Beispiel #28
0
    def start(self, timer=None):
        """
        Begin the interactive VTK session.
        """
        if timer:
            msg = "The timer argument is deprecated, please use the 'observers' setting."
            mooseutils.mooseWarning(msg)

        mooseutils.mooseDebug("{}.start()".format(self.__class__.__name__), color='MAGENTA')

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

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

        if self.getOption('style') == 'test':
            self.__vtkwindow.Finalize()
Beispiel #29
0
    def start(self, timer=None):
        """
        Begin the interactive VTK session.
        """
        if timer:
            msg = "The timer argument is deprecated, please use the 'observers' setting."
            mooseutils.mooseWarning(msg)

        mooseutils.mooseDebug("{}.start()".format(self.__class__.__name__), color='MAGENTA')

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

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

        if self.getOption('style') == 'test':
            self.__vtkwindow.Finalize()
Beispiel #30
0
    def _addPlotObject(self, line):
        """
        A helper method for inserting a line, handling color automatically, into the graph.

        Args:
            line[chigger.graph.Line]: The line object to add to this graph.
        """

        # Initialize the line (this creates the vtk object)
        if line.needsInitialize():
            line.initialize()

        # Set the line color, if not set by the user
        if not line.isOptionValid('color'):

            # Colors
            if self._vtkcolorseries is None:
                self._vtkcolorseries = vtk.vtkColorSeries()
                if self.isOptionValid('color_scheme'):
                    scheme = eval('vtk.vtkColorSeries.' +
                                  self.getOption('color_scheme').upper())
                    self._vtkcolorseries.SetColorScheme(scheme)

            n_lines = len(self._plots)
            n_colors = self._vtkcolorseries.GetNumberOfColors()
            if n_lines >= n_colors:
                mooseutils.mooseWarning(
                    'The number of lines exceeds the number of available '
                    'line colors.')

            c = self._vtkcolorseries.GetColorRepeating(n_lines)
            b = self.getOption('background')

            # If the color matches the background, flip it
            if (c[0] == b[0]) and (c[1] == b[1]) and (c[2] == c[2]):
                c[0] = 1 - c[0]
                c[1] = 1 - c[1]
                c[2] = 1 - c[2]

            line.setOption('color', c)

        self._plots.append(line)
Beispiel #31
0
    def __setValue(self, value, set_default=False):
        """
        Set the value of the option with type checking.

        Inputs:
            set_default[bool]: (default: False) When true the value passed in is also set to the
                               default.
        """

        # None is always allowed
        if value is None:
            self.unset()
            return

        # If the Option is storing another Set of options and is passed a dict(), then
        # loop through the dictionary and update each option in the set of options.
        if (self.vtype is Options) and isinstance(value, dict):
            for k, v in value.iteritems():
                self.__value[k] = v

        else:
            if not isinstance(value, self.vtype):

                # Check if we can convert (e.g., int->float)
                try:
                    value = eval(self.vtype.__name__ + '(' + str(value) +')')
                except: #pylint: disable=bare-except
                    msg = '{} must be of type {} but {} provided.'
                    mooseutils.mooseWarning(msg.format(self.name, self.vtype.__name__,
                                                       type(value).__name__))
                    value = None

            # Check that the value is allowed
            if self.allow and (value != None) and (value not in self.allow):
                msg = 'Attempting to set {} to a value of {} but only the following are allowed: {}'
                mooseutils.mooseWarning(msg.format(self.name, value, self.allow))
                value = None

            self.__value = value

            if set_default:
                self.__default = value
Beispiel #32
0
def runExe(app_path, args, print_errors=True):
    """
    Convience function to run a executable with arguments and return the output
    Input:
        app_path: str: Path to the excutable
        args: either str or list: Arguments to pass to the executable
    Return:
        str: output of running the command
    Exceptions:
        FileExistsException: If there was a problem running the executable
        BadExecutableException: If the executable didn't exit cleanly
    """
    popen_args = [str(app_path)]
    if isinstance(args, str):
        popen_args.append(args)
    else:
        popen_args.extend(args)

    proc = None
    try:
        proc = subprocess.Popen(popen_args,
                                stdout=subprocess.PIPE,
                                stderr=subprocess.STDOUT)
    except OSError as e:
        msg = "Problem running '%s'" % ' '.join(popen_args)
        if print_errors:
            mooseutils.mooseWarning(msg)
        msg += "\nError: %s" % e
        raise FileExistsException(msg)

    data = proc.communicate()
    stdout_data = data[0].decode("utf-8")
    if proc.returncode != 0:
        msg = "'%s' exited with non zero status %s.\n\n"\
                "Please make sure your application is built and able to execute the given arguments.\n"\
                "Working dir: %s\n"\
                "Output: %s" % (' '.join(popen_args), proc.returncode, os.getcwd(), stdout_data)
        if print_errors:
            mooseutils.mooseWarning(msg)
        raise BadExecutableException(msg)
    return stdout_data
Beispiel #33
0
    def renameChildBlock(self, oldname, newname):
        """
        Rename one of the children
        Input:
            oldname[str]: Current name of the child
            newname[str]: New name of the child
        """
        tmp_child = self.children.get(newname)
        if tmp_child:
            mooseutils.mooseWarning("Tried to rename %s to %s but %s already exists." % (oldname, newname, newname))
            return

        child = self.children.get(oldname)
        if child:
            del self.children[oldname]
            self.children[newname] = child
            idx = self.children_list.index(oldname)
            self.children_list.remove(oldname)
            self.children_list.insert(idx, newname)
            child.name = newname
            child.updatePaths()
Beispiel #34
0
    def _addPlotObject(self, line):
        """
        A helper method for inserting a line, handling color automatically, into the graph.

        Args:
            line[chigger.graph.Line]: The line object to add to this graph.
        """

        # Initialize the line (this creates the vtk object)
        if line.needsInitialize():
            line.initialize()

        # Set the line color, if not set by the user
        if not line.isOptionValid('color'):

            # Colors
            if self._vtkcolorseries is None:
                self._vtkcolorseries = vtk.vtkColorSeries()
                if self.isOptionValid('color_scheme'):
                    scheme = eval('vtk.vtkColorSeries.' + self.getOption('color_scheme').upper())
                    self._vtkcolorseries.SetColorScheme(scheme)

            n_lines = len(self._plots)
            n_colors = self._vtkcolorseries.GetNumberOfColors()
            if n_lines >= n_colors:
                mooseutils.mooseWarning('The number of lines exceeds the number of available '
                                        'line colors.')

            c = self._vtkcolorseries.GetColorRepeating(n_lines)
            b = self.getOption('background')

            # If the color matches the background, flip it
            if (c[0] == b[0]) and (c[1] == b[1]) and (c[2] == c[2]):
                c[0] = 1 - c[0]
                c[1] = 1 - c[1]
                c[2] = 1 - c[2]

            line.setOption('color', c)

        self._plots.append(line)
Beispiel #35
0
def runExe(app_path, args, print_errors=True):
    """
    Convience function to run a executable with arguments and return the output
    Input:
        app_path: str: Path to the excutable
        args: either str or list: Arguments to pass to the executable
    Return:
        str: output of running the command
    Exceptions:
        FileExistsException: If there was a problem running the executable
        BadExecutableException: If the executable didn't exit cleanly
    """
    popen_args = [str(app_path)]
    if isinstance(args, str):
        popen_args.append(args)
    else:
        popen_args.extend(args)

    proc = None
    try:
        proc = subprocess.Popen(popen_args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    except OSError as e:
        msg = "Problem running '%s'" % ' '.join(popen_args)
        if print_errors:
            mooseutils.mooseWarning(msg)
        msg += "\nError: %s" % e
        raise FileExistsException(msg)

    data = proc.communicate()
    stdout_data = data[0].decode("utf-8")
    if proc.returncode != 0:
        msg = "'%s' exited with non zero status %s.\n\n"\
                "Please make sure your application is built and able to execute the given arguments.\n"\
                "Working dir: %s\n"\
                "Output: %s" % (' '.join(popen_args), proc.returncode, os.getcwd(), stdout_data)
        if print_errors:
            mooseutils.mooseWarning(msg)
        raise BadExecutableException(msg)
    return stdout_data
Beispiel #36
0
    def update(self, **kwargs):
        """
        Computes the contour levels for the vtkContourFilter.
        """
        super(TubeFilter, self).update(**kwargs)

        if self.isOptionValid('radius'):
            self._vtkfilter.SetRadius(self.getOption('radius'))

        if self.isOptionValid('normalized_radius'):
            if self.isOptionValid('radius'):
                mooseutils.mooseWarning("The 'radius' and 'normalized_radius' options are both "
                                        "set, the 'radius is being used.'")
            else:
                self._vtkfilter.SetRadius(utils.compute_distance(self._source) *
                                          self.getOption('normalized_radius'))

        if self.isOptionValid('sides'):
            self._vtkfilter.SetNumberOfSides(self.getOption('sides'))

        if self.isOptionValid('caps'):
            self._vtkfilter.SetCapping(self.getOption('caps'))
Beispiel #37
0
    def update(self, options=None, **kwargs):
        """"
        Update the options given key, value pairs

        To enable unused warning, include 'warn_unused=True'
        """

        # Unused options
        changed = False
        unused = set()
        warn = kwargs.pop('warn_unused', False)

        # Update from Options object
        if isinstance(options, Options):
            for key in options.keys():
                if self.hasOption(key):
                    if options.isOptionValid(key):
                        changed = True
                        self[key] = options[key]
                else:
                    unused.add(key)

        # Update from kwargs
        for k, v in kwargs.iteritems():
            if k in self.__options:
                changed = True
                self[k] = v
            else:
                unused.add(k)

        # Warning for unused @todo warning
        if warn and len(unused) > 0:
            msg = 'The following settings where not recognized:'
            for key in unused:
                msg += ' '*4 + key
            mooseutils.mooseWarning(msg)

        return changed
Beispiel #38
0
    def update(self, options=None, **kwargs):
        """"
        Update the options given key, value pairs

        To enable unused warning, include 'warn_unused=True'
        """

        # Unused options
        changed = False
        unused = set()
        warn = kwargs.pop('warn_unused', False)

        # Update from Options object
        if isinstance(options, Options):
            for key in options.keys():
                if self.hasOption(key):
                    if options.isOptionValid(key):
                        changed = True
                        self[key] = options[key]
                else:
                    unused.add(key)

        # Update from kwargs
        for k, v in kwargs.items():
            if k in self.__options:
                changed = True
                self[k] = v
            else:
                unused.add(k)

        # Warning for unused @todo warning
        if warn and len(unused) > 0:
            msg = 'The following settings where not recognized:'
            for key in unused:
                msg += ' ' * 4 + key
            mooseutils.mooseWarning(msg)

        return changed
Beispiel #39
0
    def incompatibleChanges(self, app_info):
        """
        Tries to detect if there are any incompatible changes
        in the syntax with the current working input file.
        Input:
            app_info[ExecutableInfo]: The executable info to compare against
        Return:
            bool: True if errors occurred loading the current input file with the new syntax
        """

        if not self.app_info.json_data:
            return False
        if self.app_info.json_data and not app_info.json_data:
            return True

        try:
            old_input = self.getInputFileString()
            new_tree = InputTree(app_info)
            read_data = new_tree.setInputFileData(old_input)
            return not read_data or new_tree.input_has_errors
        except Exception as e:
            mooseutils.mooseWarning("Caught exception: %s" % e)
            return True
Beispiel #40
0
    def incompatibleChanges(self, app_info):
        """
        Tries to detect if there are any incompatible changes
        in the syntax with the current working input file.
        Input:
            app_info[ExecutableInfo]: The executable info to compare against
        Return:
            bool: True if errors occurred loading the current input file with the new syntax
        """

        if not self.app_info.json_data:
            return False
        if self.app_info.json_data and not app_info.json_data:
            return True

        try:
            old_input = self.getInputFileString()
            new_tree = InputTree(app_info)
            read_data = new_tree.setInputFileData(old_input)
            return not read_data or new_tree.input_has_errors
        except Exception as e:
            mooseutils.mooseWarning("Caught exception: %s" % e)
            return True
Beispiel #41
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())
Beispiel #42
0
    def update(self, **kwargs):
        """
        Computes the contour levels for the vtkContourFilter.
        """
        super(TubeFilter, self).update(**kwargs)

        if self.isOptionValid('radius'):
            self._vtkfilter.SetRadius(self.getOption('radius'))

        if self.isOptionValid('normalized_radius'):
            if self.isOptionValid('radius'):
                mooseutils.mooseWarning(
                    "The 'radius' and 'normalized_radius' options are both "
                    "set, the 'radius is being used.'")
            else:
                self._vtkfilter.SetRadius(
                    utils.compute_distance(self._source) *
                    self.getOption('normalized_radius'))

        if self.isOptionValid('sides'):
            self._vtkfilter.SetNumberOfSides(self.getOption('sides'))

        if self.isOptionValid('caps'):
            self._vtkfilter.SetCapping(self.getOption('caps'))
Beispiel #43
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]
Beispiel #44
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]
Beispiel #45
0
def set_options(vtkaxis, opt):
    """
    Set the options for vtkAxis object.
    """

    # Visibility
    vtkaxis.SetTicksVisible(opt['ticks_visible'])
    vtkaxis.SetAxisVisible(opt['axis_visible'])
    vtkaxis.SetLabelsVisible(opt['labels_visible'])

    # Opacity
    if opt.isOptionValid('axis_opacity'):
        opacity = opt['axis_opacity']
        vtkaxis.SetOpacity(opacity)
        vtkaxis.GetTitleProperties().SetOpacity(opacity)
        vtkaxis.GetLabelProperties().SetOpacity(opacity)

    # Ticks
    if opt.isOptionValid('num_ticks'):
        vtkaxis.SetNumberOfTicks(opt['num_ticks'])

    # Limits
    if opt.isOptionValid('lim'):
        lim = opt['lim']
        if abs(lim[1] - lim[0]) < opt['zero_tol']:
            vtkaxis.SetBehavior(vtk.vtkAxis.CUSTOM)
            vtkaxis.SetRange(0, 1)

            pos = vtk.vtkDoubleArray()
            pos.SetNumberOfTuples(2)
            pos.SetValue(0, 0)
            pos.SetValue(1, 1)

            labels = vtk.vtkStringArray()
            labels.SetNumberOfTuples(2)
            labels.SetValue(0, str(lim[0]))
            labels.SetValue(1, str(lim[1]))

            vtkaxis.SetCustomTickPositions(pos, labels)
        else:
            vtkaxis.SetCustomTickPositions(None, None)
            vtkaxis.SetBehavior(vtk.vtkAxis.FIXED)
            scale = opt['axis_scale']
            factor = opt['axis_factor']
            vtkaxis.SetRange(lim[0] * scale + factor, lim[1] * scale + factor)
            vtkaxis.RecalculateTickSpacing()
    else:
        vtkaxis.SetBehavior(vtk.vtkAxis.AUTO)
        vtkaxis.SetCustomTickPositions(None, None)

    # Color
    if opt.isOptionValid('font_color'):
        clr = opt['font_color']
        vtkaxis.GetTitleProperties().SetColor(*clr)
        vtkaxis.GetLabelProperties().SetColor(*clr)
        vtkaxis.GetPen().SetColorF(*clr)

    # Axis title
    if opt.isOptionValid('title'):
        vtkaxis.SetTitle(opt['title'])

    # Font sizes
    if opt.isOptionValid('font_size'):
        vtkaxis.GetTitleProperties().SetFontSize(opt['font_size'])
        vtkaxis.GetLabelProperties().SetFontSize(opt['font_size'])

    if opt.isOptionValid('title_font_size'):
        vtkaxis.GetTitleProperties().SetFontSize(opt['title_font_size'])
    if opt.isOptionValid('tick_font_size'):
        vtkaxis.GetLabelProperties().SetFontSize(opt['tick_font_size'])

    # Precision/notation
    if opt.isOptionValid('notation'):
        notation = opt['notation'].upper()
        vtk_notation = getattr(vtk.vtkAxis, notation + '_NOTATION')
        vtkaxis.SetNotation(vtk_notation)

    if opt.isOptionValid('precision'):
        if vtkaxis.GetNotation() in VTK_NOTATION_ENUM[1:3]:
            vtkaxis.SetPrecision(opt['precision'])
        else:
            mooseutils.mooseWarning("When using 'precision' option, 'notation' option has to be "
                                    "set to either 'scientific' or 'fixed'.")

    # Grid lines
    vtkaxis.SetGridVisible(opt['grid'])
    vtkaxis.GetGridPen().SetColorF(opt['grid_color'])

    # Set the position and points
    if opt.isOptionValid('axis_position'):
        pos = {'left':vtk.vtkAxis.LEFT, 'right':vtk.vtkAxis.RIGHT, 'top':vtk.vtkAxis.TOP,
               'bottom':vtk.vtkAxis.BOTTOM}
        vtkaxis.SetPosition(pos[opt['axis_position']])

    if opt.isOptionValid('axis_point1'):
        vtkaxis.SetPoint1(*opt['axis_point1'])

    if opt.isOptionValid('axis_point2'):
        vtkaxis.SetPoint2(*opt['axis_point2'])
Beispiel #46
0
def set_options(vtkaxis, opt):
    """
    Set the options for vtkAxis object.
    """

    # Visibility
    vtkaxis.SetTicksVisible(opt['ticks_visible'])
    vtkaxis.SetAxisVisible(opt['axis_visible'])
    vtkaxis.SetLabelsVisible(opt['labels_visible'])

    # Opacity
    if opt.isOptionValid('axis_opacity'):
        opacity = opt['axis_opacity']
        vtkaxis.SetOpacity(opacity)
        vtkaxis.GetTitleProperties().SetOpacity(opacity)
        vtkaxis.GetLabelProperties().SetOpacity(opacity)

    # Ticks
    if opt.isOptionValid('num_ticks'):
        vtkaxis.SetNumberOfTicks(opt['num_ticks'])

    # Limits
    if opt.isOptionValid('lim'):
        lim = opt['lim']
        if abs(lim[1] - lim[0]) < opt['zero_tol']:
            vtkaxis.SetBehavior(vtk.vtkAxis.CUSTOM)
            vtkaxis.SetRange(0, 1)

            pos = vtk.vtkDoubleArray()
            pos.SetNumberOfTuples(2)
            pos.SetValue(0, 0)
            pos.SetValue(1, 1)

            labels = vtk.vtkStringArray()
            labels.SetNumberOfTuples(2)
            labels.SetValue(0, str(lim[0]))
            labels.SetValue(1, str(lim[1]))

            vtkaxis.SetCustomTickPositions(pos, labels)
        else:
            vtkaxis.SetCustomTickPositions(None, None)
            vtkaxis.SetBehavior(vtk.vtkAxis.FIXED)
            scale = opt['axis_scale']
            factor = opt['axis_factor']
            vtkaxis.SetRange(lim[0] * scale + factor, lim[1] * scale + factor)
            vtkaxis.RecalculateTickSpacing()
    else:
        vtkaxis.SetBehavior(vtk.vtkAxis.AUTO)
        vtkaxis.SetCustomTickPositions(None, None)

    # Color
    if opt.isOptionValid('font_color'):
        clr = opt['font_color']
        vtkaxis.GetTitleProperties().SetColor(*clr)
        vtkaxis.GetLabelProperties().SetColor(*clr)
        vtkaxis.GetPen().SetColorF(*clr)

    # Axis title
    if opt.isOptionValid('title'):
        vtkaxis.SetTitle(opt['title'])

    # Font sizes
    if opt.isOptionValid('font_size'):
        vtkaxis.GetTitleProperties().SetFontSize(opt['font_size'])
        vtkaxis.GetLabelProperties().SetFontSize(opt['font_size'])

    if opt.isOptionValid('title_font_size'):
        vtkaxis.GetTitleProperties().SetFontSize(opt['title_font_size'])
    if opt.isOptionValid('tick_font_size'):
        vtkaxis.GetLabelProperties().SetFontSize(opt['tick_font_size'])

    # Precision/notation
    if opt.isOptionValid('notation'):
        notation = opt['notation'].upper()
        vtk_notation = getattr(vtk.vtkAxis, notation + '_NOTATION')
        vtkaxis.SetNotation(vtk_notation)

    if opt.isOptionValid('precision'):
        if vtkaxis.GetNotation() in VTK_NOTATION_ENUM[1:2]:
            vtkaxis.SetPrecision(opt['precision'])
        else:
            mooseutils.mooseWarning(
                "When using 'precision' option, 'notation' option has to be "
                "set to either 'scientific' or 'fixed'.")

    # Grid lines
    vtkaxis.SetGridVisible(opt['grid'])
    vtkaxis.GetGridPen().SetColorF(opt['grid_color'])

    # Set the position and points
    if opt.isOptionValid('axis_position'):
        pos = {
            'left': vtk.vtkAxis.LEFT,
            'right': vtk.vtkAxis.RIGHT,
            'top': vtk.vtkAxis.TOP,
            'bottom': vtk.vtkAxis.BOTTOM
        }
        vtkaxis.SetPosition(pos[opt['axis_position']])

    if opt.isOptionValid('axis_point1'):
        vtkaxis.SetPoint1(*opt['axis_point1'])

    if opt.isOptionValid('axis_point2'):
        vtkaxis.SetPoint2(*opt['axis_point2'])