コード例 #1
0
ファイル: mmg_process.py プロジェクト: Ginux1994/Kratos
def _linear_interpolation(x, x_list, y_list):
    tb = KratosMultiphysics.PiecewiseLinearTable()
    for i in range(len(x_list)):
        tb.AddRow(x_list[i], y_list[i])

    return tb.GetNearestValue(x)
    def __init__(self, main_model_part, custom_settings):

        self.main_model_part = main_model_part

        ##settings string in json format
        contact_settings = KM.Parameters("""
        {
            "contact_settings" :
            {
                "mortar_type"                            : "",
                "condn_convergence_criterion"            : false,
                "fancy_convergence_criterion"            : true,
                "print_convergence_criterion"            : false,
                "ensure_contact"                         : false,
                "gidio_debug"                            : false,
                "adaptative_strategy"                    : false,
                "split_factor"                           : 10.0,
                "max_number_splits"                      : 3,
                "contact_displacement_relative_tolerance": 1.0e-4,
                "contact_displacement_absolute_tolerance": 1.0e-9,
                "contact_residual_relative_tolerance"    : 1.0e-4,
                "contact_residual_absolute_tolerance"    : 1.0e-9,
                "use_mixed_ulm_solver"                   : true,
                "mixed_ulm_solver_parameters" :
                {
                    "solver_type": "mixed_ulm_linear_solver",
                    "tolerance" : 1.0e-6,
                    "max_iteration_number" : 200
                }
            }
        }
        """)

        ## Overwrite the default settings with user-provided parameters
        self.settings = custom_settings
        self.validate_and_transfer_matching_settings(self.settings, contact_settings)
        self.contact_settings = contact_settings["contact_settings"]

        # Construct the base solver.
        super().__init__(self.main_model_part, self.settings)

        # Setting default configurations true by default
        if (self.settings["clear_storage"].GetBool() == False):
            self.print_on_rank_zero("Clear storage", "Storage must be cleared each step. Switching to True")
            self.settings["clear_storage"].SetBool(True)
        if (self.settings["reform_dofs_at_each_step"].GetBool() == False):
            self.print_on_rank_zero("Reform DoFs", "DoF must be reformed each time step. Switching to True")
            self.settings["reform_dofs_at_each_step"].SetBool(True)
        if (self.settings["block_builder"].GetBool() == False):
            self.print_on_rank_zero("Builder and solver", "EliminationBuilderAndSolver can not used with the current implementation. Switching to BlockBuilderAndSolver")
            self.settings["block_builder"].SetBool(True)

        # Setting echo level
        self.echo_level =  self.settings["echo_level"].GetInt()

        # Initialize the processes list
        self.processes_list = None

        # Initialize the post process
        self.post_process = None

        self.print_on_rank_zero("::[Contact Mechanical Implicit Dynamic Solver]:: ", "Construction of ContactMechanicalSolver finished")
コード例 #3
0
 def test_MPMPointLoadCondition3D1N(self):
     current_model = KratosMultiphysics.Model()
     self._execute_point_load_condition_test(current_model, Dimension=3)
コード例 #4
0
 def _create_elements(self, initial_mp):
     initial_mp.CreateNewElement("UpdatedLagrangian3D8N", 1, [1,2,3,4,5,6,7,8], initial_mp.GetProperties()[1])
     KratosMultiphysics.VariableUtils().SetFlag(KratosMultiphysics.ACTIVE, True, initial_mp.Elements)
コード例 #5
0
    def __init__(self, Model, custom_settings ):
        KratosMultiphysics.Process.__init__(self)

        ##settings string in json format
        default_settings = KratosMultiphysics.Parameters("""
        {
             "help" : "This process assigns a modulus and direction value to a vector variable",
             "model_part_name": "MODEL_PART_NAME",
             "variable_name": "VARIABLE_NAME",
             "modulus" : 0.0,
             "direction": [0.0, 0.0, 0.0],
             "constrained": false,
             "interval": [0.0, "End"],
             "local_axes" : {}
        }
        """)

        #trick to allow "value" to be a string or a double value
        if(custom_settings.Has("modulus")):
            if(custom_settings["modulus"].IsString()):
                default_settings["modulus"].SetString("0.0")

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

        ##check if variable type is a vector
        self.var = KratosMultiphysics.KratosGlobals.GetVariable(self.settings["variable_name"].GetString())
        if( not isinstance(self.var, KratosMultiphysics.Array1DVariable3) ):
            raise Exception("Variable type is incorrect. Must be a three-component vector.")

        ##check normalized direction
        direction   = []
        scalar_prod = 0
        for i in range(0, self.settings["direction"].size() ):
            direction.append( self.settings["direction"][i].GetDouble() )
            scalar_prod = scalar_prod + direction[i]*direction[i]

        norm = math.sqrt(scalar_prod)

        self.value = []
        if( norm != 0.0 ):
            for j in direction:
                self.value.append( j/norm )
        else:
            for j in direction:
                self.value.append(0.0)

        ## set the value
        self.value_is_numeric = False

        if self.settings["modulus"].IsNumber():
            self.value_is_numeric = True

            modulus = self.settings["modulus"].GetDouble()
            for i in range(0, len(self.value)):
                self.value[i] *= modulus

        else:
            self.function_expression = self.settings["modulus"].GetString()

            counter = 0
            for i in self.value:
                self.value[counter] = str(i) + "*(" + self.function_expression +")"
                counter+=1


        ###set vector components process
        params = KratosMultiphysics.Parameters("{}")
        params.AddValue("model_part_name", self.settings["model_part_name"])
        params.AddValue("variable_name", self.settings["variable_name"])

        params.AddEmptyValue("value")
        params.__setitem__("value", self.settings["direction"])
        counter = 0
        for i in self.value:
            if( self.value_is_numeric ):
                params["value"][counter].SetDouble(i)
            else:
                params["value"][counter].SetString(i)
            counter+=1

        params.AddValue("constrained", self.settings["constrained"])
        params.AddValue("interval",self.settings["interval"])
        params.AddValue("local_axes", self.settings["local_axes"])

        BaseProcess.AssignVectorComponentsToNodesProcess.__init__(self, Model, params)
コード例 #6
0
ファイル: adjoint_conditions.py プロジェクト: dunli/Kratos
 def _SetSlip(self):
     Kratos.VariableUtils().SetFlag(Kratos.SLIP, True, self.model_part.Nodes)
     Kratos.VariableUtils().SetFlag(Kratos.SLIP, True, self.model_part.Conditions)
