Mass Properties using Python

Forums: 

Hello everyone. So I have the following code here:


def ask_all_bodies(the_part):
"""Returns a list of all solid bodies in the given part."""
the_bodies = []
uf_session = NXOpen.UF.UFSession.GetUFSession()

# Initialize with null tag
null_tag = 0
body_tag = null_tag

# Get first object
body_tag = uf_session.Obj.CycleObjsInPart(the_part.Tag, NXOpen.UF.UFConstants.UF_solid_type, body_tag)

# Loop through all solid objects in the part
while body_tag != null_tag:
# Get the type and subtype of the object
obj_type = 0
obj_subtype = 0
obj_type, obj_subtype = uf_session.Obj.AskTypeAndSubtype(body_tag)

# Check if it's a solid body subtype
if obj_subtype == NXOpen.UF.UFConstants.UF_solid_body_subtype:
# Get NXOpen body object from tag
nx_body = NXOpen.TaggedObjectManager.GetTaggedObject(body_tag)
the_bodies.append(nx_body)

# Get next object
body_tag = uf_session.Obj.CycleObjsInPart(the_part.Tag, NXOpen.UF.UFConstants.UF_solid_type, body_tag)

return the_bodies

def calculate_component_signature(component: Assemblies.Component, the_uf_session: NXOpen.UF.UFSession) -> Dict:
"""Calculate detailed geometric signature of a component"""
the_session = NXOpen.Session.GetSession()
lw = the_session.ListingWindow
work_part = the_session.Parts.Work

total_mass = 0.0
total_volume = 0.0
total_area = 0.0
cog_x = 0.0
cog_y = 0.0
cog_z = 0.0
cog_count = 0

uc = work_part.UnitCollection
mass_units = [
uc.GetBase("Area"),
uc.GetBase("Volume"),
uc.GetBase("Mass"),
uc.GetBase("Length")
]

measure_manager = work_part.MeasureManager

# Use the new ask_all_bodies function instead of proto_part.Bodies
bodies = ask_all_bodies(proto_part)

for body in bodies:

try:
result = measure_manager.NewMassProperties(mass_units, 0.99, [body])
total_mass += result.Mass
total_volume += result.Volume
total_area += result.Area
cog_x += result.Centroid.X
cog_y += result.Centroid.Y
cog_z += result.Centroid.Z
cog_count += 1
except Exception as e:
lw.WriteLine(f"[WARN] Skipped body due to error: {e}")

if cog_count == 0:
return None

signature = {
"surface_area": total_area,
"volume": total_volume,
"mass": total_mass,
"cog_x": cog_x / cog_count,
"cog_y": cog_y / cog_count,
"cog_z": cog_z / cog_count,
"face_count": face_count,
"edge_count": edge_count
}

return signature

Which seems to return the following error:

NXOpen.NXException: An attempt was made to use an invalid or deleted attribute id

In reference to this line:

body_tag = uf_session.Obj.CycleObjsInPart(the_part.Tag, NXOpen.UF.UFConstants.UF_solid_type, body_tag)

However, If I use a VB equivalent it seems to work. Any ideas on what the issue might be here?