Exemple #1
0
    def Initialize(self):

        self.computing_model_part = self.GetComputingModelPart()

        # If needed, create the estimate time step utility
        if (self.settings["time_stepping"]["automatic_time_step"].GetBool()):
            self.EstimateDeltaTimeUtility = self._GetAutomaticTimeSteppingUtility(
            )

        # Creating the solution strategy
        self.conv_criteria = KratosCFD.VelPrCriteria(
            self.settings["relative_velocity_tolerance"].GetDouble(),
            self.settings["absolute_velocity_tolerance"].GetDouble(),
            self.settings["relative_pressure_tolerance"].GetDouble(),
            self.settings["absolute_pressure_tolerance"].GetDouble())

        (self.conv_criteria).SetEchoLevel(self.settings["echo_level"].GetInt())

        if (self.settings["turbulence_model"].GetString() == "None"):
            if self.settings["consider_periodic_conditions"].GetBool() == True:
                self.time_scheme = KratosCFD.ResidualBasedPredictorCorrectorVelocityBossakSchemeTurbulent(
                    self.settings["alpha"].GetDouble(),
                    self.settings["move_mesh_strategy"].GetInt(),
                    self.computing_model_part.ProcessInfo[
                        KratosMultiphysics.DOMAIN_SIZE], KratosCFD.PATCH_INDEX)
            else:
                self.time_scheme = KratosCFD.ResidualBasedPredictorCorrectorVelocityBossakSchemeTurbulent(
                    self.settings["alpha"].GetDouble(),
                    self.settings["move_mesh_strategy"].GetInt(),
                    self.computing_model_part.ProcessInfo[
                        KratosMultiphysics.DOMAIN_SIZE])
        else:
            raise Exception("Turbulence models are not added yet.")

        if self.settings["consider_periodic_conditions"].GetBool() == True:
            builder_and_solver = KratosCFD.ResidualBasedBlockBuilderAndSolverPeriodic(
                self.linear_solver, KratosCFD.PATCH_INDEX)
        else:
            builder_and_solver = KratosMultiphysics.ResidualBasedBlockBuilderAndSolver(
                self.linear_solver)

        self.solver = KratosMultiphysics.ResidualBasedNewtonRaphsonStrategy(
            self.main_model_part, self.time_scheme, self.linear_solver,
            self.conv_criteria, builder_and_solver,
            self.settings["maximum_iterations"].GetInt(),
            self.settings["compute_reactions"].GetBool(),
            self.settings["reform_dofs_at_each_step"].GetBool(),
            self.settings["move_mesh_flag"].GetBool())

        (self.solver).SetEchoLevel(self.settings["echo_level"].GetInt())
        (self.solver).Check()

        self.main_model_part.ProcessInfo.SetValue(
            KratosMultiphysics.DYNAMIC_TAU,
            self.settings["dynamic_tau"].GetDouble())
        self.main_model_part.ProcessInfo.SetValue(
            KratosMultiphysics.OSS_SWITCH,
            self.settings["oss_switch"].GetInt())

        print("Monolithic solver initialization finished.")
    def Initialize(self):

        self.computing_model_part = self.GetComputingModelPart()

        MoveMeshFlag = False

        # TODO: TURBULENCE MODELS ARE NOT ADDED YET
        #~ # Turbulence model
        #~ if self.use_spalart_allmaras:
        #~ self.activate_spalart_allmaras()

        # creating the solution strategy
        self.conv_criteria = KratosCFD.VelPrCriteria(
            self.settings["relative_velocity_tolerance"].GetDouble(),
            self.settings["absolute_velocity_tolerance"].GetDouble(),
            self.settings["relative_pressure_tolerance"].GetDouble(),
            self.settings["absolute_pressure_tolerance"].GetDouble())

        (self.conv_criteria).SetEchoLevel(self.settings["echo_level"].GetInt())

        self.time_scheme = KratosCFD.ResidualBasedSimpleSteadyScheme(
            self.velocity_relaxation_factor, self.pressure_relaxation_factor,
            self.computing_model_part.ProcessInfo[
                KratosMultiphysics.DOMAIN_SIZE])

        # TODO: TURBULENCE MODELS ARE NOT ADDED YET
        #~ if self.turbulence_model is None:
        #~ if self.periodic == True:
        #~ self.time_scheme = ResidualBasedPredictorCorrectorVelocityBossakSchemeTurbulent\
        #~ (self.alpha, self.move_mesh_strategy, self.domain_size, PATCH_INDEX)
        #~ else:
        #~ self.time_scheme = ResidualBasedPredictorCorrectorVelocityBossakSchemeTurbulent\
        #~ (self.alpha, self.move_mesh_strategy, self.domain_size)
        #~ else:
        #~ self.time_scheme = ResidualBasedPredictorCorrectorVelocityBossakSchemeTurbulent\
        #~ (self.alpha, self.move_mesh_strategy, self.domain_size, self.turbulence_model)

        builder_and_solver = KratosMultiphysics.ResidualBasedBlockBuilderAndSolver(
            self.linear_solver)

        self.solver = KratosMultiphysics.ResidualBasedNewtonRaphsonStrategy(
            self.main_model_part, self.time_scheme, self.linear_solver,
            self.conv_criteria, builder_and_solver,
            self.settings["maximum_iterations"].GetInt(),
            self.settings["compute_reactions"].GetBool(),
            self.settings["reform_dofs_at_each_step"].GetBool(),
            self.settings["move_mesh_flag"].GetBool())

        (self.solver).SetEchoLevel(self.settings["echo_level"].GetInt())

        if self.settings["stabilization"].Has("dynamic_tau"):
            self.main_model_part.ProcessInfo.SetValue(
                KratosMultiphysics.DYNAMIC_TAU,
                self.settings["stabilization"]["dynamic_tau"].GetDouble())
        if self.settings["stabilization"].Has("oss_switch"):
            self.main_model_part.ProcessInfo.SetValue(
                KratosMultiphysics.OSS_SWITCH,
                self.settings["stabilization"]["oss_switch"].GetInt())

        print("Monolithic solver initialization finished.")
