예제 #1
0
    def _ImportModelPart(self, model_part, model_part_import_settings):
        """This function imports the ModelPart
        """
        self.print_on_rank_zero("::[PythonSolver]::", "Reading model part.")
        input_type = model_part_import_settings["input_type"].GetString()

        if (input_type == "mdpa"):
            problem_path = os.getcwd()
            input_filename = model_part_import_settings["input_filename"].GetString()
            import_flags = KratosMultiphysics.ModelPartIO.READ
            if model_part_import_settings.Has("ignore_variables_not_in_solution_step_data"):
                if model_part_import_settings["ignore_variables_not_in_solution_step_data"].GetBool():
                    import_flags = KratosMultiphysics.ModelPartIO.IGNORE_VARIABLES_ERROR|KratosMultiphysics.ModelPartIO.READ

            # Import model part from mdpa file.
            self.print_on_rank_zero("::[PythonSolver]::", "Reading model part from file: " + os.path.join(problem_path, input_filename) + ".mdpa")
            KratosMultiphysics.ModelPartIO(input_filename, import_flags).ReadModelPart(model_part)
            if (model_part_import_settings.Has("reorder") and model_part_import_settings["reorder"].GetBool()):
                tmp = KratosMultiphysics.Parameters("{}")
                KratosMultiphysics.ReorderAndOptimizeModelPartProcess(model_part, tmp).Execute()
            self.print_on_rank_zero("::[PythonSolver]::", "Finished reading model part from mdpa file.")
        elif (input_type == "rest"):
            self.print_on_rank_zero("::[PythonSolver]::", "Loading model part from restart file.")
            from restart_utility import RestartUtility
            RestartUtility(model_part, self._GetRestartSettings(model_part_import_settings)).LoadRestart()
            self.print_on_rank_zero("::[PythonSolver]::", "Finished loading model part from restart file.")
        elif(input_type == "use_input_model_part"):
            pass
        else:
            raise Exception("Other model part input options are not yet implemented.")
        self.print_on_rank_zero("ModelPart", model_part)
        self.print_on_rank_zero("::[PythonSolver]:: ", "Finished reading model part.")
예제 #2
0
    def _SetUpRestart(self):
        """Initialize self.restart_utility as a RestartUtility instance and check if we need to initialize the problem from a restart file."""
        if self.project_parameters.Has("restart_settings"):
            restart_settings = self.project_parameters["restart_settings"]
            self.load_restart = restart_settings["load_restart"].GetBool()
            self.save_restart = restart_settings["save_restart"].GetBool()
            restart_settings.RemoveValue("load_restart")
            restart_settings.RemoveValue("save_restart")
            restart_settings.AddValue(
                "input_filename",
                self.project_parameters["problem_data"]["problem_name"])
            restart_settings.AddValue(
                "echo_level",
                self.project_parameters["problem_data"]["echo_level"])

            if self.parallel_type == "OpenMP":
                from restart_utility import RestartUtility as Restart
            elif self.parallel_type == "MPI":
                from trilinos_restart_utility import TrilinosRestartUtility as Restart

            self.restart_utility = Restart(
                self.main_model_part,
                self.project_parameters["restart_settings"])
        else:
            self.load_restart = False
            self.save_restart = False
예제 #3
0
    def _ImportModelPart(self, model_part, model_part_import_settings):
        """This function imports the ModelPart
        """
        KratosMultiphysics.Logger.PrintInfo("::[PythonSolver]::", "Reading model part.")
        problem_path = os.getcwd()
        input_filename = model_part_import_settings["input_filename"].GetString()
        input_type = model_part_import_settings["input_type"].GetString()

        if (input_type == "mdpa"):
            # Import model part from mdpa file.
            KratosMultiphysics.Logger.PrintInfo("::[PythonSolver]::", "Reading model part from file: " + os.path.join(problem_path, input_filename) + ".mdpa")
            KratosMultiphysics.ModelPartIO(input_filename).ReadModelPart(model_part)
            if (model_part_import_settings.Has("reorder") and model_part_import_settings["reorder"].GetBool()):
                tmp = KratosMultiphysics.Parameters("{}")
                KratosMultiphysics.ReorderAndOptimizeModelPartProcess(model_part, tmp).Execute()
            KratosMultiphysics.Logger.PrintInfo("::[PythonSolver]::", "Finished reading model part from mdpa file.")
        elif (input_type == "rest"):
            KratosMultiphysics.Logger.PrintInfo("::[PythonSolver]::", "Loading model part from restart file.")
            from restart_utility import RestartUtility
            RestartUtility(model_part, self._GetRestartSettings(model_part_import_settings)).LoadRestart()
            KratosMultiphysics.Logger.PrintInfo("::[PythonSolver]::", "Finished loading model part from restart file.")
        else:
            raise Exception("Other model part input options are not yet implemented.")
        KratosMultiphysics.Logger.PrintInfo("ModelPart", model_part)
        KratosMultiphysics.Logger.PrintInfo("::[PythonSolver]:: ", "Finished reading model part.")
