Beispiel #1
0
class kratosCSMAnalyzer((__import__("analyzer_base")).analyzerBaseClass):

    # --------------------------------------------------------------------------
    def __init__(self):

        self.initializeGIDOutput()
        self.initializeProcesses()
        self.initializeSolutionLoop()

    # --------------------------------------------------------------------------
    def initializeProcesses(self):

        import process_factory
        #the process order of execution is important
        self.list_of_processes = process_factory.KratosProcessFactory(
            Model).ConstructListOfProcesses(
                ProjectParameters["constraints_process_list"])
        self.list_of_processes += process_factory.KratosProcessFactory(
            Model).ConstructListOfProcesses(
                ProjectParameters["loads_process_list"])
        if (ProjectParameters.Has("problem_process_list")):
            self.list_of_processes += process_factory.KratosProcessFactory(
                Model).ConstructListOfProcesses(
                    ProjectParameters["problem_process_list"])
        if (ProjectParameters.Has("output_process_list")):
            self.list_of_processes += process_factory.KratosProcessFactory(
                Model).ConstructListOfProcesses(
                    ProjectParameters["output_process_list"])

        #print list of constructed processes
        if (echo_level > 1):
            for process in self.list_of_processes:
                print(process)

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

    # --------------------------------------------------------------------------
    def initializeGIDOutput(self):

        computing_model_part = CSM_solver.GetComputingModelPart()
        problem_name = ProjectParameters["problem_data"][
            "problem_name"].GetString()

        from gid_output_process import GiDOutputProcess
        output_settings = ProjectParameters["output_configuration"]
        self.gid_output = GiDOutputProcess(computing_model_part, problem_name,
                                           output_settings)

        self.gid_output.ExecuteInitialize()

    # --------------------------------------------------------------------------
    def initializeSolutionLoop(self):

        ## Sets strategies, builders, linear solvers, schemes and solving info, and fills the buffer
        CSM_solver.Initialize()
        CSM_solver.SetEchoLevel(echo_level)

        for responseFunctionId in listOfResponseFunctions:
            listOfResponseFunctions[responseFunctionId].Initialize()

        # Start process
        for process in self.list_of_processes:
            process.ExecuteBeforeSolutionLoop()

        ## Set results when are written in a single file
        self.gid_output.ExecuteBeforeSolutionLoop()

    # --------------------------------------------------------------------------
    def analyzeDesignAndReportToCommunicator(self, currentDesign,
                                             optimizationIteration,
                                             communicator):

        # Calculation of value of objective function
        if communicator.isRequestingFunctionValueOf("strain_energy"):

            self.initializeNewSolutionStep(optimizationIteration)

            print("\n> Starting to update the mesh")
            startTime = timer.time()
            self.updateMeshForAnalysis(currentDesign)
            print("> Time needed for updating the mesh = ",
                  round(timer.time() - startTime, 2), "s")

            print(
                "\n> Starting StructuralMechanicsApplication to solve structure"
            )
            startTime = timer.time()
            self.solveStructure(optimizationIteration)
            print("> Time needed for solving the structure = ",
                  round(timer.time() - startTime, 2), "s")

            print("\n> Starting calculation of response value")
            startTime = timer.time()
            listOfResponseFunctions["strain_energy"].CalculateValue()
            print("> Time needed for calculation of response value = ",
                  round(timer.time() - startTime, 2), "s")

            communicator.reportFunctionValue(
                "strain_energy",
                listOfResponseFunctions["strain_energy"].GetValue())

        # Calculation of gradient of objective function
        if communicator.isRequestingGradientOf("strain_energy"):

            print("\n> Starting calculation of gradients")
            startTime = timer.time()
            listOfResponseFunctions["strain_energy"].CalculateGradient()
            print("> Time needed for calculating gradients = ",
                  round(timer.time() - startTime, 2), "s")

            gradientForCompleteModelPart = listOfResponseFunctions[
                "strain_energy"].GetGradient()
            gradientOnDesignSurface = {}
            for node in currentDesign.Nodes:
                gradientOnDesignSurface[
                    node.Id] = gradientForCompleteModelPart[node.Id]

            communicator.reportGradient("strain_energy",
                                        gradientOnDesignSurface)

    # --------------------------------------------------------------------------
    def initializeNewSolutionStep(self, optimizationIteration):
        main_model_part.CloneTimeStep(optimizationIteration)

    # --------------------------------------------------------------------------
    def updateMeshForAnalysis(self, currentDesign):
        for node in currentDesign.Nodes:
            node.X0 = node.X0 + node.GetSolutionStepValue(SHAPE_UPDATE_X)
            node.Y0 = node.Y0 + node.GetSolutionStepValue(SHAPE_UPDATE_Y)
            node.Z0 = node.Z0 + node.GetSolutionStepValue(SHAPE_UPDATE_Z)

    # --------------------------------------------------------------------------
    def solveStructure(self, optimizationIteration):

        # processes to be executed at the begining of the solution step
        for process in self.list_of_processes:
            process.ExecuteInitializeSolutionStep()

        self.gid_output.ExecuteInitializeSolutionStep()

        # Actual solution
        CSM_solver.Solve()

        # processes to be executed at the end of the solution step
        for process in self.list_of_processes:
            process.ExecuteFinalizeSolutionStep()

        # processes to be executed before witting the output
        for process in self.list_of_processes:
            process.ExecuteBeforeOutputStep()

        # write output results GiD: (frequency writing is controlled internally)
        if (self.gid_output.IsOutputStep()):
            self.gid_output.PrintOutput()

        self.gid_output.ExecuteFinalizeSolutionStep()

        # processes to be executed after witting the output
        for process in self.list_of_processes:
            process.ExecuteAfterOutputStep()

    # --------------------------------------------------------------------------
    def finalizeSolutionLoop(self):
        for process in self.list_of_processes:
            process.ExecuteFinalize()
        self.gid_output.ExecuteFinalize()
class Kratos_Execute_Test:
    def __init__(self, ProjectParameters):

        self.ProjectParameters = ProjectParameters

        self.main_model_part = ModelPart(self.ProjectParameters["problem_data"]
                                         ["model_part_name"].GetString())
        self.main_model_part.ProcessInfo.SetValue(
            DOMAIN_SIZE,
            self.ProjectParameters["problem_data"]["domain_size"].GetInt())

        self.Model = {
            self.ProjectParameters["problem_data"]["model_part_name"].GetString(
            ):
            self.main_model_part
        }

        # Construct the solver (main setting methods are located in the solver_module)
        solver_module = __import__(self.ProjectParameters["solver_settings"]
                                   ["solver_type"].GetString())
        self.solver = solver_module.CreateSolver(
            self.main_model_part, self.ProjectParameters["solver_settings"])

        # Add variables (always before importing the model part) (it must be integrated in the ImportModelPart)
        # If we integrate it in the model part we cannot use combined solvers
        self.solver.AddVariables()

        # Read model_part (note: the buffer_size is set here) (restart can be read here)
        self.solver.ImportModelPart()

        # Add dofs (always after importing the model part) (it must be integrated in the ImportModelPart)
        # If we integrate it in the model part we cannot use combined solvers
        self.solver.AddDofs()

        # Build sub_model_parts or submeshes (rearrange parts for the application of custom processes)
        # #Get the list of the submodel part in the object Model
        for i in range(self.ProjectParameters["solver_settings"]
                       ["processes_sub_model_part_list"].size()):
            part_name = self.ProjectParameters["solver_settings"][
                "processes_sub_model_part_list"][i].GetString()
            self.Model.update(
                {part_name: self.main_model_part.GetSubModelPart(part_name)})

        # Obtain the list of the processes to be applied
        self.list_of_processes = process_factory.KratosProcessFactory(
            self.Model).ConstructListOfProcesses(
                self.ProjectParameters["constraints_process_list"])
        self.list_of_processes += process_factory.KratosProcessFactory(
            self.Model).ConstructListOfProcesses(
                self.ProjectParameters["loads_process_list"])
        if (ProjectParameters.Has("list_other_processes") == True):
            self.list_of_processes += process_factory.KratosProcessFactory(
                self.Model).ConstructListOfProcesses(
                    self.ProjectParameters["list_other_processes"])
        if (ProjectParameters.Has("json_check_process") == True):
            self.list_of_processes += process_factory.KratosProcessFactory(
                self.Model).ConstructListOfProcesses(
                    self.ProjectParameters["json_check_process"])
        if (ProjectParameters.Has("check_analytic_results_process") == True):
            self.list_of_processes += process_factory.KratosProcessFactory(
                self.Model).ConstructListOfProcesses(
                    self.ProjectParameters["check_analytic_results_process"])
        if (ProjectParameters.Has("json_output_process") == True):
            self.list_of_processes += process_factory.KratosProcessFactory(
                self.Model).ConstructListOfProcesses(
                    self.ProjectParameters["json_output_process"])

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

        # ### START SOLUTION ####

        self.computing_model_part = self.solver.GetComputingModelPart()

        # ### Output settings start ####
        self.problem_path = os.getcwd()
        self.problem_name = self.ProjectParameters["problem_data"][
            "problem_name"].GetString()

        # ### Output settings start ####
        self.output_post = ProjectParameters.Has("output_configuration")
        if (self.output_post == True):
            from gid_output_process import GiDOutputProcess
            output_settings = ProjectParameters["output_configuration"]
            self.gid_output = GiDOutputProcess(self.computing_model_part,
                                               self.problem_name,
                                               output_settings)
            self.gid_output.ExecuteInitialize()

        # Sets strategies, builders, linear solvers, schemes and solving info, and fills the buffer
        self.solver.Initialize()
        self.solver.SetEchoLevel(0)  # Avoid to print anything

        if (self.output_post == True):
            self.gid_output.ExecuteBeforeSolutionLoop()

    def Solve(self):
        for process in self.list_of_processes:
            process.ExecuteBeforeSolutionLoop()

        # #Stepping and time settings (get from process info or solving info)
        # Delta time
        delta_time = self.ProjectParameters["problem_data"][
            "time_step"].GetDouble()
        # Start step
        self.main_model_part.ProcessInfo[TIME_STEPS] = 0
        # Start time
        time = self.ProjectParameters["problem_data"]["start_time"].GetDouble()
        # End time
        end_time = self.ProjectParameters["problem_data"][
            "end_time"].GetDouble()

        # Solving the problem (time integration)
        while (time <= end_time):
            time = time + delta_time
            self.main_model_part.ProcessInfo[TIME_STEPS] += 1
            self.main_model_part.CloneTimeStep(time)

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

            if (self.output_post == True):
                self.gid_output.ExecuteInitializeSolutionStep()

            self.solver.Solve()

            if (self.output_post == True):
                self.gid_output.ExecuteFinalizeSolutionStep()

            for process in self.list_of_processes:
                process.ExecuteFinalizeSolutionStep()

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

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

            if (self.output_post == True):
                if self.gid_output.IsOutputStep():
                    self.gid_output.PrintOutput()

        if (self.output_post == True):
            self.gid_output.ExecuteFinalize()

        for process in self.list_of_processes:
            process.ExecuteFinalize()
Beispiel #3
0
class FEM_Solution(MainSolidFEM.Solution):
    def Info(self):
        KratosMultiphysics.Logger.PrintInfo(
            "FEM part of the FEMDEM application")

    def KratosPrintInfo(self, message):
        KratosMultiphysics.Logger.Print(message, label="")
        KratosMultiphysics.Logger.Flush()
#============================================================================================================================

    def __init__(self, Model):

        #### TIME MONITORING START ####
        # Time control starts
        self.KratosPrintInfo(timer.ctime())
        # Measure process time
        self.t0p = timer.clock()
        # Measure wall time
        self.t0w = timer.time()
        #### TIME MONITORING END ####

        #### PARSING THE PARAMETERS ####

        # Import input
        parameter_file = open("ProjectParameters.json", 'r')
        self.ProjectParameters = KratosMultiphysics.Parameters(
            parameter_file.read())

        # set echo level
        self.echo_level = self.ProjectParameters["problem_data"][
            "echo_level"].GetInt()

        self.KratosPrintInfo(" ")

        # defining the number of threads:
        num_threads = self.GetParallelSize()
        self.KratosPrintInfo("::[KSM Simulation]:: [OMP USING " +
                             str(num_threads) + " THREADS ]")
        #parallel.PrintOMPInfo()

        #### Model_part settings start ####

        # Defining the model_part
        self.model = Model
        self.model.CreateModelPart(self.ProjectParameters["problem_data"]
                                   ["model_part_name"].GetString())
        self.main_model_part = self.model.GetModelPart(
            self.ProjectParameters["problem_data"]
            ["model_part_name"].GetString())

        if (self.ProjectParameters["solver_settings"]
            ["solution_type"].GetString() == "Dynamic"):
            self.main_model_part.ProcessInfo.SetValue(KratosFemDem.IS_DYNAMIC,
                                                      1)
        else:
            self.main_model_part.ProcessInfo.SetValue(KratosFemDem.IS_DYNAMIC,
                                                      0)

        self.time_step = self.ComputeDeltaTime()
        self.start_time = self.ProjectParameters["problem_data"][
            "start_time"].GetDouble()
        self.end_time = self.ProjectParameters["problem_data"][
            "end_time"].GetDouble()

        self.main_model_part.ProcessInfo.SetValue(
            KratosMultiphysics.DOMAIN_SIZE,
            self.ProjectParameters["problem_data"]["domain_size"].GetInt())
        self.main_model_part.ProcessInfo.SetValue(
            KratosMultiphysics.DELTA_TIME, self.time_step)
        self.main_model_part.ProcessInfo.SetValue(KratosMultiphysics.TIME,
                                                  self.start_time)

        ### replace this "model" for real one once available in kratos core
        self.Model = {
            self.ProjectParameters["problem_data"]["model_part_name"].GetString(
            ):
            self.main_model_part
        }

        #construct the solver (main setting methods are located in the solver_module)
        solver_module = __import__(self.ProjectParameters["solver_settings"]
                                   ["solver_type"].GetString())
        self.solver = solver_module.CreateSolver(
            self.main_model_part, self.ProjectParameters["solver_settings"])

        #### Output settings start ####
        self.problem_path = os.getcwd()
        self.problem_name = self.ProjectParameters["problem_data"][
            "problem_name"].GetString()