Exemple #3
0
    def Initialize(self):
        self.computing_model_part = self.GetComputingModelPart()

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

        KratosMultiphysics.NormalCalculationUtils().CalculateOnSimplex(self.computing_model_part, self.computing_model_part.ProcessInfo[KratosMultiphysics.DOMAIN_SIZE])

        self.neighbour_search = KratosMultiphysics.FindNodalNeighboursProcess(self.computing_model_part, 10, 10)
        (self.neighbour_search).Execute()

        self.accelerationLimitationUtility = KratosCFD.AccelerationLimitationUtilities( self.computing_model_part, 5.0 )

        # If needed, create the estimate time step utility
        if (self.settings["time_stepping"]["automatic_time_step"].GetBool()):
            self.EstimateDeltaTimeUtility = self._GetAutomaticTimeSteppingUtility()

        # Set the time discretization utility to compute the BDF coefficients
        time_order = self.settings["time_order"].GetInt()
        if time_order == 2:
            self.time_discretization = KratosMultiphysics.TimeDiscretization.BDF(time_order)
        else:
            raise Exception("Only \"time_order\" equal to 2 is supported. Provided \"time_order\": " + str(time_order))

        # Creating the solution strategy
        self.conv_criteria = KratosCFD.VelPrCriteria(self.settings["relative_velocity_tolerance"].GetDouble(),
                                                     self.settings["absolute_velocity_tolerance"].GetDouble(),
                                                     self.settings["relative_pressure_tolerance"].GetDouble(),
                                                     self.settings["absolute_pressure_tolerance"].GetDouble())

        (self.conv_criteria).SetEchoLevel(self.settings["echo_level"].GetInt())

        self.level_set_convection_process = self._set_level_set_convection_process()

        self.variational_distance_process = self._set_variational_distance_process()

        time_scheme = KratosMultiphysics.ResidualBasedIncrementalUpdateStaticSchemeSlip(self.main_model_part.ProcessInfo[KratosMultiphysics.DOMAIN_SIZE],   # Domain size (2,3)
                                                                                        self.main_model_part.ProcessInfo[KratosMultiphysics.DOMAIN_SIZE]+1) # DOFs (3,4)

        builder_and_solver = KratosMultiphysics.ResidualBasedBlockBuilderAndSolver(self.linear_solver)

        self.solver = KratosMultiphysics.ResidualBasedNewtonRaphsonStrategy(self.computing_model_part,
                                                                            time_scheme,
                                                                            self.linear_solver,
                                                                            self.conv_criteria,
                                                                            builder_and_solver,
                                                                            self.settings["maximum_iterations"].GetInt(),
                                                                            self.settings["compute_reactions"].GetBool(),
                                                                            self.settings["reform_dofs_at_each_step"].GetBool(),
                                                                            self.settings["move_mesh_flag"].GetBool())

        (self.solver).SetEchoLevel(self.settings["echo_level"].GetInt())

        (self.solver).Initialize() # Initialize the solver. Otherwise the constitutive law is not initializated.
        (self.solver).Check()

        self.main_model_part.ProcessInfo.SetValue(KratosMultiphysics.DYNAMIC_TAU, self.settings["formulation"]["dynamic_tau"].GetDouble())

        KratosMultiphysics.Logger.PrintInfo("NavierStokesTwoFluidsSolver", "Solver initialization finished.")
 def _GetAutomaticTimeSteppingUtility(self):
     if (self.GetComputingModelPart().ProcessInfo[Kratos.DOMAIN_SIZE] == 2):
         EstimateDeltaTimeUtility = KratosCFD.EstimateDtUtility2D(
             self.GetComputingModelPart(), self.settings["time_stepping"])
     else:
         EstimateDeltaTimeUtility = KratosCFD.EstimateDtUtility3D(
             self.GetComputingModelPart(), self.settings["time_stepping"])
     return EstimateDeltaTimeUtility
    def _CreateSolutionStrategy(self):
        computing_model_part = self.GetComputingModelPart()
        domain_size = computing_model_part.ProcessInfo[
            KratosMultiphysics.DOMAIN_SIZE]

        # Create the pressure and velocity linear solvers
        # Note that linear_solvers is a tuple. The first item is the pressure
        # linear solver. The second item is the velocity linear solver.
        linear_solvers = self._GetLinearSolver()

        # Create the fractional step settings instance
        # TODO: next part would be much cleaner if we passed directly the parameters to the c++
        if self.settings["consider_periodic_conditions"].GetBool():
            fractional_step_settings = KratosCFD.FractionalStepSettingsPeriodic(
                computing_model_part, domain_size,
                self.settings["time_order"].GetInt(),
                self.settings["use_slip_conditions"].GetBool(),
                self.settings["move_mesh_flag"].GetBool(),
                self.settings["reform_dofs_at_each_step"].GetBool(),
                KratosCFD.PATCH_INDEX)
        else:
            fractional_step_settings = KratosCFD.FractionalStepSettings(
                computing_model_part, domain_size,
                self.settings["time_order"].GetInt(),
                self.settings["use_slip_conditions"].GetBool(),
                self.settings["move_mesh_flag"].GetBool(),
                self.settings["reform_dofs_at_each_step"].GetBool())

        # Set the strategy echo level
        fractional_step_settings.SetEchoLevel(
            self.settings["echo_level"].GetInt())

        # Set the velocity and pressure fractional step strategy settings
        fractional_step_settings.SetStrategy(
            KratosCFD.StrategyLabel.Pressure, linear_solvers[0],
            self.settings["pressure_tolerance"].GetDouble(),
            self.settings["maximum_pressure_iterations"].GetInt())

        fractional_step_settings.SetStrategy(
            KratosCFD.StrategyLabel.Velocity, linear_solvers[1],
            self.settings["velocity_tolerance"].GetDouble(),
            self.settings["maximum_velocity_iterations"].GetInt())

        # Create the fractional step strategy
        if self.settings["consider_periodic_conditions"].GetBool() == True:
            solution_strategy = KratosCFD.FractionalStepStrategy(
                computing_model_part, fractional_step_settings,
                self.settings["predictor_corrector"].GetBool(),
                self.settings["compute_reactions"].GetBool(),
                KratosCFD.PATCH_INDEX)
        else:
            solution_strategy = KratosCFD.FractionalStepStrategy(
                computing_model_part, fractional_step_settings,
                self.settings["predictor_corrector"].GetBool(),
                self.settings["compute_reactions"].GetBool())

        return solution_strategy