コード例 #7
0
    def __init__(self, optimization_settings, analyzer, communicator,
                 model_part_controller):
        default_algorithm_settings = KM.Parameters("""
        {
            "name"                    : "penalized_projection",
            "max_correction_share"    : 0.75,
            "max_iterations"          : 100,
            "relative_tolerance"      : 1e-3,
            "line_search" : {
                "line_search_type"           : "manual_stepping",
                "normalize_search_direction" : true,
                "step_size"                  : 1.0
            }
        }""")
        self.algorithm_settings = optimization_settings[
            "optimization_algorithm"]
        self.algorithm_settings.RecursivelyValidateAndAssignDefaults(
            default_algorithm_settings)

        self.optimization_settings = optimization_settings
        self.mapper_settings = optimization_settings["design_variables"][
            "filter"]

        self.analyzer = analyzer
        self.communicator = communicator
        self.model_part_controller = model_part_controller

        self.design_surface = None
        self.mapper = None
        self.data_logger = None
        self.optimization_utilities = None

        self.objectives = optimization_settings["objectives"]
        self.constraints = optimization_settings["constraints"]
        self.constraint_gradient_variables = {}
        for itr, constraint in enumerate(self.constraints):
            self.constraint_gradient_variables.update({
                constraint["identifier"].GetString(): {
                    "gradient":
                    KM.KratosGlobals.GetVariable("DC" + str(itr + 1) + "DX"),
                    "mapped_gradient":
                    KM.KratosGlobals.GetVariable("DC" + str(itr + 1) +
                                                 "DX_MAPPED")
                }
            })
        self.max_correction_share = self.algorithm_settings[
            "max_correction_share"].GetDouble()

        self.step_size = self.algorithm_settings["line_search"][
            "step_size"].GetDouble()
        self.max_iterations = self.algorithm_settings["max_iterations"].GetInt(
        ) + 1
        self.relative_tolerance = self.algorithm_settings[
            "relative_tolerance"].GetDouble()

        self.optimization_model_part = model_part_controller.GetOptimizationModelPart(
        )
        self.optimization_model_part.AddNodalSolutionStepVariable(
            KSO.SEARCH_DIRECTION)
        self.optimization_model_part.AddNodalSolutionStepVariable(
            KSO.CORRECTION)
コード例 #8
0
    def _ConstructSolver(self, builder_and_solver, scheme,
                         convergence_criterion, strategy_type):

        nonlocal_damage = self.settings["mechanical_solver_settings"][
            "nonlocal_damage"].GetBool()
        max_iters = self.settings["mechanical_solver_settings"][
            "max_iteration"].GetInt()
        compute_reactions = self.settings["mechanical_solver_settings"][
            "compute_reactions"].GetBool()
        reform_step_dofs = self.settings["mechanical_solver_settings"][
            "reform_dofs_at_each_step"].GetBool()
        move_mesh_flag = self.settings["mechanical_solver_settings"][
            "move_mesh_flag"].GetBool()

        if strategy_type == "Newton-Raphson":
            if nonlocal_damage:
                self.strategy_params = KratosMultiphysics.Parameters("{}")
                self.strategy_params.AddValue(
                    "loads_sub_model_part_list",
                    self.loads_sub_sub_model_part_list)
                self.strategy_params.AddValue(
                    "loads_variable_list",
                    self.settings["mechanical_solver_settings"]
                    ["loads_variable_list"])
                self.strategy_params.AddValue(
                    "body_domain_sub_model_part_list",
                    self.body_domain_sub_sub_model_part_list)
                self.strategy_params.AddValue(
                    "characteristic_length",
                    self.settings["mechanical_solver_settings"]
                    ["characteristic_length"])
                self.strategy_params.AddValue(
                    "search_neighbours_step",
                    self.settings["mechanical_solver_settings"]
                    ["search_neighbours_step"])
                solver = KratosPoro.PoromechanicsNewtonRaphsonNonlocalStrategy(
                    self.mechanical_computing_model_part, scheme,
                    self.mechanical_linear_solver, convergence_criterion,
                    builder_and_solver, self.strategy_params, max_iters,
                    compute_reactions, reform_step_dofs, move_mesh_flag)
            else:
                self.main_model_part.ProcessInfo.SetValue(
                    KratosPoro.IS_CONVERGED, True)
                solver = KratosMultiphysics.ResidualBasedNewtonRaphsonStrategy(
                    self.mechanical_computing_model_part, scheme,
                    self.mechanical_linear_solver, convergence_criterion,
                    builder_and_solver, max_iters, compute_reactions,
                    reform_step_dofs, move_mesh_flag)
        else:
            # Arc-Length strategy
            self.strategy_params = KratosMultiphysics.Parameters("{}")
            self.strategy_params.AddValue(
                "desired_iterations",
                self.settings["mechanical_solver_settings"]
                ["desired_iterations"])
            self.strategy_params.AddValue(
                "max_radius_factor",
                self.settings["mechanical_solver_settings"]
                ["max_radius_factor"])
            self.strategy_params.AddValue(
                "min_radius_factor",
                self.settings["mechanical_solver_settings"]
                ["min_radius_factor"])
            self.strategy_params.AddValue("loads_sub_model_part_list",
                                          self.loads_sub_sub_model_part_list)
            self.strategy_params.AddValue(
                "loads_variable_list",
                self.settings["mechanical_solver_settings"]
                ["loads_variable_list"])
            if nonlocal_damage:
                self.strategy_params.AddValue(
                    "body_domain_sub_model_part_list",
                    self.body_domain_sub_sub_model_part_list)
                self.strategy_params.AddValue(
                    "characteristic_length",
                    self.settings["mechanical_solver_settings"]
                    ["characteristic_length"])
                self.strategy_params.AddValue(
                    "search_neighbours_step",
                    self.settings["mechanical_solver_settings"]
                    ["search_neighbours_step"])
                solver = KratosPoro.PoromechanicsRammArcLengthNonlocalStrategy(
                    self.mechanical_computing_model_part, scheme,
                    self.mechanical_linear_solver, convergence_criterion,
                    builder_and_solver, self.strategy_params, max_iters,
                    compute_reactions, reform_step_dofs, move_mesh_flag)
            else:
                solver = KratosPoro.PoromechanicsRammArcLengthStrategy(
                    self.mechanical_computing_model_part, scheme,
                    self.mechanical_linear_solver, convergence_criterion,
                    builder_and_solver, self.strategy_params, max_iters,
                    compute_reactions, reform_step_dofs, move_mesh_flag)

        return solver
コード例 #9
0
    def AddVariables(self):

        ## Mechanical Variables
        # Add displacements
        self.main_model_part.AddNodalSolutionStepVariable(
            KratosMultiphysics.DISPLACEMENT)
        # Add reactions for the displacements
        self.main_model_part.AddNodalSolutionStepVariable(
            KratosMultiphysics.REACTION)
        # Add dynamic variables
        self.main_model_part.AddNodalSolutionStepVariable(
            KratosMultiphysics.VELOCITY)
        self.main_model_part.AddNodalSolutionStepVariable(
            KratosMultiphysics.ACCELERATION)
        # Add variables for the solid conditions
        self.main_model_part.AddNodalSolutionStepVariable(
            KratosStructural.POINT_LOAD)
        self.main_model_part.AddNodalSolutionStepVariable(KratosDam.FORCE_LOAD)
        self.main_model_part.AddNodalSolutionStepVariable(
            KratosMultiphysics.POSITIVE_FACE_PRESSURE)
        # Add volume acceleration
        self.main_model_part.AddNodalSolutionStepVariable(
            KratosMultiphysics.VOLUME_ACCELERATION)
        # Add variables for post-processing
        self.main_model_part.AddNodalSolutionStepVariable(
            KratosMultiphysics.NODAL_AREA)
        self.main_model_part.AddNodalSolutionStepVariable(
            KratosDam.NODAL_CAUCHY_STRESS_TENSOR)
        self.main_model_part.AddNodalSolutionStepVariable(
            KratosDam.INITIAL_NODAL_CAUCHY_STRESS_TENSOR)
        self.main_model_part.AddNodalSolutionStepVariable(
            KratosDam.Vi_POSITIVE)
        self.main_model_part.AddNodalSolutionStepVariable(
            KratosDam.Viii_POSITIVE)
        self.main_model_part.AddNodalSolutionStepVariable(
            KratosPoro.NODAL_JOINT_WIDTH)
        self.main_model_part.AddNodalSolutionStepVariable(
            KratosPoro.NODAL_JOINT_AREA)
        self.main_model_part.AddNodalSolutionStepVariable(
            KratosDam.NODAL_YOUNG_MODULUS)

        ## Thermal variables
        thermal_settings = KratosMultiphysics.ConvectionDiffusionSettings()
        thermal_settings.SetDiffusionVariable(KratosMultiphysics.CONDUCTIVITY)
        thermal_settings.SetUnknownVariable(KratosMultiphysics.TEMPERATURE)
        thermal_settings.SetSpecificHeatVariable(
            KratosMultiphysics.SPECIFIC_HEAT)
        thermal_settings.SetDensityVariable(KratosMultiphysics.DENSITY)
        thermal_settings.SetVolumeSourceVariable(KratosMultiphysics.HEAT_FLUX)
        thermal_settings.SetSurfaceSourceVariable(
            KratosMultiphysics.FACE_HEAT_FLUX)
        self.main_model_part.ProcessInfo.SetValue(
            KratosMultiphysics.CONVECTION_DIFFUSION_SETTINGS, thermal_settings)

        # Add thermal variables
        self.main_model_part.AddNodalSolutionStepVariable(
            KratosMultiphysics.CONDUCTIVITY)
        self.main_model_part.AddNodalSolutionStepVariable(
            KratosMultiphysics.TEMPERATURE)
        self.main_model_part.AddNodalSolutionStepVariable(
            KratosMultiphysics.SPECIFIC_HEAT)
        self.main_model_part.AddNodalSolutionStepVariable(
            KratosMultiphysics.DENSITY)
        self.main_model_part.AddNodalSolutionStepVariable(
            KratosMultiphysics.HEAT_FLUX)
        self.main_model_part.AddNodalSolutionStepVariable(
            KratosMultiphysics.FACE_HEAT_FLUX)
        self.main_model_part.AddNodalSolutionStepVariable(
            KratosDam.NODAL_REFERENCE_TEMPERATURE)
        self.main_model_part.AddNodalSolutionStepVariable(
            KratosDam.PLACEMENT_TEMPERATURE)

        # This Variable is used for computing heat source according Azenha Formulation
        self.main_model_part.AddNodalSolutionStepVariable(
            KratosDam.ALPHA_HEAT_SOURCE)
        self.main_model_part.AddNodalSolutionStepVariable(
            KratosDam.TIME_ACTIVATION)

        print("Variables correctly added")