#============================================================================================================================

    def AddMaterials(self):

        # Assign material to model_parts (if Materials.json exists)
        import process_factory

        if os.path.isfile("Materials.json"):
            materials_file = open("Materials.json", 'r')
            MaterialParameters = KratosMultiphysics.Parameters(
                materials_file.read())

            if (MaterialParameters.Has("material_models_list")):

                ## Get the list of the model_part's in the object Model
                for i in range(self.ProjectParameters["solver_settings"]
                               ["problem_domain_sub_model_part_list"].size()):
                    part_name = self.ProjectParameters["solver_settings"][
                        "problem_domain_sub_model_part_list"][i].GetString()
                    if (self.main_model_part.HasSubModelPart(part_name)):
                        self.Model.update({
                            part_name:
                            self.main_model_part.GetSubModelPart(part_name)
                        })

                assign_materials_processes = process_factory.KratosProcessFactory(
                    self.Model).ConstructListOfProcesses(
                        MaterialParameters["material_models_list"])
            for process in assign_materials_processes:
                process.Execute()
        else:
            self.KratosPrintInfo(" No Materials.json found ")

#============================================================================================================================

    def AddProcesses(self):

        # Build sub_model_parts or submeshes (rearrange parts for the application of custom processes)
        ## Get the list of the submodel part in the object Model
        for i in range(self.ProjectParameters["solver_settings"]
                       ["processes_sub_model_part_list"].size()):
            part_name = self.ProjectParameters["solver_settings"][
                "processes_sub_model_part_list"][i].GetString()
            if (self.main_model_part.HasSubModelPart(part_name)):
                self.Model.update({
                    part_name:
                    self.main_model_part.GetSubModelPart(part_name)
                })

        # Obtain the list of the processes to be applied
        import process_handler

        process_parameters = KratosMultiphysics.Parameters("{}")
        process_parameters.AddValue(
            "echo_level", self.ProjectParameters["problem_data"]["echo_level"])
        process_parameters.AddValue(
            "constraints_process_list",
            self.ProjectParameters["constraints_process_list"])
        process_parameters.AddValue(
            "loads_process_list", self.ProjectParameters["loads_process_list"])
        if (self.ProjectParameters.Has("problem_process_list")):
            process_parameters.AddValue(
                "problem_process_list",
                self.ProjectParameters["problem_process_list"])
        if (self.ProjectParameters.Has("output_process_list")):
            process_parameters.AddValue(
                "output_process_list",
                self.ProjectParameters["output_process_list"])

        return (process_handler.ProcessHandler(self.Model, process_parameters))

#============================================================================================================================

    def Run(self):

        self.Initialize()
        self.RunMainTemporalLoop()
        self.Finalize()
#============================================================================================================================

    def Initialize(self):

        # Add variables (always before importing the model part)
        self.solver.AddVariables()

        # Read model_part (note: the buffer_size is set here) (restart is read here)
        self.solver.ImportModelPart()

        # Add dofs (always after importing the model part)
        if ((self.main_model_part.ProcessInfo).Has(
                KratosMultiphysics.IS_RESTARTED)):
            if (self.main_model_part.ProcessInfo[
                    KratosMultiphysics.IS_RESTARTED] == False):
                self.solver.AddDofs()
        else:
            self.solver.AddDofs()

        # Add materials (assign material to model_parts if Materials.json exists)
        self.AddMaterials()

        # Add processes
        self.model_processes = self.AddProcesses()
        self.model_processes.ExecuteInitialize()

        # Print model_part and properties
        if (self.echo_level > 1):
            self.KratosPrintInfo("")
            self.KratosPrintInfo(self.main_model_part)
            for properties in self.main_model_part.Properties:
                self.KratosPrintInfo(properties)

        #### START SOLUTION ####
        self.computing_model_part = self.solver.GetComputingModelPart()

        ## Sets strategies, builders, linear solvers, schemes and solving info, and fills the buffer
        self.solver.Initialize()
        self.solver.SetEchoLevel(self.echo_level)

        # Initialize GiD  I/O (gid outputs, file_lists)
        self.SetGraphicalOutput()

        self.GraphicalOutputExecuteInitialize()

        self.model_processes.ExecuteBeforeSolutionLoop()

        self.GraphicalOutputExecuteBeforeSolutionLoop()

        # Set time settings
        self.step = self.main_model_part.ProcessInfo[KratosMultiphysics.STEP]
        self.time = self.main_model_part.ProcessInfo[KratosMultiphysics.TIME]

        self.end_time = self.ProjectParameters["problem_data"][
            "end_time"].GetDouble()
        self.delta_time = self.ProjectParameters["problem_data"][
            "time_step"].GetDouble()

#============================================================================================================================

    def RunMainTemporalLoop(self):

        # Solving the problem (time integration)
        while (self.time < self.end_time):

            self.InitializeSolutionStep()
            self.SolveSolutionStep()
            self.FinalizeSolutionStep()

#============================================================================================================================

    def InitializeSolutionStep(self):

        self.KratosPrintInfo("[STEP: " + str(self.step) + "  --  TIME: " +
                             str(self.time) + "  --  TIME_STEP: " +
                             str(self.delta_time) + "]")

        # processes to be executed at the begining of the solution step
        self.model_processes.ExecuteInitializeSolutionStep()
        self.GraphicalOutputExecuteInitializeSolutionStep()
        self.solver.InitializeSolutionStep()

#============================================================================================================================

    def SolveSolutionStep(self):
        self.clock_time = self.StartTimeMeasuring()
        self.solver.Solve()
        self.StopTimeMeasuring(self.clock_time, "Solving", False)

#============================================================================================================================

    def FinalizeSolutionStep(self):

        self.GraphicalOutputExecuteFinalizeSolutionStep()

        # processes to be executed at the end of the solution step
        self.model_processes.ExecuteFinalizeSolutionStep()

        # processes to be executed before witting the output
        self.model_processes.ExecuteBeforeOutputStep()

        # write output results GiD: (frequency writing is controlled internally)
        self.GraphicalOutputPrintOutput()

        # processes to be executed after witting the output
        self.model_processes.ExecuteAfterOutputStep()

#============================================================================================================================

    def Finalize(self):

        # Ending the problem (time integration finished)
        self.GraphicalOutputExecuteFinalize()
        self.model_processes.ExecuteFinalize()
        self.KratosPrintInfo(" ")
        self.KratosPrintInfo(
            "=================================================")
        self.KratosPrintInfo(
            " - Kratos FemDem Application Calculation End   - ")
        self.KratosPrintInfo(
            "=================================================")
        self.KratosPrintInfo(" ")
        #### END SOLUTION ####
        # Measure process time
        tfp = timer.clock()
        # Measure wall time
        tfw = timer.time()
        KratosMultiphysics.Logger.PrintInfo(
            "::[KSM Simulation]:: [Elapsed Time = %.2f" % (tfw - self.t0w),
            "seconds] (%.2f" % (tfp - self.t0p), "seconds of cpu/s time)")
        KratosMultiphysics.Logger.PrintInfo(timer.ctime())

#============================================================================================================================

    def SetGraphicalOutput(self):
        from gid_output_process import GiDOutputProcess
        self.output_settings = self.ProjectParameters["output_configuration"]
        self.graphical_output = GiDOutputProcess(self.computing_model_part,
                                                 self.problem_name,
                                                 self.output_settings)

    #============================================================================================================================
    def GraphicalOutputExecuteInitialize(self):
        self.graphical_output.ExecuteInitialize()

    #============================================================================================================================
    def GraphicalOutputExecuteBeforeSolutionLoop(self):
        # writing a initial state results file or single file (if no restart)
        if ((self.main_model_part.ProcessInfo).Has(
                KratosMultiphysics.IS_RESTARTED)):
            if (self.main_model_part.ProcessInfo[
                    KratosMultiphysics.IS_RESTARTED] == False):
                self.graphical_output.ExecuteBeforeSolutionLoop()

    #============================================================================================================================
    def GraphicalOutputExecuteInitializeSolutionStep(self):
        self.graphical_output.ExecuteInitializeSolutionStep()

    #============================================================================================================================
    def GraphicalOutputExecuteFinalizeSolutionStep(self):
        self.graphical_output.ExecuteFinalizeSolutionStep()

    #============================================================================================================================
    def GraphicalOutputPrintOutput(self):
        if (self.graphical_output.IsOutputStep()):
            self.graphical_output.PrintOutput()

    #============================================================================================================================
    def GraphicalOutputExecuteFinalize(self):
        self.graphical_output.ExecuteFinalize()

    #============================================================================================================================
    def SetParallelSize(self, num_threads):
        parallel = KratosMultiphysics.OpenMPUtils()
        parallel.SetNumThreads(int(num_threads))

    #============================================================================================================================
    def GetParallelSize(self):
        parallel = KratosMultiphysics.OpenMPUtils()
        return parallel.GetNumThreads()

    #============================================================================================================================
    def StartTimeMeasuring(self):
        # Measure process time
        time_ip = timer.clock()
        return time_ip

    #============================================================================================================================
    def StopTimeMeasuring(self, time_ip, process, report):
        # Measure process time
        time_fp = timer.clock()
        if (report):
            used_time = time_fp - time_ip
            print("::[KSM Simulation]:: [ %.2f" % round(used_time, 2), "s",
                  process, " ] ")
    if (output_post == True):
        gid_output.ExecuteInitializeSolutionStep()

    solver.Solve()

    for process in list_of_processes:
        process.ExecuteFinalizeSolutionStep()

    if (output_post == True):
        gid_output.ExecuteFinalizeSolutionStep()

    for process in list_of_processes:
        process.ExecuteBeforeOutputStep()

    if (output_post == True) and (gid_output.IsOutputStep()):
        gid_output.PrintOutput()

    for process in list_of_processes:
        process.ExecuteAfterOutputStep()

    solver.SaveRestart()

for process in list_of_processes:
    process.ExecuteFinalize()

if (output_post == True):
    gid_output.ExecuteFinalize()

if (parallel_type == "OpenMP") or (mpi.rank == 0):
    Logger.PrintInfo("::[KSM Simulation]:: ", "Analysis -END- ")
Beispiel #5
0
    solver.Solve()

    if (parallel_type == "OpenMP") or (KratosMPI.mpi.rank == 0):
        print("Time step ",step," solved.")

    for process in list_of_processes:
        process.ExecuteFinalizeSolutionStep()

    gid_output_structure.ExecuteFinalizeSolutionStep()
    gid_output_fluid.ExecuteFinalizeSolutionStep()

    #TODO: decide if it shall be done only when output is processed or not
    for process in list_of_processes:
        process.ExecuteBeforeOutputStep()

    if gid_output_structure.IsOutputStep():
        gid_output_structure.PrintOutput()

    if gid_output_fluid.IsOutputStep():
        gid_output_fluid.PrintOutput()

    for process in list_of_processes:
        process.ExecuteAfterOutputStep()

    out = out + Dt

for process in list_of_processes:
    process.ExecuteFinalize()

