Skip to content

Enclosure

enclosure

Enclosure module.

Enclosures allow to calculate slab/excludes and similar concepts to an arbitrary shape located on a main_layer or reference layer or region.

Direction

Bases: IntEnum

Direction for applying standard minkowski sums.

Attributes:

Name Type Description
X

Only apply in x-direction.

Y

Only apply in y-direction.

BOTH

Apply in both x/y-direction. Equivalent to a minkowski sum with a square.

Source code in kfactory/enclosure.py
64
65
66
67
68
69
70
71
72
73
74
75
76
class Direction(IntEnum):
    """Direction for applying standard minkowski sums.

    Attributes:
        X: Only apply in x-direction.
        Y: Only apply in y-direction.
        BOTH: Apply in both x/y-direction. Equivalent to a
            minkowski sum with a square.
    """

    X = 1
    Y = 2
    BOTH = 3

KCellEnclosure pydantic-model

Bases: BaseModel

Collection of enclosures for cells.

Fields:

Source code in kfactory/enclosure.py
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
class KCellEnclosure(BaseModel):
    """Collection of [enclosures][kfactory.enclosure.LayerEnclosure] for cells."""

    enclosures: LayerEnclosureCollection

    def __init__(self, enclosures: Iterable[LayerEnclosure]) -> None:
        """Init. Allow usage of an iterable object instead of a collection."""
        super().__init__(
            enclosures=LayerEnclosureCollection(enclosures=list(enclosures))
        )

    def __hash__(self) -> int:
        """Hash of the KCellEnclosure."""
        return hash(tuple(self.enclosures.enclosures))

    def minkowski_region(
        self,
        r: kdb.Region,
        d: int | None,
        shape: Callable[[int], list[kdb.Point] | kdb.Box | kdb.Edge | kdb.Polygon],
    ) -> kdb.Region:
        """Calculaste a region from a minkowski sum.

        If the distance is negative, the function will take the inverse region and apply
        the minkowski and take the inverse again.

        Args:
            r: Target region.
            d: Distance to pass to the shape. Can be any integer. [dbu]
            shape: Function returning a shape for the minkowski region.
        """
        if d is None:
            return kdb.Region()
        if d == 0:
            return r.dup()
        if d > 0:
            return r.minkowski_sum(shape(d))
        shape_ = shape(abs(d))
        if isinstance(shape_, list):
            box_shape = kdb.Polygon(cast("list[kdb.Point]", shape_))
            bbox_maxsize = max(
                box_shape.bbox().width(),
                box_shape.bbox().height(),
            )
        else:
            bbox_maxsize = max(
                shape_.bbox().width(),
                shape_.bbox().height(),
            )
        bbox_r = kdb.Region(r.bbox().enlarged(bbox_maxsize))
        return r - (bbox_r - r).minkowski_sum(shape_)

    def apply_minkowski_enc(
        self,
        c: KCell,
        direction: Direction = Direction.BOTH,
    ) -> None:
        """Apply an enclosure with a vector in y-direction.

        This can be used for tapers/
        waveguides or similar that are straight.

        Args:
            c: Cell to apply the enclosure to.
            direction: X/Y or both directions, see [kfactory.enclosure.DIRECTION].
                Uses a box if both directions are selected.
        """
        match direction:
            case Direction.BOTH:

                def box(d: int) -> kdb.Box:
                    return kdb.Box(-d, -d, d, d)

                self.apply_minkowski_custom(c, shape=box)

            case Direction.Y:

                def edge(d: int) -> kdb.Edge:
                    return kdb.Edge(0, -d, 0, d)

                self.apply_minkowski_custom(c, shape=edge)

            case Direction.X:

                def edge(d: int) -> kdb.Edge:
                    return kdb.Edge(-d, 0, d, 0)

                self.apply_minkowski_custom(c, shape=edge)

            case _:
                raise ValueError("Undefined direction")

    def apply_minkowski_y(self, c: KCell) -> None:
        """Apply an enclosure with a vector in y-direction.

        This can be used for tapers/
        waveguides or similar that are straight.

        Args:
            c: Cell to apply the enclosure to.
        """
        return self.apply_minkowski_enc(c, direction=Direction.Y)

    def apply_minkowski_x(self, c: KCell) -> None:
        """Apply an enclosure with a vector in x-direction.

        This can be used for tapers/
        waveguides or similar that are straight.

        Args:
            c: Cell to apply the enclosure to.
        """
        return self.apply_minkowski_enc(c, direction=Direction.X)

    def apply_minkowski_custom(
        self,
        c: KCell,
        shape: Callable[[int], kdb.Edge | kdb.Polygon | kdb.Box],
    ) -> None:
        """Apply an enclosure with a custom shape.

        This can be used for tapers/
        waveguides or similar that are straight.

        Args:
            c: Cell to apply the enclosure to.
            shape: A function that will return a shape which takes one argument
                the size of the section in dbu.
            shape: Reference to use as a base for the enclosure.
        """
        regions = {}
        for enc in self.enclosures.enclosures:
            main_layer = c.kcl.layer(enc.main_layer)
            if not c.bbox(main_layer).empty():
                rsi = c.begin_shapes_rec(main_layer)
                r = kdb.Region(rsi)
                for layer, layersec in enc.layer_sections.items():
                    if layer not in regions:
                        reg = kdb.Region()
                        regions[layer] = reg
                    else:
                        reg = regions[layer]
                    for section in layersec.sections:
                        reg += self.minkowski_region(
                            r, section.d_max, shape
                        ) - self.minkowski_region(r, section.d_min, shape)

                        reg.merge()

        for layer, region in regions.items():
            c.shapes(c.kcl.layer(layer)).insert(region)

    def apply_minkowski_tiled(
        self,
        c: KCell,
        tile_size: float | None = None,
        n_pts: int = 64,
        n_threads: int | None = None,
        carve_out_ports: bool = True,
    ) -> None:
        """Minkowski regions with tiling processor.

        Useful if the target is a big or complicated enclosure. Will split target ref
        into tiles and calculate them in parallel. Uses a circle as a shape for the
        minkowski sum.

        Args:
            c: Target KCell to apply the enclosures into.
            tile_size: Tile size. This should be in the order off 10+ maximum size
                of the maximum size of sections. [um]
                If None is set, the minimum size is set to 10xmax(d_max) of all sections
                or 200um whichever is bigger.
            n_pts: Number of points in the circle. < 3 will create a triangle. 4 a
                diamond, etc.
            n_threads: Number o threads to use. By default (`None`) it will use as many
                threads as are set to the process (usually all cores of the machine).
            carve_out_ports: Carves out a box of port_width +
        """
        tp = kdb.TilingProcessor()
        tp.frame = c.dbbox()  # ty:ignore[invalid-assignment]
        tp.dbu = c.kcl.dbu
        tp.threads = n_threads or config.n_threads
        inputs: set[str] = set()
        port_hole_map: dict[kdb.LayerInfo, kdb.Region] = defaultdict(kdb.Region)
        ports_by_layer: dict[kdb.LayerInfo, list[Port]] = defaultdict(list)
        for port in c.ports:
            ports_by_layer[c.kcl.layer(c.kcl.get_info(port.layer))].append(port)

        maxsize = 0
        for enc in self.enclosures.enclosures:
            assert enc.main_layer is not None
            main_layer = c.kcl.layer(enc.main_layer)
            for layer, layersection in enc.layer_sections.items():
                li = c.kcl.layer(layer)
                size = layersection.sections[-1].d_max
                maxsize = max(maxsize, size)

                for port in ports_by_layer[main_layer]:
                    if port._base.trans:
                        port_hole_map[li].insert(
                            port_hole(port.width, size).transformed(port.trans)
                        )
                    else:
                        port_hole_map[li].insert(
                            port_hole(port.width, size).transformed(
                                kdb.ICplxTrans(port.dcplx_trans, port.kcl.dbu)
                            )
                        )

        min_tile_size_rec = 10 * maxsize * tp.dbu

        if tile_size is None:
            tile_size = max(min_tile_size_rec * 2, 200)

        if float(tile_size) <= min_tile_size_rec:
            logger.warning(
                "Tile size should be larger than the maximum of "
                "the enclosures (recommendation: {} / {})",
                tile_size,
                min_tile_size_rec,
            )
        tp.tile_border(maxsize * tp.dbu, maxsize * tp.dbu)
        tp.tile_size(tile_size, tile_size)
        layer_regiontilesoperators: dict[
            tuple[int, LayerSection], RegionTilesOperator
        ] = {}

        logger.debug("Starting KCellEnclosure on {}", c.kcl._future_cell_name or c.name)

        n_enc = len(self.enclosures.enclosures)

        for i, enc in enumerate(self.enclosures.enclosures):
            assert enc.main_layer is not None
            if not c.bbox(c.kcl.layer(enc.main_layer)).empty():
                main_layer = c.kcl.layer(enc.main_layer)
                inp = f"main_layer_{main_layer}"
                if enc.main_layer not in inputs:
                    tp.input(
                        inp,
                        c.kcl.layout,
                        c.cell_index(),
                        main_layer,
                    )
                    inputs.add(main_layer)
                    logger.debug("Created input {}", inp)

                for layer, layer_section in enc.layer_sections.items():
                    li = c.kcl.layer(layer)
                    if (main_layer, layer_section) in layer_regiontilesoperators:
                        layer_regiontilesoperators[
                            main_layer, layer_section
                        ].layers.append(li)
                    else:
                        out = f"target_{li}"
                        operator = RegionTilesOperator(cell=c, layers=[li])
                        layer_regiontilesoperators[main_layer, layer_section] = operator
                        tp.output(out, operator)
                        logger.debug("Created output {}", out)

                    for section in reversed(layer_section.sections):
                        queue_str = (
                            "var max_shape = Polygon.ellipse("
                            f"Box.new({section.d_max * 2},{section.d_max * 2}),"
                            f" {n_pts});"
                            f"var tile_reg = _tile & _frame.sized({maxsize});"
                        )
                        match section.d_max:
                            case d if d > 0:
                                max_region = (
                                    "var max_reg = "
                                    f"{inp}.minkowski_sum(max_shape).merged();"
                                )
                            case d if d < 0:
                                max_region = (
                                    f"var max_reg = tile_reg - (tile_reg - {inp});"
                                )
                            case 0:
                                max_region = f"var max_reg = {inp} & tile_reg;"
                        queue_str += max_region
                        if section.d_min is not None:
                            queue_str += (
                                "var min_shape = Polygon.ellipse("
                                f"Box.new({section.d_min * 2},{section.d_min * 2}),"
                                " 64);"
                            )
                            match section.d_min:
                                case d if d > 0:
                                    min_region = (
                                        f"var min_reg = {inp}.minkowski_sum(min_shape);"
                                    )
                                case d if d < 0:
                                    min_region = (
                                        "var min_reg = tile_reg - (tile_reg - "
                                        f"{inp}).minkowski_sum(min_shape);"
                                    )
                                case 0:
                                    min_region = f"var min_reg = {inp} & tile_reg;"
                            queue_str += min_region
                            queue_str += (
                                f"_output({out},(max_reg - min_reg) & _tile, true);"
                            )
                        else:
                            queue_str += f"_output({out}, max_reg & _tile, true);"

                        logger.debug(
                            "{}/{}: Queuing string for {} on layer {}: '{}'",
                            i + 1,
                            n_enc,
                            c.kcl._future_cell_name or c.name,
                            layer,
                            queue_str,
                        )
                        tp.queue(queue_str)

        c.kcl.start_changes()
        logger.debug(
            "Starting enclosure {}",
            c.kcl._future_cell_name or c.name,
            enc.name,
        )
        tp.execute(f"Minkowski {c.name}")
        c.kcl.end_changes()
        logger.debug("Finished enclosure {}", enc.name)

        if carve_out_ports:
            for operator in layer_regiontilesoperators.values():
                # for layer in operator.layers:
                operator.insert(port_hole_map=port_hole_map)
        else:
            for operator in layer_regiontilesoperators.values():
                operator.insert()
        logger.debug("Finished KCellEnclosure on {}", c.kcl._future_cell_name or c.name)

__hash__

__hash__() -> int

Hash of the KCellEnclosure.

Source code in kfactory/enclosure.py
1405
1406
1407
def __hash__(self) -> int:
    """Hash of the KCellEnclosure."""
    return hash(tuple(self.enclosures.enclosures))

__init__

__init__(enclosures: Iterable[LayerEnclosure]) -> None

Init. Allow usage of an iterable object instead of a collection.

Source code in kfactory/enclosure.py
1399
1400
1401
1402
1403
def __init__(self, enclosures: Iterable[LayerEnclosure]) -> None:
    """Init. Allow usage of an iterable object instead of a collection."""
    super().__init__(
        enclosures=LayerEnclosureCollection(enclosures=list(enclosures))
    )

apply_minkowski_custom

apply_minkowski_custom(
    c: KCell, shape: Callable[[int], Edge | Polygon | Box]
) -> None

Apply an enclosure with a custom shape.

This can be used for tapers/ waveguides or similar that are straight.

Parameters:

Name Type Description Default
c KCell

Cell to apply the enclosure to.

required
shape Callable[[int], Edge | Polygon | Box]

A function that will return a shape which takes one argument the size of the section in dbu.

required
shape Callable[[int], Edge | Polygon | Box]

Reference to use as a base for the enclosure.