Exemple #6
0
    def _GetAutomaticTimeSteppingUtility(self):
        if (self.computing_model_part.ProcessInfo[KratosMultiphysics.DOMAIN_SIZE] == 2):
            EstimateDeltaTimeUtility = KratosCFD.EstimateDtUtility2D(self.computing_model_part,
                                                                     self.settings["time_stepping"])
        else:
            EstimateDeltaTimeUtility = KratosCFD.EstimateDtUtility3D(self.computing_model_part,
                                                                     self.settings["time_stepping"])

        return EstimateDeltaTimeUtility
    def Initialize(self):

        ## Construct the communicator
        self.EpetraCommunicator = TrilinosApplication.CreateCommunicator()

        ## Get the computing model part
        self.computing_model_part = self.GetComputingModelPart()

        domain_size = self.main_model_part.ProcessInfo[KratosMultiphysics.DOMAIN_SIZE]
        if self.settings["response_function_settings"]["response_type"].GetString() == "drag":
            if (domain_size == 2):
                self.response_function = FluidDynamicsApplication.DragResponseFunction2D(self.settings["response_function_settings"]["custom_settings"], self.main_model_part)
            elif (domain_size == 3):
                self.response_function = FluidDynamicsApplication.DragResponseFunction3D(self.settings["response_function_settings"]["custom_settings"], self.main_model_part)
            else:
                raise Exception("Invalid DOMAIN_SIZE: " + str(domain_size))
        else:
            raise Exception("invalid response_type: " + self.settings["response_function_settings"]["response_type"].GetString())

        self.sensitivity_builder = KratosMultiphysics.SensitivityBuilder(self.settings["sensitivity_settings"], self.main_model_part, self.response_function)

        if self.settings["scheme_settings"]["scheme_type"].GetString() == "bossak":
            self.time_scheme = TrilinosApplication.TrilinosResidualBasedAdjointBossakScheme(self.settings["scheme_settings"], self.response_function)
        elif self.settings["scheme_settings"]["scheme_type"].GetString() == "steady":
            self.time_scheme = TrilinosApplication.TrilinosResidualBasedAdjointSteadyScheme(self.response_function)
        else:
            raise Exception("invalid scheme_type: " + self.settings["scheme_settings"]["scheme_type"].GetString())

        if self.main_model_part.ProcessInfo[KratosMultiphysics.DOMAIN_SIZE] == 3:
            guess_row_size = 20*4
        elif self.main_model_part.ProcessInfo[KratosMultiphysics.DOMAIN_SIZE] == 2:
            guess_row_size = 10*3

        self.builder_and_solver = TrilinosApplication.TrilinosBlockBuilderAndSolver(self.EpetraCommunicator,
                                                                               guess_row_size,
                                                                               self.trilinos_linear_solver)

        self.solver = TrilinosApplication.TrilinosLinearStrategy(self.main_model_part,
                                                                 self.time_scheme,
                                                                 self.trilinos_linear_solver,
                                                                 self.builder_and_solver,
                                                                 False,
                                                                 False,
                                                                 False,
                                                                 False)

        (self.solver).SetEchoLevel(self.settings["echo_level"].GetInt())

        (self.solver).Initialize()
        (self.response_function).Initialize()
        (self.sensitivity_builder).Initialize()

        self.main_model_part.ProcessInfo.SetValue(KratosMultiphysics.DYNAMIC_TAU, self.settings["dynamic_tau"].GetDouble())
        self.main_model_part.ProcessInfo.SetValue(KratosMultiphysics.OSS_SWITCH, self.settings["oss_switch"].GetInt())

        if self._IsPrintingRank():
            KratosMultiphysics.Logger.PrintInfo(self.__class__.__name__,"Monolithic MPI solver initialization finished.")
    def Initialize(self):
        self.computing_model_part = self.GetComputingModelPart()

        # If needed, create the estimate time step utility
        if (self.settings["time_stepping"]["automatic_time_step"].GetBool()):
            self.EstimateDeltaTimeUtility = self._GetAutomaticTimeSteppingUtility()

        #TODO: next part would be much cleaner if we passed directly the parameters to the c++
        if self.settings["consider_periodic_conditions"] == True:
            self.solver_settings = KratosCFD.FractionalStepSettingsPeriodic(self.computing_model_part,
                                                                            self.computing_model_part.ProcessInfo[KratosMultiphysics.DOMAIN_SIZE],
                                                                            self.settings.GetInt(),
                                                                            self.settings["use_slip_conditions"].GetBool(),
                                                                            self.settings["move_mesh_flag"].GetBool(),
                                                                            self.settings["reform_dofs_at_each_step"].GetBool(),
                                                                            KratosCFD.PATCH_INDEX)

        else:
            self.solver_settings = KratosCFD.FractionalStepSettings(self.computing_model_part,
                                                                    self.computing_model_part.ProcessInfo[KratosMultiphysics.DOMAIN_SIZE],
                                                                    self.settings["time_order"].GetInt(),
                                                                    self.settings["use_slip_conditions"].GetBool(),
                                                                    self.settings["move_mesh_flag"].GetBool(),
                                                                    self.settings["reform_dofs_at_each_step"].GetBool())

        self.solver_settings.SetEchoLevel(self.settings["echo_level"].GetInt())

        self.solver_settings.SetStrategy(KratosCFD.StrategyLabel.Velocity,
                                         self.velocity_linear_solver,
                                         self.settings["velocity_tolerance"].GetDouble(),
                                         self.settings["maximum_velocity_iterations"].GetInt())

        self.solver_settings.SetStrategy(KratosCFD.StrategyLabel.Pressure,
                                         self.pressure_linear_solver,
                                         self.settings["pressure_tolerance"].GetDouble(),
                                         self.settings["maximum_pressure_iterations"].GetInt())


        if self.settings["consider_periodic_conditions"].GetBool() == True:
            self.solver = KratosCFD.FSStrategy(self.computing_model_part,
                                               self.solver_settings,
                                               self.settings["predictor_corrector"].GetBool(),
                                               KratosCFD.PATCH_INDEX)
        else:
            self.solver = KratosCFD.FSStrategy(self.computing_model_part,
                                               self.solver_settings,
                                               self.settings["predictor_corrector"].GetBool())

        self.main_model_part.ProcessInfo.SetValue(KratosMultiphysics.DYNAMIC_TAU, self.settings["dynamic_tau"].GetDouble())
        self.main_model_part.ProcessInfo.SetValue(KratosMultiphysics.OSS_SWITCH, self.settings["oss_switch"].GetInt())

        (self.solver).Initialize()

        self.solver.Check()

        KratosMultiphysics.Logger.PrintInfo("NavierStokesSolverFractionalStep", "Solver initialization finished.")