gid_output_structure.ExecuteFinalize()
gid_output_fluid.ExecuteFinalize()
Beispiel #6
0
class Solution(object):
    def __init__(self):

        #### TIME MONITORING START ####

        # Time control starts
        print(timer.ctime())
        # Measure process time
        self.t0p = timer.clock()
        # Measure wall time
        self.t0w = timer.time()
        #### TIME MONITORING END ####

        #### PARSING THE PARAMETERS ####

        # Import input
        parameter_file = open("ProjectParameters.json", 'r')
        self.ProjectParameters = KratosMultiphysics.Parameters(
            parameter_file.read())

        #set echo level
        self.echo_level = self.ProjectParameters["problem_data"][
            "echo_level"].GetInt()

        print(" ")

        # defining the number of threads:
        num_threads = self.ProjectParameters["problem_data"]["threads"].GetInt(
        )
        self.SetParallelSize(num_threads)
        print("::[KPFEM Simulation]:: [OMP USING", num_threads, "THREADS ]")
        #parallel.PrintOMPInfo()

        print(" ")
        print("::[KPFEM Simulation]:: [Time Step:",
              self.ProjectParameters["problem_data"]["time_step"].GetDouble(),
              " echo:", self.echo_level, "]")

        #### Model_part settings start ####

        # Defining the model_part
        self.main_model_part = KratosMultiphysics.ModelPart(
            self.ProjectParameters["problem_data"]
            ["model_part_name"].GetString())

        self.main_model_part.ProcessInfo.SetValue(
            KratosMultiphysics.SPACE_DIMENSION,
            self.ProjectParameters["problem_data"]["dimension"].GetInt())
        self.main_model_part.ProcessInfo.SetValue(
            KratosMultiphysics.DOMAIN_SIZE,
            self.ProjectParameters["problem_data"]["dimension"].GetInt())
        self.main_model_part.ProcessInfo.SetValue(
            KratosMultiphysics.DELTA_TIME,
            self.ProjectParameters["problem_data"]["time_step"].GetDouble())
        self.main_model_part.ProcessInfo.SetValue(
            KratosMultiphysics.TIME,
            self.ProjectParameters["problem_data"]["start_time"].GetDouble())
        if (self.ProjectParameters["problem_data"].Has("gravity_vector")):
            self.main_model_part.ProcessInfo.SetValue(
                KratosMultiphysics.GRAVITY_X,
                self.ProjectParameters["problem_data"]["gravity_vector"]
                [0].GetDouble())
            self.main_model_part.ProcessInfo.SetValue(
                KratosMultiphysics.GRAVITY_Y,
                self.ProjectParameters["problem_data"]["gravity_vector"]
                [1].GetDouble())
            self.main_model_part.ProcessInfo.SetValue(
                KratosMultiphysics.GRAVITY_Z,
                self.ProjectParameters["problem_data"]["gravity_vector"]
                [2].GetDouble())

        ###TODO replace this "model" for real one once available in kratos core
        self.Model = {
            self.ProjectParameters["problem_data"]["model_part_name"].GetString(
            ):
            self.main_model_part
        }

        #construct the solver (main setting methods are located in the solver_module)
        solver_module = __import__(self.ProjectParameters["solver_settings"]
                                   ["solver_type"].GetString())
        self.solver = solver_module.CreateSolver(
            self.main_model_part, self.ProjectParameters["solver_settings"])

        #### Output settings start ####

        self.problem_path = os.getcwd()
        self.problem_name = self.ProjectParameters["problem_data"][
            "problem_name"].GetString()

    def AddNodalVariablesToModelPart(self):

        # Add variables (always before importing the model part)
        self.solver.AddVariables()

        # Add PfemSolidMechanicsApplication Variables
        import pfem_variables
        pfem_variables.AddVariables(self.main_model_part)

    def Run(self):

        self.Initialize()

        self.RunMainTemporalLoop()

        self.Finalize()

    def Initialize(self):

        # Add variables (always before importing the model part)
        self.AddNodalVariablesToModelPart()

        # Read model_part (note: the buffer_size is set here) (restart is read here)
        self.solver.ImportModelPart()

        # Add dofs (always after importing the model part)
        if ((self.main_model_part.ProcessInfo).Has(
                KratosMultiphysics.IS_RESTARTED)):
            if (self.main_model_part.ProcessInfo[
                    KratosMultiphysics.IS_RESTARTED] == False):
                self.solver.AddDofs()
        else:
            self.solver.AddDofs()

        # Build sub_model_parts or submeshes (rearrange parts for the application of custom processes)
        ## Get the list of the submodel part in the object Model
        for i in range(self.ProjectParameters["solver_settings"]
                       ["processes_sub_model_part_list"].size()):
            part_name = self.ProjectParameters["solver_settings"][
                "processes_sub_model_part_list"][i].GetString()
            if (self.main_model_part.HasSubModelPart(part_name)):
                self.Model.update({
                    part_name:
                    self.main_model_part.GetSubModelPart(part_name)
                })

        #### Model_part settings end ####

        #print model_part and properties
        if (self.echo_level > 1):
            print("")
            print(self.main_model_part)
            for properties in self.main_model_part.Properties:
                print(properties)

        #### Processes settings start ####

        #obtain the list of the processes to be applied

        import process_handler

        process_parameters = KratosMultiphysics.Parameters("{}")
        process_parameters.AddValue(
            "echo_level", self.ProjectParameters["problem_data"]["echo_level"])
        process_parameters.AddValue(
            "constraints_process_list",
            self.ProjectParameters["constraints_process_list"])
        process_parameters.AddValue(
            "loads_process_list", self.ProjectParameters["loads_process_list"])
        if (self.ProjectParameters.Has("problem_process_list")):
            process_parameters.AddValue(
                "problem_process_list",
                self.ProjectParameters["problem_process_list"])
        if (self.ProjectParameters.Has("output_process_list")):
            process_parameters.AddValue(
                "output_process_list",
                self.ProjectParameters["output_process_list"])
        if (self.ProjectParameters.Has("processes_sub_model_part_tree_list")):
            process_parameters.AddValue(
                "processes_sub_model_part_tree_list",
                self.ProjectParameters["processes_sub_model_part_tree_list"])

        self.model_processes = process_handler.ProcessHandler(
            self.Model, process_parameters)

        self.model_processes.ExecuteInitialize()

        #### processes settings end ####

        # --PLOT GRAPHS OPTIONS START--###############
        #self.problem_path = os.getcwd() #current path
        #plot_active = general_variables.PlotGraphs
        #graph_plot = plot_utils.GraphPlotUtility(model_part, self.problem_path)
        # --PLOT GRAPHS OPTIONS END--#################

        #### START SOLUTION ####

        self.computing_model_part = self.solver.GetComputingModelPart()

        self.SetGraphicalOutput()

        ## Sets strategies, builders, linear solvers, schemes and solving info, and fills the buffer
        self.solver.Initialize()
        self.solver.InitializeStrategy()
        self.solver.SetEchoLevel(self.echo_level)

        # Initialize GiD  I/O (gid outputs, file_lists)
        self.GraphicalOutputExecuteInitialize()

        #### Output settings end ####

        # writing a initial state results file
        current_id = 0
        #if(load_restart == False):
        #    if (general_variables.TryToSetTheWeight):
        #        if (general_variables.TryToSetConstantWeight):
        #            conditions.SetConstantWeight( general_variables.TryToSetWeightVertical, general_variables.TryToSetWeightHorizontal);
        #        else:
        #            conditions.SetWeight();

        # set solver info starting parameters
        # solving_info = solving_info_utils.SolvingInfoUtility(model_part, SolverSettings)

        print(" ")
        print("::[KPFEM Simulation]:: Analysis -START- ")

        self.model_processes.ExecuteBeforeSolutionLoop()

        self.GraphicalOutputExecuteBeforeSolutionLoop()

        # Set time settings
        self.step = self.main_model_part.ProcessInfo[KratosMultiphysics.STEP]
        self.time = self.main_model_part.ProcessInfo[KratosMultiphysics.TIME]

        self.end_time = self.ProjectParameters["problem_data"][
            "end_time"].GetDouble()
        self.delta_time = self.ProjectParameters["problem_data"][
            "time_step"].GetDouble()

    def RunMainTemporalLoop(self):

        # Solving the problem (time integration)
        while (self.time < self.end_time):

            self.InitializeSolutionStep()
            self.SolveSolutionStep()
            self.FinalizeSolutionStep()

    def InitializeSolutionStep(self):

        # current time parameters
        # self.main_model_part.ProcessInfo.GetPreviousSolutionStepInfo()[KratosMultiphysics.DELTA_TIME] = self.delta_time
        self.delta_time = self.main_model_part.ProcessInfo[
            KratosMultiphysics.DELTA_TIME]

        self.time = self.time + self.delta_time
        self.step = self.step + 1

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

        print(" [STEP:", self.step, " TIME:", self.time, "]")

        # processes to be executed at the begining of the solution step
        self.model_processes.ExecuteInitializeSolutionStep()

        self.GraphicalOutputExecuteInitializeSolutionStep()

        # solve time step
        self.clock_time = self.StartTimeMeasuring()

        self.solver.InitializeSolutionStep()

    def SolveSolutionStep(self):

        self.solver.Predict()

        self.solver.SolveSolutionStep()

        self.solver.FinalizeSolutionStep()

    def FinalizeSolutionStep(self):

        self.StopTimeMeasuring(self.clock_time, "Solving", False)

        self.GraphicalOutputExecuteFinalizeSolutionStep()

        # processes to be executed at the end of the solution step
        self.model_processes.ExecuteFinalizeSolutionStep()

        # processes to be executed before witting the output
        self.model_processes.ExecuteBeforeOutputStep()

        # write output results GiD: (frequency writing is controlled internally)
        self.GraphicalOutputPrintOutput()

        # processes to be executed after witting the output
        self.model_processes.ExecuteAfterOutputStep()

    def Finalize(self):

        # Ending the problem (time integration finished)
        self.GraphicalOutputExecuteFinalize()

        self.model_processes.ExecuteFinalize()

        print("::[KPFEM Simulation]:: Analysis -END- ")
        print(" ")

        # Check solving information for any problem
        #~ self.solver.InfoCheck() # InfoCheck not implemented yet.

        #### END SOLUTION ####

        # Measure process time
        tfp = timer.clock()
        # Measure wall time
        tfw = timer.time()

        print("::[KPFEM Simulation]:: [Elapsed Time = %.2f" % (tfw - self.t0w),
              "seconds] (%.2f" % (tfp - self.t0p), "seconds of cpu/s time)")

        print(timer.ctime())

        # to create a benchmark: add standard benchmark files and decomment next two lines
        # rename the file to: run_test.py
        #from run_test_benchmark_results import *
        #WriteBenchmarkResults(model_part)

    def SetGraphicalOutput(self):
        from gid_output_process import GiDOutputProcess
        self.output_settings = self.ProjectParameters["output_configuration"]
        self.graphical_output = GiDOutputProcess(self.computing_model_part,
                                                 self.problem_name,
                                                 self.output_settings)

    def GraphicalOutputExecuteInitialize(self):
        self.graphical_output.ExecuteInitialize()

    def GraphicalOutputExecuteBeforeSolutionLoop(self):
        # writing a initial state results file or single file (if no restart)
        if ((self.main_model_part.ProcessInfo).Has(
                KratosMultiphysics.IS_RESTARTED)):
            if (self.main_model_part.ProcessInfo[
                    KratosMultiphysics.IS_RESTARTED] == False):
                self.graphical_output.ExecuteBeforeSolutionLoop()

    def GraphicalOutputExecuteInitializeSolutionStep(self):
        self.graphical_output.ExecuteInitializeSolutionStep()

    def GraphicalOutputExecuteFinalizeSolutionStep(self):
        self.graphical_output.ExecuteFinalizeSolutionStep()

    def GraphicalOutputPrintOutput(self):
        if (self.graphical_output.IsOutputStep()):
            self.graphical_output.PrintOutput()

    def GraphicalOutputExecuteFinalize(self):
        self.graphical_output.ExecuteFinalize()

    def SetParallelSize(self, num_threads):
        parallel = KratosMultiphysics.OpenMPUtils()
        parallel.SetNumThreads(int(num_threads))

    def GetParallelSize(self):
        parallel = KratosMultiphysics.OpenMPUtils()
        return parallel.GetNumThreads()

    def StartTimeMeasuring(self):
        # Measure process time
        time_ip = timer.clock()
        return time_ip

    def StopTimeMeasuring(self, time_ip, process, report):
        # Measure process time
        time_fp = timer.clock()
        if (report):
            used_time = time_fp - time_ip
            print("::[KSM Simulation]:: [ %.2f" % round(used_time, 2), "s",
                  process, " ] ")