예제 #4
0
    def _ImportModelPart(self, model_part, model_part_import_settings):
        """This function imports the ModelPart
        """
        KratosMultiphysics.Logger.PrintInfo("::[PythonSolver]::",
                                            "Reading model part.")
        input_type = model_part_import_settings["input_type"].GetString()

        if (input_type == "mdpa"):
            problem_path = os.getcwd()
            input_filename = model_part_import_settings[
                "input_filename"].GetString()

            # Setting some mdpa-import-related flags
            import_flags = KratosMultiphysics.ModelPartIO.READ
            if model_part_import_settings.Has(
                    "ignore_variables_not_in_solution_step_data"):
                if model_part_import_settings[
                        "ignore_variables_not_in_solution_step_data"].GetBool(
                        ):
                    import_flags = KratosMultiphysics.ModelPartIO.IGNORE_VARIABLES_ERROR | import_flags
            skip_timer = True
            if model_part_import_settings.Has("skip_timer"):
                skip_timer = model_part_import_settings["skip_timer"].GetBool()
            if skip_timer:
                import_flags = KratosMultiphysics.ModelPartIO.SKIP_TIMER | import_flags

            # Import model part from mdpa file.
            KratosMultiphysics.Logger.PrintInfo(
                "::[PythonSolver]::", "Reading model part from file: " +
                os.path.join(problem_path, input_filename) + ".mdpa")
            if (model_part_import_settings.Has("reorder_consecutive")
                    and model_part_import_settings["reorder_consecutive"].
                    GetBool()):
                KratosMultiphysics.ReorderConsecutiveModelPartIO(
                    input_filename, import_flags).ReadModelPart(model_part)
            else:
                KratosMultiphysics.ModelPartIO(
                    input_filename, import_flags).ReadModelPart(model_part)

            if (model_part_import_settings.Has("reorder")
                    and model_part_import_settings["reorder"].GetBool()):
                tmp = KratosMultiphysics.Parameters("{}")
                KratosMultiphysics.ReorderAndOptimizeModelPartProcess(
                    model_part, tmp).Execute()
            KratosMultiphysics.Logger.PrintInfo(
                "::[PythonSolver]::",
                "Finished reading model part from mdpa file.")

        elif (input_type == "rest"):
            KratosMultiphysics.Logger.PrintInfo(
                "::[PythonSolver]::", "Loading model part from restart file.")
            from restart_utility import RestartUtility
            RestartUtility(
                model_part, self._GetRestartSettings(
                    model_part_import_settings)).LoadRestart()
            KratosMultiphysics.Logger.PrintInfo(
                "::[PythonSolver]::",
                "Finished loading model part from restart file.")

        elif (input_type == "use_input_model_part"):
            KratosMultiphysics.Logger.PrintInfo(
                "::[PythonSolver]::",
                "Using already imported model part - no reading necessary.")

        else:
            raise Exception(
                "Other model part input options are not yet implemented.")

        KratosMultiphysics.Logger.PrintInfo("ModelPart", model_part)
        KratosMultiphysics.Logger.PrintInfo("::[PythonSolver]:: ",
                                            "Finished reading model part.")
