Exemplo n.º 1
0
    def __post_process(self):
        from gid_output_process import GiDOutputProcess
        self.gid_output = GiDOutputProcess(
            self.main_model_part, "gid_output",
            KM.Parameters("""
                                        {
                                            "result_file_configuration" : {
                                                "gidpost_flags": {
                                                    "GiDPostMode": "GiD_PostBinary",
                                                    "WriteDeformedMeshFlag": "WriteUndeformed",
                                                    "MultiFileFlag": "SingleFile"
                                                },
                                                "nodal_results"       : ["NORMAL","DISPLACEMENT","VELOCITY","ACCELERATION"],
                                                "nodal_nonhistorical_results": ["DELTA_COORDINATES","AUXILIAR_COORDINATES","NORMAL_GAP"],
                                                "nodal_flags_results": ["ACTIVE","SLAVE","MASTER"]
                                            }
                                        }
                                        """))

        self.gid_output.ExecuteInitialize()
        self.gid_output.ExecuteBeforeSolutionLoop()
        self.gid_output.ExecuteInitializeSolutionStep()
        self.gid_output.PrintOutput()
        self.gid_output.ExecuteFinalizeSolutionStep()
        self.gid_output.ExecuteFinalize()
    def __post_process(self):
        from gid_output_process import GiDOutputProcess
        self.gid_output = GiDOutputProcess(
            self.main_model_part, "gid_output",
            KratosMultiphysics.Parameters("""
                                        {
                                            "result_file_configuration" : {
                                                "gidpost_flags": {
                                                    "GiDPostMode": "GiD_PostBinary",
                                                    "WriteDeformedMeshFlag": "WriteUndeformed",
                                                    "WriteConditionsFlag": "WriteConditionsOnly",
                                                    "MultiFileFlag": "SingleFile"
                                                },
                                                "nodal_results"       : ["NORMAL"],
                                                "nodal_nonhistorical_results": [],
                                                "nodal_flags_results": ["ACTIVE","SLAVE"]
                                            }
                                        }
                                        """))

        self.gid_output.ExecuteInitialize()
        self.gid_output.ExecuteBeforeSolutionLoop()
        self.gid_output.ExecuteInitializeSolutionStep()
        self.gid_output.PrintOutput()
        self.gid_output.ExecuteFinalizeSolutionStep()
        self.gid_output.ExecuteFinalize()
    def __post_process(self, main_model_part):
        from gid_output_process import GiDOutputProcess
        self.gid_output = GiDOutputProcess(
            main_model_part, "gid_output",
            KratosMultiphysics.Parameters("""
                                        {
                                            "result_file_configuration" : {
                                                "gidpost_flags": {
                                                    "GiDPostMode": "GiD_PostBinary",
                                                    "WriteDeformedMeshFlag": "WriteUndeformed",
                                                    "WriteConditionsFlag": "WriteConditions",
                                                    "MultiFileFlag": "SingleFile"
                                                },
                                                "nodal_results"       : ["DISPLACEMENT"],
                                                "gauss_point_results" : []
                                            }
                                        }
                                        """))

        self.gid_output.ExecuteInitialize()
        self.gid_output.ExecuteBeforeSolutionLoop()
        self.gid_output.ExecuteInitializeSolutionStep()
        self.gid_output.PrintOutput()
        self.gid_output.ExecuteFinalizeSolutionStep()
        self.gid_output.ExecuteFinalize()
Exemplo n.º 4
0
    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
        import python_solvers_wrapper_fluid
        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)
Exemplo n.º 5
0
    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()