Beispiel #7
0
class ManufacturedSolutionProblem:
    def __init__(self, ProjectParameters, input_file_name, print_output,
                 problem_type, analytical_solution_type):

        self.problem_type = problem_type
        self.print_output = print_output
        self.input_file_name = input_file_name
        self.ProjectParameters = ProjectParameters
        self.analytical_solution_type = analytical_solution_type
        self.model = KratosMultiphysics.Model()

    def SetFluidProblem(self):

        ## Set the current mesh case problem info
        if (self.problem_type == "analytical_solution"):
            self.ProjectParameters["problem_data"]["problem_name"].SetString(
                self.input_file_name + "_manufactured")
        else:
            self.ProjectParameters["problem_data"]["problem_name"].SetString(
                self.input_file_name)
        self.ProjectParameters["solver_settings"]["model_import_settings"][
            "input_filename"].SetString(self.input_file_name)

        ## Solver construction
        self.solver = python_solvers_wrapper_fluid.CreateSolver(
            self.model, self.ProjectParameters)

        self.solver.AddVariables()

        ## Read the model - note that SetBufferSize is done here
        self.solver.ImportModelPart()
        self.solver.PrepareModelPart()

        self.main_model_part = self.model.GetModelPart(
            self.ProjectParameters["problem_data"]
            ["model_part_name"].GetString())

        ## Add AddDofs
        self.solver.AddDofs()

        ## Initialize GiD  I/O
        if (self.print_output):
            from gid_output_process import GiDOutputProcess
            self.gid_output = GiDOutputProcess(
                self.solver.GetComputingModelPart(),
                self.ProjectParameters["problem_data"]
                ["problem_name"].GetString(),
                self.ProjectParameters["output_configuration"])

            self.gid_output.ExecuteInitialize()

        ## Solver initialization
        self.solver.Initialize()

        ## Compute and set the nodal area
        self.SetNodalArea()

        ## Set the distance to 1 to have full fluid elements
        if (self.ProjectParameters["solver_settings"]
            ["solver_type"].GetString() == "Embedded"):
            for node in self.main_model_part.Nodes:
                node.SetSolutionStepValue(KratosMultiphysics.DISTANCE, 0, 1.0)

        ## Fix the pressure in one node (bottom left corner)
        for node in self.main_model_part.Nodes:
            if ((node.X < 0.001) and (node.Y < 0.001)):
                node.Fix(KratosMultiphysics.PRESSURE)
                node.SetSolutionStepValue(KratosMultiphysics.PRESSURE, 0, 0.0)

    def SolveFluidProblem(self):

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

        time = 0.0

        if (self.print_output):
            self.gid_output.ExecuteBeforeSolutionLoop()

        while (time <= end_time):

            time = self.solver.AdvanceInTime(time)

            if (self.print_output):
                self.gid_output.ExecuteInitializeSolutionStep()

            if (self.problem_type == "analytical_solution"):
                # Fix the manufactured solution values (only for visualization purposes)
                self.SetManufacturedSolutionValues(fix=True,
                                                   set_only_boundaries=False)
            else:
                # Set the manufactured solution source terms
                self.SetManufacturedSolutionValues(fix=True,
                                                   set_only_boundaries=True)
                self.SetManufacturedSolutionSourceValues()

            if (self.main_model_part.ProcessInfo[KratosMultiphysics.STEP] < 3):
                self.SetManufacturedSolutionValues(
                    False
                )  # Set the analytical solution in the two first steps
            else:
                if (self.problem_type != "analytical_solution"):
                    self.solver.InitializeSolutionStep()
                    self.solver.Predict()
                    self.solver.SolveSolutionStep()
                    self.solver.FinalizeSolutionStep()

            if (self.print_output):
                self.gid_output.ExecuteFinalizeSolutionStep()

                if self.gid_output.IsOutputStep():
                    self.gid_output.PrintOutput()

        if (self.print_output):
            self.gid_output.ExecuteFinalize()

    def SetManufacturedSolutionValues(self,
                                      fix=True,
                                      set_only_boundaries=False):
        ## Set the analytical solution for the manufactured solution computation
        time = self.main_model_part.ProcessInfo[KratosMultiphysics.TIME]

        if (set_only_boundaries == False):
            for node in self.main_model_part.Nodes:
                vel = self.ComputeNodalVelocityManufacturedSolution(node, time)
                pres = self.ComputeNodalPressureManufacturedSolution(node)

                if (fix == True):
                    node.Fix(KratosMultiphysics.VELOCITY_X)
                    node.Fix(KratosMultiphysics.VELOCITY_Y)
                    node.Fix(KratosMultiphysics.PRESSURE)

                node.SetSolutionStepValue(KratosMultiphysics.VELOCITY_X, 0,
                                          vel[0])
                node.SetSolutionStepValue(KratosMultiphysics.VELOCITY_Y, 0,
                                          vel[1])
                node.SetSolutionStepValue(KratosMultiphysics.PRESSURE, 0, pres)
        else:
            for node in self.main_model_part.GetSubModelPart(
                    "Inlet2D_Contour").Nodes:
                vel = self.ComputeNodalVelocityManufacturedSolution(node, time)

                if (fix == True):
                    node.Fix(KratosMultiphysics.VELOCITY_X)
                    node.Fix(KratosMultiphysics.VELOCITY_Y)

                node.SetSolutionStepValue(KratosMultiphysics.VELOCITY_X, 0,
                                          vel[0])
                node.SetSolutionStepValue(KratosMultiphysics.VELOCITY_Y, 0,
                                          vel[1])

    def SetNodalArea(self):
        # Compute nodal area
        for element in self.main_model_part.Elements:
            x = []
            y = []
            for node in element.GetNodes():
                x.append(node.X)
                y.append(node.Y)

            Area = 0.5 * (
                (x[1] * y[2] - x[2] * y[1]) + (x[2] * y[0] - x[0] * y[2]) +
                (x[0] * y[1] - x[1] * y[0]))  # Element area (Jacobian/2)
            # print("Element "+str(element.Id)+" area: "+str(Area))

            for node in element.GetNodes():
                aux = node.GetSolutionStepValue(
                    KratosMultiphysics.NODAL_AREA
                )  # Current nodal area (from other elements)
                aux += Area / 3.0  # Accumulate the current element nodal area
                node.SetSolutionStepValue(KratosMultiphysics.NODAL_AREA, 0,
                                          aux)
                node.SetValue(KratosMultiphysics.NODAL_AREA, aux)

        ## Check nodal area computation (squared shaped domain of 1x1 m)
        AreaTotal = 0.0
        for node in self.main_model_part.Nodes:
            # print("Node id "+str(node.Id)+" nodal area: "+str(node.GetValue(KratosMultiphysics.NODAL_AREA)))
            AreaTotal += node.GetValue(KratosMultiphysics.NODAL_AREA)

        if (abs(1.0 - AreaTotal) > 1e-5):
            print("Obtained total area: " + str(AreaTotal))
            raise Exception("Error in NODAL_AREA computation.")

    def SetManufacturedSolutionSourceValues(self):
        ## Set the body force as source term
        time = self.main_model_part.ProcessInfo[KratosMultiphysics.TIME]
        solver_type = self.ProjectParameters["solver_settings"][
            "solver_type"].GetString()

        for node in self.main_model_part.Nodes:
            if solver_type == "Monolithic":
                # If VMS2D element is used, set mu as the Kinematic viscosity and density in the nodes
                rho = node.GetSolutionStepValue(KratosMultiphysics.DENSITY)
                mu = rho * node.GetSolutionStepValue(
                    KratosMultiphysics.VISCOSITY)
            elif solver_type == "Embedded":
                # If the symbolic elements are used, get the density and viscosity from the first element properties
                for elem in self.main_model_part.Elements:
                    rho = elem.Properties[KratosMultiphysics.DENSITY]
                    mu = elem.Properties[KratosMultiphysics.DYNAMIC_VISCOSITY]
                    break

            rhof = self.ComputeNodalSourceTermManufacturedSolution(
                node, time, rho, mu)

            node.SetSolutionStepValue(
                KratosMultiphysics.BODY_FORCE_X, 0,
                rhof[0] / rho)  # Set the x-component body force field
            node.SetSolutionStepValue(
                KratosMultiphysics.BODY_FORCE_Y, 0,
                rhof[1] / rho)  # Set the y-component body force field

    def ComputeVelocityErrorNorm(self):
        err_v = 0

        for node in self.main_model_part.Nodes:
            weight = node.GetValue(KratosMultiphysics.NODAL_AREA)
            vel_x = node.GetSolutionStepValue(KratosMultiphysics.VELOCITY_X)
            vel_y = node.GetSolutionStepValue(KratosMultiphysics.VELOCITY_Y)
            end_time = self.main_model_part.ProcessInfo[
                KratosMultiphysics.TIME]

            analytical_vel = self.ComputeNodalVelocityManufacturedSolution(
                node, end_time)

            err_x = analytical_vel[0] - vel_x
            err_y = analytical_vel[1] - vel_y
            err_node = err_x**2 + err_y**2
            err_v += weight * err_node

        return math.sqrt(
            err_v
        )  # Note, there is no need of dividing by the total area (sum of weights) since it is 1

    def ComputePressureErrorNorm(self):
        err_p = 0

        for node in self.main_model_part.Nodes:
            weight = node.GetValue(KratosMultiphysics.NODAL_AREA)
            pres = node.GetSolutionStepValue(KratosMultiphysics.PRESSURE)
            analytical_pres = self.ComputeNodalPressureManufacturedSolution(
                node)
            err_p += weight * (analytical_pres - pres)**2

        return math.sqrt(
            err_p
        )  # Note, there is no need of dividing by the total area (sum of weights) since it is 1

    def ComputeNodalSourceTermManufacturedSolution(self, node, time, rho, mu):
        if (self.analytical_solution_type == "sinusoidal_transient_field"):
            rhofx = -rho * math.pi * math.sin(math.pi * node.X) * math.cos(
                math.pi * node.Y) * math.sin(
                    math.pi * time) + 2 * mu * math.pi * math.pi * math.sin(
                        math.pi * node.X
                    ) * math.cos(math.pi * node.Y) * math.cos(
                        math.pi * time) + rho * math.pi * (math.cos(
                            math.pi * time)**2) * math.sin(
                                math.pi * node.X) * math.cos(math.pi * node.X)
            rhofy = rho * math.pi * math.cos(math.pi * node.X) * math.sin(
                math.pi * node.Y) * math.sin(
                    math.pi * time) - 2 * mu * math.pi * math.pi * math.cos(
                        math.pi * node.X
                    ) * math.sin(math.pi * node.Y) * math.cos(
                        math.pi * time) + rho * math.pi * (math.cos(
                            math.pi * time)**2) * math.sin(
                                math.pi * node.Y) * math.cos(math.pi * node.Y)

        elif (self.analytical_solution_type == "nonlinear_transient_field"):
            rhofx = rho * math.pi * (node.X**2) * node.Y * math.cos(
                math.pi * time) - 2 * mu * node.Y * math.sin(
                    math.pi * time) + rho * (node.X**3) * (node.Y**2) * (
                        (math.sin(math.pi * time))**2)
            rhofy = -rho * math.pi * node.X * (node.Y**2) * math.cos(
                math.pi * time) + 2 * mu * node.X * math.sin(
                    math.pi * time) + rho * (node.X**2) * (node.Y**3) * (
                        (math.sin(math.pi * time))**2)

        elif (self.analytical_solution_type == "nonlinear_stationary_field"):
            rhofx = -2 * mu * node.Y + rho * node.X**3 * node.Y**2
            rhofy = 2 * mu * node.X + rho * node.X**2 * node.Y**3

        return [rhofx, rhofy]

    def ComputeNodalVelocityManufacturedSolution(self, node, time):
        if (self.analytical_solution_type == "sinusoidal_transient_field"):
            vx = math.sin(math.pi * node.X) * math.cos(
                math.pi * node.Y) * math.cos(math.pi * time)
            vy = -math.cos(math.pi * node.X) * math.sin(
                math.pi * node.Y) * math.cos(math.pi * time)

        elif (self.analytical_solution_type == "nonlinear_transient_field"):
            vx = node.X**2 * node.Y * math.sin(math.pi * time)
            vy = -node.X * node.Y**2 * math.sin(math.pi * time)

        elif (self.analytical_solution_type == "nonlinear_stationary_field"):
            vx = node.X**2 * node.Y
            vy = -node.X * node.Y**2

        return [vx, vy]

    def ComputeNodalPressureManufacturedSolution(self, node):
        # We consider solenoidal velocity fields in order to have a known zero pressure solution on the continuum
        return 0.0
class Kratos_Execute_Test:
    def __init__(self, ProjectParameters):

        self.ProjectParameters = ProjectParameters

        self.main_model_part = KratosMultiphysics.ModelPart(
            self.ProjectParameters["problem_data"]
            ["model_part_name"].GetString())
        self.main_model_part.ProcessInfo.SetValue(
            KratosMultiphysics.DOMAIN_SIZE,
            self.ProjectParameters["problem_data"]["domain_size"].GetInt())

        self.Model = {
            self.ProjectParameters["problem_data"]["model_part_name"].GetString(
            ):
            self.main_model_part
        }

        self.problem_type = self.ProjectParameters["problem_data"][
            "problem_type"].GetString()

        self.solve_problem = self.ProjectParameters["problem_data"][
            "solve_problem"].GetBool()

        if (self.problem_type == "fluid"
                and missing_external_fluid_dependencies == False):
            ## Solver construction
            import python_solvers_wrapper_fluid as fluid_wrapper
            self.solver = fluid_wrapper.CreateSolver(self.main_model_part,
                                                     self.ProjectParameters)
        elif (self.problem_type == "solid"
              and missing_external_solid_dependencies == False):
            # Construct the solver (main setting methods are located in the solver_module)
            solver_module = __import__(
                self.ProjectParameters["solver_settings"]
                ["solver_type"].GetString())
            self.solver = solver_module.CreateSolver(
                self.main_model_part,
                self.ProjectParameters["solver_settings"])
        else:
            raise NameError(
                'Problem type not defined or failing in the import')

        # Add variables (always before importing the model part) (it must be integrated in the ImportModelPart)
        # If we integrate it in the model part we cannot use combined solvers
        self.solver.AddVariables()

        self.main_model_part.AddNodalSolutionStepVariable(
            KratosMultiphysics.NODAL_H)
        self.main_model_part.AddNodalSolutionStepVariable(
            KratosMultiphysics.NODAL_AREA)

        # Read model_part (note: the buffer_size is set here) (restart can be read here)
        self.solver.ImportModelPart()

        # Add dofs (always after importing the model part) (it must be integrated in the ImportModelPart)
        # If we integrate it in the model part we cannot use combined solvers
        self.solver.AddDofs()

        # ### Output settings start ####
        self.problem_path = os.getcwd()
        self.problem_name = self.ProjectParameters["problem_data"][
            "problem_name"].GetString()

        # ### Output settings start ####
        self.output_post = ProjectParameters.Has("output_configuration")
        if (self.output_post == True):
            from gid_output_process import GiDOutputProcess
            output_settings = ProjectParameters["output_configuration"]
            self.gid_output = GiDOutputProcess(
                self.solver.GetComputingModelPart(), self.problem_name,
                output_settings)
            self.gid_output.ExecuteInitialize()

        # Sets strategies, builders, linear solvers, schemes and solving info, and fills the buffer
        self.solver.Initialize()
        self.solver.SetEchoLevel(0)  # Avoid to print anything

        if self.problem_type == "fluid":
            # Build sub_model_parts or submeshes (rearrange parts for the application of custom processes)
            # #Get the list of the submodel part in the object Model
            for i in range(self.ProjectParameters["solver_settings"]
                           ["skin_parts"].size()):
                skin_part_name = self.ProjectParameters["solver_settings"][
                    "skin_parts"][i].GetString()
                self.Model.update({
                    skin_part_name:
                    self.main_model_part.GetSubModelPart(skin_part_name)
                })

            ## Get the list of the initial conditions submodel parts in the object Model
            for i in range(
                    self.ProjectParameters["initial_conditions_process_list"].
                    size()):
                initial_cond_part_name = self.ProjectParameters[
                    "initial_conditions_process_list"][i]["Parameters"][
                        "model_part_name"].GetString()
                self.Model.update({
                    initial_cond_part_name:
                    self.main_model_part.GetSubModelPart(
                        initial_cond_part_name)
                })

            ## Get the gravity submodel part in the object Model
            for i in range(self.ProjectParameters["gravity"].size()):
                gravity_part_name = self.ProjectParameters["gravity"][i][
                    "Parameters"]["model_part_name"].GetString()
                self.Model.update({
                    gravity_part_name:
                    self.main_model_part.GetSubModelPart(gravity_part_name)
                })

        elif self.problem_type == "solid":
            # Build sub_model_parts or submeshes (rearrange parts for the application of custom processes)
            # #Get the list of the submodel part in the object Model
            for i in range(self.ProjectParameters["solver_settings"]
                           ["processes_sub_model_part_list"].size()):
                part_name = self.ProjectParameters["solver_settings"][
                    "processes_sub_model_part_list"][i].GetString()
                self.Model.update({
                    part_name:
                    self.main_model_part.GetSubModelPart(part_name)
                })

        ## Remeshing processes construction
        if (self.ProjectParameters.Has("initial_remeshing_process") == True):
            remeshing_processes = process_factory.KratosProcessFactory(
                self.Model).ConstructListOfProcesses(
                    self.ProjectParameters["initial_remeshing_process"])
            if (ProjectParameters.Has("list_other_processes") == True):
                remeshing_processes += process_factory.KratosProcessFactory(
                    self.Model).ConstructListOfProcesses(
                        self.ProjectParameters["list_other_processes"])

            ## Remeshing processes initialization
            print("STARTING ADAPTATIVE LOOP")
            if (self.ProjectParameters.Has("adaptative_loop") == True):
                adaptative_loop = ProjectParameters["adaptative_loop"].GetInt()
            else:
                adaptative_loop = 1
            for n in range(adaptative_loop):
                print("ADAPTATIVE INTERATION: ", n + 1)
                for process in reversed(remeshing_processes):
                    process.ExecuteInitialize()

        # Obtain the list of the processes to be applied
        if self.problem_type == "fluid":
            self.list_of_processes = process_factory.KratosProcessFactory(
                self.Model).ConstructListOfProcesses(
                    self.ProjectParameters["gravity"])
            self.list_of_processes += process_factory.KratosProcessFactory(
                self.Model).ConstructListOfProcesses(
                    self.ProjectParameters["initial_conditions_process_list"])
            self.list_of_processes += process_factory.KratosProcessFactory(
                self.Model).ConstructListOfProcesses(
                    self.ProjectParameters["boundary_conditions_process_list"])
        elif self.problem_type == "solid":
            self.list_of_processes = process_factory.KratosProcessFactory(
                self.Model).ConstructListOfProcesses(
                    self.ProjectParameters["constraints_process_list"])
            self.list_of_processes += process_factory.KratosProcessFactory(
                self.Model).ConstructListOfProcesses(
                    self.ProjectParameters["loads_process_list"])
        if (self.ProjectParameters.Has("list_other_processes") == True):
            self.list_of_processes += process_factory.KratosProcessFactory(
                self.Model).ConstructListOfProcesses(
                    self.ProjectParameters["list_other_processes"])
        if (self.ProjectParameters.Has("json_check_process") == True):
            self.list_of_processes += process_factory.KratosProcessFactory(
                self.Model).ConstructListOfProcesses(
                    self.ProjectParameters["json_check_process"])
        if (self.ProjectParameters.Has("json_output_process") == True):
            self.list_of_processes += process_factory.KratosProcessFactory(
                self.Model).ConstructListOfProcesses(
                    self.ProjectParameters["json_output_process"])
        if (self.ProjectParameters.Has("compare_two_files_check_process") ==
                True):
            self.list_of_processes += process_factory.KratosProcessFactory(
                self.Model).ConstructListOfProcesses(
                    self.ProjectParameters["compare_two_files_check_process"])
        if (self.ProjectParameters.Has("recursive_remeshing_process") == True):
            self.list_of_processes += process_factory.KratosProcessFactory(
                self.Model).ConstructListOfProcesses(
                    self.ProjectParameters["recursive_remeshing_process"])

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

        # ### START SOLUTION ####

        self.computing_model_part = self.solver.GetComputingModelPart()

        if (self.output_post == True):
            self.gid_output.ExecuteBeforeSolutionLoop()

    def Solve(self):
        if self.solve_problem == True:
            for process in self.list_of_processes:
                process.ExecuteBeforeSolutionLoop()

            # #Stepping and time settings (get from process info or solving info)
            # Delta time
            delta_time = self.ProjectParameters["problem_data"][
                "time_step"].GetDouble()
            # Start step
            self.main_model_part.ProcessInfo[KratosMultiphysics.TIME_STEPS] = 0
            # Start time
            time = self.ProjectParameters["problem_data"][
                "start_time"].GetDouble()
            # End time
            end_time = self.ProjectParameters["problem_data"][
                "end_time"].GetDouble()
            step = 0

            if self.problem_type == "fluid":
                init_step = 3
            elif self.problem_type == "solid":
                init_step = 1

            # Solving the problem (time integration)
            while (time <= end_time):
                time = time + delta_time
                self.main_model_part.ProcessInfo[
                    KratosMultiphysics.TIME_STEPS] += 1
                self.main_model_part.CloneTimeStep(time)
                step = step + 1

                if (step >= init_step):
                    for process in self.list_of_processes:
                        process.ExecuteInitializeSolutionStep()

                    if (self.main_model_part.Is(
                            KratosMultiphysics.MODIFIED) == True):
                        # WE INITIALIZE THE SOLVER
                        self.solver.Initialize()
                        # WE RECOMPUTE THE PROCESSES AGAIN
                        ## Processes initialization
                        for process in self.list_of_processes:
                            process.ExecuteInitialize()
                        ## Processes before the loop
                        for process in self.list_of_processes:
                            process.ExecuteBeforeSolutionLoop()
                        ## Processes of initialize the solution step
                        for process in self.list_of_processes:
                            process.ExecuteInitializeSolutionStep()

                    if (self.output_post == True):
                        self.gid_output.ExecuteInitializeSolutionStep()

                    self.solver.Clear()
                    self.solver.Solve()

                    if (self.output_post == True):
                        self.gid_output.ExecuteFinalizeSolutionStep()

                    for process in self.list_of_processes:
                        process.ExecuteFinalizeSolutionStep()

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

                    if (self.output_post == True):
                        if self.gid_output.IsOutputStep():
                            self.gid_output.PrintOutput()

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

            if (self.output_post == True):
                self.gid_output.ExecuteFinalize()

            for process in self.list_of_processes:
                process.ExecuteFinalize()