예제 #5
0
class FluidDynamicsAnalysis(object):
    '''Main script for fluid dynamics simulations using the navier_stokes family of python solvers.'''
    def __init__(self, parameters):
        super(FluidDynamicsAnalysis, self).__init__()

        self.project_parameters = parameters

        self.echo_level = self.project_parameters["problem_data"][
            "echo_level"].GetInt()
        self.parallel_type = self.project_parameters["problem_data"][
            "parallel_type"].GetString()

        # If this is an MPI run, load the distributed memory modules
        if (self.parallel_type == "MPI"):
            from KratosMultiphysics.mpi import mpi
            import KratosMultiphysics.MetisApplication
            import KratosMultiphysics.TrilinosApplication
            self.is_printing_rank = (mpi.rank == 0)
        else:
            self.is_printing_rank = True

    def SetUpModel(self):
        '''Initialize the model part for the problem and other general model data.'''

        model_part_name = self.project_parameters["problem_data"][
            "model_part_name"].GetString()
        self.main_model_part = Kratos.ModelPart(model_part_name)

        domain_size = self.project_parameters["problem_data"][
            "domain_size"].GetInt()
        self.main_model_part.ProcessInfo.SetValue(Kratos.DOMAIN_SIZE,
                                                  domain_size)

        ## Solver construction
        import python_solvers_wrapper_fluid
        self.solver = python_solvers_wrapper_fluid.CreateSolver(
            self.main_model_part, self.project_parameters)

        self._SetUpRestart()

        if self.load_restart:
            self.restart_utility.LoadRestart()
        else:
            self.solver.AddVariables()
            self.solver.ImportModelPart()
            self.solver.AddDofs()

        # Fill a Model instance using input
        self.model = Kratos.Model()
        self.model.AddModelPart(self.main_model_part)

    def SetUpAuxiliaryProcesses(self):
        '''
        Read the definition of initial and boundary conditions for the problem and initialize the processes that will manage them.
        Also initialize any additional processes present in the problem (such as those used to calculate additional results).
        '''
        from process_factory import KratosProcessFactory
        factory = KratosProcessFactory(self.model)
        # The list of processes will contain a list with each individual process already constructed (boundary conditions, initial conditions and gravity)
        # Note 1: gravity is constructed first. Outlet process might need its information.
        # Note 2: initial conditions are constructed before BCs. Otherwise, they may overwrite the BCs information.
        self.simulation_processes = factory.ConstructListOfProcesses(
            self.project_parameters["gravity"])
        self.simulation_processes += factory.ConstructListOfProcesses(
            self.project_parameters["initial_conditions_process_list"])
        self.simulation_processes += factory.ConstructListOfProcesses(
            self.project_parameters["boundary_conditions_process_list"])
        self.simulation_processes += factory.ConstructListOfProcesses(
            self.project_parameters["auxiliar_process_list"])

    def SetUpAnalysis(self):
        '''
        Initialize the Python solver and its auxiliary tools and processes.
        This function should prepare everything so that the simulation
        can start immediately after exiting it.
        '''

        for process in self.simulation_processes:
            process.ExecuteInitialize()

        self.solver.Initialize()

        #TODO this should be generic
        # initialize GiD  I/O
        self._SetUpGiDOutput()

        ## Writing the full ProjectParameters file before solving
        if self.is_printing_rank and self.echo_level > 1:
            with open("ProjectParametersOutput.json",
                      'w') as parameter_output_file:
                parameter_output_file.write(
                    self.project_parameters.PrettyPrintJsonString())

        ## Stepping and time settings
        self.end_time = self.project_parameters["problem_data"][
            "end_time"].GetDouble()

        if self.main_model_part.ProcessInfo[Kratos.IS_RESTARTED]:
            self.time = self.main_model_part.ProcessInfo[Kratos.TIME]
            self.step = self.main_model_part.ProcessInfo[Kratos.STEP]
        else:
            self.time = 0.0
            self.step = 0

        for process in self.simulation_processes:
            process.ExecuteBeforeSolutionLoop()

        if self.have_output:
            self.output.ExecuteBeforeSolutionLoop()

    def _SetUpGiDOutput(self):
        '''Initialize self.output as a GiD output instance.'''
        self.have_output = self.project_parameters.Has("output_configuration")
        if self.have_output:
            if self.parallel_type == "OpenMP":
                from gid_output_process import GiDOutputProcess as OutputProcess
            elif self.parallel_type == "MPI":
                from gid_output_process_mpi import GiDOutputProcessMPI as OutputProcess

            self.output = OutputProcess(
                self.solver.GetComputingModelPart(),
                self.project_parameters["problem_data"]
                ["problem_name"].GetString(),
                self.project_parameters["output_configuration"])

            self.output.ExecuteInitialize()

    def _SetUpRestart(self):
        """Initialize self.restart_utility as a RestartUtility instance and check if we need to initialize the problem from a restart file."""
        if self.project_parameters.Has("restart_settings"):
            restart_settings = self.project_parameters["restart_settings"]
            self.load_restart = restart_settings["load_restart"].GetBool()
            self.save_restart = restart_settings["save_restart"].GetBool()
            restart_settings.RemoveValue("load_restart")
            restart_settings.RemoveValue("save_restart")
            restart_settings.AddValue(
                "input_filename",
                self.project_parameters["problem_data"]["problem_name"])
            restart_settings.AddValue(
                "echo_level",
                self.project_parameters["problem_data"]["echo_level"])

            if self.parallel_type == "OpenMP":
                from restart_utility import RestartUtility as Restart
            elif self.parallel_type == "MPI":
                from trilinos_restart_utility import TrilinosRestartUtility as Restart

            self.restart_utility = Restart(
                self.main_model_part,
                self.project_parameters["restart_settings"])
        else:
            self.load_restart = False
            self.save_restart = False

    def _TimeBufferIsInitialized(self):
        # We always have one extra old step (step 0, read from input)
        return self.step + 1 >= self.solver.GetMinimumBufferSize()

    def RunMainTemporalLoop(self):
        '''The main solution loop.'''
        while self.time <= self.end_time:

            dt = self.solver.ComputeDeltaTime()
            self.time = self.time + dt
            self.step = self.step + 1

            self.main_model_part.CloneTimeStep(self.time)
            self.main_model_part.ProcessInfo[Kratos.STEP] = self.step

            if self.is_printing_rank:
                Kratos.Logger.PrintInfo("Fluid Dynamics Analysis", "STEP = ",
                                        self.step)
                Kratos.Logger.PrintInfo("Fluid Dynamics Analysis", "TIME = ",
                                        self.time)

            self.InitializeSolutionStep()
            self.SolveSingleStep()
            self.FinalizeSolutionStep()

    def InitializeSolutionStep(self):

        for process in self.simulation_processes:
            process.ExecuteInitializeSolutionStep()

        if self.have_output:
            self.output.ExecuteInitializeSolutionStep()

        if self._TimeBufferIsInitialized():
            self.solver.InitializeSolutionStep()

    def SolveSingleStep(self):
        if self._TimeBufferIsInitialized():
            self.solver.SolveSolutionStep()

    def FinalizeSolutionStep(self):

        if self._TimeBufferIsInitialized():
            self.solver.FinalizeSolutionStep()

        # shouldn't this go at the end of the iteration???
        for process in self.simulation_processes:
            process.ExecuteFinalizeSolutionStep()

        if self.have_output:
            self.output.ExecuteFinalizeSolutionStep()

        if self.have_output and self.output.IsOutputStep():

            for process in self.simulation_processes:
                process.ExecuteBeforeOutputStep()

            self.output.PrintOutput()

            for process in self.simulation_processes:
                process.ExecuteAfterOutputStep()

        if self.save_restart:
            self.restart_utility.SaveRestart()

    def FinalizeAnalysis(self):
        '''Finalize the simulation and close open files.'''

        for process in self.simulation_processes:
            process.ExecuteFinalize()

        if self.have_output:
            self.output.ExecuteFinalize()

    def InitializeAnalysis(self):
        '''Wrapper function comprising the definition of the model and the initialization of the problem.'''
        self.SetUpModel()
        self.SetUpAuxiliaryProcesses()
        self.SetUpAnalysis()

    def Run(self):
        '''Wrapper function for the solution.'''
        self.InitializeAnalysis()
        self.RunMainTemporalLoop()
        self.FinalizeAnalysis()