コード例 #10
0
    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_selfweight_solver",
            "model_import_settings":{
                "input_type": "mdpa",
                "input_filename": "unknown_name",
                "input_file_label": 0
            },
            "echo_level": 0,
            "buffer_size": 2,
            "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": "ilu0",
                    "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
        import KratosMultiphysics.python_linear_solver_factory as linear_solver_factory
        self.mechanical_linear_solver = linear_solver_factory.ConstructSolver(
            self.settings["mechanical_solver_settings"]
            ["linear_solver_settings"])

        print("Construction of DamSelfweightSolver finished")
コード例 #11
0
    def _ExecuteAfterReading(self):

        self.mechanical_model_part_name = "mechanical_computing_domain"

        self.body_domain_sub_sub_model_part_list = []
        for i in range(self.settings["mechanical_solver_settings"]
                       ["body_domain_sub_model_part_list"].size()):
            self.body_domain_sub_sub_model_part_list.append(
                "sub_" + self.settings["mechanical_solver_settings"]
                ["body_domain_sub_model_part_list"][i].GetString())
        self.body_domain_sub_sub_model_part_list = KratosMultiphysics.Parameters(
            json.dumps(self.body_domain_sub_sub_model_part_list))

        self.loads_sub_sub_model_part_list = []
        for i in range(self.settings["mechanical_solver_settings"]
                       ["loads_sub_model_part_list"].size()):
            self.loads_sub_sub_model_part_list.append(
                "sub_" + self.settings["mechanical_solver_settings"]
                ["loads_sub_model_part_list"][i].GetString())
        self.loads_sub_sub_model_part_list = KratosMultiphysics.Parameters(
            json.dumps(self.loads_sub_sub_model_part_list))

        # Auxiliary Kratos parameters object to be called by the CheckAndPepareModelProcess
        aux_params = KratosMultiphysics.Parameters("{}")
        aux_params.AddEmptyValue("mechanical_model_part_name").SetString(
            self.mechanical_model_part_name)
        aux_params.AddValue(
            "mechanical_domain_sub_model_part_list",
            self.settings["mechanical_solver_settings"]
            ["problem_domain_sub_model_part_list"])
        aux_params.AddValue(
            "mechanical_loads_sub_model_part_list",
            self.settings["mechanical_solver_settings"]
            ["mechanical_loads_sub_model_part_list"])
        aux_params.AddValue(
            "body_domain_sub_model_part_list",
            self.settings["mechanical_solver_settings"]
            ["body_domain_sub_model_part_list"])
        aux_params.AddValue("body_domain_sub_sub_model_part_list",
                            self.body_domain_sub_sub_model_part_list)
        aux_params.AddValue(
            "loads_sub_model_part_list",
            self.settings["mechanical_solver_settings"]
            ["loads_sub_model_part_list"])
        aux_params.AddValue("loads_sub_sub_model_part_list",
                            self.loads_sub_sub_model_part_list)

        # CheckAndPrepareModelProcess creates the solid_computational_model_part
        from KratosMultiphysics.DamApplication import check_and_prepare_selfweight_model_process_dam
        check_and_prepare_selfweight_model_process_dam.CheckAndPrepareSelfweightModelProcess(
            self.main_model_part, aux_params).Execute()

        # Constitutive law import
        from KratosMultiphysics.DamApplication import dam_constitutive_law_utility
        dam_constitutive_law_utility.SetConstitutiveLaw(self.main_model_part)

        self.main_model_part.SetBufferSize(
            self.settings["buffer_size"].GetInt())
        minimum_buffer_size = self.GetMinimumBufferSize()
        if (minimum_buffer_size > self.main_model_part.GetBufferSize()):
            self.main_model_part.SetBufferSize(minimum_buffer_size)
コード例 #12
0
            "bathymetry_process_list", "initial_conditions_process_list",
            "boundary_conditions_process_list"
        ]

    def _GetSimulationName(self):
        return "Shallow Water Analysis"


if __name__ == "__main__":
    from sys import argv

    if len(argv) > 2:
        err_msg = 'Too many input arguments!\n'
        err_msg += 'Use this script in the following way:\n'
        err_msg += '- With default ProjectParameters (read from "ProjectParameters.json"):\n'
        err_msg += '    "python3 shallow_water_analysis.py"\n'
        err_msg += '- With custom ProjectParameters:\n'
        err_msg += '    "python3 shallow_water_analysis.py CustomProjectParameters.json"\n'
        raise Exception(err_msg)

    if len(argv) == 2:  # ProjectParameters is being passed from outside
        project_parameters_file_name = argv[1]
    else:  # using default name
        project_parameters_file_name = "ProjectParameters.json"

    with open(project_parameter_file_name, 'r') as parameter_file:
        parameters = Kratos.Parameters(parameter_file.read())

    model = Kratos.Model()
    ShallowWaterAnalysis(model, parameters).Run()
