예제 #1
0
 def _CreateLinearSolver(self):
     # Create the pressure linear solver
     pressure_linear_solver_configuration = self.settings["pressure_linear_solver_settings"]
     pressure_linear_solver = trilinos_linear_solver_factory.ConstructSolver(pressure_linear_solver_configuration)
     # Create the velocity linear solver
     velocity_linear_solver_configuration = self.settings["velocity_linear_solver_settings"]
     velocity_linear_solver = trilinos_linear_solver_factory.ConstructSolver(velocity_linear_solver_configuration)
     # Return a tuple containing both linear solvers
     return (pressure_linear_solver, velocity_linear_solver)
예제 #2
0
    def set_variational_distance_process(self):
        # Construct the variational distance calculation process
        self.EpetraCommunicator = KratosTrilinos.CreateCommunicator()
        maximum_iterations = 5

        ### for MPI
        trilinos_settings = KratosMultiphysics.Parameters("""
        {
            "linear_solver_settings"   : {
                "solver_type" : "amgcl"
            }
        }
        """)

        self.linear_solver = trilinos_linear_solver_factory.ConstructSolver(
            trilinos_settings["linear_solver_settings"])

        if self.complete_model.ProcessInfo[
                KratosMultiphysics.DOMAIN_SIZE] == 2:
            variational_distance_process = KratosTrilinos.TrilinosVariationalDistanceCalculationProcess2D(
                self.EpetraCommunicator, self.complete_model,
                self.linear_solver, maximum_iterations,
                KratosMultiphysics.VariationalDistanceCalculationProcess2D.
                CALCULATE_EXACT_DISTANCES_TO_PLANE, "distance_from_inlet_2D")
        else:
            variational_distance_process = KratosTrilinos.TrilinosVariationalDistanceCalculationProcess3D(
                self.EpetraCommunicator, self.complete_model,
                self.linear_solver, maximum_iterations,
                KratosMultiphysics.VariationalDistanceCalculationProcess3D.
                CALCULATE_EXACT_DISTANCES_TO_PLANE, "distance_from_inlet_3D")

        return variational_distance_process