required
Source code in kfactory/enclosure.py
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
def apply_minkowski_custom(
    self,
    c: KCell,
    shape: Callable[[int], kdb.Edge | kdb.Polygon | kdb.Box],
) -> None:
    """Apply an enclosure with a custom shape.

    This can be used for tapers/
    waveguides or similar that are straight.

    Args:
        c: Cell to apply the enclosure to.
        shape: A function that will return a shape which takes one argument
            the size of the section in dbu.
        shape: Reference to use as a base for the enclosure.
    """
    regions = {}
    for enc in self.enclosures.enclosures:
        main_layer = c.kcl.layer(enc.main_layer)
        if not c.bbox(main_layer).empty():
            rsi = c.begin_shapes_rec(main_layer)
            r = kdb.Region(rsi)
            for layer, layersec in enc.layer_sections.items():
                if layer not in regions:
                    reg = kdb.Region()
                    regions[layer] = reg
                else:
                    reg = regions[layer]
                for section in layersec.sections:
                    reg += self.minkowski_region(
                        r, section.d_max, shape
                    ) - self.minkowski_region(r, section.d_min, shape)

                    reg.merge()

    for layer, region in regions.items():
        c.shapes(c.kcl.layer(layer)).insert(region)

apply_minkowski_enc

apply_minkowski_enc(
    c: KCell, direction: Direction = Direction.BOTH
) -> None

Apply an enclosure with a vector in y-direction.

This can be used for tapers/ waveguides or similar that are straight.

Parameters:

Name Type Description Default
c KCell

Cell to apply the enclosure to.

required
direction Direction

X/Y or both directions, see [kfactory.enclosure.DIRECTION]. Uses a box if both directions are selected.

BOTH
Source code in kfactory/enclosure.py
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
def apply_minkowski_enc(
    self,
    c: KCell,
    direction: Direction = Direction.BOTH,
) -> None:
    """Apply an enclosure with a vector in y-direction.

    This can be used for tapers/
    waveguides or similar that are straight.

    Args:
        c: Cell to apply the enclosure to.
        direction: X/Y or both directions, see [kfactory.enclosure.DIRECTION].
            Uses a box if both directions are selected.
    """
    match direction:
        case Direction.BOTH:

            def box(d: int) -> kdb.Box:
                return kdb.Box(-d, -d, d, d)

            self.apply_minkowski_custom(c, shape=box)

        case Direction.Y:

            def edge(d: int) -> kdb.Edge:
                return kdb.Edge(0, -d, 0, d)

            self.apply_minkowski_custom(c, shape=edge)

        case Direction.X:

            def edge(d: int) -> kdb.Edge:
                return kdb.Edge(-d, 0, d, 0)

            self.apply_minkowski_custom(c, shape=edge)

        case _:
            raise ValueError("Undefined direction")

apply_minkowski_tiled

apply_minkowski_tiled(
    c: KCell,
    tile_size: float | None = None,
    n_pts: int = 64,
    n_threads: int | None = None,
    carve_out_ports: bool = True,
) -> None

Minkowski regions with tiling processor.

Useful if the target is a big or complicated enclosure. Will split target ref into tiles and calculate them in parallel. Uses a circle as a shape for the minkowski sum.

Parameters:

Name Type Description Default
c KCell

Target KCell to apply the enclosures into.

required
tile_size float | None

Tile size. This should be in the order off 10+ maximum size of the maximum size of sections. [um] If None is set, the minimum size is set to 10xmax(d_max) of all sections or 200um whichever is bigger.

None
n_pts int

Number of points in the circle. < 3 will create a triangle. 4 a diamond, etc.

64
n_threads int | None

Number o threads to use. By default (None) it will use as many threads as are set to the process (usually all cores of the machine).

None
carve_out_ports bool

Carves out a box of port_width +

True
Source code in kfactory/enclosure.py
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
def apply_minkowski_tiled(
    self,
    c: KCell,
    tile_size: float | None = None,
    n_pts: int = 64,
    n_threads: int | None = None,
    carve_out_ports: bool = True,
) -> None:
    """Minkowski regions with tiling processor.

    Useful if the target is a big or complicated enclosure. Will split target ref
    into tiles and calculate them in parallel. Uses a circle as a shape for the
    minkowski sum.

    Args:
        c: Target KCell to apply the enclosures into.
        tile_size: Tile size. This should be in the order off 10+ maximum size
            of the maximum size of sections. [um]
            If None is set, the minimum size is set to 10xmax(d_max) of all sections
            or 200um whichever is bigger.
        n_pts: Number of points in the circle. < 3 will create a triangle. 4 a
            diamond, etc.
        n_threads: Number o threads to use. By default (`None`) it will use as many
            threads as are set to the process (usually all cores of the machine).
        carve_out_ports: Carves out a box of port_width +
    """
    tp = kdb.TilingProcessor()
    tp.frame = c.dbbox()  # ty:ignore[invalid-assignment]
    tp.dbu = c.kcl.dbu
    tp.threads = n_threads or config.n_threads
    inputs: set[str] = set()
    port_hole_map: dict[kdb.LayerInfo, kdb.Region] = defaultdict(kdb.Region)
    ports_by_layer: dict[kdb.LayerInfo, list[Port]] = defaultdict(list)
    for port in c.ports:
        ports_by_layer[c.kcl.layer(c.kcl.get_info(port.layer))].append(port)

    maxsize = 0
    for enc in self.enclosures.enclosures:
        assert enc.main_layer is not None
        main_layer = c.kcl.layer(enc.main_layer)
        for layer, layersection in enc.layer_sections.items():
            li = c.kcl.layer(layer)
            size = layersection.sections[-1].d_max
            maxsize = max(maxsize, size)

            for port in ports_by_layer[main_layer]:
                if port._base.trans:
                    port_hole_map[li].insert(
                        port_hole(port.width, size).transformed(port.trans)
                    )
                else:
                    port_hole_map[li].insert(
                        port_hole(port.width, size).transformed(
                            kdb.ICplxTrans(port.dcplx_trans, port.kcl.dbu)
                        )
                    )

    min_tile_size_rec = 10 * maxsize * tp.dbu

    if tile_size is None:
        tile_size = max(min_tile_size_rec * 2, 200)

    if float(tile_size) <= min_tile_size_rec:
        logger.warning(
            "Tile size should be larger than the maximum of "
            "the enclosures (recommendation: {} / {})",
            tile_size,
            min_tile_size_rec,
        )
    tp.tile_border(maxsize * tp.dbu, maxsize * tp.dbu)
    tp.tile_size(tile_size, tile_size)
    layer_regiontilesoperators: dict[
        tuple[int, LayerSection], RegionTilesOperator
    ] = {}

    logger.debug("Starting KCellEnclosure on {}", c.kcl._future_cell_name or c.name)

    n_enc = len(self.enclosures.enclosures)

    for i, enc in enumerate(self.enclosures.enclosures):
        assert enc.main_layer is not None
        if not c.bbox(c.kcl.layer(enc.main_layer)).empty():
            main_layer = c.kcl.layer(enc.main_layer)
            inp = f"main_layer_{main_layer}"
            if enc.main_layer not in inputs:
                tp.input(
                    inp,
                    c.kcl.layout,
                    c.cell_index(),
                    main_layer,
                )
                inputs.add(main_layer)
                logger.debug("Created input {}", inp)

            for layer, layer_section in enc.layer_sections.items():
                li = c.kcl.layer(layer)
                if (main_layer, layer_section) in layer_regiontilesoperators:
                    layer_regiontilesoperators[
                        main_layer, layer_section
                    ].layers.append(li)
                else:
                    out = f"target_{li}"
                    operator = RegionTilesOperator(cell=c, layers=[li])
                    layer_regiontilesoperators[main_layer, layer_section] = operator
                    tp.output(out, operator)
                    logger.debug("Created output {}", out)

                for section in reversed(layer_section.sections):
                    queue_str = (
                        "var max_shape = Polygon.ellipse("
                        f"Box.new({section.d_max * 2},{section.d_max * 2}),"
                        f" {n_pts});"
                        f"var tile_reg = _tile & _frame.sized({maxsize});"
                    )
                    match section.d_max:
                        case d if d > 0:
                            max_region = (
                                "var max_reg = "
                                f"{inp}.minkowski_sum(max_shape).merged();"
                            )
                        case d if d < 0:
                            max_region = (
                                f"var max_reg = tile_reg - (tile_reg - {inp});"
                            )
                        case 0:
                            max_region = f"var max_reg = {inp} & tile_reg;"
                    queue_str += max_region
                    if section.d_min is not None:
                        queue_str += (
                            "var min_shape = Polygon.ellipse("
                            f"Box.new({section.d_min * 2},{section.d_min * 2}),"
                            " 64);"
                        )
                        match section.d_min:
                            case d if d > 0:
                                min_region = (
                                    f"var min_reg = {inp}.minkowski_sum(min_shape);"
                                )
                            case d if d < 0:
                                min_region = (
                                    "var min_reg = tile_reg - (tile_reg - "
                                    f"{inp}).minkowski_sum(min_shape);"
                                )
                            case 0:
                                min_region = f"var min_reg = {inp} & tile_reg;"
                        queue_str += min_region
                        queue_str += (
                            f"_output({out},(max_reg - min_reg) & _tile, true);"
                        )
                    else:
                        queue_str += f"_output({out}, max_reg & _tile, true);"

                    logger.debug(
                        "{}/{}: Queuing string for {} on layer {}: '{}'",
                        i + 1,
                        n_enc,
                        c.kcl._future_cell_name or c.name,
                        layer,
                        queue_str,
                    )
                    tp.queue(queue_str)

    c.kcl.start_changes()
    logger.debug(
        "Starting enclosure {}",
        c.kcl._future_cell_name or c.name,
        enc.name,
    )
    tp.execute(f"Minkowski {c.name}")
    c.kcl.end_changes()
    logger.debug("Finished enclosure {}", enc.name)

    if carve_out_ports:
        for operator in layer_regiontilesoperators.values():
            # for layer in operator.layers:
            operator.insert(port_hole_map=port_hole_map)
    else:
        for operator in layer_regiontilesoperators.values():
            operator.insert()
    logger.debug("Finished KCellEnclosure on {}", c.kcl._future_cell_name or c.name)

apply_minkowski_x

apply_minkowski_x(c: KCell) -> None

Apply an enclosure with a vector in x-direction.

This can be used for tapers/ waveguides or similar that are straight.

Parameters:

Name Type Description Default
c KCell

Cell to apply the enclosure to.

required
Source code in kfactory/enclosure.py
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
def apply_minkowski_x(self, c: KCell) -> None:
    """Apply an enclosure with a vector in x-direction.

    This can be used for tapers/
    waveguides or similar that are straight.

    Args:
        c: Cell to apply the enclosure to.
    """
    return self.apply_minkowski_enc(c, direction=Direction.X)

apply_minkowski_y

apply_minkowski_y(c: KCell) -> None

Apply an enclosure with a vector in y-direction.

This can be used for tapers/ waveguides or similar that are straight.

Parameters:

Name Type Description Default
c KCell

Cell to apply the enclosure to.

required
Source code in kfactory/enclosure.py
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
def apply_minkowski_y(self, c: KCell) -> None:
    """Apply an enclosure with a vector in y-direction.

    This can be used for tapers/
    waveguides or similar that are straight.

    Args:
        c: Cell to apply the enclosure to.
    """
    return self.apply_minkowski_enc(c, direction=Direction.Y)

minkowski_region

minkowski_region(
    r: Region,
    d: int | None,
    shape: Callable[
        [int], list[Point] | Box | Edge | Polygon
    ],
) -> kdb.Region

Calculaste a region from a minkowski sum.

If the distance is negative, the function will take the inverse region and apply the minkowski and take the inverse again.

Parameters:

Name Type Description Default
r Region

Target region.

required
d int | None

Distance to pass to the shape. Can be any integer. [dbu]

required
shape Callable[[int], list[Point] | Box | Edge | Polygon]

Function returning a shape for the minkowski region.

required
Source code in kfactory/enclosure.py
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
def minkowski_region(
    self,
    r: kdb.Region,
    d: int | None,
    shape: Callable[[int], list[kdb.Point] | kdb.Box | kdb.Edge | kdb.Polygon],
) -> kdb.Region:
    """Calculaste a region from a minkowski sum.

    If the distance is negative, the function will take the inverse region and apply
    the minkowski and take the inverse again.

    Args:
        r: Target region.
        d: Distance to pass to the shape. Can be any integer. [dbu]
        shape: Function returning a shape for the minkowski region.
    """
    if d is None:
        return kdb.Region()
    if d == 0:
        return r.dup()
    if d > 0:
        return r.minkowski_sum(shape(d))
    shape_ = shape(abs(d))
    if isinstance(shape_, list):
        box_shape = kdb.Polygon(cast("list[kdb.Point]", shape_))
        bbox_maxsize = max(
            box_shape.bbox().width(),
            box_shape.bbox().height(),
        )
    else:
        bbox_maxsize = max(
            shape_.bbox().width(),
            shape_.bbox().height(),
        )
    bbox_r = kdb.Region(r.bbox().enlarged(bbox_maxsize))
    return r - (bbox_r - r).minkowski_sum(shape_)

KCellLayerEnclosures pydantic-model

Bases: BaseModel

Collection of LayerEnclosures.

Fields:

Validators:

Source code in kfactory/enclosure.py
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
class KCellLayerEnclosures(BaseModel):
    """Collection of LayerEnclosures."""

    enclosures: list[LayerEnclosure]

    def __hash__(self) -> int:
        return hash(tuple(self.enclosures))

    @field_validator("enclosures")
    @classmethod
    def enclosures_must_have_main_layer(
        cls, v: list[LayerEnclosure]
    ) -> list[LayerEnclosure]:
        """The PDK Enclosure must have main layers defined for each Enclosure.

        The PDK Enclosure uses this to automatically apply enclosures.
        """
        for le in v:
            assert le.main_layer is not None, (
                "Enclosure for PDKEnclosure must have a main layer defined"
            )
        return v

    def __getitem__(self, key: str | int) -> LayerEnclosure:
        """Retrieve enclosure by main layer."""
        try:
            return next(filter(lambda enc: enc.main_layer == key, self.enclosures))
        except StopIteration as e:
            raise KeyError(f"Unknown key {key}") from e

    def get_enclosure(
        self,
        enclosure: str | LayerEnclosure | LayerEnclosureSpec,
    ) -> LayerEnclosure:
        if isinstance(enclosure, str):
            return self[enclosure]
        if isinstance(enclosure, dict) and enclosure.get("dsections") is None:
            enclosure = LayerEnclosure(
                sections=enclosure.get("sections", []),
                name=enclosure.get("name"),
                main_layer=enclosure["main_layer"],
            )

        if enclosure not in self.enclosures:
            self.enclosures.append(enclosure)  # ty:ignore[invalid-argument-type]
        return enclosure  # ty:ignore[invalid-return-type]