Exemplo n.º 6
0
    def __init__(self, ProjectParameters):

        self.ProjectParameters = ProjectParameters

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

        Model = {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, 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_flag = False
        if (self.output_flag == True):
            from gid_output_process import GiDOutputProcess
            self.gid_output = GiDOutputProcess(self.solver.GetComputingModelPart(),
                                               ProjectParameters["problem_data"]["problem_name"].GetString() ,
                                               ProjectParameters["output_configuration"])

            self.gid_output.ExecuteInitialize()

        ## Solver initialization
        self.solver.Initialize()

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

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

        ## Processes construction
        import process_factory
        self.list_of_processes = process_factory.KratosProcessFactory(Model).ConstructListOfProcesses( ProjectParameters["gravity"] )
        self.list_of_processes += process_factory.KratosProcessFactory(Model).ConstructListOfProcesses( ProjectParameters["boundary_conditions_process_list"] )

        ## Processes initialization
        for process in self.list_of_processes:
            process.ExecuteInitialize()
Exemplo n.º 7
0
    def __WriteOutput(self, model_part, output_file):

        gid_output = GiDOutputProcess(
            model_part, output_file,
            KratosMultiphysics.Parameters("""
                                        {
                                            "result_file_configuration": {
                                                "gidpost_flags": {
                                                    "GiDPostMode": "GiD_PostAscii",
                                                    "WriteDeformedMeshFlag": "WriteUndeformed",
                                                    "WriteConditionsFlag": "WriteConditions",
                                                    "MultiFileFlag": "SingleFile"
                                                },
                                                "file_label": "time",
                                                "output_control_type": "step",
                                                "output_frequency": 1.0,
                                                "body_output": true,
                                                "node_output": false,
                                                "skin_output": false,
                                                "plane_output": [],
                                                "nodal_results": ["DISPLACEMENT","VISCOSITY"],
                                                "nodal_nonhistorical_results": [],
                                                "nodal_flags_results": [],
                                                "gauss_point_results": [],
                                                "additional_list_files": []
                                            }
                                        }
                                        """))

        gid_output.ExecuteInitialize()
        gid_output.ExecuteBeforeSolutionLoop()
        gid_output.ExecuteInitializeSolutionStep()
        gid_output.PrintOutput()
        gid_output.ExecuteFinalizeSolutionStep()
        gid_output.ExecuteFinalize()
Exemplo n.º 8
0
def OutputResults(model_part, file_name):
    output_parameters = Parameters("""
    {
        "result_file_configuration" : {
            "gidpost_flags"       : {
                "GiDPostMode"           : "GiD_PostBinary",
                "WriteDeformedMeshFlag" : "WriteDeformed",
                "WriteConditionsFlag"   : "WriteConditions",
                "MultiFileFlag"         : "SingleFile"
            },
            "file_label"          : "step",
            "output_control_type" : "step",
            "output_frequency"    : 1,
            "nodal_results"       : ["CONTROL_POINT_UPDATE","CONTROL_POINT_CHANGE","SHAPE_UPDATE","PRESSURE","AIR_PRESSURE","WATER_PRESSURE"]
        },
        "point_data_configuration"  : []
    }""")
    gid_output_original = GiDOutputProcess(model_part, file_name,
                                           output_parameters)
    gid_output_original.ExecuteInitialize()
    gid_output_original.ExecuteBeforeSolutionLoop()
    gid_output_original.ExecuteInitializeSolutionStep()
    gid_output_original.PrintOutput()
    gid_output_original.ExecuteFinalizeSolutionStep()
    gid_output_original.ExecuteFinalize()
Exemplo n.º 9
0
    def _CreateGidControlOutput(self, output_name):
        for element in self._GetSolver().main_model_part.Elements:
            element.Set(KratosMultiphysics.INLET, False)
            if element.IsNot(KratosMultiphysics.ACTIVE):
                element.Set(KratosMultiphysics.INLET, True)
            element.Set(KratosMultiphysics.ACTIVE, True)
        from gid_output_process import GiDOutputProcess
        gid_output = GiDOutputProcess(
            self._GetSolver().main_model_part, output_name,
            KratosMultiphysics.Parameters("""
					{
						"result_file_configuration" : {
							"gidpost_flags": {
								"GiDPostMode": "GiD_PostBinary",
								"MultiFileFlag": "SingleFile"
							},
							"nodal_results"       : ["VELOCITY_POTENTIAL","AUXILIARY_VELOCITY_POTENTIAL"],
							"nodal_nonhistorical_results": ["METRIC_TENSOR_2D","TEMPERATURE","DISTANCE","TRAILING_EDGE"],
                        	"gauss_point_results" : ["PRESSURE_COEFFICIENT","VELOCITY","WAKE","KUTTA"],
							"nodal_flags_results": [],
                        	"elemental_conditional_flags_results": ["TO_SPLIT","THERMAL","STRUCTURE"]
						}
					}
					"""))
        gid_output.ExecuteInitialize()
        gid_output.ExecuteBeforeSolutionLoop()
        gid_output.ExecuteInitializeSolutionStep()
        gid_output.PrintOutput()
        gid_output.ExecuteFinalizeSolutionStep()
        gid_output.ExecuteFinalize()

        for element in self._GetSolver().main_model_part.Elements:
            if element.Is(KratosMultiphysics.INLET):
                element.Set(KratosMultiphysics.ACTIVE, False)
    def _post_process(self, model_part):
        from gid_output_process import GiDOutputProcess
        gid_output = GiDOutputProcess(model_part,
                                    "gid_output",
                                    KratosMultiphysics.Parameters("""
                                        {
                                            "result_file_configuration" : {
                                                "gidpost_flags": {
                                                    "GiDPostMode": "GiD_PostBinary",
                                                    "WriteDeformedMeshFlag": "WriteUndeformed",
                                                    "WriteConditionsFlag": "WriteConditions",
                                                    "MultiFileFlag": "SingleFile"
                                                },
                                                "nodal_flags_results" : ["INTERFACE","ACTIVE"]
                                            }
                                        }
                                        """)
                                    )

        gid_output.ExecuteInitialize()
        gid_output.ExecuteBeforeSolutionLoop()
        gid_output.ExecuteInitializeSolutionStep()
        gid_output.PrintOutput()
        gid_output.ExecuteFinalizeSolutionStep()
        gid_output.ExecuteFinalize()
Exemplo n.º 11
0
    def __CreateGiDIO(self):

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

        if self.write_design_surface:
            self.gid_io = GiDOutputProcess(self.design_surface,
                                           design_history_file_path,
                                           gid_config)
        elif self.write_optimization_model_part:
            self.gid_io = GiDOutputProcess(self.optimization_model_part,
                                           design_history_file_path,
                                           gid_config)
Exemplo n.º 12
0
    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)
