Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
75 changes: 75 additions & 0 deletions tests/_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,81 @@ def skip_without_devsim() -> None:
pytest.skip(f"DEVSIM is unavailable: {err}", allow_module_level=True)


def restore_generic_pdk() -> None:
"""Activate the generic PDK and put its layers back at their enum slots.

All PDKs share one ``kfactory`` layout. Activating a PDK that has a layer
enum (IHP) deletes the empty layers of the previous one (gdsfactory's
``_prune_foreign_layers``), so the generic slots 0, 3, 4, ... are free until
the generic PDK is activated again. A raw ``(layer, datatype)`` registered
meanwhile takes the lowest free slot, say ``(2, 0)`` at slot 0. When the
generic PDK returns, gdsfactory moves that layer to ``SLAB150``'s slot 3
with ``Layout.move_layer`` and ``delete_layer``. Both raise ``RuntimeError``
once any cached (locked) cell exists, and gdsfactory logs and swallows it.
Slot 3 is then re-inserted without the layer name and the layout holds two
``(2, 0)`` layers: ``LAYER.SLAB150`` writes to one while a ``(2, 0)`` lookup
reads the other, and the region comes back empty.

This activates the generic PDK, moves a foreign layer out of any generic
slot, names each slot as the enum does and merges duplicate ``(layer,
datatype)`` layers into the enum's slot, unlocking cells for the moment it
takes. Shapes are moved, never dropped.
"""
try:
import gdsfactory as gf
import kfactory as kf
from kfactory import kdb
except ImportError:
return

gf.gpdk.PDK.activate()
layout = kf.kcl.layout

def tuple_of(index: int) -> tuple[int, int]:
info = layout.get_info(index)
return info.layer, info.datatype

locked = [cell for cell in layout.each_cell() if cell.is_locked()]
for cell in locked:
cell.locked = False
changed = False
try:
for layer in gf.gpdk.LAYER: # ty: ignore[not-iterable]
slot = int(layer)
key = (layer.layer, layer.datatype)
wanted = kdb.LayerInfo(layer.layer, layer.datatype, layer.name)
if layout.is_valid_layer(slot) and tuple_of(slot) != key:
held = tuple_of(slot)
twins = [
index
for index in layout.layer_indexes()
if index != slot and tuple_of(index) == held
]
if twins:
new_home = twins[0]
else:
new_home = layout.insert_layer(kdb.LayerInfo(*held))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Keep displaced layers out of IHP enum slots

When a prior module has activated IHP, the generic activation above prunes IHP's empty, fixed layer indices, and layout.insert_layer here can reuse one of those indices for the displaced foreign tuple. The added (250, 0) regression takes this branch and leaves nonempty geometry there; if a later default IHP test calls ihp.PDK.activate() while the cached locked_cell remains, IHP cannot restore its reserved slot without the same locked-cell relocation problem, so its enum may resolve to the foreign layer. Allocate a slot outside all registered enum reservations and add a generic-to-IHP regression.

AGENTS.md reference: AGENTS.md:L14-L15

Useful? React with 👍 / 👎.

layout.move_layer(slot, new_home)
layout.delete_layer(slot)
changed = True
if not layout.is_valid_layer(slot):
layout.insert_layer_at(slot, wanted)
changed = True
elif layout.get_info(slot) != wanted:
layout.set_info(slot, wanted)
changed = True
for other in list(layout.layer_indexes()):
if other != slot and tuple_of(other) == key:
layout.move_layer(other, slot)
layout.delete_layer(other)
changed = True
finally:
for cell in locked:
cell.locked = True
if changed:
gf.gpdk.PDK.activate(force=True)


def series_rc_admittance(
freq_hz: ArrayLike, r_ohm_m: float | ArrayLike, c_f_per_m: float | ArrayLike
) -> NDArray[np.complex128]:
Expand Down
19 changes: 19 additions & 0 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
import sys
from pathlib import Path

import pytest

# Add src directory to path so tests can import gsim
src_path = Path(__file__).parent.parent / "src"
if str(src_path) not in sys.path:
Expand All @@ -17,3 +19,20 @@
# later PDK switch puts IHP marker shapes on Passivdrawing (9/0).
with contextlib.suppress(ImportError):
import ihp # noqa: F401

from tests._helpers import restore_generic_pdk # noqa: E402


