Search code examples
pythoncadstepopencascadepythonocc

Access STEP Instance ID's with PythonOCC


Let's suppose I'm using this STEP file data as input:

#417=ADVANCED_FACE('face_1',(#112),#405,.F.);
#418=ADVANCED_FACE('face_2',(#113),#406,.F.);
#419=ADVANCED_FACE('face_3',(#114),#407,.F.);

I'm using pythonocc-core to read the STEP file. Then the following code will print the names of the ADVANCED_FACE instances (face_1,face_2 and face_3):

from OCC.Core.STEPControl import STEPControl_Reader
from OCC.Core.TopExp import TopExp_Explorer
from OCC.Core.TopAbs import TopAbs_FACE
from OCC.Core.StepRepr import StepRepr_RepresentationItem

reader = STEPControl_Reader()
tr = reader.WS().TransferReader()
reader.ReadFile('model.stp')
reader.TransferRoots()
shape = reader.OneShape()


exp = TopExp_Explorer(shape, TopAbs_FACE)
while exp.More():
    s = exp.Current()
    exp.Next()

    item = tr.EntityFromShapeResult(s, 1)
    item = StepRepr_RepresentationItem.DownCast(item)
    name = item.Name().ToCString()
    print(name)

How can I access the identifiers of the individual shapes? (#417,#418 and #419)

Minimal reproduction

https://github.com/flolu/step-occ-instance-ids


Solution

  • Create a STEP model after reader.TransferRoots() like this:

    model = reader.StepModel()
    

    And access the ID like this in the loop:

    id = model.IdentLabel(item)
    

    The full code looks like this and can also be found on GitHub:

    from OCC.Core.STEPControl import STEPControl_Reader
    from OCC.Core.TopExp import TopExp_Explorer
    from OCC.Core.TopAbs import TopAbs_FACE
    from OCC.Core.StepRepr import StepRepr_RepresentationItem
    
    reader = STEPControl_Reader()
    tr = reader.WS().TransferReader()
    reader.ReadFile('model.stp')
    reader.TransferRoots()
    model = reader.StepModel()
    shape = reader.OneShape()
    
    
    exp = TopExp_Explorer(shape, TopAbs_FACE)
    while exp.More():
        s = exp.Current()
        exp.Next()
    
        item = tr.EntityFromShapeResult(s, 1)
        item = StepRepr_RepresentationItem.DownCast(item)
    
        label = item.Name().ToCString()
        id = model.IdentLabel(item)
    
        print('label', label)
        print('id', id)
    

    Thanks to temurka1 for pointing this out!