Exemplo n.º 13
0
 def SetGraphicalOutput(self):
     if (self.ProjectParameters.Has("output_configuration")):
         from gid_output_process import GiDOutputProcess
         self.output_settings = self.ProjectParameters[
             "output_configuration"]
         return GiDOutputProcess(self.computing_model_part,
                                 self.problem_name, self.output_settings)
     else:
         return (KratosMultiphysics.Process())
Exemplo n.º 14
0
    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)
Exemplo n.º 15
0
    def __post_process(self, debug="GiD"):

        if debug == "GiD":
            from gid_output_process import GiDOutputProcess
            self.gid_output = GiDOutputProcess(
                self.main_model_part, "gid_output",
                KratosMultiphysics.Parameters("""
                                            {
                                                "result_file_configuration" : {
                                                    "gidpost_flags": {
                                                        "GiDPostMode": "GiD_PostBinary",
                                                        "WriteDeformedMeshFlag": "WriteUndeformed",
                                                        "WriteConditionsFlag": "WriteConditionsOnly",
                                                        "MultiFileFlag": "SingleFile"
                                                    },
                                                    "nodal_results"       : ["DISPLACEMENT","NORMAL","TEMPERATURE"],
                                                    "nodal_nonhistorical_results": ["NODAL_AREA","NODAL_MAUX","NODAL_VAUX"]
                                                }
                                            }
                                            """))

            self.gid_output.ExecuteInitialize()
            self.gid_output.ExecuteBeforeSolutionLoop()
            self.gid_output.ExecuteInitializeSolutionStep()
            self.gid_output.PrintOutput()
            self.gid_output.ExecuteFinalizeSolutionStep()
            self.gid_output.ExecuteFinalize()
        elif debug == "VTK":
            from vtk_output_process import VtkOutputProcess
            self.vtk_output_process = VtkOutputProcess(
                self.model,
                KratosMultiphysics.Parameters("""{
                                                "model_part_name"                    : "Main",
                                                "nodal_solution_step_data_variables" : ["DISPLACEMENT","NORMAL","TEMPERATURE"],
                                                "nodal_data_value_variables": ["NODAL_AREA","NODAL_MAUX","NODAL_VAUX"]
                                            }
                                            """))

            self.vtk_output_process.ExecuteInitialize()
            self.vtk_output_process.ExecuteBeforeSolutionLoop()
            self.vtk_output_process.ExecuteInitializeSolutionStep()
            self.vtk_output_process.PrintOutput()
            self.vtk_output_process.ExecuteFinalizeSolutionStep()
            self.vtk_output_process.ExecuteFinalize()
    def __VisualizeWake(self):
        # To visualize the wake
        number_of_nodes = self.fluid_model_part.NumberOfNodes()
        number_of_elements = self.fluid_model_part.NumberOfElements()

        node_id = number_of_nodes + 1
        for node in self.wake_model_part.Nodes:
            node.Id = node_id
            node.SetValue(KratosMultiphysics.REACTION_WATER_PRESSURE, 1.0)
            node_id += 1

        counter = number_of_elements + 1
        for elem in self.wake_model_part.Elements:
            elem.Id = counter
            counter += 1

        from gid_output_process import GiDOutputProcess
        output_file = "representation_of_wake"
        gid_output = GiDOutputProcess(
            self.wake_model_part, output_file,
            KratosMultiphysics.Parameters("""
                                    {
                                        "result_file_configuration": {
                                            "gidpost_flags": {
                                                "GiDPostMode": "GiD_PostAscii",
                                                "WriteDeformedMeshFlag": "WriteUndeformed",
                                                "WriteConditionsFlag": "WriteConditions",
                                                "MultiFileFlag": "SingleFile"
                                            },
                                            "file_label": "time",
                                            "output_control_type": "step",
                                            "output_frequency": 1.0,
                                            "body_output": true,
                                            "node_output": false,
                                            "skin_output": false,
                                            "plane_output": [],
                                            "nodal_results": [],
                                            "nodal_nonhistorical_results": ["REACTION_WATER_PRESSURE"],
                                            "nodal_flags_results": [],
                                            "gauss_point_results": [],
                                            "additional_list_files": []
                                        }
                                    }
                                    """))

        gid_output.ExecuteInitialize()
        gid_output.ExecuteBeforeSolutionLoop()
        gid_output.ExecuteInitializeSolutionStep()
        gid_output.PrintOutput()
        gid_output.ExecuteFinalizeSolutionStep()
        gid_output.ExecuteFinalize()