class MokBenchmarkTest(KratosUnittest.TestCase):
    def setUp(self):
        self.print_output = False
        self.work_folder = "MokBenchmarkTest"
        self.settings = "ProjectParameters.json"
        self.fluid_input_file = "mok_benchmark_Fluid"
        self.structure_input_file = "mok_benchmark_Fluid"

    def tearDown(self):
        self.deleteOutFile(self.fluid_input_file + '.time')
        self.deleteOutFile(self.structure_input_file + '.time')

    def deleteOutFile(self, filename):
        with WorkFolderScope(self.work_folder):
            try:
                remove(filename)
            except FileNotFoundError as e:
                pass

    def testMokBenchmark(self):
        with WorkFolderScope(self.work_folder):
            parameter_file = open(self.settings, 'r')
            self.ProjectParameters = Parameters(parameter_file.read())

            ## Fluid-Structure model parts definition
            self.structure_main_model_part = ModelPart(
                self.ProjectParameters["structure_solver_settings"]
                ["problem_data"]["model_part_name"].GetString())
            self.structure_main_model_part.ProcessInfo.SetValue(
                DOMAIN_SIZE,
                self.ProjectParameters["structure_solver_settings"]
                ["problem_data"]["domain_size"].GetInt())

            self.fluid_main_model_part = ModelPart(
                self.ProjectParameters["fluid_solver_settings"]["problem_data"]
                ["model_part_name"].GetString())
            self.fluid_main_model_part.ProcessInfo.SetValue(
                DOMAIN_SIZE, self.ProjectParameters["fluid_solver_settings"]
                ["problem_data"]["domain_size"].GetInt())

            FluidModel = {
                self.ProjectParameters["fluid_solver_settings"]["problem_data"]["model_part_name"].GetString(
                ):
                self.fluid_main_model_part
            }
            SolidModel = {
                self.ProjectParameters["structure_solver_settings"]["problem_data"]["model_part_name"].GetString(
                ):
                self.structure_main_model_part
            }

            ## Solver construction
            solver_module = __import__(
                self.ProjectParameters["coupling_solver_settings"]
                ["solver_settings"]["solver_type"].GetString())
            self.solver = solver_module.CreateSolver(
                self.structure_main_model_part, self.fluid_main_model_part,
                self.ProjectParameters)

            self.solver.AddVariables()

            ## Read the model - note that SetBufferSize is done here
            self.solver.ImportModelPart()

            ## Add AddDofs
            self.solver.AddDofs()

            ## Initialize GiD  I/O
            if (self.print_output == True):
                from gid_output_process import GiDOutputProcess

                self.gid_output_structure = GiDOutputProcess(
                    self.solver.structure_solver.GetComputingModelPart(),
                    self.ProjectParameters["structure_solver_settings"]
                    ["problem_data"]["problem_name"].GetString() +
                    "_structure",
                    self.ProjectParameters["structure_solver_settings"]
                    ["output_configuration"])

                self.gid_output_fluid = GiDOutputProcess(
                    self.solver.fluid_solver.GetComputingModelPart(),
                    self.ProjectParameters["fluid_solver_settings"]
                    ["problem_data"]["problem_name"].GetString() + "_fluid",
                    self.ProjectParameters["fluid_solver_settings"]
                    ["output_configuration"])

                self.gid_output_structure.ExecuteInitialize()
                self.gid_output_fluid.ExecuteInitialize()

            ## Get the list of the skin submodel parts in the object Model (FLUID)
            for i in range(self.ProjectParameters["fluid_solver_settings"]
                           ["solver_settings"]["skin_parts"].size()):
                skin_part_name = self.ProjectParameters[
                    "fluid_solver_settings"]["solver_settings"]["skin_parts"][
                        i].GetString()
                FluidModel.update({
                    skin_part_name:
                    self.fluid_main_model_part.GetSubModelPart(skin_part_name)
                })

            ## Get the list of the no-skin submodel parts in the object Model (FLUID)
            for i in range(self.ProjectParameters["fluid_solver_settings"]
                           ["solver_settings"]["no_skin_parts"].size()):
                no_skin_part_name = self.ProjectParameters[
                    "fluid_solver_settings"]["solver_settings"][
                        "no_skin_parts"][i].GetString()
                FluidModel.update({
                    no_skin_part_name:
                    self.fluid_main_model_part.GetSubModelPart(
                        no_skin_part_name)
                })

            ## Get the list of the initial conditions submodel parts in the object Model (FLUID)
            for i in range(self.ProjectParameters["fluid_solver_settings"]
                           ["initial_conditions_process_list"].size()):
                initial_cond_part_name = self.ProjectParameters[
                    "fluid_solver_settings"][
                        "initial_conditions_process_list"][i]["Parameters"][
                            "model_part_name"].GetString()
                FluidModel.update({
                    initial_cond_part_name:
                    self.fluid_main_model_part.GetSubModelPart(
                        initial_cond_part_name)
                })

            ## Get the gravity submodel part in the object Model (FLUID)
            for i in range(self.ProjectParameters["fluid_solver_settings"]
                           ["gravity"].size()):
                gravity_part_name = self.ProjectParameters[
                    "fluid_solver_settings"]["gravity"][i]["Parameters"][
                        "model_part_name"].GetString()
                FluidModel.update({
                    gravity_part_name:
                    self.fluid_main_model_part.GetSubModelPart(
                        gravity_part_name)
                })

            ## Get the list of the submodel part in the object Model (STRUCTURE)
            for i in range(
                    self.ProjectParameters["structure_solver_settings"]
                ["solver_settings"]["processes_sub_model_part_list"].size()):
                part_name = self.ProjectParameters[
                    "structure_solver_settings"]["solver_settings"][
                        "processes_sub_model_part_list"][i].GetString()
                SolidModel.update({
                    part_name:
                    self.structure_main_model_part.GetSubModelPart(part_name)
                })

            ## Processes construction
            import process_factory
            # "list_of_processes" contains all the processes already constructed (boundary conditions, initial conditions and gravity)
            # Note that the conditions are firstly constructed. Otherwise, they may overwrite the BCs information.

            # FLUID DOMAIN PROCESSES
            self.list_of_processes = process_factory.KratosProcessFactory(
                FluidModel).ConstructListOfProcesses(
                    self.ProjectParameters["fluid_solver_settings"]
                    ["initial_conditions_process_list"])
            self.list_of_processes += process_factory.KratosProcessFactory(
                FluidModel).ConstructListOfProcesses(
                    self.ProjectParameters["fluid_solver_settings"]
                    ["boundary_conditions_process_list"])
            self.list_of_processes += process_factory.KratosProcessFactory(
                FluidModel).ConstructListOfProcesses(
                    self.ProjectParameters["fluid_solver_settings"]["gravity"])

            # SOLID DOMAIN PROCESSES
            self.list_of_processes += process_factory.KratosProcessFactory(
                SolidModel).ConstructListOfProcesses(
                    self.ProjectParameters["structure_solver_settings"]
                    ["constraints_process_list"])
            self.list_of_processes += process_factory.KratosProcessFactory(
                SolidModel).ConstructListOfProcesses(
                    self.ProjectParameters["structure_solver_settings"]
                    ["loads_process_list"])

            ## Processes initialization
            for process in self.list_of_processes:
                process.ExecuteInitialize()

            # Solver initialization moved after the processes initialization, otherwise the flag INTERFACE is not set
            self.solver.Initialize()

            ## Time settings
            end_time = self.ProjectParameters["fluid_solver_settings"][
                "problem_data"]["end_time"].GetDouble()
            time = 0.0
            step = 0
            out = 0.0

            if (self.print_output == True):
                self.gid_output_structure.ExecuteBeforeSolutionLoop()
                self.gid_output_fluid.ExecuteBeforeSolutionLoop()

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

            while (time <= end_time):

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

                self.solver.SetTimeStep(step)

                self.structure_main_model_part.CloneTimeStep(time)
                self.fluid_main_model_part.CloneTimeStep(time)

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

                if (self.print_output == True):
                    self.gid_output_structure.ExecuteInitializeSolutionStep()
                    self.gid_output_fluid.ExecuteInitializeSolutionStep()

                (self.solver).Solve()

                for process in self.list_of_processes:
                    process.ExecuteFinalizeSolutionStep()

                if (self.print_output == True):
                    self.gid_output_structure.ExecuteFinalizeSolutionStep()
                    self.gid_output_fluid.ExecuteFinalizeSolutionStep()

                #TODO: decide if it shall be done only when output is processed or not
                for process in self.list_of_processes:
                    process.ExecuteBeforeOutputStep()

                if (self.print_output == True):
                    if self.gid_output_structure.IsOutputStep():
                        self.gid_output_structure.PrintOutput()
                    if self.gid_output_fluid.IsOutputStep():
                        self.gid_output_fluid.PrintOutput()

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

                out = out + Dt

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

            if (self.print_output == True):
                self.gid_output_structure.ExecuteFinalize()
                self.gid_output_fluid.ExecuteFinalize()