Exemple #9
0
    def _CreateEstimateDtUtility(self):
        domain_size = self.GetComputingModelPart().ProcessInfo[
            KratosMultiphysics.DOMAIN_SIZE]
        if domain_size == 2:
            estimate_dt_utility = KratosCFD.EstimateDtUtility2D(
                self.GetComputingModelPart(), self.settings["time_stepping"])
        else:
            estimate_dt_utility = KratosCFD.EstimateDtUtility3D(
                self.GetComputingModelPart(), self.settings["time_stepping"])

        return estimate_dt_utility
Exemple #10
0
 def _set_constitutive_law(self):
     # Construct the two fluids constitutive law
     if (self.main_model_part.ProcessInfo[KratosMultiphysics.DOMAIN_SIZE] ==
             3):
         self.main_model_part.Properties[1][
             KratosMultiphysics.
             CONSTITUTIVE_LAW] = KratosCFD.NewtonianTwoFluid3DLaw()
     elif (self.main_model_part.ProcessInfo[KratosMultiphysics.DOMAIN_SIZE]
           == 2):
         self.main_model_part.Properties[1][
             KratosMultiphysics.
             CONSTITUTIVE_LAW] = KratosCFD.NewtonianTwoFluid2DLaw()
Exemple #11
0
    def _CreateDistanceSmoothingProcess(self):
        # construct the distance smoothing process
        linear_solver = self._GetLinearSolver()
        if self.main_model_part.ProcessInfo[
                KratosMultiphysics.DOMAIN_SIZE] == 2:
            distance_smoothing_process = KratosCFD.DistanceSmoothingProcess2D(
                self.main_model_part, linear_solver)
        else:
            distance_smoothing_process = KratosCFD.DistanceSmoothingProcess3D(
                self.main_model_part, linear_solver)

        return distance_smoothing_process
Exemple #12
0
 def _set_constitutive_law(self):
     ## Construct the constitutive law needed for the embedded element
     if (self.main_model_part.ProcessInfo[KratosMultiphysics.DOMAIN_SIZE] ==
             3):
         self.main_model_part.Properties[1][
             KratosMultiphysics.
             CONSTITUTIVE_LAW] = KratosCFD.Newtonian3DLaw()
     elif (self.main_model_part.ProcessInfo[KratosMultiphysics.DOMAIN_SIZE]
           == 2):
         self.main_model_part.Properties[1][
             KratosMultiphysics.
             CONSTITUTIVE_LAW] = KratosCFD.Newtonian2DLaw()
Exemple #13
0
 def _CreateScheme(self):
     domain_size = self.GetComputingModelPart().ProcessInfo[
         KratosMultiphysics.DOMAIN_SIZE]
     # Cases in which the element manages the time integration
     if self.element_integrates_in_time:
         # Rotation utility for compressible Navier-Stokes formulations
         # A custom rotation util is required as the nodal DOFs differs from the standard incompressible case
         rotation_utility = KratosFluid.CompressibleElementRotationUtility(
             domain_size, KratosMultiphysics.SLIP)
         # "Fake" scheme for those cases in where the element manages the time integration
         # It is required to perform the nodal update once the current time step is solved
         scheme = KratosMultiphysics.ResidualBasedIncrementalUpdateStaticSchemeSlip(
             rotation_utility)
         # In case the BDF2 scheme is used inside the element, the BDF time discretization utility is required to update the BDF coefficients
         if (self.settings["time_scheme"].GetString() == "bdf2"):
             time_order = 2
             self.time_discretization = KratosMultiphysics.TimeDiscretization.BDF(
                 time_order)
         else:
             err_msg = "Requested elemental time scheme \"" + self.settings[
                 "time_scheme"].GetString() + "\" is not available.\n"
             err_msg += "Available options are: \"bdf2\""
             raise Exception(err_msg)
     # Cases in which a time scheme manages the time integration
     else:
         err_msg = "Custom scheme creation is not allowed. Compressible Navier-Stokes elements manage the time integration internally."
         raise Exception(err_msg)
     return scheme