예제 #3
0
    def __init__(self, model, custom_settings):
        self._validate_settings_in_baseclass = True  # To be removed eventually
        # Note: deliberately calling the constructor of the base python solver (the parent of my parent)
        custom_settings = self._BackwardsCompatibilityHelper(custom_settings)
        super(navier_stokes_solver_vmsmonolithic.NavierStokesSolverMonolithic,
              self).__init__(model, custom_settings)

        self.formulation = navier_stokes_solver_vmsmonolithic.StabilizedFormulation(
            self.settings["formulation"])
        self.element_name = self.formulation.element_name
        self.condition_name = self.formulation.condition_name
        self.element_integrates_in_time = self.formulation.element_integrates_in_time

        scheme_type = self.settings["time_scheme"].GetString()
        if scheme_type == "bossak":
            self.min_buffer_size = 2
        elif scheme_type == "bdf2":
            self.min_buffer_size = 3
        else:
            msg = "Unknown time_scheme option found in project parameters:\n"
            msg += "\"" + scheme_type + "\"\n"
            msg += "Accepted values are \"bossak\" or \"bdf2\".\n"
            raise Exception(msg)

        ## Construct the linear solver
        self.trilinos_linear_solver = trilinos_linear_solver_factory.ConstructSolver(
            self.settings["linear_solver_settings"])

        KratosMultiphysics.Logger.Print(
            "Construction of TrilinosNavierStokesSolverMonolithic finished.")
    def __init__(self, model, custom_settings):
        self._validate_settings_in_baseclass = True  # To be removed eventually
        # Note: deliberately calling the constructor of the base python solver (the parent of my parent)
        super(
            navier_stokes_embedded_solver.NavierStokesEmbeddedMonolithicSolver,
            self).__init__(model, custom_settings)

        self.min_buffer_size = 3
        self.embedded_formulation = navier_stokes_embedded_solver.EmbeddedFormulation(
            self.settings["formulation"])
        self.element_name = self.embedded_formulation.element_name
        self.condition_name = self.embedded_formulation.condition_name

        ## Set the formulation level set type
        self.level_set_type = self.embedded_formulation.level_set_type

        ## Set the nodal properties flag
        self.element_has_nodal_properties = self.embedded_formulation.element_has_nodal_properties

        ## Construct the linear solver
        self.trilinos_linear_solver = trilinos_linear_solver_factory.ConstructSolver(
            self.settings["linear_solver_settings"])

        KratosMultiphysics.Logger.PrintInfo(
            "NavierStokesMPIEmbeddedMonolithicSolver",
            "Construction of NavierStokesMPIEmbeddedMonolithicSolver finished."
        )
    def test_trilinos_levelset_convection(self):
        current_model = KratosMultiphysics.Model()
        self.model_part = current_model.CreateModelPart("Main",2)
        self.model_part.AddNodalSolutionStepVariable(KratosMultiphysics.DISTANCE)
        self.model_part.AddNodalSolutionStepVariable(KratosMultiphysics.VELOCITY)
        self.model_part.AddNodalSolutionStepVariable(KratosMultiphysics.PARTITION_INDEX)


        # Import the model part, perform the partitioning and create communicators
        import_settings = KratosMultiphysics.Parameters(self.parameters)
        DistributedModelPartImporter = distributed_import_model_part_utility.DistributedImportModelPartUtility(self.model_part, import_settings)
        DistributedModelPartImporter.ImportModelPart()
        DistributedModelPartImporter.CreateCommunicators()

        # Recall to set the buffer size
        self.model_part.SetBufferSize(2)

        # Set the initial distance field and the convection velocity
        for node in self.model_part.Nodes:
            node.SetSolutionStepValue(KratosMultiphysics.DISTANCE, 0, BaseDistance(node.X,node.Y,node.Z))
            node.SetSolutionStepValue(KratosMultiphysics.VELOCITY, 0, ConvectionVelocity(node.X,node.Y,node.Z))

        # Fix the left side values
        for node in self.model_part.Nodes:
            if node.X < 0.001:
                node.Fix(KratosMultiphysics.DISTANCE)

        # Set the Trilinos linear solver and Epetra communicator
        trilinos_linear_solver = trilinos_linear_solver_factory.ConstructSolver(
            KratosMultiphysics.Parameters("""{"solver_type" : "amesos" }""")
        )

        epetra_comm = TrilinosApplication.CreateCommunicator()

        # Fake time advance
        self.model_part.CloneTimeStep(40.0)

        # Convect the distance field
        TrilinosApplication.TrilinosLevelSetConvectionProcess2D(
            epetra_comm,
            KratosMultiphysics.DISTANCE,
            self.model_part,
            trilinos_linear_solver).Execute()

        # Check the obtained values
        max_distance = -1.0
        min_distance = +1.0

        for node in self.model_part.Nodes:
            d =  node.GetSolutionStepValue(KratosMultiphysics.DISTANCE)
            max_distance = max(max_distance, d)
            min_distance = min(min_distance, d)

        comm = self.model_part.GetCommunicator().GetDataCommunicator()
        min_distance = comm.MinAll(min_distance)
        max_distance = comm.MaxAll(max_distance)

        self.assertAlmostEqual(max_distance, 0.7333041045431626)
        self.assertAlmostEqual(min_distance,-0.06371359024393104)