@pytest.fixture(scope="module", autouse=True)
def _generic_pdk_layout():
"""Start and leave every test module on a clean generic PDK layer table.

Tests switch the active PDK (IHP, the FDTD test PDK) and register raw GDS
layers in gdsfactory's shared layout, and nothing switches back. With
pytest-randomly, a later module can then run with duplicated or hijacked
generic layer slots (see ``restore_generic_pdk``). Restoring per module
keeps module-scoped fixtures that activate a PDK working for their module.
"""
restore_generic_pdk()
yield
restore_generic_pdk()
113 changes: 113 additions & 0 deletions tests/test_generic_pdk_restore.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
"""``restore_generic_pdk`` heals the shared layout that tests leave behind.

Regression for test-order failures in ``tests/meep/test_physical_layers.py``:
after IHP was activated, a raw ``(2, 0)`` registered in a freed slot and the
generic PDK came back, the layout held two ``(2, 0)`` layers and
``LAYER.SLAB150`` wrote to a different one than a ``(2, 0)`` lookup read.
"""

from __future__ import annotations

import gdsfactory as gf
import kfactory as kf
import pytest
from kfactory import kdb

from tests._helpers import restore_generic_pdk

BOX = kdb.Box(0, 0, 1000, 1000) # 1 um x 1 um in dbu


def _tuples() -> list[tuple[int, int]]:
layout = kf.kcl.layout
infos = (layout.get_info(index) for index in layout.layer_indexes())
return [(info.layer, info.datatype) for info in infos]


def _assert_clean() -> None:
layout = kf.kcl.layout
tuples = _tuples()
for layer in gf.gpdk.LAYER: # ty: ignore[not-iterable]
info = layout.get_info(int(layer))
assert (info.layer, info.datatype, info.name) == (
layer.layer,
layer.datatype,
layer.name,
)
assert tuples.count((layer.layer, layer.datatype)) == 1


def _area(component: gf.Component, layer: tuple[int, int]) -> int:
"""Area (dbu^2) the component holds on whatever layer ``layer`` resolves to."""
index = component.kcl.layer(*layer)
return kdb.Region(component.kdb_cell.begin_shapes_rec(index)).area()


@pytest.fixture
def locked_cell() -> gf.Component:
"""A cached gdsfactory cell. kfactory locks it, which blocks gdsfactory's own
``Layout.move_layer`` / ``delete_layer`` when it restores the layer table."""
gf.gpdk.PDK.activate()
cell = gf.components.straight(length=7.0)
assert cell.kdb_cell.is_locked()
return cell


@pytest.mark.usefixtures("locked_cell")
def test_a_duplicated_slab_layer_is_merged_into_the_enum_slot() -> None:
restore_generic_pdk()
layout = kf.kcl.layout
slot = int(gf.gpdk.LAYER.SLAB150)
# the state gdsfactory leaves: the enum slot unnamed, a named twin elsewhere
layout.set_info(slot, kdb.LayerInfo(2, 0))
twin = layout.insert_layer(kdb.LayerInfo(2, 0, "SLAB150"))
component = gf.Component()
component.shapes(slot).insert(BOX)
component.shapes(twin).insert(BOX.moved(5000, 0))
assert _tuples().count((2, 0)) == 2

restore_generic_pdk()

_assert_clean()
assert layout.find_layer(2, 0) == slot
assert _area(component, (2, 0)) == 2_000_000 # both boxes, on the one layer


@pytest.mark.usefixtures("locked_cell")
def test_a_raw_layer_in_a_generic_slot_is_moved_out_with_its_shapes() -> None:
restore_generic_pdk()
layout = kf.kcl.layout
slot = int(gf.gpdk.LAYER.SHALLOW_ETCH)
layout.set_info(slot, kdb.LayerInfo(250, 0))
component = gf.Component()
component.shapes(slot).insert(BOX)

restore_generic_pdk()

_assert_clean()
assert layout.find_layer(250, 0) not in {None, slot}
assert _area(component, (250, 0)) == 1_000_000
assert _area(component, (2, 6)) == 0
drawn = gf.Component()
drawn.add_polygon([(0, 0), (2, 0), (2, 1), (0, 1)], layer=gf.gpdk.LAYER.SLAB150)
drawn.add_polygon(
[(4, 0), (6, 0), (6, 1), (4, 1)], layer=gf.gpdk.LAYER.SHALLOW_ETCH
)
assert _area(drawn, (2, 0)) == 2_000_000
assert _area(drawn, (2, 6)) == 2_000_000


@pytest.mark.usefixtures("locked_cell")
def test_a_raw_layer_taken_under_ihp_does_not_split_the_slab_layer() -> None:
ihp = pytest.importorskip("ihp")
restore_generic_pdk()
ihp.PDK.activate()
gf.Pdk(name="restore_generic_pdk_probe").activate() # no layer enum: no pruning
kf.kcl.layer(2, 0) # lowest free slot while the generic slots are pruned
restore_generic_pdk()

_assert_clean()
assert gf.get_active_pdk().name == gf.gpdk.PDK.name
component = gf.Component()
component.add_polygon([(0, 0), (2, 0), (2, 1), (0, 1)], layer=gf.gpdk.LAYER.SLAB150)
assert _area(component, (2, 0)) == 2_000_000
Loading