コード例 #13
0
    def testLineOutputProcess(self):
        settings = Kratos.Parameters(r'''
        [
            {
                "kratos_module" : "KratosMultiphysics.RANSApplication",
                "python_module" : "cpp_process_factory",
                "process_name"  : "LineOutputProcess",
                "Parameters" : {
                    "model_part_name"                   : "FluidModelPart",
                    "variable_names_list"               : ["DENSITY", "VELOCITY"],
                    "historical_value"                  : true,
                    "start_point"                       : [-0.09, 0.01, 0.0],
                    "end_point"                         : [0.19, 0.01, 0.0],
                    "number_of_sampling_points"         : 100,
                    "output_file_name"                  : "process_tests_data/line_output_test_output_historical",
                    "output_step_control_variable_name" : "STEP",
                    "output_step_interval"              : 1,
                    "write_header_information"          : false
                }
            },
            {
                "kratos_module" : "KratosMultiphysics.RANSApplication",
                "python_module" : "cpp_process_factory",
                "process_name"  : "LineOutputProcess",
                "Parameters" : {
                    "model_part_name"                   : "FluidModelPart",
                    "variable_names_list"               : [
                        "DENSITY",
                        "VELOCITY",
                        "EXTERNAL_FORCES_VECTOR",
                        "GREEN_LAGRANGE_STRAIN_TENSOR"],
                    "historical_value"                  : false,
                    "start_point"                       : [-0.09, 0.01, 0.0],
                    "end_point"                         : [0.19, 0.01, 0.0],
                    "number_of_sampling_points"         : 100,
                    "output_file_name"                  : "process_tests_data/line_output_test_output_non_historical",
                    "output_step_control_variable_name" : "STEP",
                    "output_step_interval"              : 1,
                    "write_header_information"          : false
                }
            },
            {
                "kratos_module" : "KratosMultiphysics",
                "python_module" : "compare_two_files_check_process",
                "Parameters" : {
                    "reference_file_name"   : "process_tests_data/line_output_test_output_historical_ref.csv",
                    "output_file_name"      : "process_tests_data/line_output_test_output_historical_1.000000.csv",
                    "remove_output_file"    : true,
                    "comparison_type"       : "csv_file",
                    "tolerance"             : 1e-6,
                    "relative_tolerance"    : 1e-9,
                    "dimension"             : 3
                }
            },
            {
                "kratos_module" : "KratosMultiphysics",
                "python_module" : "compare_two_files_check_process",
                "Parameters" : {
                    "reference_file_name"   : "process_tests_data/line_output_test_output_non_historical_ref.csv",
                    "output_file_name"      : "process_tests_data/line_output_test_output_non_historical_1.000000.csv",
                    "remove_output_file"    : true,
                    "comparison_type"       : "csv_file",
                    "tolerance"             : 1e-6,
                    "relative_tolerance"    : 1e-9,
                    "dimension"             : 3
                }
            }
        ]''')

        KratosRANS.RansTestUtilities.RandomFillNodalNonHistoricalVariable(
            self.model_part, Kratos.DENSITY, 0.0, 50.0)
        KratosRANS.RansTestUtilities.RandomFillNodalNonHistoricalVariable(
            self.model_part, Kratos.VELOCITY, 0.0, 50.0)

        for node in self.model_part.Nodes:
            v = Kratos.Vector(4)
            v[0] = node.X
            v[1] = node.Y
            v[2] = node.GetValue(Kratos.DENSITY)
            v[3] = node.GetValue(Kratos.DENSITY) * 1.1
            node.SetValue(Kratos.EXTERNAL_FORCES_VECTOR, v)

            m = Kratos.Matrix(2, 2)
            m[0, 0] = node.GetValue(Kratos.DENSITY)
            m[0, 1] = node.GetValue(Kratos.VELOCITY)[0]
            m[1, 0] = node.GetValue(Kratos.VELOCITY)[1]
            m[1, 1] = node.GetValue(Kratos.VELOCITY)[2]
            node.SetValue(Kratos.GREEN_LAGRANGE_STRAIN_TENSOR, m)

        factory = KratosProcessFactory(self.model)
        self.process_list = factory.ConstructListOfProcesses(settings)
        self.__ExecuteProcesses()
コード例 #14
0
    def EvaluateQuantityOfInterest(self):
       ##############################################################################################
       # Functions evaluating the QoI of the problem: Array of displacement at every node on the mesh #
       #                    and nodal area                                                           #
       ##############################################################################################
        ArrayOfDisplacements = []
        for node in self._GetSolver().GetComputingModelPart().Nodes:            
            ArrayOfDisplacements.append(node.GetSolutionStepValue(KratosMultiphysics.DISPLACEMENT_X, 0))
            ArrayOfDisplacements.append(node.GetSolutionStepValue(KratosMultiphysics.DISPLACEMENT_Y, 0))
        return ArrayOfDisplacements

    def EvaluateQuantityOfInterest2(self):
        computing_model_part = self._solver.GetComputingModelPart()
        dimension = self._GetSolver().settings["domain_size"].GetInt()
        area_calculator = KratosMultiphysics.CalculateNodalAreaProcess(computing_model_part , dimension)
        area_calculator.Execute()        

        ArrayOfAreas = []
        for node in self._GetSolver().GetComputingModelPart().Nodes:
            ArrayOfAreas.append(node.GetSolutionStepValue(KratosMultiphysics.NODAL_AREA))
            ArrayOfAreas.append(node.GetSolutionStepValue(KratosMultiphysics.NODAL_AREA))            
        return ArrayOfAreas    


if __name__ == "__main__":
    with open("ProjectParametersROM.json",'r') as parameter_file:
        parameters = KratosMultiphysics.Parameters(parameter_file.read())
    model = KratosMultiphysics.Model()      
    Simulation = TestStructuralMechanicsStaticROM(model,parameters)
    Simulation.Run()
コード例 #15
0
ファイル: adjoint_conditions.py プロジェクト: dunli/Kratos
 def testCalculateFirstDerivativesLHS(self):
     analytical_sensitivity = Kratos.Matrix()
     self.adjoint_condition.CalculateFirstDerivativesLHS(analytical_sensitivity, self.model_part.ProcessInfo)
     self._assertMatrixAlmostEqual(Kratos.Matrix(6, 6, 0), analytical_sensitivity, 9)
コード例 #16
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:
         # Time scheme without turbulence modelling
         if not hasattr(self, "_turbulence_model_solver"):
             # 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.GearScheme()
             # 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)
         # Time scheme with turbulence modelling
         else:
             self._turbulence_model_solver.Initialize()
             if self.settings["time_scheme"].GetString() == "bossak":
                 scheme = KratosCFD.ResidualBasedPredictorCorrectorVelocityBossakSchemeTurbulent(
                     self.settings["alpha"].GetDouble(),
                     self.settings["move_mesh_strategy"].GetInt(),
                     domain_size,
                     self.settings["turbulence_model_solver_settings"]
                     ["velocity_pressure_relaxation_factor"].GetDouble(),
                     self._turbulence_model_solver.
                     GetTurbulenceSolvingProcess())
             # 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,
                     self._turbulence_model_solver.
                     GetTurbulenceSolvingProcess())
     return scheme
コード例 #17
0
ファイル: adjoint_conditions.py プロジェクト: dunli/Kratos
 def testCalculateFirstDerivativesLHSSlip(self):
     self._SetSlip()
     analytical_sensitivity = Kratos.Matrix()
     self.adjoint_condition.CalculateFirstDerivativesLHS(analytical_sensitivity, self.model_part.ProcessInfo)
     fd_sensitivity = self._ComputeFiniteDifferenceSensitivity([Kratos.VELOCITY, Kratos.PRESSURE], 1e-7)
     self._assertMatrixAlmostEqual(fd_sensitivity, analytical_sensitivity, 9)
