Example #1
0
    def ReadModelParts(self, max_node_Id=0, max_elem_Id=0, max_cond_Id=0):
        properties = KratosMultiphysics.Properties(0)
        properties_walls = KratosMultiphysics.Properties(0)
        self.SetHardcodedProperties(properties, properties_walls)
        self.spheres_model_part.AddProperties(properties)
        self.rigid_face_model_part.AddProperties(properties_walls)

        translational_scheme = DEM.ForwardEulerScheme()
        translational_scheme.SetTranslationalIntegrationSchemeInProperties(properties, True)
        rotational_scheme = DEM.ForwardEulerScheme()
        rotational_scheme.SetRotationalIntegrationSchemeInProperties(properties, True)

        element_name = "CylinderParticle2D"
        DEM.PropertiesProxiesManager().CreatePropertiesProxies(self.spheres_model_part)

        coordinates = KratosMultiphysics.Array3()
        coordinates[0] = 0.0
        coordinates[1] = 0.0025002
        coordinates[2] = 0.0
        radius = 0.0025
        self.creator_destructor.CreateSphericParticle(self.spheres_model_part, coordinates, properties, radius, element_name)

        for node in self.spheres_model_part.Nodes:
            node.SetSolutionStepValue(KratosMultiphysics.VELOCITY_Y, -3.9)

        self.rigid_face_model_part.CreateNewNode(3, -0.01, 0.0, 0.0)
        self.rigid_face_model_part.CreateNewNode(4, 0.01, 0.0, 0.0)

        condition_name = "RigidEdge2D2N"
        self.rigid_face_model_part.CreateNewCondition(condition_name, 7, [3, 4], self.rigid_face_model_part.GetProperties()[0])
    def CreateCPlusPlusStrategy(self):
        self.SetVariablesAndOptions()

        if self.DEM_parameters["TranslationalIntegrationScheme"].GetString(
        ) == 'Verlet_Velocity':
            self.cplusplus_strategy = DEM.IterativeSolverStrategy(
                self.settings, self.max_delta_time, self.n_step_search,
                self.safety_factor, self.delta_option, self.creator_destructor,
                self.dem_fem_search, self.search_strategy,
                self.solver_settings)

        elif self.DEM_parameters["TranslationalIntegrationScheme"].GetString(
        ) in {'Hybrid_Bashforth', 'TerminalVelocityScheme'}:
            self.cplusplus_strategy = SDEM.AdamsBashforthStrategy(
                self.settings, self.max_delta_time, self.n_step_search,
                self.safety_factor, self.delta_option, self.creator_destructor,
                self.dem_fem_search, self.search_strategy,
                self.solver_settings)

        else:
            self.cplusplus_strategy = DEM.ExplicitSolverStrategy(
                self.settings, self.max_delta_time, self.n_step_search,
                self.safety_factor, self.delta_option, self.creator_destructor,
                self.dem_fem_search, self.search_strategy,
                self.solver_settings)
    def setUp(self):
        self.current_model = Kratos.Model()
        self.spheres_model_part = self.current_model.CreateModelPart(
            "SpheresPart")
        self.spheres_model_part.AddNodalSolutionStepVariable(Kratos.VELOCITY)
        self.spheres_model_part.AddNodalSolutionStepVariable(
            Kratos.ANGULAR_VELOCITY)
        self.spheres_model_part.AddNodalSolutionStepVariable(Kratos.RADIUS)
        self.spheres_model_part.AddNodalSolutionStepVariable(
            Kratos.PARTICLE_MATERIAL)
        self.spheres_model_part.AddNodalSolutionStepVariable(Kratos.NODAL_MASS)

        properties = Kratos.Properties(0)
        properties[Kratos.YOUNG_MODULUS] = 3.331
        properties[
            DEM.
            DEM_DISCONTINUUM_CONSTITUTIVE_LAW_NAME] = "DEM_D_Hertz_viscous_Coulomb"
        properties[DEM.FRICTION] = 0.0
        properties[Kratos.POISSON_RATIO] = 0.0
        properties[DEM.DAMPING_GAMMA] = 0.0
        properties[DEM.COEFFICIENT_OF_RESTITUTION] = 0.0

        self.ModifyProperties(properties)

        self.spheres_model_part.AddProperties(properties)

        DEM.PropertiesProxiesManager().CreatePropertiesProxies(
            self.spheres_model_part)

        self.creator_destructor = DEM.ParticleCreatorDestructor()