Exemple #14
0
 def __CreateDistanceModificationProcess(self):
     # Set the distance modification settings according to the level set type
     # Note that the distance modification process is applied to the volume model part
     distance_modification_settings = self.settings["distance_modification_settings"]
     distance_modification_settings.ValidateAndAssignDefaults(self.__GetDistanceModificationDefaultSettings(self.level_set_type))
     distance_modification_settings["model_part_name"].SetString(self.settings["volume_model_part_name"].GetString())
     return KratosCFD.DistanceModificationProcess(self.model, distance_modification_settings)
Exemple #15
0
    def Initialize(self):
        computing_model_part = self.GetComputingModelPart()

        # If needed, create the estimate time step utility
        if (self.settings["time_stepping"]["automatic_time_step"].GetBool()):
            self.EstimateDeltaTimeUtility = self._GetAutomaticTimeSteppingUtility()

        # Set the time discretization utility to compute the BDF coefficients
        time_order = self.settings["time_order"].GetInt()
        if time_order == 2:
            self.time_discretization = KratosMultiphysics.TimeDiscretization.BDF(time_order)
        else:
            raise Exception("Only \"time_order\" equal to 2 is supported. Provided \"time_order\": " + str(time_order))

        # Creating the solution strategy
        self.conv_criteria = KratosCFD.VelPrCriteria(self.settings["relative_velocity_tolerance"].GetDouble(),
                                                     self.settings["absolute_velocity_tolerance"].GetDouble(),
                                                     self.settings["relative_pressure_tolerance"].GetDouble(),
                                                     self.settings["absolute_pressure_tolerance"].GetDouble())

        (self.conv_criteria).SetEchoLevel(self.settings["echo_level"].GetInt())

        time_scheme = KratosMultiphysics.ResidualBasedIncrementalUpdateStaticSchemeSlip(self.main_model_part.ProcessInfo[KratosMultiphysics.DOMAIN_SIZE],   # Domain size (2,3)
                                                                                        self.main_model_part.ProcessInfo[KratosMultiphysics.DOMAIN_SIZE]+1) # DOFs (3,4)

        builder_and_solver = KratosMultiphysics.ResidualBasedBlockBuilderAndSolver(self.linear_solver)

        self.solver = KratosMultiphysics.ResidualBasedNewtonRaphsonStrategy(computing_model_part,
                                                                            time_scheme,
                                                                            self.linear_solver,
                                                                            self.conv_criteria,
                                                                            builder_and_solver,
                                                                            self.settings["maximum_iterations"].GetInt(),
                                                                            self.settings["compute_reactions"].GetBool(),
                                                                            self.settings["reform_dofs_at_each_step"].GetBool(),
                                                                            self.settings["move_mesh_flag"].GetBool())

        (self.solver).SetEchoLevel(self.settings["echo_level"].GetInt())

        (self.solver).Initialize() # Initialize the solver. Otherwise the constitutive law is not initializated.

        # Set the distance modification process
        self.__GetDistanceModificationProcess().ExecuteInitialize()

        # For the primitive Ausas formulation, set the find nodal neighbours process
        # Recall that the Ausas condition requires the nodal neighbours.
        if (self.settings["formulation"]["element_type"].GetString() == "embedded_ausas_navier_stokes"):
            number_of_avg_elems = 10
            number_of_avg_nodes = 10
            self.find_nodal_neighbours_process = KratosMultiphysics.FindNodalNeighboursProcess(self.GetComputingModelPart(),
                                                                                               number_of_avg_elems,
                                                                                               number_of_avg_nodes)

        # If required, intialize the FM-ALE utility
        if self.__fm_ale_is_active:
            self.fm_ale_step = 1
            # Fill the virtual model part geometry. Note that the mesh moving util is created in this first call
            self._get_mesh_moving_util().Initialize(self.main_model_part)

        KratosMultiphysics.Logger.PrintInfo("NavierStokesEmbeddedMonolithicSolver", "Solver initialization finished.")