__getitem__

__getitem__(key: str | int) -> LayerEnclosure

Retrieve enclosure by main layer.

Source code in kfactory/enclosure.py
1228
1229
1230
1231
1232
1233
def __getitem__(self, key: str | int) -> LayerEnclosure:
    """Retrieve enclosure by main layer."""
    try:
        return next(filter(lambda enc: enc.main_layer == key, self.enclosures))
    except StopIteration as e:
        raise KeyError(f"Unknown key {key}") from e

enclosures_must_have_main_layer pydantic-validator

enclosures_must_have_main_layer(
    v: list[LayerEnclosure],
) -> list[LayerEnclosure]

The PDK Enclosure must have main layers defined for each Enclosure.

The PDK Enclosure uses this to automatically apply enclosures.

Source code in kfactory/enclosure.py
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
@field_validator("enclosures")
@classmethod
def enclosures_must_have_main_layer(
    cls, v: list[LayerEnclosure]
) -> list[LayerEnclosure]:
    """The PDK Enclosure must have main layers defined for each Enclosure.

    The PDK Enclosure uses this to automatically apply enclosures.
    """
    for le in v:
        assert le.main_layer is not None, (
            "Enclosure for PDKEnclosure must have a main layer defined"
        )
    return v

LayerEnclosure pydantic-model

Bases: BaseModel

Definitions for calculation of enclosing (or smaller) shapes of a reference.

Attributes:

Name Type Description
layer_sections dict[LayerInfo, LayerSection]

Mapping of layers to their layer sections.

main_layer LayerInfo | None

Layer which to use unless specified otherwise.

Fields:

  • layer_sections (dict[LayerInfo, LayerSection])
  • _name (str | None)
  • main_layer (LayerInfo | None)
  • bbox_sections (dict[LayerInfo, int])
Source code in kfactory/enclosure.py
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
class LayerEnclosure(BaseModel, arbitrary_types_allowed=True, frozen=True):
    """Definitions for calculation of enclosing (or smaller) shapes of a reference.

    Attributes:
        layer_sections: Mapping of layers to their layer sections.
        main_layer: Layer which to use unless specified otherwise.
    """

    layer_sections: dict[kdb.LayerInfo, LayerSection]
    _name: str | None = PrivateAttr()
    main_layer: kdb.LayerInfo | None
    bbox_sections: dict[kdb.LayerInfo, int]

    def __eq__(self, other: object) -> bool:
        if isinstance(other, LayerEnclosure):
            if self.main_layer is not None and other.main_layer is not None:
                layer_info_equal = self.main_layer.is_equivalent(other.main_layer)
            else:
                layer_info_equal = self.main_layer == other.main_layer
            return (
                self.layer_sections == other.layer_sections
                and self.name == other.name
                and layer_info_equal
                and self.bbox_sections == other.bbox_sections
            )
        return False

    def __init__(
        self,
        sections: Sequence[
            tuple[kdb.LayerInfo, int] | tuple[kdb.LayerInfo, int, int]
        ] = [],
        name: str | None = None,
        main_layer: kdb.LayerInfo | None = None,
        dsections: Sequence[
            tuple[kdb.LayerInfo, float] | tuple[kdb.LayerInfo, float, float]
        ]
        | None = None,
        bbox_sections: Sequence[tuple[kdb.LayerInfo, int]] = [],
        kcl: KCLayout | None = None,
    ) -> None:
        """Constructor of new enclosure.

        Args:
            sections: tuples containing info for the enclosure.
                Elements must be of the form (layer, max) or (layer, min, max)
            name: Optional name of the enclosure. If a name is given in the
                cell name this name will be used for enclosure arguments.
            main_layer: Main layer used if the functions don't get an explicit layer.
            dsections: Same as sections but min/max defined in um
            kcl: `KCLayout` Used for conversion dbu -> um or when copying.
                Must be specified if `desections` is not `None`. Also necessary
                if copying to another layout and not all layers used are LayerInfos.
        """
        layer_sections: dict[kdb.LayerInfo, LayerSection] = {}

        if dsections is not None:
            assert kcl is not None, "If sections in um are defined, kcl must be set"
            sections = list(sections)
            for section in dsections:
                if len(section) == 2:
                    sections.append((section[0], kcl.to_dbu(section[1])))

                elif len(section) == 3:
                    sections.append(
                        (
                            section[0],
                            kcl.to_dbu(section[1]),
                            kcl.to_dbu(section[2]),
                        )
                    )

        for sec in sorted(
            sections,
            key=lambda sec: (sec[0].name, sec[0].layer, sec[0].datatype, sec[1]),
        ):
            if sec[0] in layer_sections:
                ls = layer_sections[sec[0]]
            else:
                ls = LayerSection()
                layer_sections[sec[0]] = ls
            ls.add_section(Section(d_max=sec[1])) if len(sec) < 3 else ls.add_section(
                Section(d_max=sec[2], d_min=sec[1])  # ty:ignore[index-out-of-bounds]
            )
        super().__init__(
            main_layer=main_layer,
            kcl=kcl,
            layer_sections=layer_sections,
            bbox_sections={t[0]: t[1] for t in bbox_sections},
        )
        self._name = name  # ty:ignore[invalid-assignment]

    @model_serializer
    def _serialize(self) -> dict[str, Any]:
        return {
            "name": self.name,
            "sections": [
                (layer, s.d_max) if s.d_min is None else (layer, s.d_min, s.d_max)
                for layer, sections in self.layer_sections.items()
                for s in sections.sections
            ],
            "main_layer": self.main_layer,
        }

    def __hash__(self) -> int:  # make hashable BaseModel subclass
        """Calculate a unique hash of the enclosure."""
        return hash((str(self), self.main_layer, tuple(self.layer_sections.items())))

    def to_dtype(self, kcl: KCLayout) -> DLayerEnclosure:
        """Convert the enclosure to a um based enclosure."""
        if self.main_layer is None:
            raise ValueError("um based enclosures must have a main_layer")
        return DLayerEnclosure(
            name=self._name,
            sections=[
                (layer, kcl.to_um(section.d_max))
                if section.d_min is None
                else (layer, kcl.to_um(section.d_min), kcl.to_um(section.d_max))
                for layer, layer_section in self.layer_sections.items()
                for section in layer_section.sections
            ],
            main_layer=self.main_layer,
        )

    @property
    def name(self) -> str:
        """Get name of the Enclosure."""
        return self.__str__()

    @property
    def is_named(self) -> bool:
        """Whether an explicit name was given (vs. a derived structural name)."""
        return self._name is not None

    @property
    def unnamed_key(self) -> str:
        """Deterministic structural key, independent of the explicit name.

        This is the same hash an unnamed enclosure is named after. Exposing it on
        named enclosures as well lets the registry alias the structural signature
        to a named enclosure.
        """
        list_to_hash: list[tuple[str, ...]] = [(str(self.main_layer),)]
        for layer, layer_section in self.layer_sections.items():
            list_to_hash.append((str(layer), str(layer_section.sections)))
        for layer, offset in sorted(
            self.bbox_sections.items(), key=lambda kv: str(kv[0])
        ):
            list_to_hash.append((str(layer), "bbox", str(offset)))
        return sha1(str(list_to_hash).encode("UTF-8")).hexdigest()[-8:]  # noqa: S324

    def minkowski_region(
        self,
        r: kdb.Region,
        d: int | None,
        shape: Callable[[int], list[kdb.Point] | kdb.Box | kdb.Edge | kdb.Polygon],
    ) -> kdb.Region:
        """Calculaste a region from a minkowski sum.

        If the distance is negative, the function will take the inverse region and apply
        the minkowski and take the inverse again.

        Args:
            r: Target region.
            d: Distance to pass to the shape. Can be any integer. [dbu]
            shape: Function returning a shape for the minkowski region.
        """
        if d is None:
            return kdb.Region()
        if d == 0:
            return r.dup()
        if d > 0:
            return r.minkowski_sum(shape(d))
        shape_ = shape(abs(d))
        if isinstance(shape_, list):
            box_shape = kdb.Polygon(cast("list[kdb.Point]", shape_))
            bbox_maxsize = max(
                box_shape.bbox().width(),
                box_shape.bbox().height(),
            )
        else:
            bbox_maxsize = max(
                shape_.bbox().width(),
                shape_.bbox().height(),
            )
        bbox_r = kdb.Region(r.bbox().enlarged(bbox_maxsize))
        return r - (bbox_r - r).minkowski_sum(shape_)

    def apply_minkowski_enc(
        self,
        c: KCell,
        ref: kdb.LayerInfo | kdb.Region | None,  # layer index or the region
        direction: Direction = Direction.BOTH,
    ) -> None:
        """Apply an enclosure with a vector in y-direction.

        This can be used for tapers/
        waveguides or similar that are straight.

        Args:
            c: Cell to apply the enclosure to.
            ref: Reference to use as a base for the enclosure.
            direction: X/Y or both directions.
                Uses a box if both directions are selected.
        """
        match direction:
            case Direction.BOTH:

                def box(d: int) -> kdb.Box:
                    return kdb.Box(-d, -d, d, d)

                self.apply_minkowski_custom(c, ref=ref, shape=box)

            case Direction.Y:

                def edge(d: int) -> kdb.Edge:
                    return kdb.Edge(0, -d, 0, d)

                self.apply_minkowski_custom(c, ref=ref, shape=edge)

            case Direction.X:

                def edge(d: int) -> kdb.Edge:
                    return kdb.Edge(-d, 0, d, 0)

                self.apply_minkowski_custom(c, ref=ref, shape=edge)

            case _:
                raise ValueError("Undefined direction")

    def apply_minkowski_y(
        self, c: KCell, ref: kdb.LayerInfo | kdb.Region | None = None
    ) -> None:
        """Apply an enclosure with a vector in y-direction.

        This can be used for tapers/
        waveguides or similar that are straight.

        Args:
            c: Cell to apply the enclosure to.
            ref: Reference to use as a base for the enclosure.
        """
        return self.apply_minkowski_enc(c, ref=ref, direction=Direction.Y)

    def apply_minkowski_x(
        self, c: KCell, ref: kdb.LayerInfo | kdb.Region | None
    ) -> None:
        """Apply an enclosure with a vector in x-direction.

        This can be used for tapers/
        waveguides or similar that are straight.

        Args:
            c: Cell to apply the enclosure to.
            ref: Reference to use as a base for the enclosure.
        """
        return self.apply_minkowski_enc(c, ref=ref, direction=Direction.X)

    def apply_minkowski_custom(
        self,
        c: KCell,
        shape: Callable[[int], kdb.Edge | kdb.Polygon | kdb.Box],
        ref: kdb.LayerInfo | kdb.Region | None = None,
    ) -> None:
        """Apply an enclosure with a custom shape.

        This can be used for tapers/
        waveguides or similar that are straight.

        Args:
            c: Cell to apply the enclosure to.
            shape: A function that will return a shape which takes one argument
                the size of the section in dbu.
            ref: Reference to use as a base for the enclosure.
        """
        if ref is None:
            ref = self.main_layer

            if ref is None:
                raise ValueError(
                    "The enclosure doesn't have  a reference `main_layer` defined."
                    " Therefore the layer must be defined in calls"
                )
        r = (
            kdb.Region(c.begin_shapes_rec(c.kcl.layer(ref)))
            if isinstance(ref, kdb.LayerInfo)
            else ref.dup()
        )
        r.merge()

        for layer, layersec in reversed(self.layer_sections.items()):
            for section in layersec.sections:
                c.shapes(c.kcl.layer(layer)).insert(
                    self.minkowski_region(r, section.d_max, shape)
                    - self.minkowski_region(r, section.d_min, shape)
                )

    def apply_minkowski_tiled(
        self,
        c: KCell,
        ref: kdb.LayerInfo | kdb.Region | None = None,
        tile_size: float | None = None,
        n_pts: int = 64,
        n_threads: int | None = None,
        carve_out_ports: Iterable[Port] = [],
    ) -> None:
        """Minkowski regions with tiling processor.

        Useful if the target is a big or complicated enclosure. Will split target ref
        into tiles and calculate them in parallel. Uses a circle as a shape for the
        minkowski sum.

        Args:
            c: Target KCell to apply the enclosures into.
            ref: The reference shapes to apply the enclosures to.
                Can be a layer or a region. If `None`, it will try to use the
                `main_layer` of the
                [enclosure][kfactory.enclosure.LayerEnclosure].
            tile_size: Tile size. This should be in the order off 10+ maximum size
                of the maximum size of sections.
            n_pts: Number of points in the circle. < 3 will create a triangle. 4 a
                diamond, etc.
            n_threads: Number o threads to use. By default (`None`) it will use as many
                threads as are set to the process (usually all cores of the machine).
            carve_out_ports: Carves out a box of port_width +
        """
        if ref is None:
            ref = self.main_layer

            if ref is None:
                raise ValueError(
                    "The enclosure doesn't have  a reference `main_layer` defined."
                    " Therefore the layer must be defined in calls"
                )
        tp = kdb.TilingProcessor()
        tp.frame = c.dbbox()  # ty:ignore[invalid-assignment]
        tp.dbu = c.kcl.dbu
        tp.threads = n_threads or config.n_threads
        maxsize = 0
        for layersection in self.layer_sections.values():
            maxsize = max(
                maxsize, *[section.d_max for section in layersection.sections]
            )

        min_tile_size_rec = 10 * maxsize * tp.dbu

        if tile_size is None:
            tile_size = min_tile_size_rec * 2

        if float(tile_size) <= min_tile_size_rec:
            logger.warning(
                "Tile size should be larger than the maximum of "
                "the enclosures (recommendation: {} / {})",
                tile_size,
                min_tile_size_rec,
            )

        tp.tile_border(maxsize * tp.dbu, maxsize * tp.dbu)

        tp.tile_size(tile_size, tile_size)
        if isinstance(ref, kdb.LayerInfo):
            tp.input("main_layer", c.kcl.layout, c.cell_index(), c.kcl.layer(ref))
        else:
            tp.input("main_layer", ref)

        operators = []
        port_holes: dict[int, kdb.Region] = defaultdict(kdb.Region)
        ports_by_layer: dict[int, list[Port]] = defaultdict(list)
        for port in c.ports:
            ports_by_layer[port.layer].append(port)

        for layer, sections in self.layer_sections.items():
            layer_index = c.kcl.layer(layer)
            operator = RegionOperator(cell=c, layer=layer_index)
            tp.output(f"target_{layer_index}", operator)
            max_size: int = _min_size
            for _i, section in enumerate(reversed(sections.sections)):
                max_size = max(max_size, section.d_max)
                queue_str = f"var tile_reg = (_tile & _frame).sized({maxsize});"
                queue_str += (
                    "var max_shape = Polygon.ellipse("
                    f"Box.new({section.d_max * 2},{section.d_max * 2}), {n_pts});"
                )
                match section.d_max:
                    case d if d > 0:
                        max_region = (
                            "var max_reg = "
                            "main_layer.minkowski_sum(max_shape).merged();"
                        )
                    case d if d < 0:
                        max_region = "var max_reg = tile_reg - (tile_reg - main_layer);"
                    case 0:
                        max_region = "var max_reg = main_layer & tile_reg;"
                queue_str += max_region
                if section.d_min is not None:
                    queue_str += (
                        "var min_shape = Polygon.ellipse("
                        f"Box.new({section.d_min * 2},{section.d_min * 2}), 64);"
                    )
                    match section.d_min:
                        case d if d > 0:
                            min_region = (
                                "var min_reg = main_layer.minkowski_sum(min_shape);"
                            )
                        case d if d < 0:
                            min_region = (
                                "var min_reg = tile_reg - "
                                "(tile_reg - main_layer).minkowski_sum(min_shape);"
                            )
                        case 0:
                            min_region = "var min_reg = main_layer & tile_reg;"
                    queue_str += min_region
                    queue_str += (
                        f"_output(target_{layer_index},"
                        "(max_reg - min_reg)& _tile, true);"
                    )
                else:
                    queue_str += f"_output(target_{layer_index},max_reg & _tile, true);"

                tp.queue(queue_str)
                logger.debug(
                    "String queued for {} on layer {}: {}", c.name, layer, queue_str
                )

            operators.append((layer_index, operator))
            if carve_out_ports:
                r = port_holes[layer_index]
                for port in carve_out_ports:
                    if port._base.trans is not None:
                        r.insert(
                            port_hole(port.width, max_size).transformed(port.trans)
                        )
                    else:
                        r.insert(
                            port_hole(port.width, max_size).transformed(
                                kdb.ICplxTrans(port.dcplx_trans, c.kcl.dbu)
                            )
                        )
                port_holes[layer_index] = r

        c.kcl.start_changes()
        logger.info("Starting minkowski on {}", c.name)
        tp.execute(f"Minkowski {c.name}")
        c.kcl.end_changes()

        if carve_out_ports:
            for layer_index, operator in operators:
                operator.insert(port_holes=port_holes[layer_index])
        else:
            for _, operator in operators:
                operator.insert()

    def apply_custom(
        self,
        c: KCell,
        shape: Callable[
            [int, int | None], kdb.Edge | kdb.Polygon | kdb.Box | kdb.Region
        ],
    ) -> None:
        """Apply a custom shape based on the section size.

        Args:
            c: The cell to apply the enclosure to.
            shape: A function taking the section size in dbu to calculate the
                full enclosure.
        """
        for layer, layersec in self.layer_sections.items():
            layer_index = c.kcl.layer(layer)
            for sec in layersec.sections:
                c.shapes(layer_index).insert(shape(sec.d_max, sec.d_min))

    def apply_bbox(
        self, c: KCell, ref: kdb.LayerInfo | kdb.Region | None = None
    ) -> None:
        """Apply an enclosure based on a bounding box.

        Args:
            c: Target cell.
            ref: Reference layer or region (the bounding box). If `None` use
                the `main_layer` of  the
                [enclosure][kfactory.enclosure.LayerEnclosure] if defined,
                else throw an error.
        """
        if ref is None:
            ref = self.main_layer

            if ref is None:
                raise ValueError(
                    "The enclosure doesn't have  a reference `main_layer` defined."
                    " Therefore the layer must be defined in calls"
                )

        if isinstance(ref, kdb.LayerInfo):
            ref_ = c.bbox(c.kcl.layer(ref))
        elif isinstance(ref, kdb.Region):
            ref_ = ref.bbox()

        def bbox_reg(d_max: int, d_min: int | None = None) -> kdb.Region:
            reg_max = kdb.Region(ref_)
            reg_max.size(d_max)
            if d_min is None:
                return reg_max
            reg_min = kdb.Region(ref_)
            reg_min.size(d_min)
            return reg_max - reg_min

        self.apply_custom(c, bbox_reg)

    def __str__(self) -> str:
        """String representation of an enclosure.

        Use [name][kfactory.enclosure.LayerEnclosure.name]
        if available. Use a hash of the sections and main_layer if the name is `None`.
        """
        if self._name is not None:
            return self._name
        return self.unnamed_key

    def extrude_path(
        self,
        c: KCell,
        path: list[kdb.DPoint],
        main_layer: kdb.LayerInfo | None,
        width: float,
        start_angle: float | None = None,
        end_angle: float | None = None,
    ) -> None:
        """Extrude a path and add it to a main layer.

        Start and end angle should be set in relation to the orientation of the path.
        If the path for example is starting E->W, the start angle should be 0 (if that
        that is the desired angle). End angle is the same if the end
        piece is stopping 2nd-last -> last in E->W.

        Args:
            c: The cell where to insert the path to
            path: Backbone of the path. [um]
            main_layer: Layer index where to put the main part of the path.
            width: Width of the core of the path
            start_angle: angle of the start piece
            end_angle: angle of the end piece
        """
        if main_layer is None:
            raise ValueError(
                "The enclosure doesn't have  a reference `main_layer` defined."
                " Therefore the layer must be defined in calls"
            )
        extrude_path(
            target=c,
            layer=main_layer,
            path=path,
            width=width,
            enclosure=self,
            start_angle=start_angle,
            end_angle=end_angle,
        )

    def extrude_path_dynamic(
        self,
        c: KCell,
        path: list[kdb.DPoint],
        main_layer: kdb.LayerInfo | None,
        widths: Callable[[float], float] | list[float],
    ) -> None:
        """Extrude a path and add it to a main layer.

        Supports a dynamic width of the path defined by a function
        returning the width for the interval [0,1], or as a list of
        widths of the same lengths as the points.

        Args:
            c: The cell where to insert the path to
            path: Backbone of the path. [um]
            main_layer: Layer index where to put the main part of the path.
            widths: Width of the core of the path
        """
        if main_layer is None:
            raise ValueError(
                "The enclosure doesn't have  a reference `main_layer` defined."
                " Therefore the layer must be defined in calls"
            )
        extrude_path_dynamic(
            target=c, layer=main_layer, path=path, widths=widths, enclosure=self
        )

    def model_copy(
        self, *, update: Mapping[str, Any] | None = {"name": None}, deep: bool = False
    ) -> LayerEnclosure:
        return super().model_copy(update=update, deep=deep)