def OutputModelPart(output_mdpa, output_filename, nodal_results):
    output_parameters = KM.Parameters(
        """ { "result_file_configuration" : { "nodal_results" : [] } }""")
    for entry in nodal_results:
        output_parameters["result_file_configuration"]["nodal_results"].Append(
            entry)
    gid_output_original = GiDOutputProcess(output_mdpa, output_filename,
                                           output_parameters)
    gid_output_original.ExecuteInitialize()
    gid_output_original.ExecuteBeforeSolutionLoop()
    gid_output_original.ExecuteInitializeSolutionStep()
    gid_output_original.PrintOutput()
    gid_output_original.ExecuteFinalizeSolutionStep()
    gid_output_original.ExecuteFinalize()
def _create_post_process(main_model_part, constitutive_law_type):
    from gid_output_process import GiDOutputProcess
    gid_output = GiDOutputProcess(
        main_model_part, "gid_output_" + constitutive_law_type,
        KratosMultiphysics.Parameters("""
                                    {
                                        "result_file_configuration" : {
                                            "gidpost_flags": {
                                                "GiDPostMode": "GiD_PostBinary",
                                                "WriteDeformedMeshFlag": "WriteUndeformed",
                                                "WriteConditionsFlag": "WriteConditions",
                                                "MultiFileFlag": "SingleFile"
                                            },
                                            "nodal_results"       : ["DISPLACEMENT"],
                                            "gauss_point_results" : ["VON_MISES_STRESS","GREEN_LAGRANGE_STRAIN_VECTOR","PK2_STRESS_VECTOR","PLASTIC_DISSIPATION","PLASTIC_STRAIN","EQUIVALENT_PLASTIC_STRAIN","PLASTIC_STRAIN_VECTOR","UNIAXIAL_STRESS"]
                                        }
                                    }
                                    """))

    gid_output.ExecuteInitialize()
    gid_output.ExecuteBeforeSolutionLoop()
    gid_output.ExecuteInitializeSolutionStep()

    return gid_output
Exemplo n.º 19
0
    def _SetUpGiDOutput(self):
        '''Initialize self.output as a GiD output instance.'''
        self.have_output = self.ProjectParameters.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.main_model_part, self.ProjectParameters["problem_data"]
                ["problem_name"].GetString(),
                self.ProjectParameters["output_configuration"])

            self.output.ExecuteInitialize()
Exemplo n.º 20
0
    def ExecuteInitialize(self):

        GiDOutputProcess.ExecuteInitialize(self)

        # Set current time parameters
        if (self.model_part.ProcessInfo[IS_RESTARTED] == True):
            self.step_count = self.model_part.ProcessInfo[STEP]
            self.printed_step_count = self.model_part.ProcessInfo[PRINTED_STEP]
            if self.output_control_is_time:
                self.next_output = self.model_part.ProcessInfo[TIME]
            else:
                self.next_output = self.model_part.ProcessInfo[STEP]
        else:
            self.next_output = 0

        self.next_output += self.output_frequency