Exemple #16
0
    def __init__(self, Model, settings):

        msg = "The python distance modification process is deprecated.\n"
        msg += "Please use (or implement) the \'distance_modification_settings\' in the \'solver_settings\'.\n"
        KratosMultiphysics.Logger.PrintWarning(
            "ApplyDistanceModificationProcess", msg)

        KratosMultiphysics.Process.__init__(self)

        default_parameters = KratosMultiphysics.Parameters("""
        {
            "model_part_name"                        : "CHOOSE_FLUID_MODELPART_NAME",
            "distance_threshold"                     : 0.01,
            "continuous_distance"                    : true,
            "check_at_each_time_step"                : false,
            "avoid_almost_empty_elements"            : true,
            "deactivate_full_negative_elements"      : true,
            "recover_original_distance_at_each_step" : false
        }  """)

        settings.ValidateAndAssignDefaults(default_parameters)

        self.fluid_model_part = Model[settings["model_part_name"].GetString()]
        self.DistanceModificationProcess = KratosFluid.DistanceModificationProcess(
            self.fluid_model_part, settings)
    def ExecuteFinalizeSolutionStep(self):

        current_time = self.model_part.ProcessInfo[KratosMultiphysics.TIME]

        if ((current_time >= self.interval[0])
                and (current_time < self.interval[1])):
            # Compute the drag force
            drag_force = KratosFluid.DragUtilities().CalculateBodyFittedDrag(
                self.model_part)

            # Write the drag force values
            if (self.model_part.GetCommunicator().MyPID() == 0):
                if (self.print_drag_to_screen):
                    print("DRAG RESULTS:")
                    print("Current time: " + str(current_time) + " x-drag: " +
                          str(drag_force[0]) + " y-drag: " +
                          str(drag_force[1]) + " z-drag: " +
                          str(drag_force[2]))

                if (self.write_drag_output_file):
                    with open(self.drag_filename, 'a') as file:
                        file.write(
                            str(current_time) + "   " + str(drag_force[0]) +
                            "   " + str(drag_force[1]) + "   " +
                            str(drag_force[2]) + "\n")
                        file.close()
    def __init__(self, Model, settings):

        KratosMultiphysics.Process.__init__(self)

        default_parameters = KratosMultiphysics.Parameters("""
        {
            "model_part_name"                        : "default_model_part_name",
            "perform_corrections"                    : true,
            "correction_frequency_in_time_steps"     : 20,
            "write_to_log_file"                      : true,
            "log_file_name"                          : "mass_conservation.log"
        }  """)

        settings.ValidateAndAssignDefaults(default_parameters)

        self._fluid_model_part = Model[settings["model_part_name"].GetString()]
        self._write_to_log = settings["write_to_log_file"].GetBool()
        self._my_log_file = settings["log_file_name"].GetString()

        self._is_printing_rank = (
            self._fluid_model_part.GetCommunicator().MyPID() == 0)
        self.mass_conservation_check_process = KratosFluid.MassConservationCheckProcess(
            self._fluid_model_part, settings)

        if self._is_printing_rank:
            KratosMultiphysics.Logger.PrintInfo(
                "ApplyMassConservationCheckProcess", "Construction finished.")
    def ActivateSpalartAllmaras(self, wall_nodes, DES, CDES=1.0):
        import KratosMultiphysics.FluidDynamicsApplication as KCFD
        for node in wall_nodes:
            node.SetValue(IS_VISITED, 1.0)

        distance_calculator = BodyDistanceCalculationUtils()
        distance_calculator.CalculateDistances2D(
            self.model_part.Elements, DISTANCE, 100.0)

        non_linear_tol = 0.001
        max_it = 10
        reform_dofset = self.ReformDofAtEachIteration
        time_order = self.time_order
        pPrecond = DiagonalPreconditioner()
        turbulence_linear_solver = BICGSTABSolver(1e-20, 5000, pPrecond)
        turbulence_model = KCFD.SpalartAllmarasTurbulenceModel(
            self.model_part,
            turbulence_linear_solver,
            self.domain_size,
            non_linear_tol,
            max_it,
            reform_dofset,
            time_order)
        turbulence_model.AdaptForFractionalStep()
        if(DES):
            turbulence_model.ActivateDES(CDES)

        self.solver.AddInitializeIterationProcess(turbulence_model)
    def ExecuteFinalizeSolutionStep(self):

        current_time = self.fluid_model_part.ProcessInfo[
            KratosMultiphysics.TIME]

        if ((current_time >= self.interval[0])
                and (current_time < self.interval[1])):

            # Integrate the drag over the model part elements
            drag_force = KratosCFD.DragUtilities().CalculateEmbeddedDrag(
                self.fluid_model_part)

            # Print drag values to screen
            if (self.print_drag_to_screen) and (
                    self.fluid_model_part.GetCommunicator().MyPID() == 0):
                print("DRAG VALUES:")
                print("Current time: " + str(current_time) + " x-drag: " +
                      str(drag_force[0]) + " y-drag: " + str(drag_force[1]) +
                      " z-drag: " + str(drag_force[2]))

            # Print drag values to file
            if (self.write_drag_output_file) and (
                    self.fluid_model_part.GetCommunicator().MyPID() == 0):
                with open(self.drag_filename, 'a') as file:
                    file.write(
                        str(current_time) + "   " + str(drag_force[0]) +
                        "   " + str(drag_force[1]) + "   " +
                        str(drag_force[2]) + "\n")
                    file.close()
    def __CreateDistanceModificationProcess(self):
        # Set the distance modification settings according to the level set type
        if (self.level_set_type == "continuous"):
            distance_modification_settings = KratosMultiphysics.Parameters(
                r'''{
                "model_part_name": "",
                "distance_threshold": 1e-3,
                "continuous_distance": true,
                "check_at_each_time_step": true,
                "avoid_almost_empty_elements": true,
                "deactivate_full_negative_elements": true
            }''')
        elif (self.level_set_type == "discontinuous"):
            distance_modification_settings = KratosMultiphysics.Parameters(
                r'''{
                "model_part_name": "",
                "distance_threshold": 1e-4,
                "continuous_distance": false,
                "check_at_each_time_step": true,
                "avoid_almost_empty_elements": false,
                "deactivate_full_negative_elements": false
            }''')
        else:
            err_msg = 'Level set type is: \'' + self.level_set_type + '\'. Expected \'continuous\' or \'discontinuous\'.'
            raise Exception(err_msg)

        # Set the volume model part name in which the distance modification is applied to
        volume_model_part_name = self.settings["fluid_solver_settings"][
            "volume_model_part_name"].GetString()
        distance_modification_settings["model_part_name"].SetString(
            volume_model_part_name)

        # Construct and return the distance modification process
        return KratosFluid.DistanceModificationProcess(
            self.model, distance_modification_settings)
    def __CreateAccelerationLimitationUtility(self):
        maximum_multiple_of_g_acceleration_allowed = 5.0
        acceleration_limitation_utility = KratosCFD.AccelerationLimitationUtilities(
            self.GetComputingModelPart(),
            maximum_multiple_of_g_acceleration_allowed)

        return acceleration_limitation_utility