is_named property

is_named: bool

Whether an explicit name was given (vs. a derived structural name).

name property

name: str

Get name of the Enclosure.

unnamed_key property

unnamed_key: str

Deterministic structural key, independent of the explicit name.

This is the same hash an unnamed enclosure is named after. Exposing it on named enclosures as well lets the registry alias the structural signature to a named enclosure.

__hash__

__hash__() -> int

Calculate a unique hash of the enclosure.

Source code in kfactory/enclosure.py
691
692
693
def __hash__(self) -> int:  # make hashable BaseModel subclass
    """Calculate a unique hash of the enclosure."""
    return hash((str(self), self.main_layer, tuple(self.layer_sections.items())))

__init__

__init__(
    sections: Sequence[
        tuple[LayerInfo, int] | tuple[LayerInfo, int, int]
    ] = [],
    name: str | None = None,
    main_layer: LayerInfo | None = None,
    dsections: Sequence[
        tuple[LayerInfo, float]
        | tuple[LayerInfo, float, float]
    ]
    | None = None,
    bbox_sections: Sequence[tuple[LayerInfo, int]] = [],
    kcl: KCLayout | None = None,
) -> None

Constructor of new enclosure.

Parameters:

Name Type Description Default
sections Sequence[tuple[LayerInfo, int] | tuple[LayerInfo, int, int]]

tuples containing info for the enclosure. Elements must be of the form (layer, max) or (layer, min, max)

[]
name str | None

Optional name of the enclosure. If a name is given in the cell name this name will be used for enclosure arguments.

None
main_layer LayerInfo | None

Main layer used if the functions don't get an explicit layer.

None
dsections Sequence[tuple[LayerInfo, float] | tuple[LayerInfo, float, float]] | None

Same as sections but min/max defined in um

None
kcl KCLayout | None

KCLayout Used for conversion dbu -> um or when copying. Must be specified if desections is not None. Also necessary if copying to another layout and not all layers used are LayerInfos.

None
Source code in kfactory/enclosure.py
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
def __init__(
    self,
    sections: Sequence[
        tuple[kdb.LayerInfo, int] | tuple[kdb.LayerInfo, int, int]
    ] = [],
    name: str | None = None,
    main_layer: kdb.LayerInfo | None = None,
    dsections: Sequence[
        tuple[kdb.LayerInfo, float] | tuple[kdb.LayerInfo, float, float]
    ]
    | None = None,
    bbox_sections: Sequence[tuple[kdb.LayerInfo, int]] = [],
    kcl: KCLayout | None = None,
) -> None:
    """Constructor of new enclosure.

    Args:
        sections: tuples containing info for the enclosure.
            Elements must be of the form (layer, max) or (layer, min, max)
        name: Optional name of the enclosure. If a name is given in the
            cell name this name will be used for enclosure arguments.
        main_layer: Main layer used if the functions don't get an explicit layer.
        dsections: Same as sections but min/max defined in um
        kcl: `KCLayout` Used for conversion dbu -> um or when copying.
            Must be specified if `desections` is not `None`. Also necessary
            if copying to another layout and not all layers used are LayerInfos.
    """
    layer_sections: dict[kdb.LayerInfo, LayerSection] = {}

    if dsections is not None:
        assert kcl is not None, "If sections in um are defined, kcl must be set"
        sections = list(sections)
        for section in dsections:
            if len(section) == 2:
                sections.append((section[0], kcl.to_dbu(section[1])))

            elif len(section) == 3:
                sections.append(
                    (
                        section[0],
                        kcl.to_dbu(section[1]),
                        kcl.to_dbu(section[2]),
                    )
                )

    for sec in sorted(
        sections,
        key=lambda sec: (sec[0].name, sec[0].layer, sec[0].datatype, sec[1]),
    ):
        if sec[0] in layer_sections:
            ls = layer_sections[sec[0]]
        else:
            ls = LayerSection()
            layer_sections[sec[0]] = ls
        ls.add_section(Section(d_max=sec[1])) if len(sec) < 3 else ls.add_section(
            Section(d_max=sec[2], d_min=sec[1])  # ty:ignore[index-out-of-bounds]
        )
    super().__init__(
        main_layer=main_layer,
        kcl=kcl,
        layer_sections=layer_sections,
        bbox_sections={t[0]: t[1] for t in bbox_sections},
    )
    self._name = name  # ty:ignore[invalid-assignment]

__str__

__str__() -> str

String representation of an enclosure.

Use name if available. Use a hash of the sections and main_layer if the name is None.

Source code in kfactory/enclosure.py
1095
1096
1097
1098
1099
1100
1101
1102
1103
def __str__(self) -> str:
    """String representation of an enclosure.

    Use [name][kfactory.enclosure.LayerEnclosure.name]
    if available. Use a hash of the sections and main_layer if the name is `None`.
    """
    if self._name is not None:
        return self._name
    return self.unnamed_key

apply_bbox

apply_bbox(
    c: KCell, ref: LayerInfo | Region | None = None
) -> None

Apply an enclosure based on a bounding box.

Parameters:

Name Type Description Default
c KCell

Target cell.

required
ref LayerInfo | Region | None

Reference layer or region (the bounding box). If None use the main_layer of the enclosure if defined, else throw an error.

None
Source code in kfactory/enclosure.py
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
def apply_bbox(
    self, c: KCell, ref: kdb.LayerInfo | kdb.Region | None = None
) -> None:
    """Apply an enclosure based on a bounding box.

    Args:
        c: Target cell.
        ref: Reference layer or region (the bounding box). If `None` use
            the `main_layer` of  the
            [enclosure][kfactory.enclosure.LayerEnclosure] if defined,
            else throw an error.
    """
    if ref is None:
        ref = self.main_layer

        if ref is None:
            raise ValueError(
                "The enclosure doesn't have  a reference `main_layer` defined."
                " Therefore the layer must be defined in calls"
            )

    if isinstance(ref, kdb.LayerInfo):
        ref_ = c.bbox(c.kcl.layer(ref))
    elif isinstance(ref, kdb.Region):
        ref_ = ref.bbox()

    def bbox_reg(d_max: int, d_min: int | None = None) -> kdb.Region:
        reg_max = kdb.Region(ref_)
        reg_max.size(d_max)
        if d_min is None:
            return reg_max
        reg_min = kdb.Region(ref_)
        reg_min.size(d_min)
        return reg_max - reg_min

    self.apply_custom(c, bbox_reg)