예제 #6
0
    def testTrilinosRedistance(self):
        # Set the model part
        current_model = KratosMultiphysics.Model()
        self.model_part = current_model.CreateModelPart("Main")
        self.model_part.AddNodalSolutionStepVariable(KratosMultiphysics.DISTANCE)
        self.model_part.AddNodalSolutionStepVariable(KratosMultiphysics.FLAG_VARIABLE)
        self.model_part.AddNodalSolutionStepVariable(KratosMultiphysics.PARTITION_INDEX)

        # Import the model part, perform the partitioning and create communicators
        import_settings = KratosMultiphysics.Parameters(self.parameters)

        ModelPartImporter = distributed_import_model_part_utility.DistributedImportModelPartUtility(self.model_part, import_settings)
        ModelPartImporter.ImportModelPart()
        ModelPartImporter.CreateCommunicators()

        # Recall to set the buffer size
        self.model_part.SetBufferSize(2)

        # Initialize the DISTANCE values
        for node in self.model_part.Nodes:
            node.SetSolutionStepValue(KratosMultiphysics.DISTANCE,0, self._ExpectedDistance(node.X,node.Y,node.Z))

        # Fake time advance
        self.model_part.CloneTimeStep(1.0)

        # Set the utility and compute the variational distance values
        trilinos_linear_solver = trilinos_linear_solver_factory.ConstructSolver(
            KratosMultiphysics.Parameters("""{"solver_type" : "amesos" }""")
        )

        epetra_comm = TrilinosApplication.CreateCommunicator()

        max_iterations = 2
        TrilinosApplication.TrilinosVariationalDistanceCalculationProcess3D(
            epetra_comm,
            self.model_part,
            trilinos_linear_solver,
            max_iterations,
            (KratosMultiphysics.VariationalDistanceCalculationProcess3D.CALCULATE_EXACT_DISTANCES_TO_PLANE).AsFalse()
            ).Execute()

        # Check the obtained values
        max_distance = -1.0
        min_distance = +1.0

        for node in self.model_part.Nodes:
            d =  node.GetSolutionStepValue(KratosMultiphysics.DISTANCE)
            max_distance = max(max_distance, d)
            min_distance = min(min_distance, d)

        comm = self.model_part.GetCommunicator().GetDataCommunicator()
        min_distance = comm.MinAll(min_distance)
        max_distance = comm.MaxAll(max_distance)

        self.assertAlmostEqual(max_distance, 0.44556526310761013) # Serial max_distance
        self.assertAlmostEqual(min_distance,-0.504972246827639) # Serial min_distance
    def __init__(self, model, custom_settings):
        self._validate_settings_in_baseclass = True  # To be removed eventually
        # Note: deliberately calling the constructor of the base python solver (the parent of my parent)
        super(NavierStokesSolverFractionalStep,
              self).__init__(model, custom_settings)

        self.element_name = "FractionalStep"
        self.condition_name = "WallCondition"
        self.min_buffer_size = 3

        ## Construct the linear solvers
        self.pressure_linear_solver = trilinos_linear_solver_factory.ConstructSolver(
            self.settings["pressure_linear_solver_settings"])
        self.velocity_linear_solver = trilinos_linear_solver_factory.ConstructSolver(
            self.settings["velocity_linear_solver_settings"])

        self.compute_reactions = self.settings["compute_reactions"].GetBool()

        KratosMultiphysics.Logger.PrintInfo(
            "TrilinosNavierStokesSolverFractionalStep",
            "Construction of TrilinosNavierStokesSolverFractionalStep solver finished."
        )
예제 #8
0
    def test_trilinos_levelset_convection(self):
        # Set the initial distance field and the convection velocity
        for node in self.model_part.Nodes:
            node.SetSolutionStepValue(KratosMultiphysics.DISTANCE, 0,
                                      BaseDistance(node.X, node.Y, node.Z))
            node.SetSolutionStepValue(
                KratosMultiphysics.VELOCITY, 0,
                ConvectionVelocity(node.X, node.Y, node.Z))

        # Fix the left side values
        for node in self.model_part.Nodes:
            if node.X < 0.001:
                node.Fix(KratosMultiphysics.DISTANCE)

        # Set the Trilinos linear solver and Epetra communicator
        trilinos_linear_solver = trilinos_linear_solver_factory.ConstructSolver(
            KratosMultiphysics.Parameters("""{"solver_type" : "amesos" }"""))

        epetra_comm = TrilinosApplication.CreateEpetraCommunicator(
            KratosMultiphysics.DataCommunicator.GetDefault())

        # Fake time advance
        self.model_part.CloneTimeStep(40.0)

        # Convect the distance field
        levelset_convection_settings = KratosMultiphysics.Parameters("""{
            "max_CFL" : 1.0,
            "max_substeps" : 0,
            "eulerian_error_compensation" : false,
            "element_type" : "levelset_convection_supg"
        }""")
        TrilinosApplication.TrilinosLevelSetConvectionProcess2D(
            epetra_comm, self.model_part, trilinos_linear_solver,
            levelset_convection_settings).Execute()

        # Check the obtained values
        max_distance = -1.0
        min_distance = +1.0

        for node in self.model_part.Nodes:
            d = node.GetSolutionStepValue(KratosMultiphysics.DISTANCE)
            max_distance = max(max_distance, d)
            min_distance = min(min_distance, d)

        comm = self.model_part.GetCommunicator().GetDataCommunicator()
        min_distance = comm.MinAll(min_distance)
        max_distance = comm.MaxAll(max_distance)

        self.assertAlmostEqual(max_distance, 0.7333041045431626)
        self.assertAlmostEqual(min_distance, -0.06371359024393104)