Exemple #23
0
    def __init__(self, Model, settings):

        KratosMultiphysics.Process.__init__(self)

        # Check the default values
        default_settings = KratosMultiphysics.Parameters( """
        {
            "model_part_name" : "CHOOSE_FLUID_MODELPART_NAME",
            "gravity" : [0.0,0.0,0.0],
            "ambient_temperature" : 273.0
        }  """ )

        # Note: if the thermal expansion coefficient is not provided, it is computed as 
        # 1/AMBIENT_TEMPERATURE which is the usual assumption for perfect gases.
        if (settings.Has("thermal_expansion_coefficient")):
            default_settings.AddEmptyValue("thermal_expansion_coefficient").SetDouble(0.0)

        settings.ValidateAndAssignDefaults(default_settings)

        # Get the fluid model part from the Model container
        self.fluid_model_part = Model[settings["model_part_name"].GetString()]

        # Save the ambient temperature in the fluid model part ProcessInfo
        ambient_temperature = settings["ambient_temperature"].GetDouble()
        self.fluid_model_part.ProcessInfo.SetValue(KratosMultiphysics.AMBIENT_TEMPERATURE, ambient_temperature)

        # Set the Boussinesq force process
        self.BoussinesqForceProcess = KratosFluid.BoussinesqForceProcess(self.fluid_model_part, settings)
    def _CreateScheme(self):
        response_function = self.GetResponseFunction()
        scheme_type = self.settings["scheme_settings"]["scheme_type"].GetString()
        domain_size = self.main_model_part.ProcessInfo[KratosMultiphysics.DOMAIN_SIZE]

        # the schemes used in fluid supports SLIP conditions which rotates element/condition
        # matrices based on nodal NORMAL. Hence, the consistent adjoints also need to
        # rotate adjoint element/condition matrices accordingly. Therefore, following
        # schemes are used.
        if scheme_type == "bossak":
            scheme = KratosCFD.VelocityBossakAdjointScheme(self.settings["scheme_settings"], response_function, domain_size, domain_size + 1)
        elif scheme_type == "steady":
            scheme = KratosCFD.SimpleSteadyAdjointScheme(response_function, domain_size, domain_size + 1)
        else:
            raise Exception("Invalid scheme_type: " + scheme_type)
        return scheme
Exemple #25
0
    def __init__(self, model, params):
        Kratos.OutputProcess.__init__(self)

        default_settings = Kratos.Parameters('''{
            "response_type"       : "PLEASE_SPECIFY_RESPONSE_TYPE",
            "model_part_name"     : "PLEASE_SPECIFY_MAIN_MODEL_PART_NAME",
            "response_settings"   : {},
            "output_file_settings": {}
        }''')

        self.model = model
        self.params = params
        self.main_model_part = self.model.GetModelPart(
            self.params["model_part_name"].GetString())
        self.params.ValidateAndAssignDefaults(default_settings)
        self.output_file = None

        response_type = self.params["response_type"].GetString()
        if (response_type == "norm_square"):
            self.response = KratosCFD.VelocityPressureNormSquareResponseFunction(
                self.params["response_settings"], self.model)
        else:
            raise Exception(
                "Unknown response_type = \"" + response_type +
                "\". Supported response types are: \n\t  1. norm_square")
    def __CreateDistanceModificationProcess(self):
        # Set suitable distance correction settings for free-surface problems
        # Note that the distance modification process is applied to the computing model part
        distance_modification_settings = self.settings["distance_modification_settings"]
        distance_modification_settings.ValidateAndAssignDefaults(self.GetDefaultParameters()["distance_modification_settings"])
        distance_modification_settings["model_part_name"].SetString(self.GetComputingModelPart().FullName())

        # Check user provided settings
        if not distance_modification_settings["continuous_distance"].GetBool():
            distance_modification_settings["continuous_distance"].SetBool(True)
            KratosMultiphysics.Logger.PrintWarning("Provided distance correction \'continuous_distance\' is \'False\'. Setting to \'True\'.")
        if not distance_modification_settings["check_at_each_time_step"].GetBool():
            distance_modification_settings["check_at_each_time_step"].SetBool(True)
            KratosMultiphysics.Logger.PrintWarning("Provided distance correction \'check_at_each_time_step\' is \'False\'. Setting to \'True\'.")
        if distance_modification_settings["avoid_almost_empty_elements"].GetBool():
            distance_modification_settings["avoid_almost_empty_elements"].SetBool(False)
            KratosMultiphysics.Logger.PrintWarning("Provided distance correction \'avoid_almost_empty_elements\' is \'True\'. Setting to \'False\' to avoid modifying the distance sign.")
        if distance_modification_settings["deactivate_full_negative_elements"].GetBool():
            distance_modification_settings["deactivate_full_negative_elements"].SetBool(False)
            KratosMultiphysics.Logger.PrintWarning("Provided distance correction \'deactivate_full_negative_elements\' is \'True\'. Setting to \'False\' to avoid deactivating the negative volume (e.g. water).")

        # Create and return the distance correction process
        return KratosCFD.DistanceModificationProcess(
            self.model,
            distance_modification_settings)
    def testFlowsMeasuring3D_1(self):
        vel = Kratos.Array3()
        vel[0] = 0.0
        vel[1] = 0.0
        vel[2] = 1.0
        node = self.fluid_model_part.CreateNewNode(1, 0.0, 0.0, 0.0)
        node.SetSolutionStepValue(Kratos.VELOCITY, vel)
        node = self.fluid_model_part.CreateNewNode(2, 1.0, 0.0, 0.0)
        node.SetSolutionStepValue(Kratos.VELOCITY, vel)
        node = self.fluid_model_part.CreateNewNode(3, 0.0, 1.0, 0.0)
        node.SetSolutionStepValue(Kratos.VELOCITY, vel)
        node = self.fluid_model_part.CreateNewNode(4, 1.0, 1.0, 0.0)
        node.SetSolutionStepValue(Kratos.VELOCITY, vel)
        vel[0] = 1.0
        vel[1] = 0.0
        vel[2] = 0.0
        node = self.fluid_model_part.CreateNewNode(5, 2.0, 0.0, 0.0)
        node.SetSolutionStepValue(Kratos.VELOCITY, vel)
        node = self.fluid_model_part.CreateNewNode(6, 2.0, 0.0, 1.0)
        node.SetSolutionStepValue(Kratos.VELOCITY, vel)
        node = self.fluid_model_part.CreateNewNode(7, 2.0, 1.0, 0.0)
        node.SetSolutionStepValue(Kratos.VELOCITY, vel)

        condition_name = "SurfaceCondition3D3N"
        self.fluid_model_part.CreateNewCondition(
            condition_name, 1, [1, 2, 3],
            self.fluid_model_part.GetProperties()[0])
        self.fluid_model_part.CreateNewCondition(
            condition_name, 2, [3, 2, 4],
            self.fluid_model_part.GetProperties()[0])
        self.fluid_model_part.CreateNewCondition(
            condition_name, 3, [5, 6, 7],
            self.fluid_model_part.GetProperties()[0])

        first_smp = self.fluid_model_part.CreateSubModelPart("first")
        first_smp.AddConditions([1, 2])
        second_smp = self.fluid_model_part.CreateSubModelPart("second")
        second_smp.AddConditions([3])

        flow_value_first = Fluid.FluidPostProcessUtilities().CalculateFlow(
            first_smp)
        flow_value_second = Fluid.FluidPostProcessUtilities().CalculateFlow(
            second_smp)

        self.assertAlmostEqual(flow_value_first, 1.0)
        self.assertAlmostEqual(flow_value_second, -0.5)