Example #4
0
    def ReadModelParts(self, max_node_Id=0, max_elem_Id=0, max_cond_Id=0):
        properties = KratosMultiphysics.Properties(0)
        properties_walls = KratosMultiphysics.Properties(0)
        SetHardcodedProperties(properties, properties_walls)
        self.spheres_model_part.AddProperties(properties)
        self.rigid_face_model_part.AddProperties(properties_walls)

        translational_scheme = DEM.ForwardEulerScheme()
        translational_scheme.SetTranslationalIntegrationSchemeInProperties(
            properties, True)
        rotational_scheme = DEM.ForwardEulerScheme()
        rotational_scheme.SetRotationalIntegrationSchemeInProperties(
            properties, True)

        element_name = "SphericContinuumParticle3D"
        DEM.PropertiesProxiesManager().CreatePropertiesProxies(
            self.spheres_model_part)

        coordinates = KratosMultiphysics.Array3()
        coordinates[0] = -1
        coordinates[1] = 0.0
        coordinates[2] = 0.0
        radius = 1
        self.creator_destructor.CreateSphericParticle(self.spheres_model_part,
                                                      coordinates, properties,
                                                      radius, element_name)

        coordinates = KratosMultiphysics.Array3()
        coordinates[0] = 0.95
        coordinates[1] = 0.0
        coordinates[2] = 0.0
        radius = 1
        self.creator_destructor.CreateSphericParticle(self.spheres_model_part,
                                                      coordinates, properties,
                                                      radius, element_name)

        for node in self.spheres_model_part.Nodes:
            node.SetSolutionStepValue(DEM.COHESIVE_GROUP, 1)

        for node in self.spheres_model_part.Nodes:
            if node.Id == 2:
                node.SetSolutionStepValue(KratosMultiphysics.VELOCITY_X, 0.0)
            if node.Id == 1:
                node.SetSolutionStepValue(KratosMultiphysics.VELOCITY_X, 0.1)

        self.rigid_face_model_part.CreateNewNode(3, -5, 5, -1.008)
        self.rigid_face_model_part.CreateNewNode(4, 5, 5, -1.008)

        self.rigid_face_model_part.CreateNewNode(5, -5, -5, -1.008)
        self.rigid_face_model_part.CreateNewNode(6, 5, -5, -1.008)

        condition_name = "RigidFace3D3N"
        self.rigid_face_model_part.CreateNewCondition(
            condition_name, 7, [5, 6, 3],
            self.rigid_face_model_part.GetProperties()[0])
        self.rigid_face_model_part.CreateNewCondition(
            condition_name, 8, [3, 6, 4],
            self.rigid_face_model_part.GetProperties()[0])
    def ReadModelParts(self, max_node_Id=0, max_elem_Id=0, max_cond_Id=0):
        properties = KratosMultiphysics.Properties(0)
        properties_walls = KratosMultiphysics.Properties(0)
        self.spheres_model_part.AddProperties(properties)
        self.rigid_face_model_part.AddProperties(properties_walls)

        translational_scheme = DEM.ForwardEulerScheme()
        translational_scheme.SetTranslationalIntegrationSchemeInProperties(
            properties, True)
        rotational_scheme = DEM.ForwardEulerScheme()
        rotational_scheme.SetRotationalIntegrationSchemeInProperties(
            properties, True)

        element_name = "SphericParticle3D"
        DEM.PropertiesProxiesManager().CreatePropertiesProxies(
            self.spheres_model_part)

        coordinates = KratosMultiphysics.Array3()
        coordinates[0] = 0.0
        coordinates[1] = 0.0
        coordinates[2] = 0.0025002
        radius = 0.0025
        self.creator_destructor.CreateSphericParticle(self.spheres_model_part,
                                                      coordinates, properties,
                                                      radius, element_name)

        # Second particle to check search flag against particles
        coordinates[2] = -0.0026
        self.creator_destructor.CreateSphericParticle(self.spheres_model_part,
                                                      coordinates, properties,
                                                      radius, element_name)

        for node in self.spheres_model_part.Nodes:
            node.SetSolutionStepValue(KratosMultiphysics.VELOCITY_Z, -3.9)
            if node.Id == 2:
                node.SetSolutionStepValue(KratosMultiphysics.VELOCITY_Z, 1)

        self.rigid_face_model_part.CreateNewNode(3, -0.01, 0.01, 0.0)
        self.rigid_face_model_part.CreateNewNode(4, 0.01, 0.01, 0.0)

        self.rigid_face_model_part.CreateNewNode(5, -0.01, -0.01, 0.0)
        self.rigid_face_model_part.CreateNewNode(6, 0.01, -0.01, 0.0)

        condition_name = "RigidFace3D3N"
        self.rigid_face_model_part.CreateNewCondition(
            condition_name, 7, [5, 6, 3],
            self.rigid_face_model_part.GetProperties()[0])
        self.rigid_face_model_part.CreateNewCondition(
            condition_name, 8, [3, 6, 4],
            self.rigid_face_model_part.GetProperties()[0])
    def ReadModelParts(self, max_node_Id=0, max_elem_Id=0, max_cond_Id=0):
        properties = KratosMultiphysics.Properties(0)
        properties_walls = KratosMultiphysics.Properties(0)
        self.SetHardcodedProperties(properties, properties_walls)
        self.spheres_model_part.AddProperties(properties)
        self.rigid_face_model_part.AddProperties(properties_walls)

        DiscontinuumConstitutiveLaw = getattr(
            DEM, properties[DEM.DEM_DISCONTINUUM_CONSTITUTIVE_LAW_NAME])()
        DiscontinuumConstitutiveLaw.SetConstitutiveLawInProperties(
            properties, False)

        translational_scheme = DEM.ForwardEulerScheme()
        translational_scheme.SetTranslationalIntegrationSchemeInProperties(
            properties, True)
        rotational_scheme = DEM.ForwardEulerScheme()
        rotational_scheme.SetRotationalIntegrationSchemeInProperties(
            properties, True)

        element_name = "SphericParticle3D"
        DEM.PropertiesProxiesManager().CreatePropertiesProxies(
            self.spheres_model_part)

        coordinates = KratosMultiphysics.Array3()
        coordinates[0] = 0.0
        coordinates[1] = 0.0
        coordinates[2] = 0.00255
        radius = 0.0025
        self.creator_destructor.CreateSphericParticle(self.spheres_model_part,
                                                      coordinates, properties,
                                                      radius, element_name)

        for node in self.spheres_model_part.Nodes:
            node.SetSolutionStepValue(KratosMultiphysics.VELOCITY_Z, -3.9)

        self.rigid_face_model_part.CreateNewNode(3, -0.01, 0.01, 0.0)
        self.rigid_face_model_part.CreateNewNode(4, 0.01, 0.01, 0.0)

        self.rigid_face_model_part.CreateNewNode(5, -0.01, -0.01, 0.0)
        self.rigid_face_model_part.CreateNewNode(6, 0.01, -0.01, 0.0)

        condition_name = "RigidFace3D3N"
        self.rigid_face_model_part.CreateNewCondition(
            condition_name, 7, [5, 6, 3],
            self.rigid_face_model_part.GetProperties()[0])
        self.rigid_face_model_part.CreateNewCondition(
            condition_name, 8, [3, 6, 4],
            self.rigid_face_model_part.GetProperties()[0])