apply_custom

apply_custom(
    c: KCell,
    shape: Callable[
        [int, int | None], Edge | Polygon | Box | Region
    ],
) -> None

Apply a custom shape based on the section size.

Parameters:

Name Type Description Default
c KCell

The cell to apply the enclosure to.

required
shape Callable[[int, int | None], Edge | Polygon | Box | Region]

A function taking the section size in dbu to calculate the full enclosure.

required
Source code in kfactory/enclosure.py
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
def apply_custom(
    self,
    c: KCell,
    shape: Callable[
        [int, int | None], kdb.Edge | kdb.Polygon | kdb.Box | kdb.Region
    ],
) -> None:
    """Apply a custom shape based on the section size.

    Args:
        c: The cell to apply the enclosure to.
        shape: A function taking the section size in dbu to calculate the
            full enclosure.
    """
    for layer, layersec in self.layer_sections.items():
        layer_index = c.kcl.layer(layer)
        for sec in layersec.sections:
            c.shapes(layer_index).insert(shape(sec.d_max, sec.d_min))

apply_minkowski_custom

apply_minkowski_custom(
    c: KCell,
    shape: Callable[[int], Edge | Polygon | Box],
    ref: LayerInfo | Region | None = None,
) -> None

Apply an enclosure with a custom shape.

This can be used for tapers/ waveguides or similar that are straight.

Parameters:

Name Type Description Default
c KCell

Cell to apply the enclosure to.

required
shape Callable[[int], Edge | Polygon | Box]

A function that will return a shape which takes one argument the size of the section in dbu.

required
ref LayerInfo | Region | None

Reference to use as a base for the enclosure.

None
Source code in kfactory/enclosure.py
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
def apply_minkowski_custom(
    self,
    c: KCell,
    shape: Callable[[int], kdb.Edge | kdb.Polygon | kdb.Box],
    ref: kdb.LayerInfo | kdb.Region | None = None,
) -> None:
    """Apply an enclosure with a custom shape.

    This can be used for tapers/
    waveguides or similar that are straight.

    Args:
        c: Cell to apply the enclosure to.
        shape: A function that will return a shape which takes one argument
            the size of the section in dbu.
        ref: Reference to use as a base for the enclosure.
    """
    if ref is None:
        ref = self.main_layer

        if ref is None:
            raise ValueError(
                "The enclosure doesn't have  a reference `main_layer` defined."
                " Therefore the layer must be defined in calls"
            )
    r = (
        kdb.Region(c.begin_shapes_rec(c.kcl.layer(ref)))
        if isinstance(ref, kdb.LayerInfo)
        else ref.dup()
    )
    r.merge()

    for layer, layersec in reversed(self.layer_sections.items()):
        for section in layersec.sections:
            c.shapes(c.kcl.layer(layer)).insert(
                self.minkowski_region(r, section.d_max, shape)
                - self.minkowski_region(r, section.d_min, shape)
            )

apply_minkowski_enc

apply_minkowski_enc(
    c: KCell,
    ref: LayerInfo | Region | None,
    direction: Direction = Direction.BOTH,
) -> None

Apply an enclosure with a vector in y-direction.

This can be used for tapers/ waveguides or similar that are straight.

Parameters:

Name Type Description Default
c KCell

Cell to apply the enclosure to.

required
ref LayerInfo | Region | None

Reference to use as a base for the enclosure.

required
direction Direction

X/Y or both directions. Uses a box if both directions are selected.

BOTH
Source code in kfactory/enclosure.py
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
def apply_minkowski_enc(
    self,
    c: KCell,
    ref: kdb.LayerInfo | kdb.Region | None,  # layer index or the region
    direction: Direction = Direction.BOTH,
) -> None:
    """Apply an enclosure with a vector in y-direction.

    This can be used for tapers/
    waveguides or similar that are straight.

    Args:
        c: Cell to apply the enclosure to.
        ref: Reference to use as a base for the enclosure.
        direction: X/Y or both directions.
            Uses a box if both directions are selected.
    """
    match direction:
        case Direction.BOTH:

            def box(d: int) -> kdb.Box:
                return kdb.Box(-d, -d, d, d)

            self.apply_minkowski_custom(c, ref=ref, shape=box)

        case Direction.Y:

            def edge(d: int) -> kdb.Edge:
                return kdb.Edge(0, -d, 0, d)

            self.apply_minkowski_custom(c, ref=ref, shape=edge)

        case Direction.X:

            def edge(d: int) -> kdb.Edge:
                return kdb.Edge(-d, 0, d, 0)

            self.apply_minkowski_custom(c, ref=ref, shape=edge)

        case _:
            raise ValueError("Undefined direction")

apply_minkowski_tiled

apply_minkowski_tiled(
    c: KCell,
    ref: LayerInfo | Region | None = None,
    tile_size: float | None = None,
    n_pts: int = 64,
    n_threads: int | None = None,
    carve_out_ports: Iterable[Port] = [],
) -> None

Minkowski regions with tiling processor.

Useful if the target is a big or complicated enclosure. Will split target ref into tiles and calculate them in parallel. Uses a circle as a shape for the minkowski sum.

Parameters:

Name Type Description Default
c KCell

Target KCell to apply the enclosures into.

required
ref LayerInfo | Region | None

The reference shapes to apply the enclosures to. Can be a layer or a region. If None, it will try to use the main_layer of the enclosure.

None
tile_size float | None

Tile size. This should be in the order off 10+ maximum size of the maximum size of sections.

None
n_pts int

Number of points in the circle. < 3 will create a triangle. 4 a diamond, etc.

64
n_threads int | None

Number o threads to use. By default (None) it will use as many threads as are set to the process (usually all cores of the machine).

None
carve_out_ports Iterable[Port]

Carves out a box of port_width +

[]
Source code in kfactory/enclosure.py
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
def apply_minkowski_tiled(
    self,
    c: KCell,
    ref: kdb.LayerInfo | kdb.Region | None = None,
    tile_size: float | None = None,
    n_pts: int = 64,
    n_threads: int | None = None,
    carve_out_ports: Iterable[Port] = [],
) -> None:
    """Minkowski regions with tiling processor.

    Useful if the target is a big or complicated enclosure. Will split target ref
    into tiles and calculate them in parallel. Uses a circle as a shape for the
    minkowski sum.

    Args:
        c: Target KCell to apply the enclosures into.
        ref: The reference shapes to apply the enclosures to.
            Can be a layer or a region. If `None`, it will try to use the
            `main_layer` of the
            [enclosure][kfactory.enclosure.LayerEnclosure].
        tile_size: Tile size. This should be in the order off 10+ maximum size
            of the maximum size of sections.
        n_pts: Number of points in the circle. < 3 will create a triangle. 4 a
            diamond, etc.
        n_threads: Number o threads to use. By default (`None`) it will use as many
            threads as are set to the process (usually all cores of the machine).
        carve_out_ports: Carves out a box of port_width +
    """
    if ref is None:
        ref = self.main_layer

        if ref is None:
            raise ValueError(
                "The enclosure doesn't have  a reference `main_layer` defined."
                " Therefore the layer must be defined in calls"
            )
    tp = kdb.TilingProcessor()
    tp.frame = c.dbbox()  # ty:ignore[invalid-assignment]
    tp.dbu = c.kcl.dbu
    tp.threads = n_threads or config.n_threads
    maxsize = 0
    for layersection in self.layer_sections.values():
        maxsize = max(
            maxsize, *[section.d_max for section in layersection.sections]
        )

    min_tile_size_rec = 10 * maxsize * tp.dbu

    if tile_size is None:
        tile_size = min_tile_size_rec * 2

    if float(tile_size) <= min_tile_size_rec:
        logger.warning(
            "Tile size should be larger than the maximum of "
            "the enclosures (recommendation: {} / {})",
            tile_size,
            min_tile_size_rec,
        )

    tp.tile_border(maxsize * tp.dbu, maxsize * tp.dbu)

    tp.tile_size(tile_size, tile_size)
    if isinstance(ref, kdb.LayerInfo):
        tp.input("main_layer", c.kcl.layout, c.cell_index(), c.kcl.layer(ref))
    else:
        tp.input("main_layer", ref)

    operators = []
    port_holes: dict[int, kdb.Region] = defaultdict(kdb.Region)
    ports_by_layer: dict[int, list[Port]] = defaultdict(list)
    for port in c.ports:
        ports_by_layer[port.layer].append(port)

    for layer, sections in self.layer_sections.items():
        layer_index = c.kcl.layer(layer)
        operator = RegionOperator(cell=c, layer=layer_index)
        tp.output(f"target_{layer_index}", operator)
        max_size: int = _min_size
        for _i, section in enumerate(reversed(sections.sections)):
            max_size = max(max_size, section.d_max)
            queue_str = f"var tile_reg = (_tile & _frame).sized({maxsize});"
            queue_str += (
                "var max_shape = Polygon.ellipse("
                f"Box.new({section.d_max * 2},{section.d_max * 2}), {n_pts});"
            )
            match section.d_max:
                case d if d > 0:
                    max_region = (
                        "var max_reg = "
                        "main_layer.minkowski_sum(max_shape).merged();"
                    )
                case d if d < 0:
                    max_region = "var max_reg = tile_reg - (tile_reg - main_layer);"
                case 0:
                    max_region = "var max_reg = main_layer & tile_reg;"
            queue_str += max_region
            if section.d_min is not None:
                queue_str += (
                    "var min_shape = Polygon.ellipse("
                    f"Box.new({section.d_min * 2},{section.d_min * 2}), 64);"
                )
                match section.d_min:
                    case d if d > 0:
                        min_region = (
                            "var min_reg = main_layer.minkowski_sum(min_shape);"
                        )
                    case d if d < 0:
                        min_region = (
                            "var min_reg = tile_reg - "
                            "(tile_reg - main_layer).minkowski_sum(min_shape);"
                        )
                    case 0:
                        min_region = "var min_reg = main_layer & tile_reg;"
                queue_str += min_region
                queue_str += (
                    f"_output(target_{layer_index},"
                    "(max_reg - min_reg)& _tile, true);"
                )
            else:
                queue_str += f"_output(target_{layer_index},max_reg & _tile, true);"

            tp.queue(queue_str)
            logger.debug(
                "String queued for {} on layer {}: {}", c.name, layer, queue_str
            )

        operators.append((layer_index, operator))
        if carve_out_ports:
            r = port_holes[layer_index]
            for port in carve_out_ports:
                if port._base.trans is not None:
                    r.insert(
                        port_hole(port.width, max_size).transformed(port.trans)
                    )
                else:
                    r.insert(
                        port_hole(port.width, max_size).transformed(
                            kdb.ICplxTrans(port.dcplx_trans, c.kcl.dbu)
                        )
                    )
            port_holes[layer_index] = r

    c.kcl.start_changes()
    logger.info("Starting minkowski on {}", c.name)
    tp.execute(f"Minkowski {c.name}")
    c.kcl.end_changes()

    if carve_out_ports:
        for layer_index, operator in operators:
            operator.insert(port_holes=port_holes[layer_index])
    else:
        for _, operator in operators:
            operator.insert()

apply_minkowski_x

apply_minkowski_x(
    c: KCell, ref: LayerInfo | Region | None
) -> None

Apply an enclosure with a vector in x-direction.

This can be used for tapers/ waveguides or similar that are straight.

Parameters:

Name Type Description Default
c KCell

Cell to apply the enclosure to.

required
ref LayerInfo | Region | None

Reference to use as a base for the enclosure.

required
Source code in kfactory/enclosure.py
831
832
833
834
835
836
837
838
839
840
841
842
843
def apply_minkowski_x(
    self, c: KCell, ref: kdb.LayerInfo | kdb.Region | None
) -> None:
    """Apply an enclosure with a vector in x-direction.

    This can be used for tapers/
    waveguides or similar that are straight.

    Args:
        c: Cell to apply the enclosure to.
        ref: Reference to use as a base for the enclosure.
    """
    return self.apply_minkowski_enc(c, ref=ref, direction=Direction.X)

apply_minkowski_y

apply_minkowski_y(
    c: KCell, ref: LayerInfo | Region | None = None
) -> None

Apply an enclosure with a vector in y-direction.

This can be used for tapers/ waveguides or similar that are straight.

Parameters:

Name Type Description Default
c KCell

Cell to apply the enclosure to.

required
ref LayerInfo | Region | None

Reference to use as a base for the enclosure.

None
Source code in kfactory/enclosure.py
817
818
819
820
821
822
823
824
825
826
827
828
829
def apply_minkowski_y(
    self, c: KCell, ref: kdb.LayerInfo | kdb.Region | None = None
) -> None:
    """Apply an enclosure with a vector in y-direction.

    This can be used for tapers/
    waveguides or similar that are straight.

    Args:
        c: Cell to apply the enclosure to.
        ref: Reference to use as a base for the enclosure.
    """
    return self.apply_minkowski_enc(c, ref=ref, direction=Direction.Y)

extrude_path

extrude_path(
    c: KCell,
    path: list[DPoint],
    main_layer: LayerInfo | None,
    width: float,
    start_angle: float | None = None,
    end_angle: float | None = None,
) -> None

Extrude a path and add it to a main layer.

Start and end angle should be set in relation to the orientation of the path. If the path for example is starting E->W, the start angle should be 0 (if that that is the desired angle). End angle is the same if the end piece is stopping 2nd-last -> last in E->W.

Parameters:

Name Type Description Default
c KCell

The cell where to insert the path to

required
path list[DPoint]

Backbone of the path. [um]

required
main_layer LayerInfo | None

Layer index where to put the main part of the path.

required
width float

Width of the core of the path

required
start_angle float | None

angle of the start piece

None
end_angle float | None

angle of the end piece