class TestDoubleCurvatureIntegration(KratosUnittest.TestCase):
    def setUp(self):
        pass

    def __base_test_integration(self, input_filename, num_nodes):
        KratosMultiphysics.Logger.GetDefaultOutput().SetSeverity(
            KratosMultiphysics.Logger.Severity.WARNING)

        self.main_model_part = KratosMultiphysics.ModelPart("Structure")
        self.main_model_part.SetBufferSize(2)

        self.main_model_part.AddNodalSolutionStepVariable(
            KratosMultiphysics.DISPLACEMENT)
        self.main_model_part.AddNodalSolutionStepVariable(
            KratosMultiphysics.VELOCITY)
        self.main_model_part.AddNodalSolutionStepVariable(
            KratosMultiphysics.ACCELERATION)
        self.main_model_part.AddNodalSolutionStepVariable(
            KratosMultiphysics.REACTION)
        self.main_model_part.AddNodalSolutionStepVariable(
            KratosMultiphysics.NORMAL)
        self.main_model_part.AddNodalSolutionStepVariable(
            ContactStructuralMechanicsApplication.
            LAGRANGE_MULTIPLIER_CONTACT_PRESSURE)
        self.main_model_part.AddNodalSolutionStepVariable(
            ContactStructuralMechanicsApplication.WEIGHTED_GAP)
        self.main_model_part.AddNodalSolutionStepVariable(
            KratosMultiphysics.NODAL_H)

        KratosMultiphysics.ModelPartIO(input_filename).ReadModelPart(
            self.main_model_part)

        KratosMultiphysics.VariableUtils().AddDof(
            KratosMultiphysics.DISPLACEMENT_X, KratosMultiphysics.REACTION_X,
            self.main_model_part)
        KratosMultiphysics.VariableUtils().AddDof(
            KratosMultiphysics.DISPLACEMENT_Y, KratosMultiphysics.REACTION_Y,
            self.main_model_part)
        KratosMultiphysics.VariableUtils().AddDof(
            KratosMultiphysics.DISPLACEMENT_Z, KratosMultiphysics.REACTION_Z,
            self.main_model_part)
        KratosMultiphysics.VariableUtils().AddDof(
            ContactStructuralMechanicsApplication.
            LAGRANGE_MULTIPLIER_CONTACT_PRESSURE,
            ContactStructuralMechanicsApplication.WEIGHTED_GAP,
            self.main_model_part)

        if (self.main_model_part.HasSubModelPart("Contact")):
            interface_model_part = self.main_model_part.GetSubModelPart(
                "Contact")
        else:
            interface_model_part = self.main_model_part.CreateSubModelPart(
                "Contact")

        self.contact_model_part = self.main_model_part.GetSubModelPart(
            "DISPLACEMENT_Displacement_Auto2")

        for node in self.contact_model_part.Nodes:
            node.Set(KratosMultiphysics.SLAVE, False)
        del (node)
        model_part_slave = self.main_model_part.GetSubModelPart(
            "Parts_Parts_Auto1")
        for node in model_part_slave.Nodes:
            node.Set(KratosMultiphysics.SLAVE, True)
        del (node)

        for prop in self.main_model_part.GetProperties():
            prop[ContactStructuralMechanicsApplication.
                 INTEGRATION_ORDER_CONTACT] = 3

        self.main_model_part.ProcessInfo[
            ContactStructuralMechanicsApplication.ACTIVE_CHECK_FACTOR] = 3.0e-1

        for node in self.contact_model_part.Nodes:
            node.Set(KratosMultiphysics.INTERFACE, True)

        Preprocess = ContactStructuralMechanicsApplication.InterfacePreprocessCondition(
            self.main_model_part)

        interface_parameters = KratosMultiphysics.Parameters(
            """{"simplify_geometry": false}""")
        Preprocess.GenerateInterfacePart3D(self.contact_model_part,
                                           interface_parameters)

        # We copy the conditions to the ContactSubModelPart
        for cond in self.contact_model_part.Conditions:
            interface_model_part.AddCondition(cond)
        del (cond)
        for node in self.contact_model_part.Nodes:
            interface_model_part.AddNode(node, 0)
        del (node)

        # We initialize the conditions
        alm_init_var = ContactStructuralMechanicsApplication.ALMFastInit(
            self.contact_model_part)
        alm_init_var.Execute()

        search_parameters = KratosMultiphysics.Parameters("""
        {
            "search_factor"               : 3.5,
            "allocation_size"             : 1000,
            "check_gap"                   : "NoCheck",
            "type_search"                 : "InRadius"
        }
        """)
        if (num_nodes == 3):
            contact_search = ContactStructuralMechanicsApplication.TreeContactSearch3D3N(
                self.main_model_part, search_parameters)
        else:
            contact_search = ContactStructuralMechanicsApplication.TreeContactSearch3D4N(
                self.main_model_part, search_parameters)

        # We initialize the search utility
        contact_search.CreatePointListMortar()
        contact_search.InitializeMortarConditions()
        contact_search.UpdateMortarConditions()

        if (num_nodes == 3):
            ## DEBUG
            #print(self.main_model_part)
            #self.__post_process()
            self.exact_integration = KratosMultiphysics.ExactMortarIntegrationUtility3D3N(
                3)
        else:
            ## DEBUG
            #print(self.main_model_part)
            #self.__post_process()
            self.exact_integration = KratosMultiphysics.ExactMortarIntegrationUtility3D4N(
                3)

    def _double_curvature_tests(self, input_filename, num_nodes,
                                list_of_border_cond):

        self.__base_test_integration(input_filename, num_nodes)

        #print("Solution obtained")
        tolerance = 5.0e-3
        for cond in self.contact_model_part.Conditions:
            if cond.Is(KratosMultiphysics.SLAVE):
                to_test = (cond.Id in list_of_border_cond)
                if (to_test == False):
                    area = self.exact_integration.TestGetExactAreaIntegration(
                        self.main_model_part, cond)
                    condition_area = cond.GetArea()
                    check_value = abs((area - condition_area) / condition_area)
                    if (check_value > tolerance):
                        print(cond.Id, "\t", area, "\t", condition_area, "\t",
                              self.__sci_str(check_value))
                    else:
                        self.assertLess(check_value, tolerance)

    def _moving_nodes_tests(self, input_filename, num_nodes):

        self.__base_test_integration(input_filename, num_nodes)

        for iter in range(1):
            delta_disp = 1.0e-6
            for node in self.main_model_part.GetSubModelPart(
                    "GroupPositiveX").Nodes:
                node.X += delta_disp
            del (node)
            for node in self.main_model_part.GetSubModelPart(
                    "GroupPositiveY").Nodes:
                node.Y += delta_disp
            del (node)
            for node in self.main_model_part.GetSubModelPart(
                    "GroupNegativeX").Nodes:
                node.X -= delta_disp
            del (node)
            for node in self.main_model_part.GetSubModelPart(
                    "GroupNegativeY").Nodes:
                node.Y -= delta_disp
            del (node)

            #print("Solution obtained")
            tolerance = 5.0e-5
            for cond in self.contact_model_part.Conditions:
                if cond.Is(KratosMultiphysics.SLAVE):
                    area = self.exact_integration.TestGetExactAreaIntegration(
                        self.contact_model_part, cond)
                    condition_area = cond.GetArea()
                    check_value = abs((area - condition_area) / condition_area)
                    if (check_value > tolerance):
                        print(cond.Id, "\t", area, "\t", condition_area, "\t",
                              self.__sci_str(check_value))
                    else:
                        self.assertLess(check_value, tolerance)

    def test_double_curvature_integration_triangle(self):
        input_filename = os.path.dirname(
            os.path.realpath(__file__)
        ) + "/integration_tests/test_double_curvature_integration_triangle"

        # These conditions are in the border, and can not be integrated 100% accurate
        list_of_border_cond = [
            1262, 1263, 1264, 1265, 1269, 1270, 1273, 1275, 1278, 1282, 1284,
            1285, 1286, 1288, 1290, 1291, 1292, 1294, 1295, 1297, 1298, 1302,
            1303, 1305, 1306, 1307, 1310, 1313, 1314, 1318, 1319, 1320, 1323,
            1325, 1327, 1328, 1329, 1331, 1336, 1337, 1338, 1340, 1341, 1342,
            1343, 1344, 1346, 1347, 1348, 1349, 1350, 1353, 1355, 1357, 1359,
            1360, 1366, 1367, 1368, 1369, 1370, 1377, 1378, 1379, 1381, 1382,
            1384, 1385, 1387, 1393, 1394, 1395, 1399, 1400, 1406, 1410, 1411,
            1412, 1414, 1415, 1418, 1419, 1420, 1424, 1427, 1429, 1431, 1436,
            1438, 1444, 1446, 1447, 1448, 1449, 1459, 1462, 1463, 1465, 1467,
            1468, 1474, 1477, 1479, 1485, 1491, 1493, 1507, 1515, 1517, 1531,
            1537, 1539, 1547, 1549, 1553, 1563, 1569, 1575, 1623, 1640, 1644,
            1654, 1656, 1663, 1667, 1675, 1685, 1687, 1693, 1697, 1703, 1707,
            1713, 1715, 1717, 1719, 1721, 1723, 1725
        ]

        self._double_curvature_tests(input_filename, 3, list_of_border_cond)

    def test_double_curvature_integration_quad(self):
        input_filename = os.path.dirname(
            os.path.realpath(__file__)
        ) + "/integration_tests/test_double_curvature_integration_quadrilateral"

        # These conditions are in the border, and can not be integrated 100% accurate
        list_of_border_cond = [
            916, 917, 919, 920, 923, 925, 927, 929, 933, 934, 938, 940, 941,
            944, 945, 946, 949, 951, 954, 955, 962, 963, 965, 966, 967, 968,
            969, 970, 971, 973, 974, 977, 978, 979, 980, 981, 982, 983, 984,
            985, 986, 988, 989, 990, 995, 996, 1000, 1003, 1005, 1007, 1008,
            1011, 1012, 1013, 1014, 1015, 1016, 1017, 1018, 1019, 1020, 1021,
            1022, 1023, 1024, 1041, 1042, 1043, 1044, 1045, 1046, 1047, 1048,
            1049, 1050, 1051, 1052, 1053, 1054, 1055, 1058, 1060, 1064, 1066,
            1069, 1070, 1071, 1072, 1073, 1074, 1075, 1076
        ]

        self._double_curvature_tests(input_filename, 4, list_of_border_cond)

    def test_moving_mesh_integration_quad(self):
        input_filename = os.path.dirname(os.path.realpath(
            __file__)) + "/integration_tests/quadrilaterals_moving_nodes"

        self._moving_nodes_tests(input_filename, 4)

    def test_integration_quad_non_matching(self):
        input_filename = os.path.dirname(os.path.realpath(
            __file__)) + "/integration_tests/quadrilaterals_non_matching"

        list_of_border_cond = []
        self._double_curvature_tests(input_filename, 4, list_of_border_cond)

    def __post_process(self):
        from gid_output_process import GiDOutputProcess
        self.gid_output = GiDOutputProcess(
            self.main_model_part, "gid_output",
            KratosMultiphysics.Parameters("""
                                        {
                                            "result_file_configuration" : {
                                                "gidpost_flags": {
                                                    "GiDPostMode": "GiD_PostBinary",
                                                    "WriteDeformedMeshFlag": "WriteUndeformed",
                                                    "WriteConditionsFlag": "WriteConditionsOnly",
                                                    "MultiFileFlag": "SingleFile"
                                                },
                                                "nodal_results"       : ["NORMAL"],
                                                "nodal_nonhistorical_results": [],
                                                "nodal_flags_results": ["ACTIVE","SLAVE"]
                                            }
                                        }
                                        """))

        self.gid_output.ExecuteInitialize()
        self.gid_output.ExecuteBeforeSolutionLoop()
        self.gid_output.ExecuteInitializeSolutionStep()
        self.gid_output.PrintOutput()
        self.gid_output.ExecuteFinalizeSolutionStep()
        self.gid_output.ExecuteFinalize()

    def __sci_str(self, x):
        from decimal import Decimal
        s = 10 * Decimal(str(x))
        s = ('{:.' + str(len(s.normalize().as_tuple().digits) - 1) +
             'E}').format(s)
        s = s.replace('E+', 'D0')
        s = s.replace('E-', 'D0-')
        s = s.replace('.', '')
        if s.startswith('-'):
            return '-.' + s[1:]
        else:
            return '.' + s