コード例 #18
0
    def test_eigen_with_constraints(self):
        analysis_parameters_scipy = KratosMultiphysics.Parameters("""{
            "problem_data"    : {
                "parallel_type" : "OpenMP",
                "echo_level"    : 1,
                "start_time"    : 0.0,
                "end_time"      : 1.0
            },
            "solver_settings" : {
                "solver_type"              : "KratosMultiphysics.StructuralMechanicsApplication.structural_mechanics_custom_scipy_base_solver",
                "model_part_name"          : "Structure",
                "domain_size"              : 3,
                "model_import_settings"    : {
                    "input_type"     : "use_input_model_part"
                },
                "time_stepping"            : {
                    "time_step" : 1.1
                },
                "use_computing_model_part" : false,
                "rotation_dofs"            : true,
                "block_builder"            : false
            }
        }""")

        analysis_parameters_eigen = KratosMultiphysics.Parameters("""{
            "problem_data"    : {
                "parallel_type" : "OpenMP",
                "echo_level"    : 1,
                "start_time"    : 0.0,
                "end_time"      : 1.0
            },
            "solver_settings" : {
                "solver_type"              : "eigen_value",
                "model_part_name"          : "Structure",
                "domain_size"              : 3,
                "model_import_settings"    : {
                    "input_type"     : "use_input_model_part"
                },
                "time_stepping"            : {
                    "time_step" : 1.1
                },
                "use_computing_model_part" : false,
                "rotation_dofs"            : true,
                "block_builder"            : true,
                "eigensolver_settings"     : {
                   "solver_type"           : "eigen_eigensystem",
                   "number_of_eigenvalues" : 5,
                   "normalize_eigenvectors": true,
                   "max_iteration"         : 10000,
                   "tolerance"             : 1e-6
                }
            }
        }""")

        model_scipy = KratosMultiphysics.Model()
        analysis_scipy = StructuralMechanicsAnalysis(
            model_scipy, analysis_parameters_scipy.Clone())
        model_part_scipy = model_scipy["Structure"]
        SetupSystem(model_part_scipy)
        analysis_scipy.Run()

        model_eigen = KratosMultiphysics.Model()
        analysis_eigen = StructuralMechanicsAnalysis(
            model_eigen, analysis_parameters_eigen.Clone())
        model_part_eigen = model_eigen["Structure"]
        SetupSystem(model_part_eigen)
        analysis_eigen.Run()

        self.__CompareEigenSolution(model_part_scipy, model_part_eigen)
コード例 #19
0
    def __init__(self, Model, settings):
        """ The default constructor of the class

        Keyword arguments:
        self -- It signifies an instance of a class.
        Model -- the container of the different model parts.
        settings -- Kratos parameters containing solver settings.
        """
        KratosMultiphysics.Process.__init__(self)

        default_settings = KratosMultiphysics.Parameters("""
        {
            "help"                 : "This process sets a variable a certain scalar value in a given direction, for all the nodes belonging to a submodelpart. Uses assign_scalar_variable_to_conditions_process for each component",
            "mesh_id"              : 0,
            "model_part_name"      : "please_specify_model_part_name",
            "variable_name"        : "SPECIFY_VARIABLE_NAME",
            "interval"             : [0.0, 1e30],
            "modulus"              : 1.0,
            "constrained"          : true,
            "direction"            : [1.0, 0.0, 0.0],
            "local_axes"           : {}
        }
        """)

        # Trick: allow "modulus" and "direction" to be a double or a string value (otherwise the ValidateAndAssignDefaults might fail)
        if settings.Has("modulus"):
            if settings["modulus"].IsString():
                default_settings["modulus"].SetString("0.0")

        if settings.Has("direction"):
            if settings["direction"].IsString():
                default_settings["direction"].SetString("Automatic")

        # Detect "End" as a tag and replace it by a large number
        if settings.Has("interval"):
            if settings["interval"][1].IsString():
                if settings["interval"][1].GetString() == "End":
                    settings["interval"][1].SetDouble(
                        1e30)  # = default_settings["interval"][1]
                else:
                    raise Exception(
                        "The second value of interval can be \"End\" or a number, interval currently:"
                        + settings["interval"].PrettyPrintJsonString())

        settings.ValidateAndAssignDefaults(default_settings)

        self.model_part = Model[settings["model_part_name"].GetString()]

        # Construct the component by component parameter objects
        x_params = KratosMultiphysics.Parameters("{}")
        y_params = KratosMultiphysics.Parameters("{}")
        z_params = KratosMultiphysics.Parameters("{}")

        list_params = [x_params, y_params, z_params]
        for i_dir, var_string in enumerate(["_X", "_Y", "_Z"]):
            list_params[i_dir].AddValue("model_part_name",
                                        settings["model_part_name"])
            list_params[i_dir].AddValue("mesh_id", settings["mesh_id"])
            list_params[i_dir].AddValue("constrained", settings["constrained"])
            list_params[i_dir].AddValue("interval", settings["interval"])
            list_params[i_dir].AddEmptyValue("variable_name").SetString(
                settings["variable_name"].GetString() + var_string)
            list_params[i_dir].AddValue("local_axes", settings["local_axes"])

        # "Automatic" direction: get the inwards direction
        all_numeric = True
        if settings["direction"].IsString():
            if settings["direction"].GetString(
            ) == "automatic_inwards_normal" or settings["direction"].GetString(
            ) == "automatic_outwards_normal":
                # Compute the condition normals
                KratosMultiphysics.NormalCalculationUtils().CalculateOnSimplex(
                    self.model_part, self.model_part.ProcessInfo[
                        KratosMultiphysics.DOMAIN_SIZE])

                # Compute the average conditions normal in the submodelpart of interest
                avg_normal = KratosMultiphysics.VariableUtils(
                ).SumConditionVectorVariable(KratosMultiphysics.NORMAL,
                                             self.model_part)
                avg_normal_norm = math.sqrt(
                    pow(avg_normal[0], 2) + pow(avg_normal[1], 2) +
                    pow(avg_normal[2], 2))
                if avg_normal_norm < 1.0e-12:
                    raise Exception(
                        "Direction norm is close to 0 in AssignVectorByDirectionProcess."
                    )

                unit_direction = KratosMultiphysics.Vector(3)
                unit_direction = (1.0 / avg_normal_norm) * avg_normal

                # Note that the NormalCalculationUtils().CalculateOnSimplex gives the outwards normal vector
                if settings["direction"].GetString(
                ) == "automatic_inwards_normal":
                    unit_direction = (-1) * unit_direction
        # Direction is given as a vector
        elif settings["direction"].IsArray():
            unit_direction = [0.0, 0.0, 0.0]
            direction_norm = 0.0
            for i in range(0, 3):
                if settings["direction"][i].IsNumber():
                    unit_direction[i] = settings["direction"][i].GetDouble()
                    direction_norm += pow(unit_direction[i], 2)
                else:
                    function_string = settings["direction"][i].GetString()
                    unit_direction[i] = function_string
                    all_numeric = False

            # Normalize direction
            if all_numeric:
                direction_norm = math.sqrt(direction_norm)
                if direction_norm < 1.0e-12:
                    raise Exception(
                        "Direction norm is close to 0 in AssignVectorByDirectionProcess."
                    )
                for i in range(0, 3):
                    unit_direction[i] = unit_direction[i] / direction_norm

        # Set the remainding parameters
        if settings["modulus"].IsNumber():
            modulus = settings["modulus"].GetDouble()
            if all_numeric:
                for i_dir in range(3):
                    list_params[i_dir].AddEmptyValue("value").SetDouble(
                        modulus * unit_direction[i_dir])
            else:
                for i_dir in range(3):
                    list_params[i_dir].AddEmptyValue(
                        "value").SetString("(" + str(unit_direction[i_dir]) +
                                           ")*(" + str(modulus) + ")")
        elif settings["modulus"].IsString():
            # The concatenated string is: "direction[i])*(f(x,y,z,t)"
            modulus = settings["modulus"].GetString()
            for i_dir in range(3):
                list_params[i_dir].AddEmptyValue("value").SetString(
                    "(" + str(unit_direction[i_dir]) + ")*(" + modulus + ")")

        # Construct a AssignScalarToNodesProcess for each component
        self.aux_processes = []
        for i_dir in range(3):
            self.aux_processes.append(
                assign_scalar_variable_process.AssignScalarVariableProcess(
                    Model, list_params[i_dir]))