Example #7
0
 def SolveSolutionStep(self):
     # move the rigid wall object in the dem mp w.r.t. the current displacement and velocities
     for model_part_nodes in self.list_of_nodes_in_move_mesh_model_parts:
         DEMApplication.MoveMeshUtility().MoveDemMesh(
             model_part_nodes, True)
     # solve DEM
     super().SolveSolutionStep()
Example #8
0
    def __init__(self, Model, settings):
        KratosMultiphysics.Process.__init__(self)

        # Control module process acting on the imposed direction: 0 (X), 1 (Y), 2 (Z) or 3 (radial)
        # The radial direction is valid only for the vertical walls of a right cylinder with the base
        # on the 'X-Y' plane centered on (0,0). Negative target_stress means compression.

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

        self.params = KratosMultiphysics.Parameters("{}")
        self.params.AddValue("model_part_name", settings["model_part_name"])
        self.params.AddValue("imposed_direction",
                             settings["imposed_direction"])
        self.params.AddValue("target_stress_table_id",
                             settings["target_stress_table_id"])
        self.params.AddValue("initial_velocity", settings["initial_velocity"])
        self.params.AddValue("limit_velocity", settings["limit_velocity"])
        self.params.AddValue("velocity_factor", settings["velocity_factor"])
        self.params.AddValue("compression_length",
                             settings["compression_length"])
        self.params.AddValue("young_modulus", settings["young_modulus"])
        self.params.AddValue("stress_increment_tolerance",
                             settings["stress_increment_tolerance"])
        self.params.AddValue("update_stiffness", settings["update_stiffness"])
        self.params.AddValue("start_time", settings["start_time"])

        self.control_module_process = Dem.ControlModule2DProcess(
            self.model_part, self.params)