Exemple #28
0
    def _CreateScheme(self):
        domain_size = self.GetComputingModelPart().ProcessInfo[KratosMultiphysics.DOMAIN_SIZE]
        # Cases in which the element manages the time integration
        if self.element_integrates_in_time:
            # "Fake" scheme for those cases in where the element manages the time integration
            # It is required to perform the nodal update once the current time step is solved
            scheme = KratosMultiphysics.ResidualBasedIncrementalUpdateStaticSchemeSlip(
                domain_size,
                domain_size + 1)
            # In case the BDF2 scheme is used inside the element, the BDF time discretization utility is required to update the BDF coefficients
            if (self.settings["time_scheme"].GetString() == "bdf2"):
                time_order = 2
                self.time_discretization = KratosMultiphysics.TimeDiscretization.BDF(time_order)
            else:
                err_msg = "Requested elemental time scheme \"" + self.settings["time_scheme"].GetString()+ "\" is not available.\n"
                err_msg += "Available options are: \"bdf2\""
                raise Exception(err_msg)
        # Cases in which a time scheme manages the time integration
        else:
            # Bossak time integration scheme
            if self.settings["time_scheme"].GetString() == "bossak":
                if self.settings["consider_periodic_conditions"].GetBool() == True:
                    scheme = KratosCFD.ResidualBasedPredictorCorrectorVelocityBossakSchemeTurbulent(
                        self.settings["alpha"].GetDouble(),
                        domain_size,
                        KratosCFD.PATCH_INDEX)
                else:
                    scheme = KratosCFD.ResidualBasedPredictorCorrectorVelocityBossakSchemeTurbulent(
                        self.settings["alpha"].GetDouble(),
                        self.settings["move_mesh_strategy"].GetInt(),
                        domain_size)
            # BDF2 time integration scheme
            elif self.settings["time_scheme"].GetString() == "bdf2":
                scheme = KratosCFD.BDF2TurbulentScheme()
            # Time scheme for steady state fluid solver
            elif self.settings["time_scheme"].GetString() == "steady":
                scheme = KratosCFD.ResidualBasedSimpleSteadyScheme(
                        self.settings["velocity_relaxation"].GetDouble(),
                        self.settings["pressure_relaxation"].GetDouble(),
                        domain_size)
            else:
                err_msg = "Requested time scheme " + self.settings["time_scheme"].GetString() + " is not available.\n"
                err_msg += "Available options are: \"bossak\", \"bdf2\" and \"steady\""
                raise Exception(err_msg)

        return scheme
Exemple #29
0
 def _CreateBuilderAndSolver(self):
     linear_solver = self._GetLinearSolver()
     if self.settings["consider_periodic_conditions"].GetBool():
         builder_and_solver = KratosCFD.ResidualBasedBlockBuilderAndSolverPeriodic(
             linear_solver, KratosCFD.PATCH_INDEX)
     else:
         builder_and_solver = KratosMultiphysics.ResidualBasedBlockBuilderAndSolver(
             linear_solver)
     return builder_and_solver
Exemple #30
0
def Factory(settings, model):
    if(type(settings) != KratosMultiphysics.Parameters):
        raise Exception("expected input shall be a Parameters object, encapsulating a json string")

    if not settings["Parameters"].Has("model_part_name"):
        msg = "Provided settings argument does not contain the model part name.\n"
        msg += "Please provide it as the Parameters/model_part_name (string) argument."
        raise Exception(msg)

    return KratosCFD.IntegrationPointStatisticsProcess(model, settings["Parameters"])