コード例 #20
0
from __future__ import print_function, absolute_import, division  # makes KratosMultiphysics backward compatible with python 2.6 and 2.7

# Importing the Kratos Library
import KratosMultiphysics

# Check that applications were imported in the main script
KratosMultiphysics.CheckRegisteredApplications(
    "StructuralMechanicsApplication")

# Import applications
import KratosMultiphysics.StructuralMechanicsApplication as StructuralMechanicsApplication


# Convergence criteria class
class convergence_criterion:
    def __init__(self, convergence_criterion_parameters):
        # Note that all the convergence settings are introduced via a Kratos parameters object.

        D_RT = convergence_criterion_parameters[
            "displacement_relative_tolerance"].GetDouble()
        D_AT = convergence_criterion_parameters[
            "displacement_absolute_tolerance"].GetDouble()
        R_RT = convergence_criterion_parameters[
            "residual_relative_tolerance"].GetDouble()
        R_AT = convergence_criterion_parameters[
            "residual_absolute_tolerance"].GetDouble()

        echo_level = convergence_criterion_parameters["echo_level"].GetInt()
        convergence_crit = convergence_criterion_parameters[
            "convergence_criterion"].GetString()
コード例 #21
0
    def __init__(self, Model, settings):
        KratosMultiphysics.Process.__init__(self)

        default_settings = KratosMultiphysics.Parameters(""" 
            { 
                "mesh_id"         : 0, 
                "model_part_name" : "please_specify_model_part_name", 
                "variable_name"   : "SPECIFY_VARIABLE_NAME", 
                "interval"        : [0.0, 1e30], 
                "value"           : 0.0, 
                "tolerance_rank"  : 3, 
                "local_axes"      : {} 
            } 
            """)

        #detect "End" as a tag and replace it by a large number
        if (settings.Has("interval")):
            if (settings["interval"][1].IsString()):
                if (settings["interval"][1].GetString() == "End"):
                    settings["interval"][1].SetDouble(
                        1e30)  # = default_settings["interval"][1]
                else:
                    raise Exception(
                        "the second value of interval can be \"End\" or a number, interval currently:"
                        + settings["interval"].PrettyPrintJsonString())

        #here i do a trick, since i want to allow "value" to be a string or a double value
        if (settings.Has("value")):
            if (settings["value"].IsString()):
                default_settings["value"].SetString("0.0")

        settings.ValidateAndAssignDefaults(default_settings)

        #admissible values for local axes, are "empty" or
        #"local_axes"               :{
        #    "origin" : [0.0, 0.0, 0.0]
        #    "axes"  : [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0] ]
        #    }
        self.non_trivial_local_system = False
        if (settings["local_axes"].Has("origin")):  # not empty
            self.non_trivial_local_system = True
            self.R = KratosMultiphysics.Matrix(3, 3)
            self.R[0, 0] = settings["local_axes"]["axes"][0][0].GetDouble()
            self.R[0, 1] = settings["local_axes"]["axes"][0][1].GetDouble()
            self.R[0, 2] = settings["local_axes"]["axes"][0][2].GetDouble()
            self.R[1, 0] = settings["local_axes"]["axes"][1][0].GetDouble()
            self.R[1, 1] = settings["local_axes"]["axes"][1][1].GetDouble()
            self.R[1, 2] = settings["local_axes"]["axes"][1][2].GetDouble()
            self.R[2, 0] = settings["local_axes"]["axes"][2][0].GetDouble()
            self.R[2, 1] = settings["local_axes"]["axes"][2][1].GetDouble()
            self.R[2, 2] = settings["local_axes"]["axes"][2][2].GetDouble()

            self.x0 = KratosMultiphysics.Vector(3)
            self.x0[0] = settings["local_axes"]["origin"][0].GetDouble()
            self.x0[1] = settings["local_axes"]["origin"][1].GetDouble()
            self.x0[2] = settings["local_axes"]["origin"][2].GetDouble()

        self.model_part = Model[settings["model_part_name"].GetString()]
        self.variable = getattr(KratosMultiphysics,
                                settings["variable_name"].GetString())
        self.mesh = self.model_part.GetMesh(settings["mesh_id"].GetInt())
        self.interval = KratosMultiphysics.Vector(2)
        self.interval[0] = settings["interval"][0].GetDouble()
        self.interval[1] = settings["interval"][1].GetDouble()

        self.value_is_numeric = False
        self.is_time_function = False
        if settings["value"].IsNumber():
            self.value_is_numeric = True
            self.value = settings["value"].GetDouble()
        else:
            self.function_string = settings["value"].GetString()
            if (sys.version_info > (3, 0)):
                self.aux_function = aux_object_cpp_callback(
                    compile(self.function_string, '', 'eval', optimize=2))
            else:
                self.aux_function = aux_object_cpp_callback(
                    compile(self.function_string, '', 'eval'))

            if (self.function_string.find("x") == -1
                    and self.function_string.find("y") == -1
                    and self.function_string.find("z")
                    == -1):  #depends on time alone!
                self.is_time_function = True

        # Error tolerance
        self.tol = settings["tolerance_rank"].GetInt()
