# How to count number of merged polygons in a Region

I note that the count and hier_count methods in Region count the number of raw polygons, not merged polygons. Could I ask what is the suggested method to get the number of merged polygons? I thought of counting using each_merged in Python, but it's slow.

• @reacogr I'd suggest to first merge and then count. But the slowness probably arises from the merge step, not the counting. That's inevitable as the algorithmic complexity lies in the merge.

You can speed that up (often) and reduce the memory overhead by using hierarchical mode. Here is some code:

``````ly = ... some layout ...
l1 = ly.layer(layer, datatype)

# Flat:
rf = pya.Region(ly.top_cell().begin_shapes_rec(l1))
print("Original (flat):")
print(rf.hier_count())
print(rf.count())
print("Merging ...")
rf.merge()
print("Merged (flat):")
print(rf.hier_count())
print(rf.count())

# Hierarchical:
dss = pya.DeepShapeStore()
r = pya.Region(ly.top_cell().begin_shapes_rec(l1), dss)
print("Original (hier):")
print(r.hier_count())
print(r.count())
print("Merging (hier) ...")
r.merge()
print("Merged (hier):")
print(r.hier_count())
print(r.count())
``````

For a SRAM sample I get this output:

``````Original (flat):
888
2061813
Merging ...
Merged (flat):
204609
204609
Original (hier):
891
2061948
Merging (hier) ...
Merged (hier):
315
204609
``````

Which means the flat count after merge is the same (204609) while the hierarchical count is only 315 in hierarchical mode while - as expected - in flat mode it is the same than the flat count.

Matthias

• Are merged polygons maintained as separate
objects in some sort of "bundle", that you could
do this? I thought the merged-object replaces
its constituents.

And if this is the case, can a merged-polygon be
un-merged back to its original elements?

• Hi Jim,

Actually, merged regions are kept in parallel to the original polygons. In DRC, this feature is usually hidden as merged polygons are only used as inputs for most measurement methods (under the regime of "merged semantics").

You can explicitly pull merged polygons with the "merge" (in-place) or "merged" (merged copy) functions.

In hierarchical mode (in DRC that is enabled with "deep"), the merged polygons will be kept in a shadow layout which hides behind the "DeepShapeStore" object.

So "unmerging" is not supported exactly. That is not entirely out of question (at some stage, the merged polygons are represented as clusters of original polygons), but I wonder if there is a particular use case for this.

Best regards,

Matthias