None
Source code in kfactory/enclosure.py
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
def extrude_path(
    self,
    c: KCell,
    path: list[kdb.DPoint],
    main_layer: kdb.LayerInfo | None,
    width: float,
    start_angle: float | None = None,
    end_angle: float | None = None,
) -> None:
    """Extrude a path and add it to a main layer.

    Start and end angle should be set in relation to the orientation of the path.
    If the path for example is starting E->W, the start angle should be 0 (if that
    that is the desired angle). End angle is the same if the end
    piece is stopping 2nd-last -> last in E->W.

    Args:
        c: The cell where to insert the path to
        path: Backbone of the path. [um]
        main_layer: Layer index where to put the main part of the path.
        width: Width of the core of the path
        start_angle: angle of the start piece
        end_angle: angle of the end piece
    """
    if main_layer is None:
        raise ValueError(
            "The enclosure doesn't have  a reference `main_layer` defined."
            " Therefore the layer must be defined in calls"
        )
    extrude_path(
        target=c,
        layer=main_layer,
        path=path,
        width=width,
        enclosure=self,
        start_angle=start_angle,
        end_angle=end_angle,
    )

extrude_path_dynamic

extrude_path_dynamic(
    c: KCell,
    path: list[DPoint],
    main_layer: LayerInfo | None,
    widths: Callable[[float], float] | list[float],
) -> None

Extrude a path and add it to a main layer.

Supports a dynamic width of the path defined by a function returning the width for the interval [0,1], or as a list of widths of the same lengths as the points.

Parameters:

Name Type Description Default
c KCell

The cell where to insert the path to

required
path list[DPoint]

Backbone of the path. [um]

required
main_layer LayerInfo | None

Layer index where to put the main part of the path.

required
widths Callable[[float], float] | list[float]

Width of the core of the path

required
Source code in kfactory/enclosure.py
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
def extrude_path_dynamic(
    self,
    c: KCell,
    path: list[kdb.DPoint],
    main_layer: kdb.LayerInfo | None,
    widths: Callable[[float], float] | list[float],
) -> None:
    """Extrude a path and add it to a main layer.

    Supports a dynamic width of the path defined by a function
    returning the width for the interval [0,1], or as a list of
    widths of the same lengths as the points.

    Args:
        c: The cell where to insert the path to
        path: Backbone of the path. [um]
        main_layer: Layer index where to put the main part of the path.
        widths: Width of the core of the path
    """
    if main_layer is None:
        raise ValueError(
            "The enclosure doesn't have  a reference `main_layer` defined."
            " Therefore the layer must be defined in calls"
        )
    extrude_path_dynamic(
        target=c, layer=main_layer, path=path, widths=widths, enclosure=self
    )

minkowski_region

minkowski_region(
    r: Region,
    d: int | None,
    shape: Callable[
        [int], list[Point] | Box | Edge | Polygon
    ],
) -> kdb.Region

Calculaste a region from a minkowski sum.

If the distance is negative, the function will take the inverse region and apply the minkowski and take the inverse again.

Parameters:

Name Type Description Default
r Region

Target region.

required
d int | None

Distance to pass to the shape. Can be any integer. [dbu]

required
shape Callable[[int], list[Point] | Box | Edge | Polygon]

Function returning a shape for the minkowski region.

required
Source code in kfactory/enclosure.py
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
def minkowski_region(
    self,
    r: kdb.Region,
    d: int | None,
    shape: Callable[[int], list[kdb.Point] | kdb.Box | kdb.Edge | kdb.Polygon],
) -> kdb.Region:
    """Calculaste a region from a minkowski sum.

    If the distance is negative, the function will take the inverse region and apply
    the minkowski and take the inverse again.

    Args:
        r: Target region.
        d: Distance to pass to the shape. Can be any integer. [dbu]
        shape: Function returning a shape for the minkowski region.
    """
    if d is None:
        return kdb.Region()
    if d == 0:
        return r.dup()
    if d > 0:
        return r.minkowski_sum(shape(d))
    shape_ = shape(abs(d))
    if isinstance(shape_, list):
        box_shape = kdb.Polygon(cast("list[kdb.Point]", shape_))
        bbox_maxsize = max(
            box_shape.bbox().width(),
            box_shape.bbox().height(),
        )
    else:
        bbox_maxsize = max(
            shape_.bbox().width(),
            shape_.bbox().height(),
        )
    bbox_r = kdb.Region(r.bbox().enlarged(bbox_maxsize))
    return r - (bbox_r - r).minkowski_sum(shape_)

to_dtype

to_dtype(kcl: KCLayout) -> DLayerEnclosure

Convert the enclosure to a um based enclosure.

Source code in kfactory/enclosure.py
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
def to_dtype(self, kcl: KCLayout) -> DLayerEnclosure:
    """Convert the enclosure to a um based enclosure."""
    if self.main_layer is None:
        raise ValueError("um based enclosures must have a main_layer")
    return DLayerEnclosure(
        name=self._name,
        sections=[
            (layer, kcl.to_um(section.d_max))
            if section.d_min is None
            else (layer, kcl.to_um(section.d_min), kcl.to_um(section.d_max))
            for layer, layer_section in self.layer_sections.items()
            for section in layer_section.sections
        ],
        main_layer=self.main_layer,
    )

LayerEnclosureCollection pydantic-model

Bases: BaseModel

Collection of LayerEnclosures.

Fields:

Source code in kfactory/enclosure.py
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
class LayerEnclosureCollection(BaseModel):
    """Collection of LayerEnclosures."""

    enclosures: list[LayerEnclosure]

    def __hash__(self) -> int:
        return hash(tuple(self.enclosures))

    def __getitem__(self, key: str | int) -> LayerEnclosure:
        """Retrieve enclosure by main layer."""
        try:
            return next(filter(lambda enc: enc.main_layer == key, self.enclosures))
        except StopIteration as e:
            raise KeyError(f"Unknown key {key}") from e

__getitem__

__getitem__(key: str | int) -> LayerEnclosure

Retrieve enclosure by main layer.

Source code in kfactory/enclosure.py
1197
1198
1199
1200
1201
1202
def __getitem__(self, key: str | int) -> LayerEnclosure:
    """Retrieve enclosure by main layer."""
    try:
        return next(filter(lambda enc: enc.main_layer == key, self.enclosures))
    except StopIteration as e:
        raise KeyError(f"Unknown key {key}") from e

LayerEnclosureModel

Bases: RootModel[dict[str, LayerEnclosure]]

PDK access model for LayerEnclsoures.

Source code in kfactory/enclosure.py
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
class LayerEnclosureModel(RootModel[dict[str, LayerEnclosure]]):
    """PDK access model for LayerEnclsoures."""

    root: dict[str, LayerEnclosure] = Field(default_factory=dict)

    def __getitem__(self, __key: str, /) -> LayerEnclosure:
        """Retrieve element by string key."""
        return self.root[__key]

    def __getattr__(self, __key: str, /) -> LayerEnclosure:
        """Retrieve attribute by key."""
        return self.root[__key]

    def __setattr__(self, __key: str, /, __val: LayerEnclosure) -> None:
        """Add a new LayerEnclosure."""
        self.root[__key] = __val

    def __setitem__(self, __key: str, /, __val: LayerEnclosure) -> None:
        """Add a new LayerEnclosure."""
        self.root[__key] = __val

    def _canonical_for_unnamed_key(self, unnamed_key: str) -> LayerEnclosure | None:
        """Return the registered enclosure whose structural signature matches."""
        for enc in self.root.values():
            if enc.unnamed_key == unnamed_key:
                return enc
        return None

    def get_enclosure(
        self,
        enclosure: str | LayerEnclosure | LayerEnclosureSpec,
        kcl: KCLayout,
    ) -> LayerEnclosure:
        if isinstance(enclosure, str):
            if enclosure in self.root:
                return self.root[enclosure]
            # Also addressable by the structural (unnamed) key.
            existing = self._canonical_for_unnamed_key(enclosure)
            if existing is not None:
                return existing
            return self.root[enclosure]
        if isinstance(enclosure, dict):
            if "dsections" in enclosure:
                enclosure = LayerEnclosure(
                    dsections=enclosure.get("dsections", []),
                    name=enclosure.get("name"),
                    main_layer=enclosure["main_layer"],
                    kcl=kcl,
                )
            else:
                enclosure = LayerEnclosure(
                    sections=enclosure.get("sections", []),
                    name=enclosure.get("name"),
                    main_layer=enclosure["main_layer"],
                    kcl=kcl,
                )
        enclosure = cast("LayerEnclosure", enclosure)
        key = enclosure.unnamed_key
        existing = self._canonical_for_unnamed_key(key)

        if not enclosure.is_named:
            # Unnamed request: reuse the canonical entry if the signature is known.
            if existing is not None:
                return existing
            self.root[enclosure.name] = enclosure
            return enclosure

        # Named request.
        name = enclosure.name
        if name in self.root:
            # The name is already claimed: preserve the existing (lenient) name-keyed
            # behavior and return the registered enclosure.
            return self.root[name]
        if existing is None:
            self.root[name] = enclosure
            return enclosure
        if existing.is_named:
            raise CrossSectionNamingConflictError(
                f"Cannot register enclosure {name!r}: an enclosure with the same "
                f"structural signature is already registered as {existing.name!r}. "
                "A structure can have at most one name."
            )
        # Promote: the named enclosure replaces the existing unnamed one.
        self.root.pop(existing.name, None)
        self.root[name] = enclosure
        return enclosure

__getattr__

__getattr__(__key: str) -> LayerEnclosure

Retrieve attribute by key.

Source code in kfactory/enclosure.py
1737
1738
1739
def __getattr__(self, __key: str, /) -> LayerEnclosure:
    """Retrieve attribute by key."""
    return self.root[__key]

__getitem__

__getitem__(__key: str) -> LayerEnclosure

Retrieve element by string key.

Source code in kfactory/enclosure.py
1733
1734
1735
def __getitem__(self, __key: str, /) -> LayerEnclosure:
    """Retrieve element by string key."""
    return self.root[__key]

__setattr__

__setattr__(__key: str, /, __val: LayerEnclosure) -> None

Add a new LayerEnclosure.

Source code in kfactory/enclosure.py
1741
1742
1743
def __setattr__(self, __key: str, /, __val: LayerEnclosure) -> None:
    """Add a new LayerEnclosure."""
    self.root[__key] = __val

__setitem__

__setitem__(__key: str, /, __val: LayerEnclosure) -> None

Add a new LayerEnclosure.

Source code in kfactory/enclosure.py
1745
1746
1747
def __setitem__(self, __key: str, /, __val: LayerEnclosure) -> None:
    """Add a new LayerEnclosure."""
    self.root[__key] = __val

LayerSection pydantic-model

Bases: BaseModel

A collection of sections intended for a layer.

Adding a section will trigger an evaluation to merge touching or overlapping sections.

Fields:

Source code in kfactory/enclosure.py
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
class LayerSection(BaseModel):
    """A collection of sections intended for a layer.

    Adding a section will trigger an evaluation to merge
    touching or overlapping sections.
    """

    sections: list[Section] = Field(default_factory=list)

    def add_section(self, sec: Section) -> int:
        """Add a new section.

        Checks for overlaps after.
        """
        if not self.sections:
            self.sections.append(sec)
            return 0
        i = 0
        if sec.d_min is not None:
            while i < len(self.sections) and sec.d_min > self.sections[i].d_max:
                i += 1
            while i < len(self.sections) and sec.d_max >= self.sections[i].d_min:  # ty:ignore[unsupported-operator]
                sec.d_max = max(self.sections[i].d_max, sec.d_max)
                sec.d_min = min(
                    self.sections[i].d_min,  # ty:ignore[invalid-argument-type]
                    sec.d_min,
                )
                self.sections.pop(i)
                if i == len(self.sections):
                    break
        self.sections.insert(i, sec)
        return i

    def max_size(self) -> int:
        """Maximum size of the sections in this layer section."""
        return self.sections[-1].d_max

    def __hash__(self) -> int:
        """Unique hash of LayerSection."""
        return hash(tuple((s.d_min, s.d_max) for s in self.sections))

    def __len__(self) -> int:
        return len(self.sections)

__hash__

__hash__() -> int

Unique hash of LayerSection.

Source code in kfactory/enclosure.py
568
569
570
def __hash__(self) -> int:
    """Unique hash of LayerSection."""
    return hash(tuple((s.d_min, s.d_max) for s in self.sections))

add_section

add_section(sec: Section) -> int

Add a new section.

Checks for overlaps after.

Source code in kfactory/enclosure.py
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
def add_section(self, sec: Section) -> int:
    """Add a new section.

    Checks for overlaps after.
    """
    if not self.sections:
        self.sections.append(sec)
        return 0
    i = 0
    if sec.d_min is not None:
        while i < len(self.sections) and sec.d_min > self.sections[i].d_max:
            i += 1
        while i < len(self.sections) and sec.d_max >= self.sections[i].d_min:  # ty:ignore[unsupported-operator]
            sec.d_max = max(self.sections[i].d_max, sec.d_max)
            sec.d_min = min(
                self.sections[i].d_min,  # ty:ignore[invalid-argument-type]
                sec.d_min,
            )
            self.sections.pop(i)
            if i == len(self.sections):
                break
    self.sections.insert(i, sec)
    return i

max_size

max_size() -> int

Maximum size of the sections in this layer section.

Source code in kfactory/enclosure.py
564
565
566
def max_size(self) -> int:
    """Maximum size of the sections in this layer section."""
    return self.sections[-1].d_max

RegionOperator

Bases: TileOutputReceiver

Region collector. Just getst the tile and inserts it into the target cell.