Beispiel #10
0
class DesignLoggerGID(DesignLogger):

    # --------------------------------------------------------------------------
    def __init__(self, ModelPartController, OptimizationSettings):
        self.OptimizationModelPart = ModelPartController.GetOptimizationModelPart(
        )
        self.DesignSurface = ModelPartController.GetDesignSurface()
        self.OutputSettings = OptimizationSettings["output"]

        self.__DetermineOutputMode()
        self.__CreateGiDIO()

    # --------------------------------------------------------------------------
    def __DetermineOutputMode(self):
        OutputMode = self.OutputSettings["design_output_mode"].GetString()

        self.WriteDesignSurface = False
        self.WriteOptimizationModelPart = False

        if OutputMode == "WriteDesignSurface":
            self.WriteDesignSurface = True
        elif OutputMode == "WriteOptimizationModelPart":
            if self.OptimizationModelPart.NumberOfElements() == 0:
                raise NameError(
                    "Output of optimization model part in Gid-format requires definition of elements. No elements are given in current mdpa! You may change the design output mode."
                )
            self.WriteOptimizationModelPart = True
        else:
            raise NameError(
                "The following design output mode is not defined within a GiD output (name may be misspelled): "
                + OutputMode)

    # --------------------------------------------------------------------------
    def __CreateGiDIO(self):
        self.__ModifySettingsToMatchDefaultGiDOutputProcess()

        GidConfig = self.OutputSettings["output_format"]["gid_configuration"]
        ResultsDirectory = self.OutputSettings["output_directory"].GetString()
        DesignHistoryFilename = self.OutputSettings[
            "design_history_filename"].GetString()
        DesignHistoryFilenameWithPath = ResultsDirectory + "/" + DesignHistoryFilename

        if self.WriteDesignSurface:
            self.GidIO = GiDOutputProcess(self.DesignSurface,
                                          DesignHistoryFilenameWithPath,
                                          GidConfig)
        elif self.WriteOptimizationModelPart:
            self.GidIO = GiDOutputProcess(self.OptimizationModelPart,
                                          DesignHistoryFilenameWithPath,
                                          GidConfig)

    # --------------------------------------------------------------------------
    def __ModifySettingsToMatchDefaultGiDOutputProcess(self):
        self.__AddNodalResultsToGidConfiguration()
        self.__SetConditionsFlagAccordingOutputMode()

    # --------------------------------------------------------------------------
    def __AddNodalResultsToGidConfiguration(self):
        NodalResults = self.OutputSettings["nodal_results"]
        self.OutputSettings["output_format"]["gid_configuration"][
            "result_file_configuration"].AddValue("nodal_results",
                                                  NodalResults)

    # --------------------------------------------------------------------------
    def __SetConditionsFlagAccordingOutputMode(self):
        GidConfig = self.OutputSettings["output_format"]["gid_configuration"]

        if not GidConfig["result_file_configuration"]["gidpost_flags"].Has(
                "WriteConditionsFlag"):
            GidConfig["result_file_configuration"][
                "gidpost_flags"].AddEmptyValue("WriteConditionsFlag")

        if self.WriteDesignSurface:
            GidConfig["result_file_configuration"]["gidpost_flags"][
                "WriteConditionsFlag"].SetString("WriteConditions")
        elif self.WriteOptimizationModelPart:
            GidConfig["result_file_configuration"]["gidpost_flags"][
                "WriteConditionsFlag"].SetString("WriteElementsOnly")

    # --------------------------------------------------------------------------
    def InitializeLogging(self):
        self.GidIO.ExecuteInitialize()
        self.GidIO.ExecuteBeforeSolutionLoop()

    # --------------------------------------------------------------------------
    def LogCurrentDesign(self, optimizationIteration):
        OriginalTime = self.OptimizationModelPart.ProcessInfo[TIME]
        self.OptimizationModelPart.ProcessInfo[TIME] = optimizationIteration

        self.GidIO.ExecuteInitializeSolutionStep()
        if (self.GidIO.IsOutputStep()):
            self.GidIO.PrintOutput()
        self.GidIO.ExecuteFinalizeSolutionStep()

        self.OptimizationModelPart.ProcessInfo[TIME] = OriginalTime

    # --------------------------------------------------------------------------
    def FinalizeLogging(self):
        self.GidIO.ExecuteFinalize()
class ManufacturedSolutionProblem:
    def __init__(self, input_file_name, settings_file_name, problem_type):

        self.problem_type = problem_type
        self.input_file_name = input_file_name
        self.settings_file_name = settings_file_name

    def SetFluidProblem(self):

        ## Parse the ProjectParameters
        parameter_file = open(self.settings_file_name, 'r')
        self.ProjectParameters = Parameters(parameter_file.read())

        ## Set the current mesh case problem info
        if (self.problem_type == "Manufactured solution"):
            self.ProjectParameters["problem_data"]["problem_name"].SetString(
                self.input_file_name + "_manufactured")
        else:
            self.ProjectParameters["problem_data"]["problem_name"].SetString(
                self.input_file_name)
        self.ProjectParameters["solver_settings"]["model_import_settings"][
            "input_filename"].SetString(self.input_file_name)

        ## Fluid model part definition
        self.main_model_part = ModelPart(self.ProjectParameters["problem_data"]
                                         ["model_part_name"].GetString())
        self.main_model_part.ProcessInfo.SetValue(
            DOMAIN_SIZE,
            self.ProjectParameters["problem_data"]["domain_size"].GetInt())

        ###TODO replace this "model" for real one once available
        Model = {
            self.ProjectParameters["problem_data"]["model_part_name"].GetString(
            ):
            self.main_model_part
        }

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

        self.solver.AddVariables()

        ## Read the model - note that SetBufferSize is done here
        self.solver.ImportModelPart()

        ## Add AddDofs
        self.solver.AddDofs()

        ## Initialize GiD  I/O
        from gid_output_process import GiDOutputProcess
        self.gid_output = GiDOutputProcess(
            self.solver.GetComputingModelPart(),
            self.ProjectParameters["problem_data"]["problem_name"].GetString(),
            self.ProjectParameters["output_configuration"])

        self.gid_output.ExecuteInitialize()

        ## Get the list of the skin submodel parts in the object Model
        for i in range(self.ProjectParameters["solver_settings"]
                       ["skin_parts"].size()):
            skin_part_name = self.ProjectParameters["solver_settings"][
                "skin_parts"][i].GetString()
            Model.update({
                skin_part_name:
                self.main_model_part.GetSubModelPart(skin_part_name)
            })
        for i in range(self.ProjectParameters["solver_settings"]
                       ["no_skin_parts"].size()):
            no_skin_part_name = self.ProjectParameters["solver_settings"][
                "no_skin_parts"][i].GetString()
            Model.update({
                no_skin_part_name:
                self.main_model_part.GetSubModelPart(no_skin_part_name)
            })

        ## Solver initialization
        self.solver.Initialize()

        ## Compute and set the nodal area
        self.SetNodalArea()

        ## Set the distance to 1 to have full fluid elements
        if (self.ProjectParameters["solver_settings"]
            ["solver_type"].GetString() == "Embedded"):
            for node in self.main_model_part.Nodes:
                node.SetSolutionStepValue(DISTANCE, 0, 1.0)

        ## Fix the pressure in one node (bottom left corner)
        for node in self.main_model_part.Nodes:
            if ((node.X < 0.001) and (node.Y < 0.001)):
                node.Fix(PRESSURE)
                node.SetSolutionStepValue(PRESSURE, 0, 0.0)

    def SolveFluidProblem(self):

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

        time = 0.0
        step = 0
        out = 0.0

        self.gid_output.ExecuteBeforeSolutionLoop()

        while (time <= end_time):

            time = time + Dt
            step = step + 1
            self.main_model_part.CloneTimeStep(time)

            print("STEP = ", step)
            print("TIME = ", time)

            self.gid_output.ExecuteInitializeSolutionStep()

            if (self.problem_type == "Manufactured solution"):
                # Fix the manufactured solution values (only for visualization purposes)
                self.SetManufacturedSolutionValues(fix=True,
                                                   set_on_boundary=False)
            else:
                # Set the manufactured solution source terms
                self.SetManufacturedSolutionValues(fix=True,
                                                   set_on_boundary=True)
                self.SetManufacturedSolutionSourceValues()

            if (step < 3):
                self.SetManufacturedSolutionValues(
                    False
                )  # Set the analytical solution in the two first steps
            else:
                if (self.problem_type != "Manufactured solution"):
                    self.solver.Solve()

            self.gid_output.ExecuteFinalizeSolutionStep()

            if self.gid_output.IsOutputStep():
                self.gid_output.PrintOutput()

            out = out + Dt

        self.gid_output.ExecuteFinalize()

    def SetManufacturedSolutionValues(self, fix=True, set_on_boundary=False):
        ## Set the analytical solution for the manufactured solution computation
        time = self.main_model_part.ProcessInfo[TIME]
        if (set_on_boundary == False):
            for node in self.main_model_part.Nodes:
                x_vel = self.ComputeNodalVelocityXManufacturedSolution(
                    node, time)
                y_vel = self.ComputeNodalVelocityYManufacturedSolution(
                    node, time)
                press = self.ComputeNodalPressureManufacturedSolution(node)

                if (fix == True):
                    node.Fix(VELOCITY_X)
                    node.Fix(VELOCITY_Y)
                    node.Fix(PRESSURE)

                node.SetSolutionStepValue(VELOCITY_X, 0, x_vel)
                node.SetSolutionStepValue(VELOCITY_Y, 0, y_vel)
                node.SetSolutionStepValue(PRESSURE, 0, press)
        else:
            for node in self.main_model_part.GetSubModelPart(
                    "Inlet2D_Contour").Nodes:
                x_vel = self.ComputeNodalVelocityXManufacturedSolution(
                    node, time)
                y_vel = self.ComputeNodalVelocityYManufacturedSolution(
                    node, time)

                if (fix == True):
                    node.Fix(VELOCITY_X)
                    node.Fix(VELOCITY_Y)

                node.SetSolutionStepValue(VELOCITY_X, 0, x_vel)
                node.SetSolutionStepValue(VELOCITY_Y, 0, y_vel)

    def SetNodalArea(self):
        # Compute nodal area
        for element in self.main_model_part.Elements:
            x = []
            y = []
            for node in element.GetNodes():
                x.append(node.X)
                y.append(node.Y)

            Area = 0.5 * (
                (x[1] * y[2] - x[2] * y[1]) + (x[2] * y[0] - x[0] * y[2]) +
                (x[0] * y[1] - x[1] * y[0]))  # Element area (Jacobian/2)
            # print("Element "+str(element.Id)+" area: "+str(Area))

            for node in element.GetNodes():
                aux = node.GetSolutionStepValue(
                    NODAL_AREA)  # Current nodal area (from other elements)
                aux += Area / 3.0  # Accumulate the current element nodal area
                node.SetSolutionStepValue(NODAL_AREA, 0, aux)
                node.SetValue(NODAL_AREA, aux)

        ## Check nodal area computation (squared shaped domain of 1x1 m)
        AreaTotal = 0.0
        for node in self.main_model_part.Nodes:
            # print("Node id "+str(node.Id)+" nodal area: "+str(node.GetValue(NODAL_AREA)))
            AreaTotal += node.GetValue(NODAL_AREA)

        if (abs(1.0 - AreaTotal) > 1e-5):
            print("Obtained total area: " + str(AreaTotal))
            raise Exception("Error in NODAL_AREA computation.")

    def SetManufacturedSolutionSourceValues(self):
        ## Set the body force as source term
        time = self.main_model_part.ProcessInfo[TIME]

        for node in self.main_model_part.Nodes:
            rho = node.GetSolutionStepValue(DENSITY)
            # nodal_area = node.GetValue(NODAL_AREA)
            # If VMS2D element is used, set mu as the Kinematic viscosity
            if (self.ProjectParameters["solver_settings"]
                ["solver_type"].GetString() == "Embedded"):
                mu = node.GetSolutionStepValue(DYNAMIC_VISCOSITY)
            elif (self.ProjectParameters["solver_settings"]
                  ["solver_type"].GetString() == "Monolithic"):
                mu = rho * node.GetSolutionStepValue(VISCOSITY)

            # Trigonometric transient field obtained with by hand derivation
            # rhofy = -rho*pi*cos(pi*node.X)*sin(pi*node.Y)*cos(pi*time) - 2*mu*pi*pi*cos(pi*node.X)*sin(pi*node.Y)*sin(pi*time) + rho*pi*(sin(pi*time)**2)*sin(pi*node.Y)*cos(pi*node.Y)
            # rhofx =  rho*pi*sin(pi*node.X)*cos(pi*node.Y)*cos(pi*time) + 2*mu*pi*pi*sin(pi*node.X)*cos(pi*node.Y)*sin(pi*time) + rho*pi*(sin(pi*time)**2)*sin(pi*node.X)*cos(pi*node.X)
            rhofx = -rho * pi * sin(pi * node.X) * cos(pi * node.Y) * sin(
                pi * time) + 2 * mu * pi * pi * sin(pi * node.X) * cos(
                    pi * node.Y) * cos(pi * time) + rho * pi * (cos(
                        pi * time)**2) * sin(pi * node.X) * cos(pi * node.X)
            rhofy = rho * pi * cos(pi * node.X) * sin(pi * node.Y) * sin(
                pi * time) - 2 * mu * pi * pi * cos(pi * node.X) * sin(
                    pi * node.Y) * cos(pi * time) + rho * pi * (cos(
                        pi * time)**2) * sin(pi * node.Y) * cos(pi * node.Y)

            # Trigonometric transient field obtained with symbolic generation
            # rhofx =  2*pi**2*mu*sin(pi*node.X)*sin(pi*time)*cos(pi*node.Y) + rho*(pi*sin(pi*node.X)*sin(pi*node.Y)**2*sin(pi*time)**2*cos(pi*node.X) + pi*sin(pi*node.X)*sin(pi*time)**2*cos(pi*node.X)*cos(pi*node.Y)**2) + pi*rho*sin(pi*node.X)*cos(pi*node.Y)*cos(pi*time)
            # rhofy = -2*pi**2*mu*sin(pi*node.Y)*sin(pi*time)*cos(pi*node.X) + rho*(pi*sin(pi*node.X)**2*sin(pi*node.Y)*sin(pi*time)**2*cos(pi*node.Y) + pi*sin(pi*node.Y)*sin(pi*time)**2*cos(pi*node.X)**2*cos(pi*node.Y)) - pi*rho*sin(pi*node.Y)*cos(pi*node.X)*cos(pi*time)
            # print("Node id. ",node.Id," by hand: ",rhofx_an," ",rhofy_an," sym: ",rhofx," ",rhofy)

            # Non-linear transient field
            # rhofx =   rho*pi*(node.X**2)*node.Y*cos(pi*time) - 2*mu*node.Y*sin(pi*time) + rho*(node.X**3)*(node.Y**2)*((sin(pi*time))**2)
            # rhofy =  -rho*pi*node.X*(node.Y**2)*cos(pi*time) + 2*mu*node.X*sin(pi*time) + rho*(node.X**2)*(node.Y**3)*((sin(pi*time))**2)

            # Non-linear stationary field
            # rhofx = -2*mu*node.Y + rho*node.X**3*node.Y**2
            # rhofy =  2*mu*node.X + rho*node.X**2*node.Y**3

            node.SetSolutionStepValue(
                BODY_FORCE_X, 0,
                rhofx / rho)  # Set the x-component body force field
            node.SetSolutionStepValue(
                BODY_FORCE_Y, 0,
                rhofy / rho)  # Set the y-component body force field

    def ComputeVelocityErrorNorm(self):
        err_v = 0

        for node in self.main_model_part.Nodes:
            weight = node.GetValue(NODAL_AREA)
            vel_x = node.GetSolutionStepValue(VELOCITY_X)
            vel_y = node.GetSolutionStepValue(VELOCITY_Y)
            end_time = self.main_model_part.ProcessInfo[TIME]

            analytical_vel_x = self.ComputeNodalVelocityXManufacturedSolution(
                node, end_time)
            analytical_vel_y = self.ComputeNodalVelocityYManufacturedSolution(
                node, end_time)

            err_x = analytical_vel_x - vel_x
            err_y = analytical_vel_y - vel_y
            err_node = err_x**2 + err_y**2
            err_v += weight * err_node

        return sqrt(
            err_v
        )  # Note, there is no need of dividing by the total area (sum of weights) since it is 1

    def ComputePressureErrorNorm(self):
        err_p = 0

        for node in self.main_model_part.Nodes:
            weight = node.GetValue(NODAL_AREA)
            pres = node.GetSolutionStepValue(PRESSURE)
            analytical_pres = self.ComputeNodalPressureManufacturedSolution(
                node)
            err_p += weight * (analytical_pres - pres)**2

        return sqrt(
            err_p
        )  # Note, there is no need of dividing by the total area (sum of weights) since it is 1

    def ComputeNodalDensityManufacturedSolution(self, node):
        # return 1.0 + 0.1*math.sin(0.75*math.pi*node.X) + 0.15*math.cos(1.0*math.pi*node.Y) + 0.08*math.cos(1.25*math.pi*node.X*node.Y)
        return 1.0

    # def ComputeNodalVelocityXManufacturedSolution(self, node):
    def ComputeNodalVelocityXManufacturedSolution(self, node, time):
        # return sin(pi*node.X)*cos(pi*node.Y)*sin(pi*time)   # Time dependent solution
        return sin(pi * node.X) * cos(pi * node.Y) * cos(
            pi * time)  # Time dependent solution
        # return node.X**2*node.Y*sin(pi*time)                # Non-linear transient field
        # return node.X**2*node.Y                             # Non-linear stationary field

    # def ComputeNodalVelocityYManufacturedSolution(self, node):
    def ComputeNodalVelocityYManufacturedSolution(self, node, time):
        # return -cos(pi*node.X)*sin(pi*node.Y)*sin(pi*time) # Time dependent solution
        return -cos(pi * node.X) * sin(pi * node.Y) * cos(
            pi * time)  # Time dependent solution
        # return -node.X*node.Y**2*sin(pi*time)               # Non-linear transient field
        # return -node.X*node.Y**2                            # Non-linear stationary field

    def ComputeNodalPressureManufacturedSolution(self, node):
        # return 100000.0 - 30000.0*math.cos(1.0*math.pi*node.X) + 20000.0*math.sin(1.25*math.pi*node.Y) - 25000.0*math.sin(0.75*math.pi*node.X*node.Y)
        return 0.0