Exemplo n.º 22
0
# Set TIME and DELTA_TIME and fill the previous steps of the buffer with the initial conditions
time = time - (buffer_size - 1) * delta_time
main_model_part.ProcessInfo.SetValue(KratosMultiphysics.TIME, time)
for step in range(buffer_size - 1):
    time = time + delta_time
    main_model_part.CloneTimeStep(time)

# Initialize GiD I/O
computing_model_part = solver.GetComputingModelPart()
output_settings = ProjectParameters["output_configuration"]
if parallel_type == "OpenMP":
    import poromechanics_cleaning_utility
    poromechanics_cleaning_utility.CleanPreviousFiles(
        problem_path)  # Clean previous post files
    from gid_output_process import GiDOutputProcess
    gid_output = GiDOutputProcess(computing_model_part, problem_name,
                                  output_settings)
else:
    from gid_output_process_mpi import GiDOutputProcessMPI
    gid_output = GiDOutputProcessMPI(computing_model_part, problem_name,
                                     output_settings)
gid_output.ExecuteInitialize()

# Initialize the solver
solver.Initialize()

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

## Set results when they are written in a single file
gid_output.ExecuteBeforeSolutionLoop()
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()
Exemplo n.º 24
0
    def GenereateNewModelPart(self, old_main_model_part, solver,
                              list_of_processes, gid_output):

        ### Finalize Old Model ---------------------------------------------------------------------------------------

        # Finalizing output files
        gid_output.ExecuteFinalize()

        for process in list_of_processes:
            process.ExecuteFinalize()

        # Finalizing strategy
        solver.Clear()

        # Save old .post.list file
        all_list_filename = str(self.problem_name) + "_all.post.lst"
        all_list_file = open(all_list_filename, 'a')
        partial_list_filename = str(self.problem_name) + ".post.lst"
        with open(partial_list_filename) as partial_list_file:
            next(partial_list_file)
            for line in partial_list_file:
                all_list_file.write(line)
        all_list_file.close()
        # Save old .time file
        original_filename = str(self.problem_name) + ".time"
        original_filepath = os.path.join(str(self.problem_path),
                                         str(original_filename))
        new_filename = str(self.problem_name) + "_" + str(
            self.remesh_count) + "info.time"
        new_filepath = os.path.join(str(self.problem_path), str(new_filename))
        shutil.copy(str(original_filepath), str(new_filepath))

        ### Generate New Model ---------------------------------------------------------------------------------------

        # Parsing the parameters
        with open("ProjectParameters.json", 'r') as parameter_file:
            ProjectParameters = KratosMultiphysics.Parameters(
                parameter_file.read())

        ## Model part ------------------------------------------------------------------------------------------------

        # Defining the model part
        self.model_part_number = self.model_part_number + 1
        new_model_part_name = str(self.original_model_part_name) + '_' + str(
            self.model_part_number)

        new_model_part = self.model.CreateModelPart(new_model_part_name, 2)

        new_model_part.ProcessInfo.SetValue(KratosMultiphysics.DOMAIN_SIZE,
                                            self.domain_size)
        new_model_part.ProcessInfo.SetValue(
            KratosMultiphysics.DELTA_TIME,
            old_main_model_part.ProcessInfo[KratosMultiphysics.DELTA_TIME])
        new_model_part.ProcessInfo.SetValue(
            KratosPoro.TIME_UNIT_CONVERTER,
            old_main_model_part.ProcessInfo[KratosPoro.TIME_UNIT_CONVERTER])

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

        # Add problem variables
        solver.AddVariables()

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

        # Add degrees of freedom
        solver.AddDofs()

        # Print model_part
        echo_level = ProjectParameters["solver_settings"]["echo_level"].GetInt(
        )
        if (echo_level > 1):
            print(new_model_part)

        ## Initialize ------------------------------------------------------------------------------------------------

        # Construct processes to be applied
        import process_factory
        list_of_processes = process_factory.KratosProcessFactory(
            PoroModel).ConstructListOfProcesses(
                ProjectParameters["constraints_process_list"])
        list_of_processes += process_factory.KratosProcessFactory(
            PoroModel).ConstructListOfProcesses(
                ProjectParameters["loads_process_list"])

        # Initialize processes
        for process in list_of_processes:
            process.ExecuteInitialize()

        # Set TIME
        new_model_part.ProcessInfo.SetValue(
            KratosMultiphysics.TIME,
            old_main_model_part.ProcessInfo[KratosMultiphysics.TIME])

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

        # Initialize the solver
        solver.Initialize()

        # Initialize the strategy before the mapping
        solver.InitializeStrategy()

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

        ## Set results when they are written in a single file (only multiplefiles for the moment)
        gid_output.ExecuteBeforeSolutionLoop()

        ### Mapping between old and new model parts ------------------------------------------------------------------

        self.PropagationUtility.MappingModelParts(self.FracturesData,
                                                  old_main_model_part,
                                                  new_model_part,
                                                  self.move_mesh_flag)

        # set ARC_LENGTH_LAMBDA and ARC_LENGTH_RADIUS_FACTOR and update loads
        if ProjectParameters["solver_settings"]["strategy_type"].GetString(
        ) == "arc_length":
            new_model_part.ProcessInfo.SetValue(
                KratosPoro.ARC_LENGTH_LAMBDA,
                old_main_model_part.ProcessInfo[KratosPoro.ARC_LENGTH_LAMBDA])
            new_model_part.ProcessInfo.SetValue(
                KratosPoro.ARC_LENGTH_RADIUS_FACTOR,
                old_main_model_part.ProcessInfo[
                    KratosPoro.ARC_LENGTH_RADIUS_FACTOR])
            solver._UpdateLoads()

        # delete old model_part
        old_model_part_number = self.model_part_number - 1
        old_model_part_name = str(
            self.original_model_part_name) + '_' + str(old_model_part_number)
        self.model.DeleteModelPart(old_model_part_name)

        # Check new mesh
        #IsConverged = solver._CheckConvergence()

        return new_model_part, solver, list_of_processes, gid_output