예제 #9
0
    def __init__(self, model, custom_settings):
        self._validate_settings_in_baseclass=True # To be removed eventually
        super(AdjointVMSMonolithicSolver, self).__init__(model, custom_settings)

        self.element_name = "VMSAdjointElement"
        if self.settings["domain_size"].GetInt() == 2:
            self.condition_name = "LineCondition"
        elif self.settings["domain_size"].GetInt() == 3:
            self.condition_name = "SurfaceCondition"
        self.min_buffer_size = 2
        self.element_has_nodal_properties = True

        # construct the linear solver
        self.trilinos_linear_solver = trilinos_linear_solver_factory.ConstructSolver(self.settings["linear_solver_settings"])

        KratosMultiphysics.Logger.PrintInfo(self.__class__.__name__, "Construction of AdjointVMSMonolithicMPISolver finished.")
    def __init__(self, model, custom_settings):
        self._validate_settings_in_baseclass=True # To be removed eventually
        # the constructor of the "grand-parent" (jumping constructor of parent) is called to avoid conflicts in attribute settings
        super(NavierStokesTwoFluidsSolver, self).__init__(model,custom_settings)

        self.element_name = "TwoFluidNavierStokes"
        self.condition_name = "NavierStokesWallCondition"
        self.element_has_nodal_properties = True
        self.min_buffer_size = 3

        if (self.settings["solver_type"].GetString() == "TwoFluids"):
            self.element_name = "TwoFluidNavierStokes"

        ## Construct the linear solver
        self.trilinos_linear_solver = trilinos_linear_solver_factory.ConstructSolver(self.settings["linear_solver_settings"])

        KratosMultiphysics.Logger.PrintInfo("NavierStokesMPITwoFluidsSolver","Construction of NavierStokesMPITwoFluidsSolver finished.")
    def __init__(self, model, custom_settings):
        self._validate_settings_in_baseclass = True  # To be removed eventually
        # Note: deliberately calling the constructor of the base python solver (the parent of my parent)
        custom_settings = self._BackwardsCompatibilityHelper(custom_settings)
        super(navier_stokes_solver_vmsmonolithic.NavierStokesSolverMonolithic,
              self).__init__(model, custom_settings)

        self.formulation = navier_stokes_solver_vmsmonolithic.StabilizedFormulation(
            self.settings["formulation"])
        self.element_name = self.formulation.element_name
        self.condition_name = self.formulation.condition_name
        self.element_integrates_in_time = self.formulation.element_integrates_in_time
        self.element_has_nodal_properties = self.formulation.element_has_nodal_properties

        scheme_type = self.settings["time_scheme"].GetString()
        if scheme_type == "bossak":
            self.min_buffer_size = 2
        elif scheme_type == "bdf2":
            self.min_buffer_size = 3
        elif scheme_type == "steady":
            self.min_buffer_size = 1
            self._SetUpSteadySimulation()
        else:
            msg = "Unknown time_scheme option found in project parameters:\n"
            msg += "\"" + scheme_type + "\"\n"
            msg += "Accepted values are \"bossak\", \"bdf2\" or \"steady\".\n"
            raise Exception(msg)

        ## Construct the linear solver
        self.trilinos_linear_solver = trilinos_linear_solver_factory.ConstructSolver(
            self.settings["linear_solver_settings"])

        ## Construct the turbulence model solver
        if not self.settings["turbulence_model_solver_settings"].IsEquivalentTo(
                KratosMultiphysics.Parameters("{}")):
            self._turbulence_model_solver = CreateTurbulenceModel(
                model, self.settings["turbulence_model_solver_settings"], True)
            self.condition_name = self._turbulence_model_solver.GetFluidVelocityPressureConditionName(
            )
            KratosMultiphysics.Logger.PrintInfo(
                "TrilinosNavierStokesSolverMonolithic",
                "Using " + self.condition_name + " as wall condition")

        KratosMultiphysics.Logger.Print(
            "Construction of TrilinosNavierStokesSolverMonolithic finished.")
    def __init__(self, model, custom_settings):
        self._validate_settings_in_baseclass = True  # To be removed eventually
        # Note: deliberately calling the constructor of the base python solver (the parent of my parent)
        custom_settings = self._BackwardsCompatibilityHelper(custom_settings)
        super(navier_stokes_solver_vmsmonolithic.NavierStokesSolverMonolithic,
              self).__init__(model, custom_settings)

        self.formulation = navier_stokes_solver_vmsmonolithic.StabilizedFormulation(
            self.settings["formulation"])
        self.element_name = self.formulation.element_name
        self.condition_name = self.formulation.condition_name
        self.min_buffer_size = 2

        ## Construct the linear solver
        self.trilinos_linear_solver = trilinos_linear_solver_factory.ConstructSolver(
            self.settings["linear_solver_settings"])

        KratosMultiphysics.Logger.Print(
            "Construction of TrilinosNavierStokesSolverMonolithic finished.")
    def testTrilinosRedistance(self):
        # Initialize the DISTANCE values
        for node in self.model_part.Nodes:
            node.SetSolutionStepValue(
                KratosMultiphysics.DISTANCE, 0,
                self._ExpectedDistance(node.X, node.Y, node.Z))

        # Fake time advance
        self.model_part.CloneTimeStep(1.0)

        # Set the utility and compute the variational distance values
        trilinos_linear_solver = trilinos_linear_solver_factory.ConstructSolver(
            KratosMultiphysics.Parameters("""{"solver_type" : "amesos" }"""))

        epetra_comm = TrilinosApplication.CreateEpetraCommunicator(
            KratosMultiphysics.DataCommunicator.GetDefault())

        max_iterations = 2
        TrilinosApplication.TrilinosVariationalDistanceCalculationProcess3D(
            epetra_comm, self.model_part, trilinos_linear_solver,
            max_iterations,
            (KratosMultiphysics.VariationalDistanceCalculationProcess3D.
             CALCULATE_EXACT_DISTANCES_TO_PLANE).AsFalse()).Execute()

        # Check the obtained values
        max_distance = -1.0
        min_distance = +1.0

        for node in self.model_part.Nodes:
            d = node.GetSolutionStepValue(KratosMultiphysics.DISTANCE)
            max_distance = max(max_distance, d)
            min_distance = min(min_distance, d)

        comm = self.model_part.GetCommunicator().GetDataCommunicator()
        min_distance = comm.MinAll(min_distance)
        max_distance = comm.MaxAll(max_distance)

        self.assertAlmostEqual(max_distance,
                               0.44556526310761013)  # Serial max_distance
        self.assertAlmostEqual(min_distance,
                               -0.504972246827639)  # Serial min_distance
 def _CreateLinearSolver(self):
     linear_solver_configuration = self.settings["linear_solver_settings"]
     return trilinos_linear_solver_factory.ConstructSolver(
         linear_solver_configuration)
    def __init__(self, main_model_part, custom_settings):

        #TODO: shall obtain the computing_model_part from the MODEL once the object is implemented
        self.main_model_part = main_model_part

        ##settings string in json format
        default_settings = KratosMultiphysics.Parameters("""
        {
            "solver_type": "dam_MPI_UP_mechanical_solver",
            "model_import_settings":{
                "input_type": "mdpa",
                "input_filename": "unknown_name",
                "input_file_label": 0
            },
            "buffer_size": 2,
            "echo_level": 0,
            "processes_sub_model_part_list": [""],
            "mechanical_solver_settings":{
                "echo_level": 0,
                "reform_dofs_at_each_step": false,
                "clear_storage": false,
                "compute_reactions": false,
                "move_mesh_flag": true,
                "solution_type": "Quasi-Static",
                "scheme_type": "Newmark",
                "rayleigh_m": 0.0,
                "rayleigh_k": 0.0,
                "strategy_type": "Newton-Raphson",
                "convergence_criterion": "Displacement_criterion",
                "displacement_relative_tolerance": 1.0e-4,
                "displacement_absolute_tolerance": 1.0e-9,
                "residual_relative_tolerance": 1.0e-4,
                "residual_absolute_tolerance": 1.0e-9,
                "max_iteration": 15,
                "desired_iterations": 4,
                "max_radius_factor": 20.0,
                "min_radius_factor": 0.5,
                "block_builder": true,
                "nonlocal_damage": false,
                "characteristic_length": 0.05,
                "search_neighbours_step": false,
                "linear_solver_settings":{
                    "solver_type": "AMGCL",
                    "tolerance": 1.0e-6,
                    "max_iteration": 100,
                    "scaling": false,
                    "verbosity": 0,
                    "preconditioner_type": "ILU0Preconditioner",
                    "smoother_type": "ilu0",
                    "krylov_type": "gmres",
                    "coarsening_type": "aggregation"
                },
                "problem_domain_sub_model_part_list": [""],
                "body_domain_sub_model_part_list": [],
                "mechanical_loads_sub_model_part_list": [],
                "loads_sub_model_part_list": [],
                "loads_variable_list": []
            }
        }
        """)

        # Overwrite the default settings with user-provided parameters
        self.settings = custom_settings
        self.settings.ValidateAndAssignDefaults(default_settings)

        # Construct the linear solver
        self.linear_solver = trilinos_linear_solver_factory.ConstructSolver(
            self.settings["mechanical_solver_settings"]
            ["linear_solver_settings"])

        print("Construction of Dam_MPI_UPMechanicalSolver finished")
 def _create_linear_solver(self):
     return trilinos_linear_solver_factory.ConstructSolver(
         self.settings["mesh_motion_linear_solver_settings"])
    def _auxiliary_test_function(self,
                                 settings,
                                 matrix_name="A.mm",
                                 absolute_norm=False):
        comm = KratosMultiphysics.TrilinosApplication.CreateCommunicator()
        space = KratosMultiphysics.TrilinosApplication.TrilinosSparseSpace()

        #read the matrices
        pA = space.ReadMatrixMarketMatrix(GetFilePath(matrix_name), comm)
        n = space.Size1(pA.GetReference())

        pAoriginal = space.ReadMatrixMarketMatrix(GetFilePath(matrix_name),
                                                  comm)
        pb = space.CreateEmptyVectorPointer(comm)
        space.ResizeVector(pb, n)
        space.SetToZeroVector(pb.GetReference())
        space.SetValue(pb.GetReference(), 0, 1.0)  #pb[1] = 1.0

        px = space.CreateEmptyVectorPointer(comm)
        space.ResizeVector(px, n)
        pboriginal = space.CreateEmptyVectorPointer(comm)  #create a copy of b
        space.ResizeVector(pboriginal, n)
        space.SetToZeroVector(pboriginal.GetReference())
        space.UnaliasedAdd(pboriginal.GetReference(), 1.0, pb.GetReference())

        space.SetToZeroVector(px.GetReference())
        #space.SetToZeroVector(boriginal)
        #space.UnaliasedAdd(boriginal, 1.0, b) #boriginal=1*bs

        #construct the solver
        linear_solver = trilinos_linear_solver_factory.ConstructSolver(
            settings)

        #solve
        linear_solver.Solve(pA.GetReference(), px.GetReference(),
                            pb.GetReference())

        #test the results
        ptmp = space.CreateEmptyVectorPointer(comm)
        space.ResizeVector(ptmp, n)
        space.SetToZeroVector(ptmp.GetReference())
        space.Mult(pAoriginal.GetReference(), px.GetReference(),
                   ptmp.GetReference())

        pcheck = space.CreateEmptyVectorPointer(comm)
        space.ResizeVector(pcheck, n)
        space.SetToZeroVector(pcheck.GetReference())
        space.UnaliasedAdd(pcheck.GetReference(), 1.0,
                           pboriginal.GetReference())
        space.UnaliasedAdd(pcheck.GetReference(), -1.0, ptmp.GetReference())

        achieved_norm = space.TwoNorm(pcheck.GetReference())

        tolerance = 1e-9
        if (settings.Has("tolerance")):
            tolerance = settings["tolerance"].GetDouble()

        nproc = KratosMultiphysics.DataCommunicator.GetDefault().Size()
        target_norm = tolerance * space.TwoNorm(
            pboriginal.GetReference()
        ) * nproc  #multiplying by nproc the target tolerance to give some slack. Not really nice :-(

        if (achieved_norm > target_norm):
            print("target_norm   :", target_norm)
            print("achieved_norm :", achieved_norm)
        self.assertTrue(achieved_norm <= target_norm)

        #destroy the preconditioner - this is needed since  the solver should be destroyed before the destructor of the system matrix is called
        del linear_solver
 def _ConstructLinearSolver(self):
     return trilinos_linear_solver_factory.ConstructSolver(
         self.settings["linear_solver_settings"])
    def CreateStrategy(self, solver_settings, scheme_settings, model_part,
                       scalar_variable, scalar_variable_rate,
                       relaxed_scalar_variable_rate):
        default_solver_settings = Kratos.Parameters(r'''{
                "is_periodic"           : false,
                "relative_tolerance"    : 1e-3,
                "absolute_tolerance"    : 1e-5,
                "max_iterations"        : 200,
                "relaxation_factor"     : 0.5,
                "echo_level"            : 0,
                "linear_solver_settings": {
                    "solver_type"  : "amgcl"
                },
                "reform_dofs_at_each_step": true,
                "move_mesh_strategy": 0,
                "move_mesh_flag": false,
                "compute_reactions": false
        }''')

        default_scheme_settings = Kratos.Parameters(r'''{
            "scheme_type": "bossak",
            "alpha_bossak": -0.3
        }''')

        solver_settings.ValidateAndAssignDefaults(default_solver_settings)
        scheme_settings.ValidateAndAssignDefaults(default_scheme_settings)

        linear_solver = linear_solver_factory.ConstructSolver(
            solver_settings["linear_solver_settings"])

        is_periodic = solver_settings["is_periodic"].GetBool()

        if is_periodic:
            self.__InitializePeriodicConditions(model_part, scalar_variable)

        # TODO:
        if is_periodic and IsDistributedRun():
            msg = "\nCurrently periodic conditions in mpi is not supported due to following reasons:\n\n"
            msg += "    1. TrilinosResidualCriteria [ConvergenceCriterian]\n"
            msg += "PeriodicConditions duplicates one patch's equation ids to the counter patch. "
            msg += "The node and its corresponding dof might not fall in to the same partition raising an error in convergence calculation.\n\n"
            msg += "    2. ConnectivityPreserveModeller\n"
            msg += "Currently connectivity preserve modeller replaces all the conditions in an mdpa with given new condition. "
            msg += "This modeller is used to create modelparts having k-epsilon elements and conditions while sharing the same nodes as in VMS solution. "
            msg += "In the case of MPI, it is essential to have the PeriodicConditions in the mdpa file in order to properly distribute nodes to partitions using MetisApplication. "
            msg += "But if this is the case, PeriodicConditions also will be replaced by k-epsilon specific conditions casuing a segmentation fault.\n"
            msg += "    3. TrilinosBlockBuilderAndSolverPeriodic\n"
            msg += "In the case of MPI periodic in 2D, problem uses TrilinosBlockBuilderAndSolverPeriodic block builder and solver, which identifies "
            msg += "periodic conditions by number of nodes in the condition. So, In 2D all wall conditions and PeriodicConditions have only 2 nodes, all will be "
            msg += "considered as PeriodicConditions and will make the global assembly accordingly which is wrong."
            msg += "Therefore this error msg is printed in order to avoid confusion."
            raise Exception(msg)

        builder_and_solver = self.__CreateBuilderAndSolver(
            linear_solver, is_periodic)

        if (scheme_settings["scheme_type"].GetString() == "bossak"):
            convergence_criteria_type = scalar_convergence_criteria
        elif (scheme_settings["scheme_type"].GetString() == "steady"):
            convergence_criteria_type = residual_criteria

        convergence_criteria = convergence_criteria_type(
            solver_settings["relative_tolerance"].GetDouble(),
            solver_settings["absolute_tolerance"].GetDouble())

        if (scheme_settings["scheme_type"].GetString() == "bossak"):
            time_scheme = dynamic_scheme(
                scheme_settings["alpha_bossak"].GetDouble(),
                solver_settings["relaxation_factor"].GetDouble(),
                scalar_variable, scalar_variable_rate,
                relaxed_scalar_variable_rate)
        elif (scheme_settings["scheme_type"].GetString() == "steady"):
            time_scheme = steady_scheme(
                solver_settings["relaxation_factor"].GetDouble())
            self.fluid_model_part.ProcessInfo[
                Kratos.
                BOSSAK_ALPHA] = scheme_settings["alpha_bossak"].GetDouble()
            self.fluid_model_part.ProcessInfo[
                KratosRANS.IS_CO_SOLVING_PROCESS_ACTIVE] = True
            if (self.fluid_model_part.ProcessInfo[Kratos.DYNAMIC_TAU] != 0.0):
                Kratos.Logger.PrintWarning(
                    self.__class__.__name__,
                    "Steady solution doesn't have zero DYNAMIC_TAU [ DYNAMIC_TAU = "
                    +
                    str(self.fluid_model_part.ProcessInfo[Kratos.DYNAMIC_TAU])
                    + " ].")
        else:
            raise Exception("Unknown scheme_type = \"" +
                            scheme_settings["scheme_type"] + "\"")

        strategy = newton_raphson_strategy(
            model_part, time_scheme, linear_solver, convergence_criteria,
            builder_and_solver, solver_settings["max_iterations"].GetInt(),
            solver_settings["compute_reactions"].GetBool(),
            solver_settings["reform_dofs_at_each_step"].GetBool(),
            solver_settings["move_mesh_flag"].GetBool())

        strategy.SetEchoLevel(solver_settings["echo_level"].GetInt() - 2)
        builder_and_solver.SetEchoLevel(
            solver_settings["echo_level"].GetInt() - 3)
        convergence_criteria.SetEchoLevel(
            solver_settings["echo_level"].GetInt() - 1)

        if (is_periodic):
            Kratos.Logger.PrintInfo(
                self.__class__.__name__,
                "Successfully created periodic solving strategy for " +
                scalar_variable.Name() + ".")
        else:
            Kratos.Logger.PrintInfo(
                self.__class__.__name__,
                "Successfully created solving strategy for " +
                scalar_variable.Name() + ".")

        return strategy