class KratosExecuteMokBenchmark(KratosUnittest.TestCase):
    def __init__(self, ProjectParameters):

        self.ProjectParameters = ProjectParameters

        ## Fluid-Structure model parts definition
        self.structure_main_model_part = ModelPart(
            self.ProjectParameters["structure_solver_settings"]["problem_data"]
            ["model_part_name"].GetString())
        self.structure_main_model_part.ProcessInfo.SetValue(
            DOMAIN_SIZE, self.ProjectParameters["structure_solver_settings"]
            ["problem_data"]["domain_size"].GetInt())

        self.fluid_main_model_part = ModelPart(
            self.ProjectParameters["fluid_solver_settings"]["problem_data"]
            ["model_part_name"].GetString())
        self.fluid_main_model_part.ProcessInfo.SetValue(
            DOMAIN_SIZE, self.ProjectParameters["fluid_solver_settings"]
            ["problem_data"]["domain_size"].GetInt())

        FluidModel = {
            self.ProjectParameters["fluid_solver_settings"]["problem_data"]["model_part_name"].GetString(
            ):
            self.fluid_main_model_part
        }
        SolidModel = {
            self.ProjectParameters["structure_solver_settings"]["problem_data"]["model_part_name"].GetString(
            ):
            self.structure_main_model_part
        }

        ## Solver construction
        solver_module = __import__(
            "partitioned_fsi_solver"
        )  # Currently there is only one FSI solver up to date
        self.solver = solver_module.CreateSolver(
            self.structure_main_model_part, self.fluid_main_model_part,
            self.ProjectParameters)

        self.solver.AddVariables()

        ## Read the model - note that SetBufferSize is done here
        self.solver.ImportModelPart()

        ## Add AddDofs
        self.solver.AddDofs()

        ## Initialize GiD  I/O
        self.output_post = False  # Set this variable to True if it is need to print the results for debugging purposes
        if (self.output_post == True):
            from gid_output_process import GiDOutputProcess

            self.gid_output_structure = GiDOutputProcess(
                self.solver.structure_solver.GetComputingModelPart(),
                self.ProjectParameters["structure_solver_settings"]
                ["problem_data"]["problem_name"].GetString() + "_structure",
                self.ProjectParameters["structure_solver_settings"]
                ["output_configuration"])

            self.gid_output_fluid = GiDOutputProcess(
                self.solver.fluid_solver.GetComputingModelPart(),
                self.ProjectParameters["fluid_solver_settings"]["problem_data"]
                ["problem_name"].GetString() + "_fluid",
                self.ProjectParameters["fluid_solver_settings"]
                ["output_configuration"])

            self.gid_output_structure.ExecuteInitialize()
            self.gid_output_fluid.ExecuteInitialize()

        ## Get the list of the skin submodel parts in the object Model (FLUID)
        for i in range(self.ProjectParameters["fluid_solver_settings"]
                       ["solver_settings"]["skin_parts"].size()):
            skin_part_name = self.ProjectParameters["fluid_solver_settings"][
                "solver_settings"]["skin_parts"][i].GetString()
            FluidModel.update({
                skin_part_name:
                self.fluid_main_model_part.GetSubModelPart(skin_part_name)
            })

        ## Get the list of the no-skin submodel parts in the object Model (FLUID)
        for i in range(self.ProjectParameters["fluid_solver_settings"]
                       ["solver_settings"]["no_skin_parts"].size()):
            no_skin_part_name = self.ProjectParameters[
                "fluid_solver_settings"]["solver_settings"]["no_skin_parts"][
                    i].GetString()
            FluidModel.update({
                no_skin_part_name:
                self.fluid_main_model_part.GetSubModelPart(no_skin_part_name)
            })

        ## Get the list of the initial conditions submodel parts in the object Model (FLUID)
        for i in range(self.ProjectParameters["fluid_solver_settings"]
                       ["initial_conditions_process_list"].size()):
            initial_cond_part_name = self.ProjectParameters[
                "fluid_solver_settings"]["initial_conditions_process_list"][i][
                    "Parameters"]["model_part_name"].GetString()
            FluidModel.update({
                initial_cond_part_name:
                self.fluid_main_model_part.GetSubModelPart(
                    initial_cond_part_name)
            })

        ## Get the gravity submodel part in the object Model (FLUID)
        for i in range(self.ProjectParameters["fluid_solver_settings"]
                       ["gravity"].size()):
            gravity_part_name = self.ProjectParameters[
                "fluid_solver_settings"]["gravity"][i]["Parameters"][
                    "model_part_name"].GetString()
            FluidModel.update({
                gravity_part_name:
                self.fluid_main_model_part.GetSubModelPart(gravity_part_name)
            })

        ## Get the list of the submodel part in the object Model (STRUCTURE)
        for i in range(
                self.ProjectParameters["structure_solver_settings"]
            ["solver_settings"]["processes_sub_model_part_list"].size()):
            part_name = self.ProjectParameters["structure_solver_settings"][
                "solver_settings"]["processes_sub_model_part_list"][
                    i].GetString()
            SolidModel.update({
                part_name:
                self.structure_main_model_part.GetSubModelPart(part_name)
            })

        ## Processes construction
        import process_factory
        # "list_of_processes" contains all the processes already constructed (boundary conditions, initial conditions and gravity)
        # Note that the conditions are firstly constructed. Otherwise, they may overwrite the BCs information.

        # FLUID DOMAIN PROCESSES
        self.list_of_processes = process_factory.KratosProcessFactory(
            FluidModel).ConstructListOfProcesses(
                self.ProjectParameters["fluid_solver_settings"]
                ["initial_conditions_process_list"])
        self.list_of_processes += process_factory.KratosProcessFactory(
            FluidModel).ConstructListOfProcesses(
                self.ProjectParameters["fluid_solver_settings"]
                ["boundary_conditions_process_list"])
        self.list_of_processes += process_factory.KratosProcessFactory(
            FluidModel).ConstructListOfProcesses(
                self.ProjectParameters["fluid_solver_settings"]["gravity"])

        # SOLID DOMAIN PROCESSES
        self.list_of_processes += process_factory.KratosProcessFactory(
            SolidModel).ConstructListOfProcesses(
                self.ProjectParameters["structure_solver_settings"]
                ["constraints_process_list"])
        self.list_of_processes += process_factory.KratosProcessFactory(
            SolidModel).ConstructListOfProcesses(
                self.ProjectParameters["structure_solver_settings"]
                ["loads_process_list"])

        ## Processes initialization
        for process in self.list_of_processes:
            process.ExecuteInitialize()

        # Solver initialization moved after the processes initialization, otherwise the flag INTERFACE is not set
        self.solver.Initialize()

    def Solve(self):

        ## Time settings
        end_time = self.ProjectParameters["fluid_solver_settings"][
            "problem_data"]["end_time"].GetDouble()
        time = 0.0
        step = 0
        out = 0.0

        if (self.output_post == True):
            self.gid_output_structure.ExecuteBeforeSolutionLoop()
            self.gid_output_fluid.ExecuteBeforeSolutionLoop()

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

        while (time <= end_time):

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

            self.solver.SetTimeStep(step)

            self.structure_main_model_part.CloneTimeStep(time)
            self.fluid_main_model_part.CloneTimeStep(time)

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

            if (self.output_post == True):
                self.gid_output_structure.ExecuteInitializeSolutionStep()
                self.gid_output_fluid.ExecuteInitializeSolutionStep()

            (self.solver).Solve()

            for process in self.list_of_processes:
                process.ExecuteFinalizeSolutionStep()

            if (self.output_post == True):
                self.gid_output_structure.ExecuteFinalizeSolutionStep()
                self.gid_output_fluid.ExecuteFinalizeSolutionStep()

            #TODO: decide if it shall be done only when output is processed or not
            for process in self.list_of_processes:
                process.ExecuteBeforeOutputStep()

            if (self.output_post == True):
                if self.gid_output_structure.IsOutputStep():
                    self.gid_output_structure.PrintOutput()
                if self.gid_output_fluid.IsOutputStep():
                    self.gid_output_fluid.PrintOutput()

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

            out = out + Dt

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

        if (self.output_post == True):
            self.gid_output_structure.ExecuteFinalize()
            self.gid_output_fluid.ExecuteFinalize()
Beispiel #13
0
class DesignLoggerGID(DesignLogger):

    # --------------------------------------------------------------------------
    def __init__(self, model_part_controller, optimization_settings):
        self.output_settings = optimization_settings["output"]
        minimal_gid_settings = Parameters("""
        {
            "name"              : "gid",
            "gid_configuration" : {
                "result_file_configuration" : {
                    "gidpost_flags" : { }
                }
            }
        }""")

        output_format = self.output_settings["output_format"]
        if not output_format.Has("gid_configuration"):
            output_format.AddValue("gid_configuration",
                                   minimal_gid_settings["gid_configuration"])

        gid_configuration = output_format["gid_configuration"]
        if not gid_configuration.Has("result_file_configuration"):
            gid_configuration.AddValue(
                "result_file_configuration",
                minimal_gid_settings["gid_configuration"]
                ["result_file_configuration"])

        self.optimization_model_part = model_part_controller.GetOptimizationModelPart(
        )
        self.design_surface = model_part_controller.GetDesignSurface()

        self.__DetermineOutputMode()
        self.__CreateGiDIO()

    # --------------------------------------------------------------------------
    def __DetermineOutputMode(self):
        output_mode = self.output_settings["design_output_mode"].GetString()

        self.write_design_surface = False
        self.write_optimization_model_part = False

        if output_mode == "WriteDesignSurface":
            self.write_design_surface = True
        elif output_mode == "WriteOptimizationModelPart":
            if self.optimization_model_part.NumberOfElements() == 0:
                raise NameError(
                    "Output of optimization model part in Gid-format requires definition of elements. No elements are given in current mdpa! You may change the design output mode."
                )
            self.write_optimization_model_part = True
        else:
            raise NameError(
                "The following design output mode is not defined within a GiD output (name may be misspelled): "
                + output_mode)

    # --------------------------------------------------------------------------
    def __CreateGiDIO(self):
        self.__ModifySettingsToMatchDefaultGiDOutputProcess()

        gid_config = self.output_settings["output_format"]["gid_configuration"]
        results_directory = self.output_settings["output_directory"].GetString(
        )
        design_history_filename = self.output_settings[
            "design_history_filename"].GetString()
        design_history_filename_with_path = results_directory + "/" + design_history_filename

        if self.write_design_surface:
            self.gid_io = GiDOutputProcess(self.design_surface,
                                           design_history_filename_with_path,
                                           gid_config)
        elif self.write_optimization_model_part:
            self.gid_io = GiDOutputProcess(self.optimization_model_part,
                                           design_history_filename_with_path,
                                           gid_config)

    # --------------------------------------------------------------------------
    def __ModifySettingsToMatchDefaultGiDOutputProcess(self):
        self.__AddNodalResultsToGidConfiguration()
        self.__SetConditionsFlagAccordingOutputMode()

    # --------------------------------------------------------------------------
    def __AddNodalResultsToGidConfiguration(self):
        nodal_results = self.output_settings["nodal_results"]
        self.output_settings["output_format"]["gid_configuration"][
            "result_file_configuration"].AddValue("nodal_results",
                                                  nodal_results)

    # --------------------------------------------------------------------------
    def __SetConditionsFlagAccordingOutputMode(self):
        gid_config = self.output_settings["output_format"]["gid_configuration"]

        if not gid_config["result_file_configuration"]["gidpost_flags"].Has(
                "WriteConditionsFlag"):
            gid_config["result_file_configuration"][
                "gidpost_flags"].AddEmptyValue("WriteConditionsFlag")

        if self.write_design_surface:
            gid_config["result_file_configuration"]["gidpost_flags"][
                "WriteConditionsFlag"].SetString("WriteConditions")
        elif self.write_optimization_model_part:
            gid_config["result_file_configuration"]["gidpost_flags"][
                "WriteConditionsFlag"].SetString("WriteElementsOnly")

    # --------------------------------------------------------------------------
    def InitializeLogging(self):
        self.gid_io.ExecuteInitialize()
        self.gid_io.ExecuteBeforeSolutionLoop()

    # --------------------------------------------------------------------------
    def LogCurrentDesign(self, optimizationIteration):
        OriginalTime = self.optimization_model_part.ProcessInfo[TIME]
        self.optimization_model_part.ProcessInfo[TIME] = optimizationIteration

        self.gid_io.ExecuteInitializeSolutionStep()
        if (self.gid_io.IsOutputStep()):
            self.gid_io.PrintOutput()
        self.gid_io.ExecuteFinalizeSolutionStep()

        self.optimization_model_part.ProcessInfo[TIME] = OriginalTime

    # --------------------------------------------------------------------------
    def FinalizeLogging(self):
        self.gid_io.ExecuteFinalize()