Source code in kfactory/enclosure.py
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
class RegionOperator(kdb.TileOutputReceiver):
    """Region collector. Just getst the tile and inserts it into the target cell."""

    def __init__(self, cell: KCell, layer: kdb.LayerInfo) -> None:
        """Initialization.

        Args:
            cell: Target cell.
            layer: Target layer.
        """
        self.kcell = cell
        self.layer = layer
        self.region = kdb.Region()

    def put(
        self,
        ix: int,
        iy: int,
        tile: kdb.Box,
        region: kdb.Region,
        dbu: float,
        clip: bool,
    ) -> None:
        """Tiling Processor output call.

        Args:
            ix: x-axis index of tile.
            iy: y_axis index of tile.
            tile: The bounding box of the tile.
            region: The target object of the `klayout.db.TilingProcessor`
            dbu: dbu used by the processor.
            clip: Whether the target was clipped to the tile or not.
        """
        self.region.insert(region)

    @overload
    def insert(self) -> None: ...

    @overload
    def insert(self, port_holes: kdb.Region) -> None: ...

    def insert(
        self,
        port_holes: kdb.Region | None = None,
    ) -> None:
        """Insert the finished region into the cell.

        Args:
            port_holes: Carve out holes around the ports.
        """
        if port_holes:
            self.region -= port_holes
        self.kcell.shapes(self.layer).insert(self.region)

__init__

__init__(cell: KCell, layer: LayerInfo) -> None

Initialization.

Parameters:

Name Type Description Default
cell KCell

Target cell.

required
layer LayerInfo

Target layer.

required
Source code in kfactory/enclosure.py
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
def __init__(self, cell: KCell, layer: kdb.LayerInfo) -> None:
    """Initialization.

    Args:
        cell: Target cell.
        layer: Target layer.
    """
    self.kcell = cell
    self.layer = layer
    self.region = kdb.Region()

insert

insert() -> None
insert(port_holes: Region) -> None
insert(port_holes: Region | None = None) -> None

Insert the finished region into the cell.

Parameters:

Name Type Description Default
port_holes Region | None

Carve out holes around the ports.

None
Source code in kfactory/enclosure.py
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
def insert(
    self,
    port_holes: kdb.Region | None = None,
) -> None:
    """Insert the finished region into the cell.

    Args:
        port_holes: Carve out holes around the ports.
    """
    if port_holes:
        self.region -= port_holes
    self.kcell.shapes(self.layer).insert(self.region)

put

put(
    ix: int,
    iy: int,
    tile: Box,
    region: Region,
    dbu: float,
    clip: bool,
) -> None

Tiling Processor output call.

Parameters:

Name Type Description Default
ix int

x-axis index of tile.

required
iy int

y_axis index of tile.

required
tile Box

The bounding box of the tile.

required
region Region

The target object of the klayout.db.TilingProcessor

required
dbu float

dbu used by the processor.

required
clip bool

Whether the target was clipped to the tile or not.

required
Source code in kfactory/enclosure.py
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
def put(
    self,
    ix: int,
    iy: int,
    tile: kdb.Box,
    region: kdb.Region,
    dbu: float,
    clip: bool,
) -> None:
    """Tiling Processor output call.

    Args:
        ix: x-axis index of tile.
        iy: y_axis index of tile.
        tile: The bounding box of the tile.
        region: The target object of the `klayout.db.TilingProcessor`
        dbu: dbu used by the processor.
        clip: Whether the target was clipped to the tile or not.
    """
    self.region.insert(region)

RegionTilesOperator

Bases: TileOutputReceiver

Region collector. Just getst the tile and inserts it into the target cell.

As it can be used multiple times for the same tile, it needs to merge when inserting.

Source code in kfactory/enclosure.py
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
class RegionTilesOperator(kdb.TileOutputReceiver):
    """Region collector. Just getst the tile and inserts it into the target cell.

    As it can be used multiple times for the same tile, it needs to merge when
    inserting.
    """

    def __init__(
        self,
        cell: KCell,
        layers: list[kdb.LayerInfo],
    ) -> None:
        """Initialization.

        Args:
            cell: Target cell.
            layers: Target layers.
        """
        self.kcell = cell
        self.layers = layers
        self.merged_region: kdb.Region = kdb.Region()
        self.merged = False
        self.regions: dict[int, dict[int, kdb.Region]] = defaultdict(
            lambda: defaultdict(kdb.Region)
        )

    def put(
        self,
        ix: int,
        iy: int,
        tile: kdb.Box,
        region: kdb.Region,
        dbu: float,
        clip: bool,
    ) -> None:
        """Tiling Processor output call.

        Args:
            ix: x-axis index of tile.
            iy: y_axis index of tile.
            tile: The bounding box of the tile.
            region: The target object of the `klayout.db.TilingProcessor`
            dbu: dbu used by the processor.
            clip: Whether the target was clipped to the tile or not.
        """
        self.regions[ix][iy].insert(region)

    def merge_region(self) -> None:
        """Create one region from the individual tiles."""
        for dicts in self.regions.values():
            for reg in dicts.values():
                self.merged_region.insert(reg)

    @overload
    def insert(self) -> None: ...

    @overload
    def insert(self, port_hole_map: dict[kdb.LayerInfo, kdb.Region]) -> None: ...

    def insert(
        self,
        port_hole_map: dict[kdb.LayerInfo, kdb.Region] | None = None,
    ) -> None:
        """Insert the finished region into the cell.

        Args:
            port_hole_map: Carve out holes around the ports.
        """
        if not self.merged:
            self.merge_region()

        if port_hole_map:
            for layer in self.layers:
                self.merged_region -= port_hole_map[layer]
            self.kcell.shapes(layer).insert(self.merged_region)
        else:
            for layer in self.layers:
                self.kcell.shapes(layer).insert(self.merged_region)

__init__

__init__(cell: KCell, layers: list[LayerInfo]) -> None

Initialization.

Parameters:

Name Type Description Default
cell KCell

Target cell.

required
layers list[LayerInfo]

Target layers.

required
Source code in kfactory/enclosure.py
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
def __init__(
    self,
    cell: KCell,
    layers: list[kdb.LayerInfo],
) -> None:
    """Initialization.

    Args:
        cell: Target cell.
        layers: Target layers.
    """
    self.kcell = cell
    self.layers = layers
    self.merged_region: kdb.Region = kdb.Region()
    self.merged = False
    self.regions: dict[int, dict[int, kdb.Region]] = defaultdict(
        lambda: defaultdict(kdb.Region)
    )

insert

insert() -> None
insert(port_hole_map: dict[LayerInfo, Region]) -> None
insert(
    port_hole_map: dict[LayerInfo, Region] | None = None,
) -> None

Insert the finished region into the cell.

Parameters:

Name Type Description Default
port_hole_map dict[LayerInfo, Region] | None

Carve out holes around the ports.

None
Source code in kfactory/enclosure.py
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
def insert(
    self,
    port_hole_map: dict[kdb.LayerInfo, kdb.Region] | None = None,
) -> None:
    """Insert the finished region into the cell.

    Args:
        port_hole_map: Carve out holes around the ports.
    """
    if not self.merged:
        self.merge_region()

    if port_hole_map:
        for layer in self.layers:
            self.merged_region -= port_hole_map[layer]
        self.kcell.shapes(layer).insert(self.merged_region)
    else:
        for layer in self.layers:
            self.kcell.shapes(layer).insert(self.merged_region)

merge_region

merge_region() -> None

Create one region from the individual tiles.

Source code in kfactory/enclosure.py
1355
1356
1357
1358
1359
def merge_region(self) -> None:
    """Create one region from the individual tiles."""
    for dicts in self.regions.values():
        for reg in dicts.values():
            self.merged_region.insert(reg)

put

put(
    ix: int,
    iy: int,
    tile: Box,
    region: Region,
    dbu: float,
    clip: bool,
) -> None

Tiling Processor output call.

Parameters:

Name Type Description Default
ix int

x-axis index of tile.

required
iy int

y_axis index of tile.

required
tile Box

The bounding box of the tile.

required
region Region

The target object of the klayout.db.TilingProcessor

required
dbu float

dbu used by the processor.

required
clip bool

Whether the target was clipped to the tile or not.

required
Source code in kfactory/enclosure.py
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
def put(
    self,
    ix: int,
    iy: int,
    tile: kdb.Box,
    region: kdb.Region,
    dbu: float,
    clip: bool,
) -> None:
    """Tiling Processor output call.

    Args:
        ix: x-axis index of tile.
        iy: y_axis index of tile.
        tile: The bounding box of the tile.
        region: The target object of the `klayout.db.TilingProcessor`
        dbu: dbu used by the processor.
        clip: Whether the target was clipped to the tile or not.
    """
    self.regions[ix][iy].insert(region)

Section pydantic-model

Bases: BaseModel

Section of an Enclosure.

Maximum only Section:
    ┌────────────────────────┐  ▲
    │                        │  │
    │  ┌──────────────────┐  │  │
    │  │                  │  │  │
    │  │    Reference     │  │  │ Section
    │  │                  │  │  │ (d_max only)
    │  └─────────────┬────┘  │  │
    │                │d_max  │  │
    └────────────────▼───────┘  ▼


Minimum & Maximum Section:
    ┌─────────────────┐
    │     Section     │
    │  ┌───────────┐  │
    │  │           │  │
    │  │  ┌─────┐  │◄─┼──d_min
    │  │  │ Ref │  │  │
    │  │  └─────┘  │  │
    │  │           │  │◄─d_max
    │  └───────────┘  │
    │                 │
    └─────────────────┘

Attributes:

Name Type Description
d_min int | None

Start of the section. If None, the section will span all the way between the maxes.

d_max int

the maximum extent of the section from the reference.

Fields:

  • d_min (int | None)
  • d_max (int)
Source code in kfactory/enclosure.py
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
class Section(BaseModel):
    """Section of an Enclosure.

        Maximum only Section:
            ┌────────────────────────┐  ▲
            │                        │  │
            │  ┌──────────────────┐  │  │
            │  │                  │  │  │
            │  │    Reference     │  │  │ Section
            │  │                  │  │  │ (d_max only)
            │  └─────────────┬────┘  │  │
            │                │d_max  │  │
            └────────────────▼───────┘  ▼


        Minimum & Maximum Section:
            ┌─────────────────┐
            │     Section     │
            │  ┌───────────┐  │
            │  │           │  │
            │  │  ┌─────┐  │◄─┼──d_min
            │  │  │ Ref │  │  │
            │  │  └─────┘  │  │
            │  │           │  │◄─d_max
            │  └───────────┘  │
            │                 │
            └─────────────────┘

    Attributes:
        d_min: Start of the section. If `None`,
            the section will span all the way between the maxes.
        d_max: the maximum extent of the section from the reference.
    """

    d_min: int | None = None
    d_max: int

    def __hash__(self) -> int:
        """Hash of the section."""
        return hash((self.d_min, self.d_max))

__hash__

__hash__() -> int

Hash of the section.

Source code in kfactory/enclosure.py
526
527
528
def __hash__(self) -> int:
    """Hash of the section."""
    return hash((self.d_min, self.d_max))

extrude_path

extrude_path(
    target: KCell,
    layer: LayerInfo,
    path: list[DPoint],
    width: float,
    enclosure: LayerEnclosure | None = None,
    start_angle: float | None = None,
    end_angle: float | None = None,
) -> kdb.DPolygon

Extrude a path from a list of points and a static width.

Parameters:

Name Type Description Default
target KCell

the cell where to insert the shapes to (and get the database unit from)

required
layer LayerInfo

the main layer that should be extruded

required
path list[DPoint]

list of floating-points points

required
width float

width in um

required
enclosure LayerEnclosure | None

optional enclosure object, specifying necessary layers.this will extrude around the layer

None
start_angle float | None

optionally specify a custom starting angle if None will be autocalculated from the first two elements

None
end_angle float | None

optionally specify a custom ending angle if None will be autocalculated from the last two elements

None
Source code in kfactory/enclosure.py
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
def extrude_path(
    target: KCell,
    layer: kdb.LayerInfo,
    path: list[kdb.DPoint],
    width: float,
    enclosure: LayerEnclosure | None = None,
    start_angle: float | None = None,
    end_angle: float | None = None,
) -> kdb.DPolygon:
    """Extrude a path from a list of points and a static width.

    Args:
        target: the cell where to insert the shapes to (and get the database unit from)
        layer: the main layer that should be extruded
        path: list of floating-points points
        width: width in um
        enclosure: optional enclosure object, specifying necessary
            layers.this will extrude around the `layer`
        start_angle: optionally specify a custom starting angle if `None`
            will be autocalculated from the first two elements
        end_angle: optionally specify a custom ending angle if `None` will be
            autocalculated from the last two elements
    """
    layer_list = {layer: LayerSection(sections=[Section(d_max=0)])}
    j = 0
    if enclosure is not None:
        if layer not in enclosure.layer_sections:
            layer_list |= enclosure.layer_sections
            j = 0
        else:
            layer_list = enclosure.layer_sections.copy()
            j = layer_list[layer].add_section(Section(d_max=0))

    for _layer, layer_sec in layer_list.items():
        reg = kdb.Region()
        for i, section in enumerate(layer_sec.sections):
            path_ = path_pts_to_polygon(
                *extrude_path_points(
                    path,
                    width + 2 * section.d_max * target.kcl.dbu,
                    start_angle,
                    end_angle,
                )
            )
            r = kdb.Region(target.kcl.to_dbu(path_))
            if section.d_min is not None:
                path_ = path_pts_to_polygon(
                    *extrude_path_points(
                        path,
                        width + 2 * section.d_min * target.kcl.dbu,
                        start_angle,
                        end_angle,
                    )
                )
                r -= kdb.Region(target.kcl.to_dbu(path_))
            reg.insert(r)
            if _layer == layer and i == j:
                ret_path = path_
        target.shapes(target.kcl.layer(_layer)).insert(reg.merge())
    return ret_path

extrude_path_cross_section

extrude_path_cross_section(
    target: KCell,
    path: list[DPoint],
    cross_section: AnyCrossSection,
    start_angle: float | None = None,
    end_angle: float | None = None,
) -> None

Extrude a (symmetric or asymmetric) cross section along a path.

The standard static-width extrusion that takes a cross section instead of a (layer, width, enclosure) triple. Symmetric cross sections are extruded exactly as extrude_path (centered width + enclosure sections — byte-identical output). Asymmetric cross sections are extruded as one signed band [section_min, section_max] per strip (the main strip plus each aux section), so the profile keeps its left/right offsets; strips sharing a layer are merged.