def Factory(settings, Model):
    if (type(settings) != KratosMultiphysics.Parameters):
        raise Exception(
            "expected input shall be a Parameters object, encapsulating a json string"
        )

    process_settings = settings["Parameters"]

    folder_settings = KratosMultiphysics.Parameters("""{
            "help"                 : "This process applies constraints to the rigid walls in a certain submodelpart, for a certain time interval",
            "mesh_id"              : 0,
            "model_part_name"      : "please_specify_model_part_name",
            "force_settings" : {
                "value"                : [10.0, "3*t", "x+y"]
            },
            "moment_settings" : {
                "value"                : [10.0, "3*t", "x+y"]
            },
            "interval"             : [0.0, 1e30]
        }""")

    process_settings.AddMissingParameters(folder_settings)

    if process_settings.Has("model_part_name"):
        computing_model_part = Model[
            process_settings["model_part_name"].GetString()]
    else:  # using default name
        computing_model_part = Model["DEM_FEM_boundary"]

    process_settings.RemoveValue("help")

    return DEM.ApplyForcesAndMomentsToWallsProcess(computing_model_part,
                                                   process_settings)
    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 applies constraints to the particles in a certain submodelpart, for a certain time interval",
            "mesh_id"              : 0,
            "model_part_name"      : "please_specify_model_part_name",
            "velocity_constraints_settings" : {
                "constrained"          : [true,true,true],
                "value"                : [10.0, "3*t", "x+y"]
            },
            "angular_velocity_constraints_settings" : {
                "constrained"          : [true,true,true],
                "value"                : [10.0, "3*t", "x+y"]
            },
            "interval"             : [0.0, 1e30]
        }
        """)
        #example of admissible values for "value" : [10.0, "3*t", "x+y"]

        ## Trick to ensure that if someone sets constrained as a single bool, it is transformed to a vector
        if settings["velocity_constraints_settings"].Has("constrained"):
            if settings["velocity_constraints_settings"]["constrained"].IsBool(
            ):
                is_fixed = settings["velocity_constraints_settings"][
                    "constrained"].GetBool()
                settings["velocity_constraints_settings"][
                    "constrained"] = default_settings[
                        "velocity_constraints_settings"]["constrained"]
                for i in range(3):
                    settings["velocity_constraints_settings"]["constrained"][
                        i].SetBool(is_fixed)

        if settings["angular_velocity_constraints_settings"].Has(
                "constrained"):
            if settings["angular_velocity_constraints_settings"][
                    "constrained"].IsBool():
                is_fixed = settings["angular_velocity_constraints_settings"][
                    "constrained"].GetBool()
                settings["angular_velocity_constraints_settings"][
                    "constrained"] = default_settings[
                        "angular_velocity_constraints_settings"]["constrained"]
                for i in range(3):
                    settings["angular_velocity_constraints_settings"][
                        "constrained"][i].SetBool(is_fixed)

        settings.ValidateAndAssignDefaults(default_settings)

        self.model_part = Model[settings["model_part_name"].GetString()]
        self.cplusplus_version_of_this_process = DEM.ApplyKinematicConstraintsProcess(
            self.model_part, settings)
Example #11
0
    def GetParticleHistoryWatcher(self):
        watcher_type = self.sdem_parameters[
            "full_particle_history_watcher"].GetString()

        if watcher_type == 'Empty':
            return None
        elif watcher_type == 'ParticlesHistoryWatcher':
            return DEM.ParticlesHistoryWatcher()
Example #12
0
    def __init__(self, Model, settings):
        KratosMultiphysics.Process.__init__(self)

        # Control module process acting on the imposed direction: 0 (X), 1 (Y), 2 (Z) or 3 (radial)
        # The radial direction is valid only for the vertical walls of a right cylinder with the base
        # on the 'X-Y' plane centered on (0,0). Negative target_stress means compression.

        self.model_part = Model[settings["model_part_name"].GetString()]
        self.control_module_process = Dem.ControlModule2DProcess(
            self.model_part, settings)
Example #13
0
    def Writeresults(self, time):

        # We reorder the Id of the model parts
        femdem_util = FEMDEM.FEMDEMCouplingUtilities()
        reorder_util_elem = FEMDEM.RenumberingNodesUtility(
            self.solid_model_part, self.fluid_model_part)
        reorder_util_elem.RenumberElements()

        Logger.PrintInfo("", "")
        Logger.PrintInfo(
            "",
            "*****************  PRINTING RESULTS FOR GID  *************************"
        )
        Logger.PrintInfo("", "")
        Logger.Flush()

        number_pfem_nodes = femdem_util.GetNumberOfNodes(self.fluid_model_part)
        for node in self.balls_model_part.Nodes:
            node.Id = node.Id + number_pfem_nodes

        if self.GiDMultiFileFlag == "Multiples":
            self.mixed_solid_fluid_model_part.Elements.clear()
            self.mixed_solid_fluid_model_part.Nodes.clear()

            self.mixed_solid_balls_model_part.Elements.clear()
            self.mixed_solid_balls_model_part.Nodes.clear()

            self.mixed_solid_balls_fluid_model_part.Elements.clear()
            self.mixed_solid_balls_fluid_model_part.Nodes.clear()

            # Now we fill the mixed MDPA in order to print
            post_utils = DEMApplication.PostUtilities()
            post_utils.AddModelPartToModelPart(
                self.mixed_solid_fluid_model_part, self.fluid_model_part)

            post_utils.AddModelPartToModelPart(
                self.mixed_solid_balls_model_part, self.balls_model_part)
            post_utils.AddModelPartToModelPart(
                self.mixed_solid_balls_model_part, self.rigid_faces_model_part)

            post_utils.AddModelPartToModelPart(
                self.mixed_solid_balls_fluid_model_part, self.balls_model_part)
            post_utils.AddModelPartToModelPart(
                self.mixed_solid_balls_fluid_model_part,
                self.rigid_faces_model_part)
            post_utils.AddModelPartToModelPart(
                self.mixed_solid_balls_fluid_model_part, self.solid_model_part)
            post_utils.AddModelPartToModelPart(
                self.mixed_solid_balls_fluid_model_part, self.fluid_model_part)

            FEMDEM.FEMDEMCouplingUtilities().RemoveDuplicates(
                self.mixed_solid_fluid_model_part)

        self.write_dem_fem_results(time)
        reorder_util_elem.UndoRenumberElements()
    def ModifyProperties(self, properties, param=0):

        if not param:
            DiscontinuumConstitutiveLaw = getattr(
                DEM, properties[DEM.DEM_DISCONTINUUM_CONSTITUTIVE_LAW_NAME])()
            DiscontinuumConstitutiveLaw.SetConstitutiveLawInProperties(
                properties, False)

        scheme = DEM.SymplecticEulerScheme()
        scheme.SetTranslationalIntegrationSchemeInProperties(properties, False)
        scheme.SetRotationalIntegrationSchemeInProperties(properties, False)
 def SetFluidSolverParameters(self):
     self.time           = self.pp.Start_time
     self.Dt             = self.pp.Dt
     self.out            = self.Dt
     if "REACTION" in self.pp.nodal_results:
         self.fluid_model_part.AddNodalSolutionStepVariable(Kratos.REACTION)
     if "DISTANCE" in self.pp.nodal_results:
         self.fluid_model_part.AddNodalSolutionStepVariable(Kratos.DISTANCE)
     self.vars_man.AddNodalVariables(self.fluid_model_part, self.vars_man.fluid_vars)
     if self.pp.type_of_inlet == 'ForceImposed':
         self.DEM_inlet = DEM.DEM_Force_Based_Inlet(self.dem_inlet_model_part, self.pp.force)
    def __init__(self, gid_io, project_parameters, fluid_model_part,
                 balls_model_part, clusters_model_part, rigid_faces_model_part,
                 mixed_model_part):

        self.gid_io = weakref.proxy(gid_io)
        self.fluid_model_part = fluid_model_part
        self.balls_model_part = balls_model_part
        self.clusters_model_part = clusters_model_part
        self.rigid_faces_model_part = rigid_faces_model_part
        self.mixed_model_part = mixed_model_part
        self.pp = project_parameters
        self.post_utilities = DEMApp.PostUtilities()
    def Writeresults(self, time):

        Logger.PrintInfo("DEM-Struct", "")
        Logger.PrintInfo(
            "DEM-Struct",
            "*******************  PRINTING RESULTS FOR GID  ***************************"
        )
        Logger.Flush()

        if self.GiDMultiFileFlag == "Multiples":
            self.mixed_model_part.Elements.clear()
            self.mixed_model_part.Nodes.clear()
            # here order is important!
            DEMApplication.PostUtilities().AddModelPartToModelPart(
                self.mixed_model_part, self.balls_model_part)
            DEMApplication.PostUtilities().AddModelPartToModelPart(
                self.mixed_model_part, self.rigid_faces_model_part)
            DEMApplication.PostUtilities().AddModelPartToModelPart(
                self.mixed_model_part, self.contact_model_part)
            DEMApplication.PostUtilities().AddModelPartToModelPart(
                self.mixed_model_part, self.structures_model_part)

        self.write_dem_fem_results(time)
Example #18
0
    def setUp(self):
        self.current_model = Kratos.Model()
        self.spheres_model_part = self.current_model.CreateModelPart(
            "SpheresPart")
        self.spheres_model_part.AddNodalSolutionStepVariable(Kratos.VELOCITY)
        self.spheres_model_part.AddNodalSolutionStepVariable(
            Kratos.ANGULAR_VELOCITY)
        self.spheres_model_part.AddNodalSolutionStepVariable(Kratos.RADIUS)
        self.spheres_model_part.AddNodalSolutionStepVariable(
            Kratos.PARTICLE_MATERIAL)
        self.spheres_model_part.AddNodalSolutionStepVariable(Kratos.NODAL_MASS)

        properties = Kratos.Properties(0)
        properties[Kratos.YOUNG_MODULUS] = 3.331
        properties[Kratos.POISSON_RATIO] = 0.0

        self.ModifyProperties(properties)

        self.spheres_model_part.AddProperties(properties)

        DEM.PropertiesProxiesManager().CreatePropertiesProxies(
            self.spheres_model_part)

        self.creator_destructor = DEM.ParticleCreatorDestructor()
Example #19
0
    def __init__(self, Model, settings):

        #NOTE: Negative target_stress means compression

        self.spheres_model_part = Model["SpheresPart"]
        self.fem_model_part = Model["RigidFacePart"]  #rigid_walls_model_part

        self.parameters = settings[
            "multiaxial_control_module_generalized_2d_utility"]

        self.cm_step = 0
        self.output_interval = self.parameters["Parameters"][
            "output_interval"].GetInt()

        self.cm_utility = Dem.MultiaxialControlModuleGeneralized2DUtilities(
            self.spheres_model_part, self.fem_model_part, self.parameters)
def Factory(settings, Model):
    if (type(settings) != KratosMultiphysics.Parameters):
        raise Exception(
            "expected input shall be a Parameters object, encapsulating a json string"
        )

    process_settings = settings["Parameters"]

    folder_settings = KratosMultiphysics.Parameters("""
    {
        "help"                 : "This process applies constraints to the particles in a certain submodelpart, for a certain time interval",
        "mesh_id"              : 0,
        "model_part_name"      : "please_specify_model_part_name",
        "velocity_constraints_settings" : {
            "constrained"          : [true,true,true],
            "value"                : [10.0, "3*t", "x+y"],
            "table"                : [0, 0, 0]
        },
        "angular_velocity_constraints_settings" : {
            "constrained"          : [true,true,true],
            "value"                : [10.0, "3*t", "x+y"],
            "table"                : [0, 0, 0]
        },
        "interval"             : [0.0, 1e30]
    }
    """)

    process_settings.AddMissingParameters(folder_settings)

    if process_settings.Has("model_part_name"):
        computing_model_part = Model[
            process_settings["model_part_name"].GetString()]
    else:  # using default name
        computing_model_part = Model["DEM"]

    process_settings.RemoveValue("help")

    return DEM.ApplyKinematicConstraintsToWallsProcess(computing_model_part,
                                                       process_settings)
Example #21
0
def RunCoupledSystem():
    ## create structural analysis
    model = KratosMultiphysics.Model()
    with open("ProjectParameters.json", 'r') as parameter_file:
        parameters = KratosMultiphysics.Parameters(parameter_file.read())

    structural_analysis = structural_mechanics_analysis.StructuralMechanicsAnalysis(
        model, parameters)

    structural_analysis.Initialize()

    print("-----> Initialized fem part")

    ## create dem analysis
    model_dem = KratosMultiphysics.Model()
    dem_analysis = main_script.Solution(model_dem)
    dem_analysis.Initialize()
    dem_analysis.InitializeTime()

    print("-----> Initialized dem part")

    ## create model parts
    mp_struct = model["Structure.computing_domain"]

    mp_dem = dem_analysis.rigid_face_model_part.GetSubModelPart('1')
    mp_dem_particle = dem_analysis.spheres_model_part

    ####################################################################### WALL
    ## create point load condition on all fem nodes
    cond_counter = 0
    node_id_list = []
    for node_i in mp_struct.Nodes:
        node_id = node_i.Id
        node_id_list.append(node_id)
        cond_counter += 1
        mp_struct.CreateNewCondition("PointLoadCondition3D1N", cond_counter,
                                     [node_id],
                                     mp_struct.GetProperties()[0])

    print("-----> Created fem PointLoadConditions")

    ## create structural submodal part used for mapping
    struct_smp = mp_struct.CreateSubModelPart("struct_sub")
    struct_smp.AddNodes(node_id_list)
    ## set up mapper
    print("-----> Added node list for mapping part")

    mapper_settings = KratosMultiphysics.Parameters("""{"mapper_settings":
                    {"mapper_type": "nearest_neighbor",
                    "interface_submodel_part_destination": "struct_sub",
                    "echo_level":1}}""")

    print("-----> Wrote mapper settings")
    mapper = KratosMapping.MapperFactory.CreateMapper(
        mp_dem, mp_struct, mapper_settings["mapper_settings"])

    print("-----> Initialized mapper")

    dem_mesh_moving_utility = DEMApplication.MoveMeshUtility()

    print("-----> Starting time loop:")
    ## run solving loop
    while dem_analysis.time < dem_analysis.final_time:
        print('current t: ', dem_analysis.time)

        ## call dem functions
        dem_analysis.UpdateTimeParameters()

        dem_analysis.BeforeSolveOperations(dem_analysis.time)
        dem_analysis.SolverSolve()
        dem_analysis.AfterSolveOperations()

        dem_analysis.FinalizeSingleTimeStep()

        ## map loads
        mapper.Map(DEMApplication.CONTACT_FORCES,
                   StructuralMechanicsApplication.POINT_LOAD)

        ## call fem functions
        structural_analysis.time = structural_analysis._GetSolver(
        ).AdvanceInTime(structural_analysis.time)
        structural_analysis.InitializeSolutionStep()
        structural_analysis._GetSolver().Predict()
        structural_analysis._GetSolver().SolveSolutionStep()
        structural_analysis.FinalizeSolutionStep()
        structural_analysis.OutputSolutionStep()

        ## map-1 vel,disp
        mapper.InverseMap(KratosMultiphysics.VELOCITY,
                          KratosMultiphysics.VELOCITY)
        mapper.InverseMap(KratosMultiphysics.DISPLACEMENT,
                          KratosMultiphysics.DISPLACEMENT)

        ## move dem wall mesh
        dem_mesh_moving_utility.MoveDemMesh(mp_dem.Nodes, True)

        dem_analysis.OutputSingleTimeLoop(
        )  ## do this at the end of the loop to see deformed net

    ## finalize dem
    dem_analysis.Finalize()
    dem_analysis.CleanUpOperations()

    ## finalize fem
    structural_analysis.Finalize()
Example #22
0
    def Initialize(self):
        Say('Initializing simulation...\n')
        self.run_code = self.GetRunCode()

        # Moving to the recently created folder
        os.chdir(self.main_path)
        if self.do_print_results:
            [self.post_path, data_and_results, self.graphs_path, MPI_results] = \
            self.procedures.CreateDirectories(str(self.main_path),
                                            str(self.project_parameters["problem_data"]["problem_name"].GetString()),
                                            self.run_code)
            SDP.CopyInputFilesIntoFolder(self.main_path, self.post_path)
            self.MPI_results = MPI_results

        self.FluidInitialize()

        self.DispersePhaseInitialize()

        self.SetAllModelParts()

        if self.project_parameters.Has(
                'sdem_output_processes') and self.do_print_results:
            gid_output_options = self.project_parameters[
                "sdem_output_processes"]["gid_output"][0]["Parameters"]
            result_file_configuration = gid_output_options[
                "postprocess_parameters"]["result_file_configuration"]
            write_conditions_option = result_file_configuration[
                "gidpost_flags"]["WriteConditionsFlag"].GetString(
                ) == "WriteConditions"
            deformed_mesh_option = result_file_configuration["gidpost_flags"][
                "WriteDeformedMeshFlag"].GetString() == "WriteDeformed"
            old_gid_output_post_options_dict = {
                'GiD_PostAscii': 'Ascii',
                'GiD_PostBinary': 'Binary',
                'GiD_PostAsciiZipped': 'AsciiZipped'
            }
            old_gid_output_multiple_file_option_dict = {
                'SingleFile': 'Single',
                'MultipleFiles': 'Multiples'
            }
            post_mode_key = result_file_configuration["gidpost_flags"][
                "GiDPostMode"].GetString()
            multiple_files_option_key = result_file_configuration[
                "gidpost_flags"]["MultiFileFlag"].GetString()

            self.swimming_DEM_gid_io = \
            swimming_DEM_gid_output.SwimmingDEMGiDOutput(
                file_name = self.project_parameters["problem_data"]["problem_name"].GetString(),
                vol_output = result_file_configuration["body_output"].GetBool(),
                post_mode = old_gid_output_post_options_dict[post_mode_key],
                multifile = old_gid_output_multiple_file_option_dict[multiple_files_option_key],
                deformed_mesh = deformed_mesh_option,
                write_conditions = write_conditions_option)

            self.swimming_DEM_gid_io.initialize_swimming_DEM_results(
                self.spheres_model_part, self.cluster_model_part,
                self.rigid_face_model_part, self.mixed_model_part)

        self.SetPointGraphPrinter()

        self.AssignKinematicViscosityFromDynamicViscosity()

        super(SwimmingDEMAnalysis, self).Initialize()

        # coarse-graining: applying changes to the physical properties of the model to adjust for
        # the similarity transformation if required (fluid effects only).
        SDP.ApplySimilarityTransformations(
            self.fluid_model_part, self.project_parameters["similarity"]
            ["similarity_transformation_type"].GetInt(),
            self.project_parameters["similarity"]
            ["model_over_real_diameter_factor"].GetDouble())

        if self.do_print_results:
            self.SetPostUtils()

        # creating an IOTools object to perform other printing tasks
        self.io_tools = SDP.IOTools(self.project_parameters)

        dem_physics_calculator = DEM.SphericElementGlobalPhysicsCalculator(
            self.spheres_model_part)

        if self.project_parameters["coupling"]["coupling_level_type"].GetInt():
            default_meso_scale_length_needed = (
                self.project_parameters["coupling"]["backward_coupling"]
                ["meso_scale_length"].GetDouble() <= 0.0
                and self.spheres_model_part.NumberOfElements(0) > 0)

            if default_meso_scale_length_needed:
                biggest_size = (
                    2 * dem_physics_calculator.CalculateMaxNodalVariable(
                        self.spheres_model_part, Kratos.RADIUS))
                self.project_parameters["coupling"]["backward_coupling"][
                    "meso_scale_length"].SetDouble(20 * biggest_size)

            elif self.spheres_model_part.NumberOfElements(0) == 0:
                self.project_parameters["coupling"]["backward_coupling"][
                    "meso_scale_length"].SetDouble(1.0)

        # creating a custom functions calculator for the implementation of
        # additional custom functions
        fluid_domain_dimension = self.project_parameters["fluid_parameters"][
            "solver_settings"]["domain_size"].GetInt()
        self.custom_functions_tool = SDP.FunctionsCalculator(
            fluid_domain_dimension)

        # creating a debug tool
        self.dem_volume_tool = self.GetVolumeDebugTool()

        #self.SetEmbeddedTools()

        Say('Initialization Complete\n')

        if self.project_parameters["custom_fluid"][
                "flow_in_porous_DEM_medium_option"].GetBool():
            SDP.FixModelPart(self.spheres_model_part)

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

        #    I N I T I A L I Z I N G    T I M E    L O O P

        ##################################################
        self.step = 0
        self.time = self.fluid_parameters["problem_data"][
            "start_time"].GetDouble()
        self.fluid_time_step = self._GetFluidAnalysis()._GetSolver(
        )._ComputeDeltaTime()
        self.time_step = self.spheres_model_part.ProcessInfo.GetValue(
            Kratos.DELTA_TIME)
        self.rigid_face_model_part.ProcessInfo[
            Kratos.DELTA_TIME] = self.time_step
        self.cluster_model_part.ProcessInfo[Kratos.DELTA_TIME] = self.time_step
        self.stationarity = False

        # setting up loop counters:
        self.DEM_to_fluid_counter = self.GetBackwardCouplingCounter()
        self.stationarity_counter = self.GetStationarityCounter()
        self.print_counter = self.GetPrintCounter()
        self.debug_info_counter = self.GetDebugInfo()
        self.particles_results_counter = self.GetParticlesResultsCounter()
        self.quadrature_counter = self.GetHistoryForceQuadratureCounter()
        # Phantom
        self._GetDEMAnalysis(
        ).analytic_data_counter = self.ProcessAnalyticDataCounter()
        self.mat_deriv_averager = SDP.Averager(1, 3)
        self.laplacian_averager = SDP.Averager(1, 3)

        self.report.total_steps_expected = int(self.end_time / self.time_step)

        Say(self.report.BeginReport(self.timer))

        # creating a Post Utils object that executes several post-related tasks
        self.post_utils_DEM = DP.PostUtils(
            self.project_parameters['dem_parameters'], self.spheres_model_part)

        # otherwise variables are set to 0 by default:
        SDP.InitializeVariablesWithNonZeroValues(self.project_parameters,
                                                 self.fluid_model_part,
                                                 self.spheres_model_part)

        if self.do_print_results:
            self.SetUpResultsDatabase()

        # ANALYTICS BEGIN
        self.project_parameters.AddEmptyValue(
            "perform_analytics_option").SetBool(False)

        if self.project_parameters["perform_analytics_option"].GetBool():
            import KratosMultiphysics.SwimmingDEMApplication.analytics as analytics
            variables_to_measure = [Kratos.PRESSURE]
            steps_between_measurements = 100
            gauge = analytics.Gauge(self.fluid_model_part,
                                    self.fluid_time_step, self.end_time,
                                    variables_to_measure,
                                    steps_between_measurements)
            point_coors = [0.0, 0.0, 0.01]
            target_node = SDP.FindClosestNode(self.fluid_model_part,
                                              point_coors)
            target_id = target_node.Id
            Say(target_node.X, target_node.Y, target_node.Z)
            Say(target_id)

            def condition(node):
                return node.Id == target_id

            gauge.ConstructArrayOfNodes(condition)
            Say(gauge.variables)
        # ANALYTICS END

        self.FillHistoryForcePrecalculatedVectors()

        self.PerformZeroStepInitializations()

        if self.do_print_results:
            self._Print()
Example #23
0
 def SetAnalyticParticleWatcher(self):
     from analytic_tools import analytic_data_procedures
     self.particle_watcher = DEM.AnalyticParticleWatcher()
     self.particle_watcher_analyser = analytic_data_procedures.ParticleWatcherAnalyzer(
         analytic_particle_watcher=self.particle_watcher,
         path=self.main_path)
Example #24
0
    def __init__(self, Model, settings ):
        KratosMultiphysics.Process.__init__(self)

        self.model_part = Model[settings["model_part_name"].GetString()]
        self.automatic_dt_process = Dem.AutomaticDTProcess(self.model_part, settings)
Example #25
0
    def test_random_variable(self):
        settings = KratosMultiphysics.Parameters("""
        {
            "pdf_breakpoints" : [0, 1, 2, 3, 3.5, 4, 4.5, 5, 5.5, 6],
            "pdf_values"      : [1, 2, 3, 4, 3.5, 3, 2.5, 2, 1.5, 1],
            "do_use_seed"     : true,
            "seed"            : 1,
            "relative_closeness_tolerance" : 1e-6
        }
        """)

        seed = settings["seed"].GetInt()

        n_bins = 25  # for the histogram
        tolerance = 0.005
        n_max_experiments = int(
            1e6)  # should be enough with the tolerance=0.005

        if settings["do_use_seed"].GetBool():
            random_variable = DEM.PiecewiseLinearRandomVariable(settings, seed)
        else:
            random_variable = DEM.PiecewiseLinearRandomVariable(settings)
        mean_expected = TestRandomVariable.GetMean(
            settings["pdf_breakpoints"].GetVector(),
            settings["pdf_values"].GetVector())
        mean = random_variable.GetMean()
        self.assertAlmostEqual(
            mean_expected, mean, None,
            'The calculated PDF mean differs from the expected one.')

        TestRandomVariable.Say('Mean:', mean)

        n_experiments = 2 * n_bins
        error = tolerance + 1
        i_iteration = 1

        # Increase number of experiments until the 'L2-norm' of the
        # error of the recovered pdf is smaller than the tolerance
        while error > tolerance:
            sample = np.zeros(n_experiments)

            for i in range(n_experiments):
                sample[i] = random_variable.Sample()

            empirical_pdf, interval_boundaries = np.histogram(sample,
                                                              n_bins,
                                                              density=True)
            centers = 0.5 * (interval_boundaries[1:] +
                             interval_boundaries[:-1])
            interval_widths = interval_boundaries[1:] - interval_boundaries[:-1]
            pdf_expected = np.array(
                [random_variable.ProbabilityDensity(x) for x in centers])

            error = TestRandomVariable.Error(empirical_pdf, pdf_expected,
                                             interval_widths)

            if i_iteration > 1:
                n_experiments *= int(max(2, (error / tolerance)**2))
            else:
                n_experiments *= 2
            if n_experiments > n_max_experiments:
                raise ValueError(
                    '\nThe requested tolerance (' +
                    '{:.4f}'.format(tolerance) + ')' +
                    ' requires a greater number of experiments than the maximum allowed ('
                    + '{:d}'.format(n_max_experiments) +
                    ')! Please, increase it (reduce desired precision).')

            TestRandomVariable.Say('Sample size', n_experiments)
            TestRandomVariable.Say(
                'Error = ' + '{:.4f}'.format(error),
                '( tolerance = ' + '{:.4f}'.format(tolerance), ')')
            i_iteration += 1

        if TestRandomVariable.debug_mode:
            import matplotlib.pyplot as plt
            plt.plot(centers, empirical_pdf)
            plt.hist(sample,
                     bins=n_bins,
                     density=True,
                     label='obtained (' + str(n_experiments) + ' samples)')
            plt.plot(centers, pdf_expected, label='desired')
            plt.legend()
            plt.savefig('piecewise_pdf.pdf')
Example #26
0
    def ModifyProperties(self, properties, param=0):

        scheme = DEM.SymplecticEulerScheme()
        scheme.SetTranslationalIntegrationSchemeInProperties(properties, False)
        scheme.SetRotationalIntegrationSchemeInProperties(properties, False)
Example #27
0
    def __init__(self, use_internal_interface=True, **kwargs):
        super(DEMWrapper, self).__init__(use_internal_interface, **kwargs)

        self.time = 0
        self.step = 0
        self.substeps = 0
        self.particle_type = "SphericParticle3D"
        self.condition_type = "RigidFace3D3N"

        # The dictionary defines the relation between CUBA and
        # kratos variables

        self.variables_dictionary = {
            "RADIUS": [CUBA.RADIUS, KRTS.RADIUS],
            "DENSITY": [CUBA.DENSITY, KRTSDEM.PARTICLE_DENSITY],
            "NODAL_MASS": [None, KRTS.NODAL_MASS],
            "VELOCITY": [
                CUBA.VELOCITY, KRTS.VELOCITY, KRTS.VELOCITY_X, KRTS.VELOCITY_Y,
                KRTS.VELOCITY_Z
            ],
            "DISPLACEMENT": [
                CUBA.DELTA_DISPLACEMENT, KRTS.DISPLACEMENT,
                KRTS.DISPLACEMENT_X, KRTS.DISPLACEMENT_Y, KRTS.DISPLACEMENT_Z
            ],
            "EXTERNAL_APPLIED_FORCE": [
                CUBA.EXTERNAL_APPLIED_FORCE, KRTSDEM.EXTERNAL_APPLIED_FORCE,
                KRTSDEM.EXTERNAL_APPLIED_FORCE_X,
                KRTSDEM.EXTERNAL_APPLIED_FORCE_Y,
                KRTSDEM.EXTERNAL_APPLIED_FORCE_Z
            ],
            "COHESIVE_GROUP": [None, KRTSDEM.COHESIVE_GROUP]
        }

        self.properties_dictionary = {
            "PARTICLE_DENSITY": [CUBA.DENSITY, KRTSDEM.PARTICLE_DENSITY],
            "YOUNG_MODULUS": [CUBA.YOUNG_MODULUS, KRTS.YOUNG_MODULUS],
            "POISSON_RATIO": [CUBA.POISSON_RATIO, KRTS.POISSON_RATIO],
            "PARTICLE_FRICTION":
            [CUBA.FRICTION_COEFFICIENT, KRTSDEM.PARTICLE_FRICTION],
            "PARTICLE_COHESION": [None, KRTSDEM.PARTICLE_COHESION],
            "ROLLING_FRICTION":
            [CUBA.ROLLING_FRICTION, KRTSDEM.ROLLING_FRICTION],
            "DEM_CONTINUUM_CONSTITUTIVE_LAW_NAME":
            [None, KRTSDEM.PARTICLE_COHESION],
            "DEM_DISCONTINUUM_CONSTITUTIVE_LAW_NAME":
            [None, KRTSDEM.PARTICLE_COHESION]
        }

        # Set DEM parameters
        self.solver_strategy = SolverStrategy
        self.creator_destructor = KRTSDEM.ParticleCreatorDestructor()
        self.dem_fem_search = KRTSDEM.DEM_FEM_Search()
        self.procedures = DEM_procedures.Procedures(DEM_parameters)

        # Define some paths as they are nedded by some modules of them.
        # These paths will NOT be used in this wrapper.
        self.graphs_path = '.'

        # This should not be nedded for Simphony
        self.parallelutils = DEM_procedures.ParallelUtils()
        self.scheme = self.procedures.SetScheme()

        self.initialize()
Example #28
0
# To use this script just type in the terminal: python (or python3) cartesian_specimen_mdpa_creator.py name_of_your_case
# It creates a file called name_of_your_caseDEM.mdpa.
# Remember to overwrite the Properties and the boundary conditions if necessary!!

from __future__ import print_function, absolute_import, division  #makes KratosMultiphysics backward compatible with python 2.6 and 2.7
from KratosMultiphysics import *
import KratosMultiphysics.DEMApplication as DEMapp
import sys

if len(sys.argv) < 2:
    print(
        "You must specify the name of the file to be printed. The string 'DEM.mdpa' will be appended to the provided string. "
    )
    sys.exit()

DEMapp.PreUtilities().CreateCartesianSpecimenMdpa(sys.argv[1])