Beispiel #14
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()
class kratosCSMAnalyzer((__import__("analyzer_base")).analyzerBaseClass):

    # --------------------------------------------------------------------------
    def __init__(self):

        self.initializeGIDOutput()
        self.initializeProcesses()
        self.initializeSolutionLoop()

    # --------------------------------------------------------------------------
    def initializeProcesses(self):

        import process_factory
        #the process order of execution is important
        self.list_of_processes = process_factory.KratosProcessFactory(
            Model).ConstructListOfProcesses(
                ProjectParameters["constraints_process_list"])
        self.list_of_processes += process_factory.KratosProcessFactory(
            Model).ConstructListOfProcesses(
                ProjectParameters["loads_process_list"])
        if (ProjectParameters.Has("problem_process_list")):
            self.list_of_processes += process_factory.KratosProcessFactory(
                Model).ConstructListOfProcesses(
                    ProjectParameters["problem_process_list"])
        if (ProjectParameters.Has("output_process_list")):
            self.list_of_processes += process_factory.KratosProcessFactory(
                Model).ConstructListOfProcesses(
                    ProjectParameters["output_process_list"])

        #print list of constructed processes
        if (echo_level > 1):
            for process in self.list_of_processes:
                print(process)

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

    # --------------------------------------------------------------------------
    def initializeGIDOutput(self):

        computing_model_part = CSM_solver.GetComputingModelPart()
        problem_name = ProjectParameters["problem_data"][
            "problem_name"].GetString()

        from gid_output_process import GiDOutputProcess
        output_settings = ProjectParameters["output_configuration"]
        self.gid_output = GiDOutputProcess(computing_model_part, problem_name,
                                           output_settings)

        self.gid_output.ExecuteInitialize()

    # --------------------------------------------------------------------------
    def initializeSolutionLoop(self):

        ## Sets strategies, builders, linear solvers, schemes and solving info, and fills the buffer
        CSM_solver.Initialize()
        CSM_solver.SetEchoLevel(echo_level)

        mesh_solver.Initialize()
        mesh_solver.SetEchoLevel(echo_level)

        for responseFunctionId in listOfResponseFunctions:
            listOfResponseFunctions[responseFunctionId].Initialize()

        # Start process
        for process in self.list_of_processes:
            process.ExecuteBeforeSolutionLoop()

        ## Set results when are written in a single file
        self.gid_output.ExecuteBeforeSolutionLoop()

    # --------------------------------------------------------------------------
    def analyzeDesignAndReportToCommunicator(self, currentDesign,
                                             optimizationIteration,
                                             communicator):

        # Calculation of value of objective function
        if communicator.isRequestingFunctionValueOf("strain_energy"):

            self.initializeNewSolutionStep(optimizationIteration)

            print("\n> Starting ALEApplication to update the mesh")
            startTime = timer.time()
            self.updateMeshForAnalysis()
            print("> Time needed for updating the mesh = ",
                  round(timer.time() - startTime, 2), "s")

            print(
                "\n> Starting StructuralMechanicsApplication to solve structure"
            )
            startTime = timer.time()
            self.solveStructure(optimizationIteration)
            print("> Time needed for solving the structure = ",
                  round(timer.time() - startTime, 2), "s")

            print("\n> Starting calculation of strain energy")
            startTime = timer.time()
            listOfResponseFunctions["strain_energy"].CalculateValue()
            print("> Time needed for calculation of strain energy = ",
                  round(timer.time() - startTime, 2), "s")

            communicator.reportFunctionValue(
                "strain_energy",
                listOfResponseFunctions["strain_energy"].GetValue())

        # Calculation of value of constraint function
        if communicator.isRequestingFunctionValueOf("mass"):

            print("\n> Starting calculation of value of mass constraint")
            listOfResponseFunctions["mass"].CalculateValue()
            constraintFunctionValue = listOfResponseFunctions["mass"].GetValue(
            ) - listOfResponseFunctions["mass"].GetInitialValue()
            print(
                "> Time needed for calculation of value of mass constraint = ",
                round(timer.time() - startTime, 2), "s")

            communicator.reportFunctionValue("mass", constraintFunctionValue)
            communicator.setFunctionReferenceValue(
                "mass", listOfResponseFunctions["mass"].GetInitialValue())

        # Calculation of gradients of objective function
        if communicator.isRequestingGradientOf("strain_energy"):

            print("\n> Starting calculation of gradient of objective function")
            startTime = timer.time()
            listOfResponseFunctions["strain_energy"].CalculateGradient()
            print(
                "> Time needed for calculating gradient of objective function = ",
                round(timer.time() - startTime, 2), "s")

            gradientForCompleteModelPart = listOfResponseFunctions[
                "strain_energy"].GetGradient()
            gradientOnDesignSurface = {}
            for node in currentDesign.Nodes:
                gradientOnDesignSurface[
                    node.Id] = gradientForCompleteModelPart[node.Id]

            # If contribution from mesh-motion to gradient shall be considered
            # self.computeAndAddMeshDerivativesToGradient(gradientOnDesignSurface, gradientForCompleteModelPart)

            communicator.reportGradient("strain_energy",
                                        gradientOnDesignSurface)

        # Calculation of gradients of constraint function
        if communicator.isRequestingGradientOf("mass"):

            print(
                "\n> Starting calculation of gradient of constraint function")
            startTime = timer.time()
            listOfResponseFunctions["mass"].CalculateGradient()
            print(
                "> Time needed for calculating gradient of constraint function = ",
                round(timer.time() - startTime, 2), "s")

            gradientForCompleteModelPart = listOfResponseFunctions[
                "mass"].GetGradient()
            gradientOnDesignSurface = {}
            for node in currentDesign.Nodes:
                gradientOnDesignSurface[
                    node.Id] = gradientForCompleteModelPart[node.Id]

            communicator.reportGradient("mass", gradientOnDesignSurface)

    # --------------------------------------------------------------------------
    def initializeNewSolutionStep(self, optimizationIteration):
        main_model_part.CloneTimeStep(optimizationIteration)

    # --------------------------------------------------------------------------
    def updateMeshForAnalysis(self):

        # Extract surface nodes
        sub_model_part_name = "surface_nodes"
        GeometryUtilities(main_model_part).ExtractSurfaceNodes(
            sub_model_part_name)

        # Apply shape update as boundary condition for computation of mesh displacement
        for node in main_model_part.GetSubModelPart(sub_model_part_name).Nodes:
            node.Fix(MESH_DISPLACEMENT_X)
            node.Fix(MESH_DISPLACEMENT_Y)
            node.Fix(MESH_DISPLACEMENT_Z)
            disp = Vector(3)
            disp[0] = node.GetSolutionStepValue(SHAPE_UPDATE_X)
            disp[1] = node.GetSolutionStepValue(SHAPE_UPDATE_Y)
            disp[2] = node.GetSolutionStepValue(SHAPE_UPDATE_Z)
            node.SetSolutionStepValue(MESH_DISPLACEMENT, 0, disp)

        # Solve for mesh-update
        mesh_solver.Solve()

        # Update reference mesh (Since shape updates are imposed as incremental quantities)
        mesh_solver.get_mesh_motion_solver().UpdateReferenceMesh()

        # Log absolute mesh displacement
        for node in main_model_part.Nodes:
            mesh_change = Vector(3)
            mesh_change[0] = node.GetSolutionStepValue(
                MESH_CHANGE_X) + node.GetSolutionStepValue(MESH_DISPLACEMENT_X)
            mesh_change[1] = node.GetSolutionStepValue(
                MESH_CHANGE_Y) + node.GetSolutionStepValue(MESH_DISPLACEMENT_Y)
            mesh_change[2] = node.GetSolutionStepValue(
                MESH_CHANGE_Z) + node.GetSolutionStepValue(MESH_DISPLACEMENT_Z)
            node.SetSolutionStepValue(MESH_CHANGE, 0, mesh_change)

    # --------------------------------------------------------------------------
    def solveStructure(self, optimizationIteration):

        # processes to be executed at the begining of the solution step
        for process in self.list_of_processes:
            process.ExecuteInitializeSolutionStep()

        self.gid_output.ExecuteInitializeSolutionStep()

        # Actual solution
        CSM_solver.Solve()

        # processes to be executed at the end of the solution step
        for process in self.list_of_processes:
            process.ExecuteFinalizeSolutionStep()

        # processes to be executed before witting the output
        for process in self.list_of_processes:
            process.ExecuteBeforeOutputStep()

        # write output results GiD: (frequency writing is controlled internally)
        if (self.gid_output.IsOutputStep()):
            self.gid_output.PrintOutput()

        self.gid_output.ExecuteFinalizeSolutionStep()

        # processes to be executed after witting the output
        for process in self.list_of_processes:
            process.ExecuteAfterOutputStep()

    # --------------------------------------------------------------------------
    def computeAndAddMeshDerivativesToGradient(self, gradientOnDesignSurface,
                                               gradientForCompleteModelPart):

        # Here we solve the pseudo-elastic mesh-motion system again using modified BCs
        # The contributions from the mesh derivatives appear as reaction forces
        for node in main_model_part.Nodes:

            # Apply dirichlet conditions
            if node.Id in gradientOnDesignSurface.keys():
                node.Fix(MESH_DISPLACEMENT_X)
                node.Fix(MESH_DISPLACEMENT_Y)
                node.Fix(MESH_DISPLACEMENT_Z)
                xs = Vector(3)
                xs[0] = 0.0
                xs[1] = 0.0
                xs[2] = 0.0
                node.SetSolutionStepValue(MESH_DISPLACEMENT, 0, xs)
            # Apply RHS conditions
            else:
                rhs = Vector(3)
                rhs[0] = gradientForCompleteModelPart[node.Id][0]
                rhs[1] = gradientForCompleteModelPart[node.Id][1]
                rhs[2] = gradientForCompleteModelPart[node.Id][2]
                node.SetSolutionStepValue(MESH_RHS, 0, rhs)

        # Solve mesh-motion problem with previously modified BCs
        mesh_solver.Solve()

        # Compute and add gradient contribution from mesh motion
        for node_id in gradientOnDesignSurface.keys():
            node = main_model_part.Nodes[node_id]
            sens_contribution = Vector(3)
            sens_contribution = node.GetSolutionStepValue(MESH_REACTION)
            gradientOnDesignSurface[
                node.Id] = gradientOnDesignSurface[node_id] + sens_contribution

    # --------------------------------------------------------------------------
    def finalizeSolutionLoop(self):
        for process in self.list_of_processes:
            process.ExecuteFinalize()
        self.gid_output.ExecuteFinalize()
Beispiel #16
0
    solver.Solve()
    
    StopTimeMeasuring(clock_time,"Solving", False);

    gid_output.ExecuteFinalizeSolutionStep()
    
    # processes to be executed at the end of the solution step
    for process in list_of_processes:
        process.ExecuteFinalizeSolutionStep()

    # processes to be executed before witting the output
    for process in list_of_processes:
        process.ExecuteBeforeOutputStep()
    
    # write output results GiD: (frequency writing is controlled internally)
    if(gid_output.IsOutputStep()):
        gid_output.PrintOutput()
                      
    # processes to be executed after witting the output
    for process in list_of_processes:
        process.ExecuteAfterOutputStep()


# Ending the problem (time integration finished)
gid_output.ExecuteFinalize()

for process in list_of_processes:
    process.ExecuteFinalize()

print("::[KSM Simulation]:: Analysis -END- ")
print(" ")
Beispiel #17
0
    solver.Solve()

    # streamlines_output_utility
    if (UseStreamlineUtility == True):
        streamline_utility.ComputeOutputStep(main_model_part, domain_size)

    gid_output.ExecuteFinalizeSolutionStep()

    for process in list_of_processes:
        process.ExecuteFinalizeSolutionStep()

    for process in list_of_processes:
        process.ExecuteBeforeOutputStep()

    # Write GiD results
    if gid_output.IsOutputStep():
        gid_output.PrintOutput()

    for process in list_of_processes:
        process.ExecuteAfterOutputStep()

## Finalize --------------------------------------------------------------------------------------------------

# Finalizing output files
gid_output.ExecuteFinalize()

for process in list_of_processes:
    process.ExecuteFinalize()

# Finalizing strategy
if parallel_type == "OpenMP":
Beispiel #18
0
        for process in list_of_processes_bg:
            process.ExecuteFinalizeSolutionStep()
        for process in list_of_processes_bf:
            process.ExecuteFinalizeSolutionStep()
        
        gid_output_bg.ExecuteFinalizeSolutionStep()
        gid_output_bf.ExecuteFinalizeSolutionStep()

        #TODO: decide if it shall be done only when output is processed or not
        for process in list_of_processes_bg:
            process.ExecuteBeforeOutputStep()
        for process in list_of_processes_bf:
            process.ExecuteBeforeOutputStep()
        
    
        if gid_output_bg.IsOutputStep():
            gid_output_bg.PrintOutput()
            gid_output_bf.PrintOutput()
        
        for process in list_of_processes_bg:
            process.ExecuteAfterOutputStep()
        for process in list_of_processes_bf:
            process.ExecuteAfterOutputStep()
        

        out = out + Dt

for process in list_of_processes_bg:
    process.ExecuteFinalize()
for process in list_of_processes_bf:
    process.ExecuteFinalize()