Calculate center of mass using PyDPF

Ayush Kumar
Ayush Kumar Member, Moderator, Employee Posts: 450
100 Answers 250 Likes 100 Comments First Anniversary
✭✭✭✭

Calculate center of mass using PyDPF

Tagged:

Comments

  • Ayush Kumar
    Ayush Kumar Member, Moderator, Employee Posts: 450
    100 Answers 250 Likes 100 Comments First Anniversary
    ✭✭✭✭
    from ansys.dpf import core as dpf
    
    rst = r"\Path\to\file.rst"
    
    ds = dpf.DataSources(rst)
    
    model = dpf.Model(rst)
    dpf_mesh = model.metadata.meshed_region
    
    all_mats = []
    
    mats = dpf_mesh.property_field("mat")
    mat_prop = model.operator("mapdl_material_properties")
    mat_prop.inputs.materials.connect(mats)
    
    mat_prop.inputs.properties_name.connect("DENS")
    mat_field = mat_prop.outputs.properties_value.get_data()[0]
    for eid in dpf_mesh.elements.scoping.ids:
        mat_id = mats.get_entity_data_by_id(eid)
        density = mat_field.get_entity_data_by_id(mat_id[0])
        all_mats.append(density)
    
    # Create Density Field
    density = dpf.fields_factory.create_scalar_field(num_entities=dpf_mesh.elements.n_elements)
    density.location = dpf.locations.elemental
    density.scoping.ids = dpf_mesh.elements.scoping.ids
    density.data = all_mats
    
    # Element volume
    el_vol = dpf.operators.geo.elements_volume(mesh=dpf_mesh)
    
    # Calculate elemental mass
    elemental_mass = dpf.operators.math.generalized_inner_product(fieldA=el_vol, fieldB=density)
    
    # Get element centroids
    centroids = dpf.operators.result.element_centroids(data_sources=ds)
    centroids_f = centroids.outputs.fields_container.get_data()[0]
    
    # Get common scoping
    eids = dpf.operators.scoping.intersect() # operator instantiation
    eids.inputs.scopingA.connect(centroids_f.scoping)
    eids.inputs.scopingB.connect(density.scoping)
    eids_out = eids.outputs.intersection.get_data()
    
    # Rescoped to ensure same elements
    centroids_r = dpf.operators.scoping.rescope(fields=centroids_f, mesh_scoping=eids_out)
    density_r = dpf.operators.scoping.rescope(fields=density, mesh_scoping=eids_out)
    
    # Density * centroids
    den_dot_cent = dpf.operators.math.generalized_inner_product(fieldA=centroids_r.outputs.fields_as_field, fieldB=density_r.outputs.fields_as_field)
    
    # Integrate coordinates over element volume
    den_dot_cent_int = dpf.operators.geo.integrate_over_elements(field=den_dot_cent, mesh=dpf_mesh)
    
    # Int. across body
    all_sum = dpf.operators.math.accumulate(fieldA=den_dot_cent_int)
    all_sum_f = all_sum.outputs.field.get_data()
    all_sum_f.unit = ""  # Unit causing issues in division
    
    # Total mass
    total_mass = dpf.operators.math.accumulate(fieldA=elemental_mass)
    total_mass_f = total_mass.outputs.field.get_data()
    total_mass_f.unit = ""
    
    # COG
    cog = dpf.operators.math.component_wise_divide(fieldA=all_sum_f, fieldB=total_mass_f)