コード例 #22
0
    def __init__(self, convergence_criterion_parameters):
        # Note that all the convergence settings are introduced via a Kratos parameters object.

        D_RT = convergence_criterion_parameters[
            "displacement_relative_tolerance"].GetDouble()
        D_AT = convergence_criterion_parameters[
            "displacement_absolute_tolerance"].GetDouble()
        R_RT = convergence_criterion_parameters[
            "residual_relative_tolerance"].GetDouble()
        R_AT = convergence_criterion_parameters[
            "residual_absolute_tolerance"].GetDouble()

        echo_level = convergence_criterion_parameters["echo_level"].GetInt()
        convergence_crit = convergence_criterion_parameters[
            "convergence_criterion"].GetString()

        if (echo_level >= 1):
            KratosMultiphysics.Logger.PrintInfo(
                "::[Mechanical Solver]:: ", "CONVERGENCE CRITERION : " +
                convergence_criterion_parameters["convergence_criterion"].
                GetString())

        rotation_dofs = False
        if (convergence_criterion_parameters.Has("rotation_dofs")):
            if (convergence_criterion_parameters["rotation_dofs"].GetBool()):
                rotation_dofs = True

        # Convergence criteria if there are rotation DOFs in the problem
        if (rotation_dofs is True):
            if (convergence_crit == "displacement_criterion"):
                self.mechanical_convergence_criterion = StructuralMechanicsApplication.DisplacementAndOtherDoFCriteria(
                    D_RT, D_AT)
                self.mechanical_convergence_criterion.SetEchoLevel(echo_level)

            elif (convergence_crit == "residual_criterion"):
                self.mechanical_convergence_criterion = StructuralMechanicsApplication.ResidualDisplacementAndOtherDoFCriteria(
                    R_RT, R_AT)
                self.mechanical_convergence_criterion.SetEchoLevel(echo_level)

            elif (convergence_crit == "and_criterion"):
                Displacement = StructuralMechanicsApplication.DisplacementAndOtherDoFCriteria(
                    D_RT, D_AT)
                Displacement.SetEchoLevel(echo_level)
                Residual = StructuralMechanicsApplication.ResidualDisplacementAndOtherDoFCriteria(
                    R_RT, R_AT)
                Residual.SetEchoLevel(echo_level)
                self.mechanical_convergence_criterion = KratosMultiphysics.AndCriteria(
                    Residual, Displacement)

            elif (convergence_crit == "or_criterion"):
                Displacement = StructuralMechanicsApplication.DisplacementAndOtherDoFCriteria(
                    D_RT, D_AT)
                Displacement.SetEchoLevel(echo_level)
                Residual = StructuralMechanicsApplication.ResidualDisplacementAndOtherDoFCriteria(
                    R_RT, R_AT)
                Residual.SetEchoLevel(echo_level)
                self.mechanical_convergence_criterion = KratosMultiphysics.OrCriteria(
                    Residual, Displacement)
            else:
                err_msg = "The requested convergence criterion \"" + convergence_crit + "\" is not available!\n"
                err_msg += "Available options are: \"displacement_criterion\", \"residual_criterion\", \"and_criterion\", \"or_criterion\""
                raise Exception(err_msg)

        # Convergence criteria without rotation DOFs
        else:
            if (convergence_crit == "displacement_criterion"):
                self.mechanical_convergence_criterion = KratosMultiphysics.DisplacementCriteria(
                    D_RT, D_AT)
                self.mechanical_convergence_criterion.SetEchoLevel(echo_level)

            elif (convergence_crit == "residual_criterion"):
                self.mechanical_convergence_criterion = KratosMultiphysics.ResidualCriteria(
                    R_RT, R_AT)
                self.mechanical_convergence_criterion.SetEchoLevel(echo_level)

            elif (convergence_crit == "and_criterion"):
                Displacement = KratosMultiphysics.DisplacementCriteria(
                    D_RT, D_AT)
                Displacement.SetEchoLevel(echo_level)
                Residual = KratosMultiphysics.ResidualCriteria(R_RT, R_AT)
                Residual.SetEchoLevel(echo_level)
                self.mechanical_convergence_criterion = KratosMultiphysics.AndCriteria(
                    Residual, Displacement)

            elif (convergence_crit == "or_criterion"):
                Displacement = KratosMultiphysics.DisplacementCriteria(
                    D_RT, D_AT)
                Displacement.SetEchoLevel(echo_level)
                Residual = KratosMultiphysics.ResidualCriteria(R_RT, R_AT)
                Residual.SetEchoLevel(echo_level)
                self.mechanical_convergence_criterion = KratosMultiphysics.OrCriteria(
                    Residual, Displacement)
            else:
                err_msg = "The requested convergence criterion \"" + convergence_crit + "\" is not available!\n"
                err_msg += "Available options are: \"displacement_criterion\", \"residual_criterion\", \"and_criterion\", \"or_criterion\, \"adaptative_remesh_criteria\""
                raise Exception(err_msg)
コード例 #23
0
 def _create_conditions(self, initial_mp):
     initial_mp.CreateNewCondition("Condition3D4N", 1, [2,4,8,6], initial_mp.GetProperties()[1])
     KratosMultiphysics.VariableUtils().SetFlag(KratosMultiphysics.BOUNDARY, True, initial_mp.Conditions)
     for condition in initial_mp.Conditions:
         condition.SetValue(KratosParticle.PARTICLES_PER_CONDITION, 0)
コード例 #24
0
import os

# Import kratos core and applications
import KratosMultiphysics
import KratosMultiphysics.DelaunayMeshingApplication    as KratosPfemg
import KratosMultiphysics.PfemFluidDynamicsApplication  as KratosPfemFluid

######################################################################################
######################################################################################
######################################################################################

#### PARSING THE PARAMETERS ####

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

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

print(" ")

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


print(" ")
from __future__ import print_function, absolute_import, division  # makes KM backward compatible with python 2.6 and 2.7
#import kratos core and applications
import KratosMultiphysics as KM
import KratosMultiphysics.StructuralMechanicsApplication as SMA
import KratosMultiphysics.ContactStructuralMechanicsApplication as CSMA

# Check that KM was imported in the main script
KM.CheckForPreviousImport()

# Import the implicit solver (the explicit one is derived from it)
import structural_mechanics_implicit_dynamic_solver

def CreateSolver(main_model_part, custom_settings):
    return ImplicitMechanicalSolver(main_model_part, custom_settings)

class ImplicitMechanicalSolver(structural_mechanics_implicit_dynamic_solver.ImplicitMechanicalSolver):
    """The structural mechanics contact implicit dynamic solver.

    This class creates the mechanical solvers for contact implicit dynamic analysis.
    It currently supports Newmark, Bossak and dynamic relaxation schemes.

    Public member variables:
    dynamic_settings -- settings for the implicit dynamic solvers.

    See structural_mechanics_solver.py for more information.
    """
    def __init__(self, main_model_part, custom_settings):

        self.main_model_part = main_model_part

        ##settings string in json format
 def _create_solution_scheme(self):
     return KratosMultiphysics.ResidualBasedAdjointStaticScheme(
         self.response_function)
コード例 #27
0
from __future__ import print_function, absolute_import, division #makes KratosMultiphysics backward compatible with python 2.6 and 2.7
# importing the Kratos Library
import KratosMultiphysics
import KratosMultiphysics.ShallowWaterApplication as KratosShallow

# Check that KratosMultiphysics was imported in the main script
KratosMultiphysics.CheckForPreviousImport()

## Import base class file
import shallow_water_base_solver

def CreateSolver(model_part, custom_settings):
    return EulerianConservedVarSolver(model_part, custom_settings)

class EulerianConservedVarSolver(shallow_water_base_solver.ShallowWaterBaseSolver):
    def AddVariables(self):
        super(EulerianConservedVarSolver,self).AddVariables()
        self.model_part.AddNodalSolutionStepVariable(KratosMultiphysics.MOMENTUM)

    def AddDofs(self):
        super(EulerianConservedVarSolver,self)._AddConservedDofs()

    def Solve(self):
        # If a node and it's neighbours are dry, set ACTIVE flag to false
        (self.ShallowVariableUtils).SetDryWetState()
        # Solve equations
        (self.solver).Solve()
        # Compute free surface
        (self.ShallowVariableUtils).ComputeFreeSurfaceElevation()
        # Compute velocity
        (self.ShallowVariableUtils).ComputeVelocity()
コード例 #28
0
ファイル: adjoint_conditions.py プロジェクト: dunli/Kratos
 def testCalculateSensitivityMatrixSlip(self):
     self._SetSlip()
     analytical_sensitivity = Kratos.Matrix()
     self.adjoint_condition.CalculateSensitivityMatrix(Kratos.SHAPE_SENSITIVITY, analytical_sensitivity, self.model_part.ProcessInfo)
     fd_sensitivity = self._ComputeFiniteDifferenceSensitivity([Kratos.SHAPE_SENSITIVITY], 1e-7)
     self._assertMatrixAlmostEqual(fd_sensitivity, analytical_sensitivity, 9)