Exemplo n.º 25
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()
Exemplo n.º 26
0
 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)
Exemplo n.º 27
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, " ] ")
Exemplo n.º 28
0
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()
Exemplo n.º 29
0
    ProjectParameters["solver_settings"]["solver_type"].GetString())
solver = solver_module.CreateSolver(main_model_part,
                                    ProjectParameters["solver_settings"])

solver.AddVariables()

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

## Add AddDofs
solver.AddDofs()

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

gid_output.ExecuteInitialize()

##here all of the allocation of the strategies etc is done
solver.Initialize()

##TODO: replace MODEL for the Kratos one ASAP
## Get the list of the skin submodel parts in the object Model
for i in range(ProjectParameters["solver_settings"]["skin_parts"].size()):
    skin_part_name = ProjectParameters["solver_settings"]["skin_parts"][
        i].GetString()
    Model.update(
        {skin_part_name: main_model_part.GetSubModelPart(skin_part_name)})
Exemplo n.º 30
0
solver_module = __import__(ProjectParameters["coupling_solver_settings"]["solver_settings"]["solver_type"].GetString())
solver = solver_module.CreateSolver(structure_main_model_part, fluid_main_model_part, ProjectParameters)

solver.AddVariables()

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

## Add AddDofs
solver.AddDofs()

## Initialize GiD  I/O
if (parallel_type == "OpenMP"):
    from gid_output_process import GiDOutputProcess
    gid_output_structure = GiDOutputProcess(solver.structure_solver.GetComputingModelPart(),
                                        ProjectParameters["structure_solver_settings"]["problem_data"]["problem_name"].GetString()+"_structure",
                                        ProjectParameters["structure_solver_settings"]["output_configuration"])
    gid_output_fluid = GiDOutputProcess(solver.fluid_solver.GetComputingModelPart(),
                                        ProjectParameters["fluid_solver_settings"]["problem_data"]["problem_name"].GetString()+"_fluid",
                                        ProjectParameters["fluid_solver_settings"]["output_configuration"])

elif (parallel_type == "MPI"):
    from gid_output_process_mpi import GiDOutputProcessMPI
    gid_output_structure = GiDOutputProcessMPI(solver.structure_solver.GetComputingModelPart(),
                                               ProjectParameters["structure_solver_settings"]["problem_data"]["problem_name"].GetString()+"_structure",
                                               ProjectParameters["structure_solver_settings"]["output_configuration"])

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