예제 #20
0
 def _ConstructLinearSolver(self):
     from KratosMultiphysics.TrilinosApplication import trilinos_linear_solver_factory
     return trilinos_linear_solver_factory.ConstructSolver(self.settings["linear_solver_settings"])
    def test_trilinos_levelset_convection_BFECC(self):

        # Set the initial distance field and the convection velocity
        for node in self.model_part.Nodes:
            node.SetSolutionStepValue(
                KratosMultiphysics.DISTANCE,
                BaseJumpedDistance(node.X, node.Y, node.Z))
            node.SetSolutionStepValue(
                KratosMultiphysics.VELOCITY,
                ConvectionVelocity(node.X, node.Y, node.Z))

        # Fix the left side values
        for node in self.model_part.Nodes:
            if node.X < 0.001:
                node.Fix(KratosMultiphysics.DISTANCE)

        # Set the Trilinos linear solver and Epetra communicator
        trilinos_linear_solver = trilinos_linear_solver_factory.ConstructSolver(
            KratosMultiphysics.Parameters("""{"solver_type" : "amesos" }"""))
        epetra_comm = TrilinosApplication.CreateEpetraCommunicator(
            KratosMultiphysics.DataCommunicator.GetDefault())

        # Fake time advance
        self.model_part.CloneTimeStep(30.0)

        kratos_comm = KratosMultiphysics.DataCommunicator.GetDefault()
        KratosMultiphysics.FindGlobalNodalNeighboursProcess(
            kratos_comm, self.model_part).Execute()

        KratosMultiphysics.ComputeNonHistoricalNodalGradientProcess(
            self.model_part, KratosMultiphysics.DISTANCE,
            KratosMultiphysics.DISTANCE_GRADIENT,
            KratosMultiphysics.NODAL_AREA).Execute()

        levelset_convection_settings = KratosMultiphysics.Parameters("""{
            "levelset_variable_name" : "DISTANCE",
            "levelset_convection_variable_name" : "VELOCITY",
            "levelset_gradient_variable_name" : "DISTANCE_GRADIENT",
            "max_CFL" : 1.0,
            "max_substeps" : 0,
            "eulerian_error_compensation" : true,
            "cross_wind_stabilization_factor" : 0.7
        }""")
        TrilinosApplication.TrilinosLevelSetConvectionProcess2D(
            epetra_comm, self.model_part, trilinos_linear_solver,
            levelset_convection_settings).Execute()

        max_distance = -1.0
        min_distance = +1.0

        for node in self.model_part.Nodes:
            d = node.GetSolutionStepValue(KratosMultiphysics.DISTANCE)
            max_distance = max(max_distance, d)
            min_distance = min(min_distance, d)

        min_distance = kratos_comm.MinAll(min_distance)
        max_distance = kratos_comm.MaxAll(max_distance)

        # gid_output = GiDOutputProcess(model_part,
        #                            "levelset_test_2D",
        #                            KratosMultiphysics.Parameters("""
        #                                {
        #                                    "result_file_configuration" : {
        #                                        "gidpost_flags": {
        #                                            "GiDPostMode": "GiD_PostBinary",
        #                                            "WriteDeformedMeshFlag": "WriteUndeformed",
        #                                            "WriteConditionsFlag": "WriteConditions",
        #                                            "MultiFileFlag": "SingleFile"
        #                                        },
        #                                        "nodal_results"       : ["DISTANCE","VELOCITY"]
        #                                    }
        #                                }
        #                                """)
        #                            )

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

        self.assertAlmostEqual(max_distance, 1.0617777301844604)
        self.assertAlmostEqual(min_distance, -0.061745786561321375)