Parameters:

Name Type Description Default
target KCell

the cell where to insert the shapes to (and get the database unit from)

required
path list[DPoint]

list of floating-points points (in um)

required
cross_section AnyCrossSection

the cross section to extrude

required
start_angle float | None

optionally specify a custom starting angle if None will be autocalculated from the first two elements

None
end_angle float | None

optionally specify a custom ending angle if None will be autocalculated from the last two elements

None
Source code in kfactory/enclosure.py
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
def extrude_path_cross_section(
    target: KCell,
    path: list[kdb.DPoint],
    cross_section: AnyCrossSection,
    start_angle: float | None = None,
    end_angle: float | None = None,
) -> None:
    """Extrude a (symmetric or asymmetric) cross section along a path.

    The standard static-width extrusion that takes a cross section instead of a
    ``(layer, width, enclosure)`` triple. Symmetric cross sections are extruded exactly
    as `extrude_path` (centered ``width`` + enclosure sections — byte-identical output).
    Asymmetric cross sections are extruded as one signed band ``[section_min,
    section_max]`` per strip (the main strip plus each aux section), so the profile
    keeps its left/right offsets; strips sharing a layer are merged.

    Args:
        target: the cell where to insert the shapes to (and get the database unit from)
        path: list of floating-points points (in um)
        cross_section: the cross section to extrude
        start_angle: optionally specify a custom starting angle if `None` will
            be autocalculated from the first two elements
        end_angle: optionally specify a custom ending angle if `None` will be
            autocalculated from the last two elements
    """
    from .cross_section import AsymmetricalCrossSection

    if not isinstance(cross_section, AsymmetricalCrossSection):
        # Symmetric: identical to the legacy width + enclosure path.
        extrude_path(
            target,
            cross_section.main_layer,
            path,
            target.kcl.to_um(cross_section.width),
            cross_section.enclosure,
            start_angle,
            end_angle,
        )
        return

    to_um = target.kcl.to_um
    # One signed band [section_min, section_max] per strip; strips merged per layer.
    strips: dict[kdb.LayerInfo, list[tuple[float, float]]] = defaultdict(list)
    strips[cross_section.layer].append(
        (to_um(cross_section.section_min), to_um(cross_section.section_max))
    )
    for sec in cross_section.sections:
        strips[sec.layer].append((to_um(sec.section_min), to_um(sec.section_max)))

    for _layer, bands in strips.items():
        reg = kdb.Region()
        for lo, hi in bands:
            polygon = path_pts_to_polygon(
                *_extrude_path_band_points(path, lo, hi, start_angle, end_angle)
            )
            reg.insert(target.kcl.to_dbu(polygon))
        target.shapes(target.kcl.layer(_layer)).insert(reg.merge())

extrude_path_dynamic

extrude_path_dynamic(
    target: KCell,
    layer: LayerInfo,
    path: list[DPoint],
    widths: Callable[[float], float] | list[float],
    enclosure: LayerEnclosure | None = None,
    start_angle: float | None = None,
    end_angle: float | None = None,
) -> None

Extrude a path with dynamic width.

Extrude from a list of points and a list of widths and add an enclosure if specified.

Parameters:

Name Type Description Default
target KCell

the cell where to insert the shapes to (and get the database unit from)

required
layer LayerInfo

the main layer that should be extruded

required
path list[DPoint]

list of floating-points points

required
widths Callable[[float], float] | list[float]

function (from t==0 to t==1) defining a width profile for the path | list with width for the profile (needs same length as path)

required
enclosure LayerEnclosure | None

optional enclosure object, specifying necessary layers.this will extrude around the layer

None
start_angle float | None

optionally specify a custom starting angle if None will be autocalculated from the first two elements

None
end_angle float | None

optionally specify a custom ending angle if None will be autocalculated from the last two elements

None
Source code in kfactory/enclosure.py
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
def extrude_path_dynamic(
    target: KCell,
    layer: kdb.LayerInfo,
    path: list[kdb.DPoint],
    widths: Callable[[float], float] | list[float],
    enclosure: LayerEnclosure | None = None,
    start_angle: float | None = None,
    end_angle: float | None = None,
) -> None:
    """Extrude a path with dynamic width.

    Extrude from a list of points and a list of widths and add an enclosure if
        specified.

    Args:
        target: the cell where to insert the shapes to (and get the database unit from)
        layer: the main layer that should be extruded
        path: list of floating-points points
        widths: function (from t==0 to t==1) defining a width profile for the path |
            list with width for the profile (needs same length as path)
        enclosure: optional enclosure object, specifying necessary layers.this will
            extrude around the `layer`
        start_angle: optionally specify a custom starting angle if `None` will be
            autocalculated from the first two elements
        end_angle: optionally specify a custom ending angle if `None` will be
            autocalculated from the last two elements
    """
    layer_list = {layer: LayerSection(sections=[Section(d_max=0)])}
    if enclosure is not None:
        if layer not in enclosure.layer_sections:
            layer_list.update(enclosure.layer_sections)
        else:
            layer_list[layer].sections.copy()
            layer_list = enclosure.layer_sections.copy()
            for section in layer_list[layer].sections:
                layer_list[layer].add_section(section)
    if is_callable_widths(widths):
        for layer_, layer_sec in layer_list.items():
            reg = kdb.Region()
            for section in layer_sec.sections:

                def w_max(x: float, section: Section = section) -> float:
                    assert section.d_max is not None
                    return widths(x) + 2 * section.d_max * target.kcl.layout.dbu

                r = kdb.Region(
                    target.kcl.to_dbu(
                        path_pts_to_polygon(
                            *extrude_path_dynamic_points(
                                path,
                                w_max,
                                start_angle,
                                end_angle,
                            )
                        )
                    )
                )
                if section.d_min is not None:

                    def w_min(x: float, section: Section = section) -> float:
                        assert section.d_min is not None
                        return widths(x) + 2 * section.d_min * target.kcl.layout.dbu

                    r -= kdb.Region(
                        target.kcl.to_dbu(
                            path_pts_to_polygon(
                                *extrude_path_dynamic_points(
                                    path,
                                    w_min,
                                    start_angle,
                                    end_angle,
                                )
                            )
                        )
                    )
                reg.insert(r)
            target.shapes(target.kcl.layer(layer_)).insert(reg.merge())

    else:
        for layer_, layer_sec in layer_list.items():
            reg = kdb.Region()
            for section in layer_sec.sections:
                max_widths = [w + 2 * section.d_max * target.kcl.dbu for w in widths]  # ty:ignore[not-iterable]
                r = kdb.Region(
                    target.kcl.to_dbu(
                        path_pts_to_polygon(
                            *extrude_path_dynamic_points(
                                path,
                                max_widths,
                                start_angle,
                                end_angle,
                            )
                        )
                    )
                )
                if section.d_min is not None:
                    min_widths = [
                        w + 2 * section.d_min * target.kcl.dbu
                        for w in widths  # ty:ignore[not-iterable]
                    ]
                    r -= kdb.Region(
                        target.kcl.to_dbu(
                            path_pts_to_polygon(
                                *extrude_path_dynamic_points(
                                    path,
                                    min_widths,
                                    start_angle,
                                    end_angle,
                                )
                            )
                        )
                    )
                reg.insert(r)
            target.shapes(target.kcl.layer(layer_)).insert(reg.merge())

extrude_path_dynamic_points

extrude_path_dynamic_points(
    path: list[DPoint],
    widths: Callable[[float], float] | list[float],
    start_angle: float | None = None,
    end_angle: float | None = None,
) -> tuple[list[kdb.DPoint], list[kdb.DPoint]]

Extrude a profile with a list of points and a list of widths.

Parameters:

Name Type Description Default
path list[DPoint]

list of floating-points points

required
widths Callable[[float], float] | list[float]

function (from t==0 to t==1) defining a width profile for the path | list with width for the profile (needs same length as path)

required
start_angle float | None

optionally specify a custom starting angle if None will be autocalculated from the first two elements

None
end_angle float | None

optionally specify a custom ending angle if None will be autocalculated from the last two elements

None
Source code in kfactory/enclosure.py
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
def extrude_path_dynamic_points(
    path: list[kdb.DPoint],
    widths: Callable[[float], float] | list[float],
    start_angle: float | None = None,
    end_angle: float | None = None,
) -> tuple[list[kdb.DPoint], list[kdb.DPoint]]:
    """Extrude a profile with a list of points and a list of widths.

    Args:
        path: list of floating-points points
        widths: function (from t==0 to t==1) defining a width profile for the path
            | list with width for the profile (needs same length as path)
        start_angle: optionally specify a custom starting angle if `None` will be
            autocalculated from the first two elements
        end_angle: optionally specify a custom ending angle if `None` will be
            autocalculated from the last two elements
    """
    start = path[1] - path[0]
    end = path[-1] - path[-2]
    if start_angle is None:
        start_angle = np.rad2deg(np.arctan2(start.y, start.x))
    if end_angle is None:
        end_angle = np.rad2deg(np.rad2deg(np.arctan2(end.y, end.x)))

    p_start = path[0]
    p_end = path[-1]

    start_trans = kdb.DCplxTrans(1, start_angle, False, p_start.x, p_start.y)
    end_trans = kdb.DCplxTrans(1, end_angle, False, p_end.x, p_end.y)

    if callable(widths):
        length = sum(((p2 - p1).abs() for p2, p1 in itertools.pairwise(path)))
        z: float = 0
        ref_vector = kdb.DCplxTrans(kdb.DVector(0, widths(z / length) / 2))  # ty:ignore[call-top-callable, unsupported-operator]
        vector_top = [start_trans * ref_vector]
        vector_bot = [start_trans * kdb.DCplxTrans.R180 * ref_vector]
        p_old = path[0]
        p = path[1]
        z += (p - p_old).abs()
        for point in path[2:]:
            ref_vector = kdb.DCplxTrans(kdb.DVector(0, widths(z / length) / 2))  # ty:ignore[call-top-callable, unsupported-operator]
            p_new = point
            v = p_new - p_old
            angle = np.rad2deg(np.arctan2(v.y, v.x))
            transformation = kdb.DCplxTrans(1, angle, False, p.x, p.y)
            vector_top.append(transformation * ref_vector)
            vector_bot.append(transformation * kdb.DCplxTrans.R180 * ref_vector)
            z += (p_new - p).abs()
            p_old = p
            p = p_new
        ref_vector = kdb.DCplxTrans(kdb.DVector(0, widths(z / length) / 2))  # ty:ignore[call-top-callable, unsupported-operator]
    else:
        ref_vector = kdb.DCplxTrans(kdb.DVector(0, widths[0] / 2))
        vector_top = [start_trans * ref_vector]
        vector_bot = [start_trans * kdb.DCplxTrans.R180 * ref_vector]
        p_old = path[0]
        p = path[1]
        for point, w in zip(path[2:], widths[1:-1], strict=False):
            ref_vector = kdb.DCplxTrans(kdb.DVector(0, w / 2))
            p_new = point
            v = p_new - p_old
            angle = np.rad2deg(np.arctan2(v.y, v.x))
            transformation = kdb.DCplxTrans(1, angle, False, p.x, p.y)
            vector_top.append(transformation * ref_vector)
            vector_bot.append(transformation * kdb.DCplxTrans.R180 * ref_vector)
            p_old = p
            p = p_new
        ref_vector = kdb.DCplxTrans(kdb.DVector(0, widths[-1] / 2))
    vector_top.append(end_trans * ref_vector)
    vector_bot.append(end_trans * kdb.DCplxTrans.R180 * ref_vector)

    return [v.disp.to_p() for v in vector_top], [v.disp.to_p() for v in vector_bot]

extrude_path_points

extrude_path_points(
    path: Sequence[DPoint],
    width: float,
    start_angle: float | None = None,
    end_angle: float | None = None,
) -> tuple[list[kdb.DPoint], list[kdb.DPoint]]

Extrude a path from a list of points and a static width.

Parameters:

Name Type Description Default
path Sequence[DPoint]

list of floating-points points

required
width float

width in um

required
start_angle float | None

optionally specify a custom starting angle if None will be autocalculated from the first two elements

None
end_angle float | None

optionally specify a custom ending angle if None will be autocalculated from the last two elements

None
Source code in kfactory/enclosure.py
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
def extrude_path_points(
    path: Sequence[kdb.DPoint],
    width: float,
    start_angle: float | None = None,
    end_angle: float | None = None,
) -> tuple[list[kdb.DPoint], list[kdb.DPoint]]:
    """Extrude a path from a list of points and a static width.

    Args:
        path: list of floating-points points
        width: width in um
        start_angle: optionally specify a custom starting angle if `None` will
            be autocalculated from the first two elements
        end_angle: optionally specify a custom ending angle if `None`
            will be autocalculated from the last two elements
    """
    return _extrude_path_band_points(
        path, -width / 2, width / 2, start_angle, end_angle
    )

is_callable_widths

is_callable_widths(
    widths: Callable[[float], float] | list[float],
) -> TypeGuard[Callable[[float], float]]

Determines whether a width object is callable or a list.

Source code in kfactory/enclosure.py
82
83
84
85
86
def is_callable_widths(
    widths: Callable[[float], float] | list[float],
) -> TypeGuard[Callable[[float], float]]:
    """Determines whether a width object is callable or a list."""
    return callable(widths)

path_pts_to_polygon

path_pts_to_polygon(
    pts_top: list[DPoint], pts_bot: list[DPoint]
) -> kdb.DPolygon

Convert a list of points to a polygon.

Source code in kfactory/enclosure.py
89
90
91
92
93
94
def path_pts_to_polygon(
    pts_top: list[kdb.DPoint], pts_bot: list[kdb.DPoint]
) -> kdb.DPolygon:
    """Convert a list of points to a polygon."""
    pts_bot.reverse()
    return kdb.DPolygon(pts_top + pts_bot)