コード例 #29
0
    def _execute_point_load_condition_test(self, current_model, Dimension):
        mp = current_model.CreateModelPart("solid_part")
        mp.SetBufferSize(2)

        mp.AddNodalSolutionStepVariable(KratosMultiphysics.DISPLACEMENT)
        mp.AddNodalSolutionStepVariable(KratosMultiphysics.REACTION)
        mp.AddNodalSolutionStepVariable(KratosParticle.POINT_LOAD)

        # Create node
        node = mp.CreateNewNode(1, 0.0, 0.0, 0.0)

        # Ensure that the property 1 is created
        mp.GetProperties()[1]

        KratosMultiphysics.VariableUtils().AddDof(
            KratosMultiphysics.DISPLACEMENT_X, KratosMultiphysics.REACTION_X,
            mp)
        KratosMultiphysics.VariableUtils().AddDof(
            KratosMultiphysics.DISPLACEMENT_Y, KratosMultiphysics.REACTION_Y,
            mp)
        KratosMultiphysics.VariableUtils().AddDof(
            KratosMultiphysics.DISPLACEMENT_Z, KratosMultiphysics.REACTION_Z,
            mp)

        if Dimension == 2:
            cond = mp.CreateNewCondition("MPMPointLoadCondition2D1N", 1, [1],
                                         mp.GetProperties()[1])
        elif Dimension == 3:
            cond = mp.CreateNewCondition("MPMPointLoadCondition3D1N", 1, [1],
                                         mp.GetProperties()[1])
        else:
            raise RuntimeError("Wrong Dimension")

        lhs = KratosMultiphysics.Matrix(0, 0)
        rhs = KratosMultiphysics.Vector(0)

        # First we apply a load to the condition
        load_on_cond = KratosMultiphysics.Vector(3)
        load_on_cond[0] = 1.8
        load_on_cond[1] = 2.6
        load_on_cond[2] = -11.47

        cond.SetValue(KratosParticle.POINT_LOAD, load_on_cond)

        cond.CalculateLocalSystem(lhs, rhs, mp.ProcessInfo)

        self.assertEqual(rhs[0], load_on_cond[0])
        self.assertEqual(rhs[1], load_on_cond[1])
        if Dimension == 3:
            self.assertEqual(rhs[2], load_on_cond[2])

        # Now we apply a load to the node
        nodal_load = KratosMultiphysics.Vector(3)
        nodal_load[0] = -5.5
        nodal_load[1] = 1.2
        nodal_load[2] = 9.3

        node.SetSolutionStepValue(KratosParticle.POINT_LOAD, nodal_load)

        cond.CalculateLocalSystem(lhs, rhs, mp.ProcessInfo)

        self.assertEqual(rhs[0], load_on_cond[0] + nodal_load[0])
        self.assertEqual(rhs[1], load_on_cond[1] + nodal_load[1])
        if Dimension == 3:
            self.assertEqual(rhs[2], load_on_cond[2] + nodal_load[2])
コード例 #30
0
ファイル: mmg_process.py プロジェクト: Ginux1994/Kratos
    def _CreateMetricsProcess(self):
        self.metric_processes = []
        if self.strategy == "LevelSet":
            level_set_parameters = KratosMultiphysics.Parameters("""{}""")
            level_set_parameters.AddValue("minimal_size",
                                          self.settings["minimal_size"])
            level_set_parameters.AddValue("enforce_current",
                                          self.settings["enforce_current"])
            level_set_parameters.AddValue(
                "anisotropy_remeshing", self.settings["anisotropy_remeshing"])
            level_set_parameters.AddValue(
                "anisotropy_parameters",
                self.settings["anisotropy_parameters"])
            level_set_parameters["anisotropy_parameters"].RemoveValue(
                "boundary_layer_min_size_ratio")
            if self.dim == 2:
                self.metric_processes.append(
                    MeshingApplication.ComputeLevelSetSolMetricProcess2D(
                        self.model_part, self.gradient_variable,
                        level_set_parameters))

            else:
                self.metric_processes.append(
                    MeshingApplication.ComputeLevelSetSolMetricProcess3D(
                        self.model_part, self.gradient_variable,
                        level_set_parameters))

        elif self.strategy == "Hessian":
            hessian_parameters = KratosMultiphysics.Parameters("""{}""")
            hessian_parameters.AddValue("minimal_size",
                                        self.settings["minimal_size"])
            hessian_parameters.AddValue("maximal_size",
                                        self.settings["maximal_size"])
            hessian_parameters.AddValue("enforce_current",
                                        self.settings["enforce_current"])
            hessian_parameters.AddValue(
                "hessian_strategy_parameters",
                self.settings["hessian_strategy_parameters"])
            hessian_parameters["hessian_strategy_parameters"].RemoveValue(
                "metric_variable")
            hessian_parameters.AddValue("anisotropy_remeshing",
                                        self.settings["anisotropy_remeshing"])
            hessian_parameters.AddValue("anisotropy_parameters",
                                        self.settings["anisotropy_parameters"])
            hessian_parameters["anisotropy_parameters"].RemoveValue(
                "boundary_layer_min_size_ratio")
            for current_metric_variable in self.metric_variable:
                if type(current_metric_variable
                        ) is KratosMultiphysics.Array1DComponentVariable:
                    if self.dim == 2:
                        self.metric_processes.append(
                            MeshingApplication.
                            ComputeHessianSolMetricProcessComp2D(
                                self.model_part, current_metric_variable,
                                hessian_parameters))
                    else:
                        self.metric_processes.append(
                            MeshingApplication.
                            ComputeHessianSolMetricProcessComp3D(
                                self.model_part, current_metric_variable,
                                hessian_parameters))
                else:
                    if self.dim == 2:
                        self.metric_processes.append(
                            MeshingApplication.
                            ComputeHessianSolMetricProcess2D(
                                self.model_part, current_metric_variable,
                                hessian_parameters))
                    else:
                        self.metric_processes.append(
                            MeshingApplication.
                            ComputeHessianSolMetricProcess3D(
                                self.model_part, current_metric_variable,
                                hessian_parameters))
        elif self.strategy == "superconvergent_patch_recovery":
            if not structural_dependencies:
                raise Exception(
                    "You need to compile the StructuralMechanicsApplication in order to use this criteria"
                )

            # We compute the error
            error_compute_parameters = KratosMultiphysics.Parameters("""{}""")
            error_compute_parameters.AddValue(
                "stress_vector_variable",
                self.settings["compute_error_extra_parameters"]
                ["stress_vector_variable"])
            error_compute_parameters.AddValue("echo_level",
                                              self.settings["echo_level"])
            if self.dim == 2:
                self.error_compute = StructuralMechanicsApplication.SPRErrorProcess2D(
                    self.model_part, error_compute_parameters)
            else:
                self.error_compute = StructuralMechanicsApplication.SPRErrorProcess3D(
                    self.model_part, error_compute_parameters)

            # Now we compute the metric
            error_metric_parameters = KratosMultiphysics.Parameters("""{}""")
            error_metric_parameters.AddValue("minimal_size",
                                             self.settings["minimal_size"])
            error_metric_parameters.AddValue("maximal_size",
                                             self.settings["maximal_size"])
            error_metric_parameters.AddValue(
                "target_error", self.settings["error_strategy_parameters"]
                ["error_metric_parameters"]["interpolation_error"])
            error_metric_parameters.AddValue(
                "set_target_number_of_elements",
                self.settings["error_strategy_parameters"]
                ["set_target_number_of_elements"])
            error_metric_parameters.AddValue(
                "target_number_of_elements",
                self.settings["error_strategy_parameters"]
                ["target_number_of_elements"])
            error_metric_parameters.AddValue(
                "perform_nodal_h_averaging",
                self.settings["error_strategy_parameters"]
                ["perform_nodal_h_averaging"])
            error_metric_parameters.AddValue("echo_level",
                                             self.settings["echo_level"])

            if self.dim == 2:
                self.metric_process = MeshingApplication.MetricErrorProcess2D(
                    self.model_part, error_metric_parameters)
            else:
                self.metric_process = MeshingApplication.MetricErrorProcess3D(
                    self.model_part, error_metric_parameters)