Skip to content

Layout

layout

cell module-attribute

cell = cell

Default kcl @cell decorator.

kcl module-attribute

kcl: KCLayout = KCLayout('DEFAULT')

Default library object.

Any KCell uses this object unless another one is specified in the constructor.

vcell module-attribute

vcell = vcell

Default kcl @vcell decorator.

Constants pydantic-model

Bases: BaseModel

Constant Model class.

Config:

  • arbitrary_types_allowed: True
Source code in kfactory/layout.py
101
102
103
104
class Constants(BaseModel):
    """Constant Model class."""

    model_config = ConfigDict(arbitrary_types_allowed=True)

Factories

Bases: Mapping[str, F]

Source code in kfactory/layout.py
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
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
class Factories[F: WrappedKCellFunc[Any, Any] | WrappedVKCellFunc[Any, Any]](
    Mapping[str, F]
):
    _all: list[F]
    _by_name: dict[str, int]
    _by_tag: defaultdict[str, list[int]]
    _by_function: dict[Callable[..., Any], int]
    _locked: bool

    def __init__(self) -> None:
        self._all = []
        self._by_name = {}
        self._by_tag = defaultdict(list)
        self._by_function = {}
        self._locked = False

    @property
    def locked(self) -> bool:
        """Whether this collection rejects new factories via `add`."""
        return self._locked

    def lock(self) -> None:
        """Prevent further additions through `add`. This is irreversible."""
        self._locked = True

    def add(self, factory: F) -> None:
        if self._locked:
            raise FactoriesLockedError(
                f"Cannot add factory {factory.name!r}: this Factories collection is "
                "locked."
            )
        idx = len(self._all)
        self._all.append(factory)
        for tag in factory.tags:
            self._by_tag[tag].append(idx)
        self._by_name[factory.name] = idx
        self._by_function[factory.__call__] = idx

    def get_by_name(self, name: str) -> F:
        return self._all[self._by_name[name]]

    def is_unique(self) -> bool:
        return len(self._all) == len(self._by_name)

    def rebuild(self) -> None:
        self._by_name = {}
        self._by_tag = defaultdict(list)
        self._by_function = {}

        for idx, factory in enumerate(self._all):
            for tag in factory.tags:
                self._by_tag[tag].append(idx)
            self._by_name[factory.name] = idx
            self._by_function[factory.__call__] = idx

    def get_by_tag(self, tag: str) -> list[F]:
        return [self._all[idx] for idx in self._by_tag[tag]]

    def __iter__(self) -> Iterator[str]:
        return iter(self._by_name)

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

    def __contains__(self, key: Any) -> bool:
        if isinstance(key, str):
            return key in self._by_name
        return key in self._all

    def __getitem__(self, key: str) -> F:
        try:
            return self._all[self._by_name[key]]
        except KeyError as e:
            from rapidfuzz import process

            results = pformat(
                [
                    result[0]
                    for result in process.extract(
                        key, list(self._by_name.keys()), limit=10
                    )
                ]
            )

            raise KeyError(
                f"Unknown Factory {key!r}, closest 10 name matches: {results}"
            ) from e

    @overload
    def get(self, key: str, /) -> F | None: ...

    @overload
    def get(self, key: str, /, default: T) -> F | T: ...

    def get(self, key: str, /, default: T | None = None) -> F | T | None:
        if key in self._by_name:
            return self.get_by_name(key)
        return default

    def get_by_path(self, path: str | Path) -> list[F]:
        p = Path(path).expanduser().resolve()
        return [factory for factory in self._all if p == factory.file]

    def as_dict(self) -> dict[str, F]:
        return {name: self._all[i] for name, i in self._by_name.items()}

locked property

locked: bool

Whether this collection rejects new factories via add.

lock

lock() -> None

Prevent further additions through add. This is irreversible.

Source code in kfactory/layout.py
133
134
135
def lock(self) -> None:
    """Prevent further additions through `add`. This is irreversible."""
    self._locked = True

KCLayout pydantic-model

Bases: BaseModel

Small extension to the klayout.db.Layout.

It adds tracking for the KCell objects instead of only the klayout.db.Cell objects. Additionally it allows creation and registration through create_cell

All attributes of klayout.db.Layout are transparently accessible

Attributes:

Name Type Description
editable

Whether the layout should be opened in editable mode (default: True)

rename_function Callable[..., None]

function that takes an iterable object of ports and renames them

Fields:

  • name (str)
  • layout (Layout)
  • layer_enclosures (LayerEnclosureModel)
  • cross_sections (CrossSectionModel)
  • enclosure (KCellEnclosure)
  • library (Library)
  • factories (Factories[WrappedKCellFunc[Any, ProtoTKCell[Any]]])
  • virtual_factories (Factories[WrappedVKCellFunc[Any, VKCell]])
  • tkcells (dict[int, TKCell])
  • layers (type[LayerEnum])
  • infos (LayerInfos)
  • layer_stack (LayerStack)
  • netlist_layer_mapping (dict[LayerEnum | int, LayerEnum | int])
  • sparameters_path (Path | str | None)
  • interconnect_cml_path (Path | str | None)
  • constants (Constants)
  • rename_function (Callable[..., None])
  • _registered_functions (dict[int, Callable[..., TKCell]])
  • thread_lock (RLock)
  • info (Info)
  • settings (KCellSettings)
  • future_cell_name (str | None)
  • decorators (Decorators)
  • default_cell_output_type (type[KCell | DKCell])
  • default_vcell_output_type (type[VKCell])
  • connectivity (list[tuple[LayerInfo, LayerInfo] | tuple[LayerInfo, LayerInfo, LayerInfo]])
  • routing_strategies (dict[str, Callable[Concatenate[ProtoTKCell[Any], Sequence[Sequence[ProtoPort[Any]]], ...], list[ManhattanRoute]]])
  • technology_file (Path | None)

Validators:

  • _validate_layers
Source code in kfactory/layout.py
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 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
 297
 298
 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
 371
 372
 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
 487
 488
 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
 529
 530
 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
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 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
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
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
1251
1252
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
1306
1307
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
1386
1387
1388
1389
1390
1391
1392
1393
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
1726
1727
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
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
class KCLayout(
    BaseModel, arbitrary_types_allowed=True, extra="allow", validate_assignment=True
):
    """Small extension to the klayout.db.Layout.

    It adds tracking for the [KCell][kfactory.kcell.KCell] objects
    instead of only the `klayout.db.Cell` objects.
    Additionally it allows creation and registration through `create_cell`

    All attributes of `klayout.db.Layout` are transparently accessible

    Attributes:
        editable: Whether the layout should be opened in editable mode (default: True)
        rename_function: function that takes an iterable object of ports and renames
            them
    """

    """Store layers, enclosures, cell functions, simulation_settings ...

    only one Pdk can be active at a given time.

    Attributes:
        name: PDK name.
        enclosures: dict of enclosures factories.
        cells: dict of str mapping to KCells.
        cell_factories: dict of str mapping to cell factories.
        base_pdk: a pdk to copy from and extend.
        default_decorator: decorate all cells, if not otherwise defined on the cell.
        layers: maps name to gdslayer/datatype.
            Must be of type LayerEnum.
        layer_stack: maps name to layer numbers, thickness, zmin, sidewall_angle.
            if can also contain material properties
            (refractive index, nonlinear coefficient, sheet resistance ...).
        sparameters_path: to store Sparameters simulations.
        interconnect_cml_path: path to interconnect CML (optional).
        grid_size: in um. Defaults to 1nm.
        constants: dict of constants for the PDK.

    """
    name: str
    layout: kdb.Layout
    layer_enclosures: LayerEnclosureModel
    cross_sections: CrossSectionModel
    enclosure: KCellEnclosure
    library: kdb.Library

    factories: Factories[WrappedKCellFunc[Any, ProtoTKCell[Any]]]
    virtual_factories: Factories[WrappedVKCellFunc[Any, VKCell]]
    tkcells: dict[int, TKCell] = Field(default_factory=dict)
    layers: type[LayerEnum]
    infos: LayerInfos
    layer_stack: LayerStack
    netlist_layer_mapping: dict[LayerEnum | int, LayerEnum | int] = Field(
        default_factory=dict
    )
    sparameters_path: Path | str | None
    interconnect_cml_path: Path | str | None
    constants: Constants
    rename_function: Callable[..., None]
    _registered_functions: dict[int, Callable[..., TKCell]]
    thread_lock: RLock = Field(default_factory=RLock)

    info: Info = Field(default_factory=Info)
    settings: KCellSettings = Field(frozen=True)
    future_cell_name: str | None

    decorators: Decorators
    default_cell_output_type: type[KCell | DKCell] = KCell
    default_vcell_output_type: type[VKCell] = VKCell

    connectivity: list[
        tuple[kdb.LayerInfo, kdb.LayerInfo]
        | tuple[kdb.LayerInfo, kdb.LayerInfo, kdb.LayerInfo]
    ]

    routing_strategies: dict[
        str,
        Callable[
            Concatenate[
                ProtoTKCell[Any],
                Sequence[Sequence[ProtoPort[Any]]],
                ...,
            ],
            list[ManhattanRoute],
        ],
    ] = Field(default_factory=dict)
    technology_file: Path | None = None

    def __init__(
        self,
        name: str,
        layer_enclosures: dict[str, LayerEnclosure] | LayerEnclosureModel | None = None,
        enclosure: KCellEnclosure | None = None,
        infos: type[LayerInfos] | None = None,
        sparameters_path: Path | str | None = None,
        interconnect_cml_path: Path | str | None = None,
        layer_stack: LayerStack | None = None,
        constants: type[Constants] | None = None,
        base_kcl: KCLayout | None = None,
        port_rename_function: Callable[..., None] = rename_clockwise_multi,
        copy_base_kcl_layers: bool = True,
        info: dict[str, MetaData] | None = None,
        default_cell_output_type: type[KCell | DKCell] = KCell,
        connectivity: Sequence[
            tuple[kdb.LayerInfo, kdb.LayerInfo]
            | tuple[kdb.LayerInfo, kdb.LayerInfo, kdb.LayerInfo]
        ]
        | None = None,
        technology_file: Path | str | None = None,
    ) -> None:
        """Create a new KCLayout (PDK). Can be based on an old KCLayout.

        Args:
            name: Name of the PDK.
            layer_enclosures: Additional KCellEnclosures that should be available
                except the KCellEnclosure
            enclosure: The standard KCellEnclosure of the PDK.
            infos: A LayerInfos describing the layerstack of the PDK.
            sparameters_path: Path to the sparameters config file.
            interconnect_cml_path: Path to the interconnect file.
            layer_stack: maps name to layer numbers, thickness, zmin, sidewall_angle.
                if can also contain material properties
                (refractive index, nonlinear coefficient, sheet resistance ...).
            constants: A model containing all the constants related to the PDK.
            base_kcl: an optional basis of the PDK.
            port_rename_function: Which function to use for renaming kcell ports.
            copy_base_kcl_layers: Copy all known layers from the base if any are
                defined.
            info: Additional metadata to put into info attribute.
        """
        library = kdb.Library()
        layout = library.layout()
        layer_stack = layer_stack or LayerStack()
        constants_ = constants() if constants else Constants()
        infos_ = infos() if infos else LayerInfos()
        if layer_enclosures is not None:
            if isinstance(layer_enclosures, dict):
                layer_enclosures = LayerEnclosureModel(root=layer_enclosures)
        else:
            layer_enclosures = LayerEnclosureModel(root={})
        if technology_file:
            technology_file = Path(technology_file).resolve()
            if not technology_file.is_file():
                raise ValueError(
                    f"{technology_file=} is not an existing file."
                    " Make sure to link it to the .lyt file."
                )
        super().__init__(
            name=name,
            layer_enclosures=layer_enclosures,
            cross_sections=CrossSectionModel(kcl=self),
            enclosure=KCellEnclosure([]),
            infos=infos_,
            layers=LayerEnum,
            factories=Factories[WrappedKCellFunc[Any, ProtoTKCell[Any]]](),
            virtual_factories=Factories[WrappedVKCellFunc[Any, VKCell]](),
            sparameters_path=sparameters_path,
            interconnect_cml_path=interconnect_cml_path,
            constants=constants_,
            library=library,
            layer_stack=layer_stack,
            layout=layout,
            rename_function=port_rename_function,
            info=Info(**info) if info else Info(),
            future_cell_name=None,
            settings=KCellSettings(
                version=__version__,
                klayout_version=kdb.__version__,  # ty:ignore[unresolved-attribute]
                meta_format="v3",
            ),
            decorators=Decorators(self),
            default_cell_output_type=default_cell_output_type,
            connectivity=connectivity or [],
            technology_file=technology_file,
        )

        self.library.register(self.name)

        enclosure = KCellEnclosure(
            enclosures=[enc.model_copy() for enc in enclosure.enclosures.enclosures]
            if enclosure
            else []
        )
        self.sparameters_path = sparameters_path
        self.enclosure = enclosure
        self.interconnect_cml_path = interconnect_cml_path

        kcls[self.name] = self

    @model_validator(mode="before")
    @classmethod
    def _validate_layers(cls, data: dict[str, Any]) -> dict[str, Any]:
        data["layers"] = layerenum_from_dict(
            layers=data["infos"], layout=data["library"].layout()
        )
        data["library"].register(data["name"])
        return data

    @functools.cached_property
    def dkcells(self) -> DKCells:
        """DKCells is a mapping of int to DKCell."""
        return DKCells(self)

    @functools.cached_property
    def kcells(self) -> KCells:
        """KCells is a mapping of int to KCell."""
        return KCells(self)

    @property
    def dbu(self) -> float:
        """Get the database unit."""
        return self.layout.dbu

    @property
    def factories_locked(self) -> bool:
        """Whether both the real and virtual factory collections are locked."""
        return self.factories.locked and self.virtual_factories.locked

    def lock_factories(self) -> None:
        """Prevent further factories (real and virtual) from being registered.

        This is irreversible: once locked, a `KCLayout` will reject any new
        factory registrations (e.g. via `@kcl.cell` / `@kcl.vcell` or direct
        `factories.add` calls). Use this to seal a PDK after registering all
        of its pcell functions.
        """
        self.factories.lock()
        self.virtual_factories.lock()

    def create_layer_enclosure(
        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,
    ) -> LayerEnclosure:
        """Create a new LayerEnclosure in the KCLayout."""
        if name is None and main_layer is not None and main_layer.name != "":
            name = main_layer.name
        enc = LayerEnclosure(
            sections=sections,
            dsections=dsections,
            name=name,
            main_layer=main_layer,
            kcl=self,
        )

        self.layer_enclosures[enc.name] = enc
        return enc

    @cached_property
    def technology(self) -> kdb.Technology:
        if self.technology_file is not None:
            tech = kdb.Technology()
            tech.load(str(self.technology_file))
            kdb.Technology.register_technology(tech)
            return tech
        raise ValueError(f"{self.technology_file} is not a file or is None.")

    @overload
    def find_layer(self, name: str) -> LayerEnum: ...

    @overload
    def find_layer(self, info: kdb.LayerInfo) -> LayerEnum: ...

    @overload
    def find_layer(
        self,
        layer: int,
        datatype: int,
    ) -> LayerEnum: ...

    @overload
    def find_layer(
        self,
        layer: int,
        dataytpe: int,
        name: str,
    ) -> LayerEnum: ...

    @overload
    def find_layer(
        self, name: str, *, allow_undefined_layers: Literal[True] = True
    ) -> LayerEnum | int: ...

    @overload
    def find_layer(
        self, info: kdb.LayerInfo, *, allow_undefined_layers: Literal[True] = True
    ) -> LayerEnum | int: ...

    @overload
    def find_layer(
        self, layer: int, datatype: int, *, allow_undefined_layers: Literal[True] = True
    ) -> LayerEnum | int: ...

    @overload
    def find_layer(
        self,
        layer: int,
        dataytpe: int,
        name: str,
        allow_undefined_layers: Literal[True] = True,
    ) -> LayerEnum | int: ...

    def find_layer(
        self,
        *args: int | str | kdb.LayerInfo,
        **kwargs: int | str | kdb.LayerInfo | bool,
    ) -> LayerEnum | int:
        """Try to find a registered layer. Throws a KeyError if it cannot find it.

        Can find a layer either by name, layer and datatype (two args), LayerInfo, or
        all three of layer, datatype, and name.
        """
        allow_undefined_layers = kwargs.pop(
            "allow_undefined_layers", config.allow_undefined_layers
        )
        info = self.layout.get_info(self.layout.layer(*args, **kwargs))
        try:
            return self.layers[info.name]
        except KeyError as e:
            if allow_undefined_layers:
                return self.layout.layer(info)
            raise KeyError(
                f"Layer '{args=}, {kwargs=}' has not been defined in the KCLayout. "
                "Have you defined the layer and set it in KCLayout.info?"
            ) from e

    @overload
    def to_um(self, other: None) -> None: ...

    @overload
    def to_um(self, other: int) -> float: ...

    @overload
    def to_um(self, other: kdb.Point) -> kdb.DPoint: ...

    @overload
    def to_um(self, other: kdb.Vector) -> kdb.DVector: ...

    @overload
    def to_um(self, other: kdb.Box) -> kdb.DBox: ...

    @overload
    def to_um(self, other: kdb.Polygon) -> kdb.DPolygon: ...

    @overload
    def to_um(self, other: kdb.Path) -> kdb.DPath: ...

    @overload
    def to_um(self, other: kdb.Text) -> kdb.DText: ...

    def to_um(
        self,
        other: int
        | kdb.Point
        | kdb.Vector
        | kdb.Box
        | kdb.Polygon
        | kdb.Path
        | kdb.Text
        | None,
    ) -> (
        float
        | kdb.DPoint
        | kdb.DVector
        | kdb.DBox
        | kdb.DPolygon
        | kdb.DPath
        | kdb.DText
        | None
    ):
        """Convert Shapes or values in dbu to DShapes or floats in um."""
        if other is None:
            return None
        return kdb.CplxTrans(self.layout.dbu) * other

    @overload
    def to_dbu(self, other: None) -> None: ...
    @overload
    def to_dbu(self, other: float) -> int: ...

    @overload
    def to_dbu(self, other: kdb.DPoint) -> kdb.Point: ...

    @overload
    def to_dbu(self, other: kdb.DVector) -> kdb.Vector: ...

    @overload
    def to_dbu(self, other: kdb.DBox) -> kdb.Box: ...

    @overload
    def to_dbu(self, other: kdb.DPolygon) -> kdb.Polygon: ...

    @overload
    def to_dbu(self, other: kdb.DPath) -> kdb.Path: ...

    @overload
    def to_dbu(self, other: kdb.DText) -> kdb.Text: ...

    def to_dbu(
        self,
        other: float
        | kdb.DPoint
        | kdb.DVector
        | kdb.DBox
        | kdb.DPolygon
        | kdb.DPath
        | kdb.DText
        | None,
    ) -> (
        int
        | kdb.Point
        | kdb.Vector
        | kdb.Box
        | kdb.Polygon
        | kdb.Path
        | kdb.Text
        | None
    ):
        """Convert Shapes or values in dbu to DShapes or floats in um."""
        if other is None:
            return None
        return kdb.CplxTrans(self.layout.dbu).inverted() * other

    @overload
    def schematic_cell[**KCellParams](
        self,
        _func: Callable[KCellParams, TSchematic[Any]],
        /,
    ) -> Callable[KCellParams, KCell]: ...

    @overload
    def schematic_cell[**KCellParams](
        self,
        /,
        *,
        set_settings: bool = ...,
        set_name: bool = ...,
        check_ports: bool = ...,
        check_pins: bool = ...,
        check_instances: CheckInstances | None = ...,
        snap_ports: bool = ...,
        add_port_layers: bool = ...,
        cache: Cache[Hashable, Any] | dict[Hashable, Any] | None = ...,
        basename: str | None = ...,
        drop_params: list[str] = ...,
        register_factory: bool = ...,
        overwrite_existing: bool | None = ...,
        layout_cache: bool | None = ...,
        info: dict[str, MetaData] | None = ...,
        debug_names: bool | None = ...,
        tags: list[str] | None = ...,
        factories: Mapping[
            str, Callable[..., KCell] | Callable[..., DKCell] | Callable[..., VKCell]
        ]
        | None = None,
        cross_sections: Mapping[str, CrossSection | DCrossSection] | None = None,
        routing_strategies: dict[
            str,
            Callable[
                Concatenate[
                    ProtoTKCell[Any],
                    Sequence[ProtoPort[Any]],
                    Sequence[ProtoPort[Any]],
                    ...,
                ],
                Any,
            ],
        ]
        | None = None,
    ) -> Callable[
        [Callable[KCellParams, TSchematic[Any]]], Callable[KCellParams, KCell]
    ]: ...

    @overload
    def schematic_cell[**KCellParams](
        self,
        /,
        *,
        set_settings: bool = ...,
        set_name: bool = ...,
        check_ports: bool = ...,
        check_pins: bool = ...,
        check_instances: CheckInstances | None = ...,
        snap_ports: bool = ...,
        add_port_layers: bool = ...,
        cache: Cache[Hashable, Any] | dict[Hashable, Any] | None = ...,
        basename: str | None = ...,
        drop_params: list[str] = ...,
        register_factory: bool = ...,
        overwrite_existing: bool | None = ...,
        layout_cache: bool | None = ...,
        info: dict[str, MetaData] | None = ...,
        post_process: Iterable[Callable[[KCell], None]],
        debug_names: bool | None = ...,
        tags: list[str] | None = ...,
        factories: Mapping[
            str, Callable[..., KCell] | Callable[..., DKCell] | Callable[..., VKCell]
        ]
        | None = None,
        cross_sections: Mapping[str, CrossSection | DCrossSection] | None = None,
        routing_strategies: dict[
            str,
            Callable[
                Concatenate[
                    ProtoTKCell[Any],
                    Sequence[ProtoPort[Any]],
                    Sequence[ProtoPort[Any]],
                    ...,
                ],
                Any,
            ],
        ]
        | None = None,
    ) -> Callable[
        [Callable[KCellParams, TSchematic[Any]]], Callable[KCellParams, KCell]
    ]: ...

    @overload
    def schematic_cell[**KCellParams, KC: ProtoTKCell[Any]](
        self,
        /,
        *,
        output_type: type[KC],
        set_settings: bool = ...,
        set_name: bool = ...,
        check_ports: bool = ...,
        check_pins: bool = ...,
        check_instances: CheckInstances | None = ...,
        snap_ports: bool = ...,
        add_port_layers: bool = ...,
        cache: Cache[Hashable, Any] | dict[Hashable, Any] | None = ...,
        basename: str | None = ...,
        drop_params: list[str] = ...,
        register_factory: bool = ...,
        overwrite_existing: bool | None = ...,
        layout_cache: bool | None = ...,
        info: dict[str, MetaData] | None = ...,
        post_process: Iterable[Callable[[KC], None]],
        debug_names: bool | None = ...,
        tags: list[str] | None = ...,
        factories: Mapping[
            str, Callable[..., KCell] | Callable[..., DKCell] | Callable[..., VKCell]
        ]
        | None = None,
        cross_sections: Mapping[str, CrossSection | DCrossSection] | None = None,
        routing_strategies: dict[
            str,
            Callable[
                Concatenate[
                    ProtoTKCell[Any],
                    Sequence[ProtoPort[Any]],
                    Sequence[ProtoPort[Any]],
                    ...,
                ],
                Any,
            ],
        ]
        | None = None,
    ) -> Callable[
        [Callable[KCellParams, TSchematic[Any]]], Callable[KCellParams, KC]
    ]: ...

    @overload
    def schematic_cell[**KCellParams, KC: ProtoTKCell[Any]](
        self,
        /,
        *,
        output_type: type[KC],
        set_settings: bool = ...,
        set_name: bool = ...,
        check_ports: bool = ...,
        check_pins: bool = ...,
        check_instances: CheckInstances | None = ...,
        snap_ports: bool = ...,
        add_port_layers: bool = ...,
        cache: Cache[Hashable, Any] | dict[Hashable, Any] | None = ...,
        basename: str | None = ...,
        drop_params: list[str] = ...,
        register_factory: bool = ...,
        overwrite_existing: bool | None = ...,
        layout_cache: bool | None = ...,
        info: dict[str, MetaData] | None = ...,
        debug_names: bool | None = ...,
        tags: list[str] | None = ...,
        factories: Mapping[
            str, Callable[..., KCell] | Callable[..., DKCell] | Callable[..., VKCell]
        ]
        | None = None,
        cross_sections: Mapping[str, CrossSection | DCrossSection] | None = None,
        routing_strategies: dict[
            str,
            Callable[
                Concatenate[
                    ProtoTKCell[Any],
                    Sequence[ProtoPort[Any]],
                    Sequence[ProtoPort[Any]],
                    ...,
                ],
                Any,
            ],
        ]
        | None = None,
    ) -> Callable[
        [Callable[KCellParams, TSchematic[Any]]], Callable[KCellParams, KC]
    ]: ...

    def schematic_cell[**KCellParams, KC: ProtoTKCell[Any]](
        self,
        _func: Callable[KCellParams, TSchematic[Any]] | None = None,
        /,
        *,
        output_type: type[KC] | None = None,
        set_settings: bool = True,
        set_name: bool = True,
        check_ports: bool = True,
        check_pins: bool = True,
        check_instances: CheckInstances | None = None,
        snap_ports: bool = True,
        add_port_layers: bool = True,
        cache: Cache[Hashable, Any] | dict[Hashable, Any] | None = None,
        basename: str | None = None,
        drop_params: Sequence[str] = ("self", "cls"),
        register_factory: bool = True,
        overwrite_existing: bool | None = None,
        layout_cache: bool | None = None,
        info: dict[str, MetaData] | None = None,
        post_process: Iterable[Callable[[KC], None]] | None = None,
        debug_names: bool | None = None,
        tags: list[str] | None = None,
        factories: Mapping[
            str, Callable[..., KCell] | Callable[..., DKCell] | Callable[..., VKCell]
        ]
        | None = None,
        cross_sections: Mapping[str, CrossSection | DCrossSection] | None = None,
        routing_strategies: dict[
            str,
            Callable[
                Concatenate[
                    ProtoTKCell[Any],
                    Sequence[Sequence[ProtoPort[Any]]],
                    ...,
                ],
                Any,
            ],
        ]
        | None = None,
    ) -> (
        Callable[KCellParams, KCell]
        | Callable[
            [Callable[KCellParams, TSchematic[Any]]],
            Callable[KCellParams, KC],
        ]
        | Callable[
            [Callable[KCellParams, TSchematic[Any]]],
            Callable[KCellParams, KCell],
        ]
    ):
        if _func is None:
            if output_type is None:

                def wrap_f(
                    f: Callable[KCellParams, TSchematic[Any]],
                ) -> Callable[KCellParams, KCell]:
                    @self.cell(
                        output_type=KCell,
                        set_settings=set_settings,
                        set_name=set_name,
                        check_ports=check_ports,
                        check_pins=check_pins,
                        check_instances=check_instances,
                        snap_ports=snap_ports,
                        add_port_layers=add_port_layers,
                        cache=cache,
                        basename=basename,
                        drop_params=list(drop_params),
                        register_factory=register_factory,
                        overwrite_existing=overwrite_existing,
                        layout_cache=layout_cache,
                        info=info,
                        post_process=cast(
                            "Iterable[Callable[[KCell], None]]", post_process or []
                        ),
                        debug_names=debug_names,
                        tags=tags,
                        schematic_function=f,
                    )
                    @functools.wraps(f)
                    def kcell_func(
                        *args: KCellParams.args, **kwargs: KCellParams.kwargs
                    ) -> KCell:
                        schematic = f(*args, **kwargs)
                        if set_name:
                            schematic.name = self.future_cell_name
                        c_ = schematic.create_cell(
                            KCell,
                            factories=factories,
                            cross_sections=cross_sections,
                            routing_strategies=routing_strategies,
                        )
                        c_.schematic = schematic
                        return c_

                    return kcell_func

                return wrap_f

            post_process = cast("Iterable[Callable[[KC], None]]", post_process or [])

            def custom_wrap_f(
                f: Callable[KCellParams, TSchematic[Any]],
            ) -> Callable[KCellParams, KC]:
                @self.cell(
                    output_type=output_type,
                    set_settings=set_settings,
                    set_name=set_name,
                    check_ports=check_ports,
                    check_pins=check_pins,
                    check_instances=check_instances,
                    snap_ports=snap_ports,
                    add_port_layers=add_port_layers,
                    cache=cache,
                    basename=basename,
                    drop_params=list(drop_params),
                    register_factory=register_factory,
                    overwrite_existing=overwrite_existing,
                    layout_cache=layout_cache,
                    info=info,
                    post_process=post_process,
                    debug_names=debug_names,
                    tags=tags,
                    schematic_function=f,
                )
                @functools.wraps(f)
                def custom_kcell_func(
                    *args: KCellParams.args, **kwargs: KCellParams.kwargs
                ) -> KCell:
                    schematic = f(*args, **kwargs)
                    if set_name:
                        schematic.name = self.future_cell_name
                    c_ = schematic.create_cell(
                        KCell,
                        factories=factories,
                        cross_sections=cross_sections,
                        routing_strategies=routing_strategies,
                    )
                    c_.schematic = schematic
                    return c_

                return custom_kcell_func

            return custom_wrap_f

        def simple_wrap_f(
            f: Callable[KCellParams, TSchematic[Any]],
        ) -> Callable[KCellParams, KCell]:
            @self.cell(output_type=KCell, schematic_function=f)
            @functools.wraps(f)
            def kcell_func(
                *args: KCellParams.args, **kwargs: KCellParams.kwargs
            ) -> KCell:
                schematic = f(*args, **kwargs)
                if set_name:
                    schematic.name = self.future_cell_name
                c_ = schematic.create_cell(
                    KCell,
                    factories=factories,
                    cross_sections=cross_sections,
                    routing_strategies=routing_strategies,
                )
                c_.schematic = schematic
                return c_

            return kcell_func

        return simple_wrap_f(_func)

    @overload
    def cell[**KCellParams, KC: ProtoTKCell[Any]](
        self,
        _func: Callable[KCellParams, KC],
        /,
    ) -> Callable[KCellParams, KC]: ...

    @overload
    def cell[**KCellParams, KC: ProtoTKCell[Any]](
        self,
        /,
        *,
        set_settings: bool = ...,
        set_name: bool = ...,
        check_ports: bool = ...,
        check_pins: bool = ...,
        check_instances: CheckInstances | None = ...,
        check_unnamed_cells: CheckUnnamedCells = ...,
        snap_ports: bool = ...,
        add_port_layers: bool = ...,
        cache: Cache[Hashable, Any] | dict[Hashable, Any] | None = ...,
        basename: str | None = ...,
        drop_params: list[str] = ...,
        register_factory: bool = ...,
        overwrite_existing: bool | None = ...,
        layout_cache: bool | None = ...,
        info: dict[str, MetaData] | None = ...,
        debug_names: bool | None = ...,
        tags: list[str] | None = ...,
        lvs_equivalent_ports: list[list[str]] | None = None,
        ports: PortsDefinition | None = None,
        schematic_function: Callable[KCellParams, TSchematic[Any]],
    ) -> Callable[[Callable[KCellParams, KC]], Callable[KCellParams, KC]]: ...

    @overload
    def cell[**KCellParams, KC: ProtoTKCell[Any]](
        self,
        /,
        *,
        set_settings: bool = ...,
        set_name: bool = ...,
        check_ports: bool = ...,
        check_pins: bool = ...,
        check_instances: CheckInstances | None = ...,
        check_unnamed_cells: CheckUnnamedCells = ...,
        snap_ports: bool = ...,
        add_port_layers: bool = ...,
        cache: Cache[Hashable, Any] | dict[Hashable, Any] | None = ...,
        basename: str | None = ...,
        drop_params: list[str] = ...,
        register_factory: bool = ...,
        overwrite_existing: bool | None = ...,
        layout_cache: bool | None = ...,
        info: dict[str, MetaData] | None = ...,
        debug_names: bool | None = ...,
        tags: list[str] | None = ...,
        lvs_equivalent_ports: list[list[str]] | None = None,
        ports: PortsDefinition | None = None,
        schematic_function: None = None,
    ) -> Callable[[Callable[KCellParams, KC]], Callable[KCellParams, KC]]: ...

    @overload
    def cell[**KCellParams, KC: ProtoTKCell[Any]](
        self,
        /,
        *,
        set_settings: bool = ...,
        set_name: bool = ...,
        check_ports: bool = ...,
        check_pins: bool = ...,
        check_instances: CheckInstances | None = ...,
        check_unnamed_cells: CheckUnnamedCells = ...,
        snap_ports: bool = ...,
        add_port_layers: bool = ...,
        cache: Cache[Hashable, Any] | dict[Hashable, Any] | None = ...,
        basename: str | None = ...,
        drop_params: list[str] = ...,
        register_factory: bool = ...,
        overwrite_existing: bool | None = ...,
        layout_cache: bool | None = ...,
        info: dict[str, MetaData] | None = ...,
        post_process: Iterable[Callable[[KC], None]],
        debug_names: bool | None = ...,
        tags: list[str] | None = ...,
        lvs_equivalent_ports: list[list[str]] | None = None,
        ports: PortsDefinition | None = None,
        schematic_function: Callable[KCellParams, TSchematic[Any]],
    ) -> Callable[[Callable[KCellParams, KC]], Callable[KCellParams, KC]]: ...

    @overload
    def cell[**KCellParams, KC: ProtoTKCell[Any]](
        self,
        /,
        *,
        set_settings: bool = ...,
        set_name: bool = ...,
        check_ports: bool = ...,
        check_pins: bool = ...,
        check_instances: CheckInstances | None = ...,
        check_unnamed_cells: CheckUnnamedCells = ...,
        snap_ports: bool = ...,
        add_port_layers: bool = ...,
        cache: Cache[Hashable, Any] | dict[Hashable, Any] | None = ...,
        basename: str | None = ...,
        drop_params: list[str] = ...,
        register_factory: bool = ...,
        overwrite_existing: bool | None = ...,
        layout_cache: bool | None = ...,
        info: dict[str, MetaData] | None = ...,
        post_process: Iterable[Callable[[KC], None]],
        debug_names: bool | None = ...,
        tags: list[str] | None = ...,
        lvs_equivalent_ports: list[list[str]] | None = None,
        ports: PortsDefinition | None = None,
        schematic_function: None = None,
    ) -> Callable[[Callable[KCellParams, KC]], Callable[KCellParams, KC]]: ...

    @overload
    def cell[**KCellParams, KC: ProtoTKCell[Any]](
        self,
        /,
        *,
        output_type: type[KC],
        set_settings: bool = ...,
        set_name: bool = ...,
        check_ports: bool = ...,
        check_pins: bool = ...,
        check_instances: CheckInstances | None = ...,
        check_unnamed_cells: CheckUnnamedCells = ...,
        snap_ports: bool = ...,
        add_port_layers: bool = ...,
        cache: Cache[Hashable, Any] | dict[Hashable, Any] | None = ...,
        basename: str | None = ...,
        drop_params: list[str] = ...,
        register_factory: bool = ...,
        overwrite_existing: bool | None = ...,
        layout_cache: bool | None = ...,
        info: dict[str, MetaData] | None = ...,
        post_process: Iterable[Callable[[KC], None]],
        debug_names: bool | None = ...,
        tags: list[str] | None = ...,
        lvs_equivalent_ports: list[list[str]] | None = None,
        ports: PortsDefinition | None = None,
        schematic_function: Callable[KCellParams, TSchematic[Any]],
    ) -> Callable[
        [Callable[KCellParams, ProtoTKCell[Any]]], Callable[KCellParams, KC]
    ]: ...

    @overload
    def cell[**KCellParams, KC: ProtoTKCell[Any]](
        self,
        /,
        *,
        output_type: type[KC],
        set_settings: bool = ...,
        set_name: bool = ...,
        check_ports: bool = ...,
        check_pins: bool = ...,
        check_instances: CheckInstances | None = ...,
        check_unnamed_cells: CheckUnnamedCells = ...,
        snap_ports: bool = ...,
        add_port_layers: bool = ...,
        cache: Cache[Hashable, Any] | dict[Hashable, Any] | None = ...,
        basename: str | None = ...,
        drop_params: list[str] = ...,
        register_factory: bool = ...,
        overwrite_existing: bool | None = ...,
        layout_cache: bool | None = ...,
        info: dict[str, MetaData] | None = ...,
        post_process: Iterable[Callable[[KC], None]],
        debug_names: bool | None = ...,
        tags: list[str] | None = ...,
        lvs_equivalent_ports: list[list[str]] | None = None,
        ports: PortsDefinition | None = None,
        schematic_function: None = None,
    ) -> Callable[
        [Callable[KCellParams, ProtoTKCell[Any]]], Callable[KCellParams, KC]
    ]: ...

    @overload
    def cell[**KCellParams, KC: ProtoTKCell[Any]](
        self,
        /,
        *,
        output_type: type[KC],
        set_settings: bool = ...,
        set_name: bool = ...,
        check_ports: bool = ...,
        check_pins: bool = ...,
        check_instances: CheckInstances | None = ...,
        check_unnamed_cells: CheckUnnamedCells = ...,
        snap_ports: bool = ...,
        add_port_layers: bool = ...,
        cache: Cache[Hashable, Any] | dict[Hashable, Any] | None = ...,
        basename: str | None = ...,
        drop_params: list[str] = ...,
        register_factory: bool = ...,
        overwrite_existing: bool | None = ...,
        layout_cache: bool | None = ...,
        info: dict[str, MetaData] | None = ...,
        debug_names: bool | None = ...,
        tags: list[str] | None = ...,
        lvs_equivalent_ports: list[list[str]] | None = None,
        ports: PortsDefinition | None = None,
        schematic_function: Callable[KCellParams, TSchematic[Any]],
    ) -> Callable[
        [Callable[KCellParams, ProtoTKCell[Any]]], Callable[KCellParams, KC]
    ]: ...

    @overload
    def cell[**KCellParams, KC: ProtoTKCell[Any]](
        self,
        /,
        *,
        output_type: type[KC],
        set_settings: bool = ...,
        set_name: bool = ...,
        check_ports: bool = ...,
        check_pins: bool = ...,
        check_instances: CheckInstances | None = ...,
        check_unnamed_cells: CheckUnnamedCells = ...,
        snap_ports: bool = ...,
        add_port_layers: bool = ...,
        cache: Cache[Hashable, Any] | dict[Hashable, Any] | None = ...,
        basename: str | None = ...,
        drop_params: list[str] = ...,
        register_factory: bool = ...,
        overwrite_existing: bool | None = ...,
        layout_cache: bool | None = ...,
        info: dict[str, MetaData] | None = ...,
        debug_names: bool | None = ...,
        tags: list[str] | None = ...,
        lvs_equivalent_ports: list[list[str]] | None = None,
        ports: PortsDefinition | None = None,
        schematic_function: None = None,
    ) -> Callable[
        [Callable[KCellParams, ProtoTKCell[Any]]], Callable[KCellParams, KC]
    ]: ...

    def cell[**KCellParams, KC: ProtoTKCell[Any]](
        self,
        _func: Callable[KCellParams, ProtoTKCell[Any]] | None = None,
        /,
        *,
        output_type: type[KC] | None = None,
        set_settings: bool = True,
        set_name: bool = True,
        check_ports: bool = True,
        check_pins: bool = True,
        check_instances: CheckInstances | None = None,
        check_unnamed_cells: CheckUnnamedCells | None = None,
        snap_ports: bool = True,
        add_port_layers: bool = True,
        cache: Cache[Hashable, Any] | dict[Hashable, Any] | None = None,
        basename: str | None = None,
        drop_params: Sequence[str] = ("self", "cls"),
        register_factory: bool = True,
        overwrite_existing: bool | None = None,
        layout_cache: bool | None = None,
        info: dict[str, MetaData] | None = None,
        post_process: Iterable[Callable[[KC], None]] | None = None,
        debug_names: bool | None = None,
        tags: list[str] | None = None,
        lvs_equivalent_ports: list[list[str]] | None = None,
        ports: PortsDefinition | None = None,
        schematic_function: Callable[KCellParams, TSchematic[Any]] | None = None,
    ) -> (
        Callable[KCellParams, KC]
        | Callable[
            [Callable[KCellParams, ProtoTKCell[Any]]],
            Callable[KCellParams, KC],
        ]
    ):
        """Decorator to cache and auto name the cell.

        This will use `functools.cache` to cache the function call.
        Additionally, if enabled this will set the name and from the args/kwargs of the
        function and also paste them into a settings dictionary of the
        [KCell][kfactory.kcell.KCell].

        Args:
            output_type: The type of the cell to return.
            set_settings: Copy the args & kwargs into the settings dictionary
            set_name: Auto create the name of the cell to the functionname plus a
                string created from the args/kwargs
            check_ports: Check uniqueness of port names.
            check_pins: Check uniqueness of pin names.
            check_instances: Check for any complex instances. A complex instance is a an
                instance that has a magnification != 1 or non-90° rotation.
                Depending on the setting, an error is raised, the cell is flattened,
                a VInstance is created instead of a regular instance, or they are
                ignored.
            check_unnamed_cells: Check for unnamed child cells (matching
                ``Unnamed_\\d+``). ``"error"`` raises, ``"warning"`` logs a warning,
                ``"ignore"`` skips the check.
            snap_ports: Snap the centers of the ports onto the grid
                (only x/y, not angle).
            add_port_layers: Add special layers of `KCLayout.netlist_layer_mapping`
                to the ports if the port layer is in the mapping.
            cache: Provide a user defined cache instead of an internal one. This
                can be used for example to clear the cache.
                expensive if the cell is called often).
            basename: Overwrite the name normally inferred from the function or class
                name.
            drop_params: Drop these parameters before writing the
                [settings][kfactory.kcell.KCell.settings]
            register_factory: Register the resulting KCell-function to the
                `KCLayout.factories`
            layout_cache: If true, treat the layout like a cache, if a cell with the
                same name exists already, pick that one instead of using running the
                function. This only works if `set_name` is true. Can be globally
                configured through `config.cell_layout_cache`.
            overwrite_existing: If cells were created with the same name, delete other
                cells with the same name. Can be globally configured through
                `config.cell_overwrite_existing`.
            info: Additional metadata to put into info attribute.
            post_process: List of functions to call after the cell has been created.
            debug_names: Check on setting the name whether a cell with this name already
                exists.
            tags: Tag cell functions with user defined tags.
        Returns:
            A wrapped cell function which caches responses and modifies the cell
            according to settings.
        """
        if check_instances is None:
            check_instances = config.check_instances
        if check_unnamed_cells is None:
            check_unnamed_cells = config.check_unnamed_cells
        if overwrite_existing is None:
            overwrite_existing = config.cell_overwrite_existing
        if layout_cache is None:
            layout_cache = config.cell_layout_cache
        if debug_names is None:
            debug_names = config.debug_names
        if post_process is None:
            post_process = []

        def decorator_autocell(
            f: Callable[KCellParams, KCIN],
        ) -> Callable[KCellParams, KC]:
            sig = inspect.signature(f)
            if output_type is not None:
                output_cell_type_: type[KC | ProtoTKCell[Any]] = output_type
            elif sig.return_annotation is not inspect.Signature.empty:
                # Use get_type_hints to resolve string annotations
                try:
                    type_hints = get_type_hints(f, globalns=f.__globals__)  # ty:ignore[unresolved-attribute]
                    output_cell_type_ = type_hints.get("return", sig.return_annotation)

                except Exception:
                    # Fallback to raw annotation if get_type_hints fails
                    logger.opt(depth=2).warning(
                        "Cannot determine output type ((D)KCell type)"
                        f"from annotation {sig.return_annotation!r}. "
                        "Trying to continue but likely this will fail.",
                    )
                    output_cell_type_ = sig.return_annotation
            else:
                output_cell_type_ = self.default_cell_output_type

            output_cell_type__ = cast("type[KC]", output_cell_type_)

            cache_: Cache[Hashable, Any] | dict[Hashable, Any] = cache or Cache(
                maxsize=float("inf")
            )
            wrapper_autocell: WrappedKCellFunc[KCellParams, KC] = WrappedKCellFunc[
                KCellParams, KC
            ](
                kcl=self,
                f=f,
                sig=sig,
                output_type=output_cell_type__,
                cache=cache_,
                set_settings=set_settings,
                set_name=set_name,
                check_ports=check_ports,
                check_pins=check_pins,
                check_instances=check_instances,
                check_unnamed_cells=check_unnamed_cells,
                snap_ports=snap_ports,
                add_port_layers=add_port_layers,
                basename=basename,
                drop_params=drop_params,
                overwrite_existing=overwrite_existing,
                layout_cache=layout_cache,
                info=info,
                post_process=post_process,  # ty:ignore[invalid-argument-type]
                debug_names=debug_names,
                tags=tags,
                lvs_equivalent_ports=lvs_equivalent_ports,
                ports=ports,
                schematic_function=schematic_function,
            )

            if register_factory:
                with self.thread_lock:
                    if wrapper_autocell.name is None:
                        raise ValueError(f"Function {f} has no name.")
                    self.factories.add(wrapper_autocell)

            @functools.wraps(f)
            def func(*args: KCellParams.args, **kwargs: KCellParams.kwargs) -> KC:
                return wrapper_autocell(*args, **kwargs)

            return func

        return decorator_autocell if _func is None else decorator_autocell(_func)

    @overload
    def vcell[**KCellParams, VK: VKCell](
        self,
        _func: Callable[KCellParams, VK],
        /,
    ) -> Callable[KCellParams, VK]: ...

    @overload
    def vcell[**KCellParams, VK: VKCell](
        self,
        /,
        *,
        set_settings: bool = True,
        set_name: bool = True,
        add_port_layers: bool = True,
        cache: Cache[Hashable, Any] | dict[Hashable, Any] | None = None,
        basename: str | None = None,
        drop_params: Sequence[str] = ("self", "cls"),
        register_factory: bool = True,
        info: dict[str, MetaData] | None = None,
        check_ports: bool = True,
        check_pins: bool = True,
        check_unnamed_cells: CheckUnnamedCells = ...,
        tags: list[str] | None = None,
        lvs_equivalent_ports: list[list[str]] | None = None,
        ports: PortsDefinition | None = None,
    ) -> Callable[[Callable[KCellParams, VK]], Callable[KCellParams, VK]]: ...

    @overload
    def vcell[**KCellParams, VK: VKCell](
        self,
        /,
        *,
        set_settings: bool = True,
        set_name: bool = True,
        add_port_layers: bool = True,
        cache: Cache[Hashable, Any] | dict[Hashable, Any] | None = None,
        basename: str | None = None,
        drop_params: Sequence[str] = ("self", "cls"),
        register_factory: bool = True,
        post_process: Iterable[Callable[[VKCell], None]],
        info: dict[str, MetaData] | None = None,
        check_ports: bool = True,
        check_pins: bool = True,
        check_unnamed_cells: CheckUnnamedCells = ...,
        tags: list[str] | None = None,
        lvs_equivalent_ports: list[list[str]] | None = None,
        ports: PortsDefinition | None = None,
    ) -> Callable[[Callable[KCellParams, VK]], Callable[KCellParams, VK]]: ...

    @overload
    def vcell[**KCellParams, VK: VKCell](
        self,
        /,
        *,
        output_type: type[VK],
        set_settings: bool = True,
        set_name: bool = True,
        add_port_layers: bool = True,
        cache: Cache[Hashable, Any] | dict[Hashable, Any] | None = None,
        basename: str | None = None,
        drop_params: Sequence[str] = ("self", "cls"),
        register_factory: bool = True,
        info: dict[str, MetaData] | None = None,
        check_ports: bool = True,
        check_pins: bool = True,
        check_unnamed_cells: CheckUnnamedCells = ...,
        tags: list[str] | None = None,
        lvs_equivalent_ports: list[list[str]] | None = None,
        ports: PortsDefinition | None = None,
    ) -> Callable[[Callable[KCellParams, VKCell]], Callable[KCellParams, VK]]: ...

    @overload
    def vcell[**KCellParams, VK: VKCell](
        self,
        /,
        *,
        output_type: type[VK],
        set_settings: bool = True,
        set_name: bool = True,
        add_port_layers: bool = True,
        cache: Cache[Hashable, Any] | dict[Hashable, Any] | None = None,
        basename: str | None = None,
        drop_params: Sequence[str] = ("self", "cls"),
        register_factory: bool = True,
        post_process: Iterable[Callable[[VKCell], None]],
        info: dict[str, MetaData] | None = None,
        check_ports: bool = True,
        check_pins: bool = True,
        check_unnamed_cells: CheckUnnamedCells = ...,
        tags: list[str] | None = None,
        lvs_equivalent_ports: list[list[str]] | None = None,
        ports: PortsDefinition | None = None,
    ) -> Callable[[Callable[KCellParams, VKCell]], Callable[KCellParams, VK]]: ...

    def vcell[**KCellParams, VK: VKCell](
        self,
        _func: Callable[KCellParams, VKCell] | None = None,
        /,
        *,
        output_type: type[VK] | None = None,
        set_settings: bool = True,
        set_name: bool = True,
        add_port_layers: bool = True,
        cache: Cache[Hashable, Any] | dict[Hashable, Any] | None = None,
        basename: str | None = None,
        drop_params: Sequence[str] = ("self", "cls"),
        register_factory: bool = True,
        post_process: Iterable[Callable[[VKCell], None]] | None = None,
        info: dict[str, MetaData] | None = None,
        check_ports: bool = True,
        check_pins: bool = True,
        check_unnamed_cells: CheckUnnamedCells = CheckUnnamedCells.WARNING,
        tags: list[str] | None = None,
        lvs_equivalent_ports: list[list[str]] | None = None,
        ports: PortsDefinition | None = None,
    ) -> (
        Callable[KCellParams, VK]
        | Callable[[Callable[KCellParams, VK]], Callable[KCellParams, VK]]
    ):
        """Decorator to cache and auto name the cell.

        This will use `functools.cache` to cache the function call.
        Additionally, if enabled this will set the name and from the args/kwargs of the
        function and also paste them into a settings dictionary of the
        [KCell][kfactory.kcell.KCell].

        Args:
            set_settings: Copy the args & kwargs into the settings dictionary
            set_name: Auto create the name of the cell to the functionname plus a
                string created from the args/kwargs
            check_ports: Check uniqueness of port names.
            check_pins: Check uniqueness of pin names.
            check_unnamed_cells: Check for unnamed child cells (matching
                ``Unnamed_\\d+``). ``"error"`` raises, ``"warning"`` logs a warning,
                ``"ignore"`` skips the check.
            add_port_layers: Add special layers of `KCLayout.netlist_layer_mapping`
                to the ports if the port layer is in the mapping.
            cache: Provide a user defined cache instead of an internal one. This
                can be used for example to clear the cache.
            basename: Overwrite the name normally inferred from the function or class
                name.
            drop_params: Drop these parameters before writing the
                [settings][kfactory.kcell.KCell.settings]
            register_factory: Register the resulting KCell-function to the
                `KCLayout.factories`
            info: Additional metadata to put into info attribute.
            post_process: List of functions to call after the cell has been created.
        Returns:
            A wrapped vcell function which caches responses and modifies the VKCell
            according to settings.
        """
        if check_unnamed_cells is None:
            check_unnamed_cells = config.check_unnamed_cells
        if post_process is None:
            post_process = ()

        def decorator_autocell(
            f: Callable[KCellParams, VKCell],
        ) -> Callable[KCellParams, VK]:
            sig = inspect.signature(f)
            output_cell_type_: type[VK | VKCell]
            if output_type is not None:
                output_cell_type_ = output_type
            elif sig.return_annotation is not inspect.Signature.empty:
                # Use get_type_hints to resolve string annotations
                try:
                    type_hints = get_type_hints(f, globalns=f.__globals__)  # ty:ignore[unresolved-attribute]
                    output_cell_type_ = type_hints.get("return", sig.return_annotation)

                except Exception:
                    # Fallback to raw annotation if get_type_hints fails
                    logger.opt(depth=2).warning(
                        "Cannot determine output type ((D)KCell type)"
                        f"from annotation {sig.return_annotation!r}. "
                        "Trying to continue but likely this will fail.",
                    )
                    output_cell_type_ = sig.return_annotation
            else:
                output_cell_type_ = self.default_vcell_output_type

            output_cell_type__ = cast("type[VK]", output_cell_type_)
            # previously was a KCellCache, but dict should do for most case
            cache_: Cache[Hashable, VK] | dict[Hashable, VK] = cache or Cache(
                maxsize=float("inf")
            )

            wrapper_autocell = WrappedVKCellFunc(
                kcl=self,
                f=f,
                sig=sig,
                cache=cache_,
                set_settings=set_settings,
                set_name=set_name,
                add_port_layers=add_port_layers,
                basename=basename,
                drop_params=drop_params,
                post_process=post_process,
                output_type=output_cell_type__,
                info=info,
                check_ports=check_ports,
                check_pins=check_pins,
                check_unnamed_cells=check_unnamed_cells,
                tags=tags,
                lvs_equivalent_ports=lvs_equivalent_ports,
                ports=ports,
            )

            if register_factory:
                if wrapper_autocell.name is None:
                    raise ValueError(f"Function {f} has no name.")
                self.virtual_factories.add(wrapper_autocell)  # ty:ignore[invalid-argument-type]

            @functools.wraps(f)
            def func(*args: KCellParams.args, **kwargs: KCellParams.kwargs) -> VK:
                return wrapper_autocell(*args, **kwargs)

            return func

        return decorator_autocell if _func is None else decorator_autocell(_func)

    def kcell(self, name: str | None = None, ports: Ports | None = None) -> KCell:
        """Create a new cell based ont he pdk's layout object."""
        return KCell(name=name, kcl=self, ports=ports)

    def dkcell(self, name: str | None = None, ports: DPorts | None = None) -> DKCell:
        """Create a new cell based ont he pdk's layout object."""
        return DKCell(name=name, kcl=self, ports=ports)

    def vkcell(self, name: str | None = None) -> VKCell:
        """Create a new cell based ont he pdk's layout object."""
        return VKCell(name=name, kcl=self)

    def set_layers_from_infos(self, name: str, layers: LayerInfos) -> type[LayerEnum]:
        """Create a new LAYER enum based on the pdk's kcl."""
        return layerenum_from_dict(name=name, layers=layers, layout=self.layout)

    def __getattr__(self, name: str) -> Any:
        """If KCLayout doesn't have an attribute, look in the KLayout Cell."""
        if name != "_name" and name not in self.__class__.model_fields:
            return self.layout.__getattribute__(name)
        return None

    def __setattr__(self, name: str, value: Any) -> None:
        """Use a custom setter to automatically set attributes.

        If the attribute is not in this object, set it on the
        Layout object.
        """
        if name in self.__class__.model_fields:
            super().__setattr__(name, value)
        elif hasattr(self.layout, name):
            self.layout.__setattr__(name, value)

    def layerenum_from_dict(
        self, name: str = "LAYER", *, layers: LayerInfos
    ) -> type[LayerEnum]:
        """Create a new [LayerEnum][kfactory.kcell.LayerEnum] from this KCLayout."""
        return layerenum_from_dict(layers=layers, name=name, layout=self.layout)

    def clear(self, keep_layers: bool = True) -> None:
        """Clear the Layout.

        If the layout is cleared, all the LayerEnums and
        """
        for c in self.layout.cells("*"):
            c.locked = False
        self.layout.clear()
        self.tkcells = {}

        if keep_layers:
            self.layers = self.layerenum_from_dict(layers=self.infos)
        else:
            self.layers = self.layerenum_from_dict(layers=LayerInfos())

    def dup(self, init_cells: bool = True) -> KCLayout:
        """Create a duplication of the `~KCLayout` object.

        Args:
            init_cells: initialize the all cells in the new KCLayout object

        Returns:
            Copy of itself
        """
        kcl = KCLayout(self.name + "_DUPLICATE")
        kcl.layout.assign(self.layout.dup())
        if init_cells:
            for i, kc in self.tkcells.items():
                kcl.tkcells[i] = kc.model_copy(
                    update={"kdb_cell": kc.kdb_cell, "kcl": kcl}
                )
        kcl.rename_function = self.rename_function
        return kcl

    def layout_cell(self, name: str | int) -> kdb.Cell | None:
        """Get a cell by name or index from the Layout object."""
        return self.layout.cell(name)

    @overload
    def cells(self, name: str) -> list[kdb.Cell]: ...

    @overload
    def cells(self) -> int: ...

    def cells(self, name: str | None = None) -> int | list[kdb.Cell]:
        if name is None:
            return self.layout.cells()
        return self.layout.cells(name)

    def create_cell(
        self,
        name: str,
        *args: str,
        allow_duplicate: bool = False,
    ) -> kdb.Cell:
        """Create a new cell in the library.

        This shouldn't be called manually.
        The constructor of KCell will call this method.

        Args:
            name: The (initial) name of the cell.
            allow_duplicate: Allow the creation of a cell with the same name which
                already is registered in the Layout.
                This will create a cell with the name `name` + `$1` or `2..n`
                increasing by the number of existing duplicates
            args: additional arguments passed to
                `klayout.db.Layout.create_cell`

        Returns:
            klayout.db.Cell: klayout.db.Cell object created in the Layout

        """
        with self.thread_lock:
            if allow_duplicate or (self.layout_cell(name) is None):
                return self.layout.create_cell(name, *args)
            raise ValueError(
                f"Cellname {name} already exists in the layout/KCLayout. "
                "Please make sure the cellname is"
                " unique or pass `allow_duplicate` when creating the library"
            )

    def delete_cell(self, cell: AnyTKCell | int) -> None:
        """Delete a cell in the kcl object."""
        with self.thread_lock:
            if isinstance(cell, int):
                self.layout.cell(cell).locked = False
                self.layout.delete_cell(cell)
                self.tkcells.pop(cell, None)
            else:
                ci = cell.cell_index()
                self.layout.cell(ci).locked = False
                self.layout.delete_cell(ci)
                self.tkcells.pop(ci, None)

    def delete_cell_rec(self, cell_index: int) -> None:
        """Deletes a KCell plus all subcells."""
        with self.thread_lock:
            self.layout.delete_cell_rec(cell_index)
            self.rebuild()

    def delete_cells(self, cell_index_list: Sequence[int]) -> None:
        """Delete a sequence of cell by indexes."""
        with self.thread_lock:
            for ci in cell_index_list:
                self.layout.cell(ci).locked = False
                self.tkcells.pop(ci, None)
            self.layout.delete_cells(cell_index_list)
            self.rebuild()

    def assign(self, layout: kdb.Layout) -> None:
        """Assign a new Layout object to the KCLayout object."""
        with self.thread_lock:
            self.layout.assign(layout)
            self.rebuild()

    def rebuild(self) -> None:
        """Rebuild the KCLayout based on the Layout object."""
        kcells2delete: list[int] = []
        with self.thread_lock:
            for ci, c in self.tkcells.items():
                if c.kdb_cell._destroyed():
                    kcells2delete.append(ci)

            for ci in kcells2delete:
                del self.tkcells[ci]

            for cell in self.cells("*"):
                if cell.cell_index() not in self.tkcells:
                    self.tkcells[cell.cell_index()] = self.get_cell(
                        cell.cell_index(), KCell
                    ).base

    def register_cell(self, kcell: AnyTKCell, allow_reregister: bool = False) -> None:
        """Register an existing cell in the KCLayout object.

        Args:
            kcell: KCell 56 be registered in the KCLayout
            allow_reregister: Overwrite the existing KCell registration with this one.
                Doesn't allow name duplication.
        """
        with self.thread_lock:
            if (kcell.cell_index() not in self.tkcells) or allow_reregister:
                self.tkcells[kcell.cell_index()] = kcell.base
            else:
                raise ValueError(
                    f"Cannot register {kcell} if it has been registered already"
                    " exists in the library"
                )

    def __getitem__(self, obj: str | int) -> KCell:
        """Retrieve a cell by name(str) or index(int).

        Attrs:
            obj: name of cell or cell_index
        """
        return self.get_cell(obj)

    def get_cell[KC: ProtoTKCell[Any]](
        self,
        obj: str | int,
        cell_type: type[KC] = KCell,  # ty:ignore[invalid-parameter-default]
        error_search_limit: int | None = 10,
    ) -> KC:
        """Retrieve a cell by name(str) or index(int).

        Attrs:
            obj: name of cell or cell_index
            cell_type: type of cell to return
        """
        if isinstance(obj, int):
            # search by index
            try:
                return cell_type(base=self.tkcells[obj])
            except KeyError:
                kdb_c = self.layout_cell(obj)
                if kdb_c is None:
                    raise
                return cell_type(name=kdb_c.name, kcl=self, kdb_cell=kdb_c)
        # search by name/key
        kdb_c = self.layout_cell(obj)
        if kdb_c is not None:
            try:
                return cell_type(base=self.tkcells[kdb_c.cell_index()])
            except KeyError:
                c = cell_type(name=kdb_c.name, kcl=self, kdb_cell=kdb_c)
                c.get_meta_data()
                return c
        if error_search_limit:
            # limit the print of available cells
            # and throw closest names with fuzzy search
            from rapidfuzz import process

            closest_names = [
                result[0]
                for result in process.extract(
                    obj,
                    (cell.name for cell in self.kcells.values()),
                    limit=error_search_limit,
                )
            ]
            raise ValueError(
                f"Library doesn't have a KCell named {obj},"
                f" closest {error_search_limit} are: \n"
                f"{pformat(closest_names)}"
            )

        raise ValueError(
            f"Library doesn't have a KCell named {obj},"
            " available KCells are"
            f"{pformat(sorted([cell.name for cell in self.kcells.values()]))}"
        )

    def read(
        self,
        filename: str | Path,
        options: kdb.LoadLayoutOptions | None = None,
        register_cells: bool | None = None,
        test_merge: bool = True,
        update_kcl_meta_data: Literal["overwrite", "skip", "drop"] = "skip",
        meta_format: Literal["v1", "v2", "v3"] | None = None,
    ) -> kdb.LayerMap:
        """Read a GDS file into the existing Layout.

        Any existing meta info (KCell.info and KCell.settings) will be overwritten if
        a KCell already exists. Instead of overwriting the cells, they can also be
        loaded into new cells by using the corresponding cell_conflict_resolution.

        This will fail if any of the read cells try to load into a locked KCell.

        Layout meta infos are ignored from the loaded layout.

        Args:
            filename: Path of the GDS file.
            options: KLayout options to load from the GDS. Can determine how merge
                conflicts are handled for example. See
                https://www.klayout.de/doc-qt5/code/class_LoadLayoutOptions.html
            register_cells: If `True` create KCells for all cells in the GDS.
            test_merge: Check the layouts first whether they are compatible
                (no differences).
            update_kcl_meta_data: How to treat loaded KCLayout info.
                overwrite: overwrite existing info entries
                skip: keep existing info values
                drop: don't add any new info
            meta_format: How to read KCell metainfo from the gds. `v1` had stored port
                transformations as strings, never versions have them stored and loaded
                in their native KLayout formats.
        """
        if options is None:
            options = load_layout_options()
        with self.thread_lock:
            if meta_format is None:
                meta_format = config.meta_format
            if register_cells is None:
                register_cells = meta_format == config.meta_format
            layout_b = kdb.Layout()
            layout_b.read(str(filename), options)
            if (
                self.cells() > 0
                and test_merge
                and (
                    options.cell_conflict_resolution
                    != kdb.LoadLayoutOptions.CellConflictResolution.RenameCell
                )
            ):
                self.set_meta_data()
                for kcell in self.kcells.values():
                    kcell.set_meta_data()
                diff = MergeDiff(
                    layout_a=self.layout,
                    layout_b=layout_b,
                    name_a=self.name,
                    name_b=Path(filename).stem,
                )
                diff.compare()
                if diff.dbu_differs:
                    raise MergeError(
                        "Layouts' DBU differ. Check the log for more info."
                    )
                if diff.diff_xor.cells() > 0:
                    diff_kcl = KCLayout(self.name + "_XOR")
                    diff_kcl.layout.assign(diff.diff_xor)
                    show(diff_kcl)

                    err_msg = (
                        f"Layout {self.name} cannot merge with layout "
                        f"{Path(filename).stem} safely. See the error messages "
                        f"or check with KLayout."
                    )

                    if diff.layout_meta_diff:
                        yaml = ruamel.yaml.YAML(typ=["rt", "string"])
                        err_msg += (
                            "\nLayout Meta Diff:\n```\n"
                            + yaml.dumps(dict(diff.layout_meta_diff))  # ty:ignore[unresolved-attribute]
                            + "\n```"
                        )
                    if diff.cells_meta_diff:
                        yaml = ruamel.yaml.YAML(typ=["rt", "string"])
                        err_msg += (
                            "\nLayout Meta Diff:\n```\n"
                            + yaml.dumps(dict(diff.cells_meta_diff))  # ty:ignore[unresolved-attribute]
                            + "\n```"
                        )

                    raise MergeError(err_msg)

            cells = set(self.cells("*"))
            saveopts = save_layout_options()
            saveopts.gds2_max_cellname_length = (
                kdb.SaveLayoutOptions().gds2_max_cellname_length
            )
            binary_layout = layout_b.write_bytes(saveopts)
            locked_cells = [
                kdb_cell for kdb_cell in self.layout.each_cell() if kdb_cell.locked
            ]
            for kdb_cell in locked_cells:
                kdb_cell.locked = False
            lm = self.layout.read_bytes(binary_layout, options)
            for kdb_cell in locked_cells:
                kdb_cell.locked = True
            info, settings = self.get_meta_data()

            match update_kcl_meta_data:
                case "overwrite":
                    for k, v in info.items():
                        self.info[k] = v
                case "skip":
                    info_ = self.info.model_dump()

                    info.update(info_)
                    self.info = Info(**info)

                case "drop":
                    pass
                case _:
                    raise ValueError(
                        f"Unknown meta update strategy {update_kcl_meta_data=}"
                        ", available strategies are 'overwrite', 'skip', or 'drop'"
                    )
            meta_format = settings.get("meta_format") or config.meta_format
            load_cells = {
                cell
                for c in layout_b.cells("*")
                if (cell := self.layout_cell(c.name)) is not None
            }
            new_cells = load_cells - cells

            if register_cells:
                for c in sorted(new_cells, key=lambda _c: _c.hierarchy_levels()):
                    kc = KCell(kdb_cell=c, kcl=self)
                    kc.get_meta_data(
                        meta_format=meta_format,
                    )

            for c in load_cells & cells:
                kc = self.kcells[c.cell_index()]
                kc.get_meta_data(meta_format=meta_format)

            return lm

    def get_meta_data(self) -> tuple[dict[str, Any], dict[str, Any]]:
        """Read KCLayout meta info from the KLayout object."""
        settings: dict[str, Any] = {}
        info: dict[str, Any] = {}
        cross_sections: list[dict[str, Any]] = []
        for meta in self.layout.each_meta_info():
            if meta.name.startswith("kfactory:info"):
                info[meta.name.removeprefix("kfactory:info:")] = meta.value
            elif meta.name.startswith("kfactory:settings"):
                settings[meta.name.removeprefix("kfactory:settings:")] = meta.value
            elif meta.name.startswith("kfactory:layer_enclosure:"):
                self.get_enclosure(
                    LayerEnclosure(
                        **meta.value,
                    )
                )
            elif meta.name.startswith("kfactory:cross_section:"):
                cross_sections.append(
                    {
                        "name": meta.name.removeprefix("kfactory:cross_section:"),
                        **meta.value,
                    }
                )

        for cs in cross_sections:
            self.get_symmetrical_cross_section(
                SymmetricalCrossSection(
                    width=cs["width"],
                    enclosure=self.get_enclosure(cs["layer_enclosure"]),
                    name=cs["name"],
                )
            )

        return info, settings

    def set_meta_data(self) -> None:
        """Set the info/settings of the KCLayout."""
        if config.write_kfactory_settings:
            for name, setting in self.settings.model_dump().items():
                self.add_meta_info(
                    kdb.LayoutMetaInfo(f"kfactory:settings:{name}", setting, None, True)
                )
        for name, info in self.info.model_dump().items():
            self.add_meta_info(
                kdb.LayoutMetaInfo(f"kfactory:info:{name}", info, None, True)
            )
        for enclosure in self.layer_enclosures.root.values():
            self.add_meta_info(
                kdb.LayoutMetaInfo(
                    f"kfactory:layer_enclosure:{enclosure.name}",
                    enclosure.model_dump(),
                    None,
                    True,
                )
            )
        for cross_section in self.cross_sections.cross_sections.values():
            self.add_meta_info(
                kdb.LayoutMetaInfo(
                    f"kfactory:cross_section:{cross_section.name}",
                    {
                        "width": cross_section.width,
                        "layer_enclosure": cross_section.enclosure.name,
                    },
                    None,
                    True,
                )
            )

    def write(
        self,
        filename: str | Path,
        options: kdb.SaveLayoutOptions | None = None,
        set_meta_data: bool = True,
        convert_external_cells: bool = False,
        autoformat_from_file_extension: bool = True,
    ) -> None:
        """Write a GDS file into the existing Layout.

        Args:
            filename: Path of the GDS file.
            options: KLayout options to load from the GDS. Can determine how merge
                conflicts are handled for example. See
                https://www.klayout.de/doc-qt5/code/class_LoadLayoutOptions.html
            set_meta_data: Make sure all the cells have their metadata set
            convert_external_cells: Whether to make KCells not in this KCLayout to
            autoformat_from_file_extension: Set the format of the output file
                automatically from the file extension of `filename`. This is necessary
                for the options. If not set, this will default to `GDSII`.
        """
        if options is None:
            options = save_layout_options()
        if isinstance(filename, Path):
            filename = str(filename.resolve())
        for kc in list(self.kcells.values()):
            kc.insert_vinsts()
        match (set_meta_data, convert_external_cells):
            case (True, True):
                self.set_meta_data()
                for kcell in self.kcells.values():
                    if not kcell.destroyed():
                        kcell.set_meta_data()
                        if kcell.is_library_cell():
                            kcell.convert_to_static(recursive=True)
            case (True, False):
                self.set_meta_data()
                for kcell in self.kcells.values():
                    if not kcell.destroyed():
                        kcell.set_meta_data()
            case (False, True):
                for kcell in self.kcells.values():
                    if kcell.is_library_cell() and not kcell.destroyed():
                        kcell.convert_to_static(recursive=True)

        if autoformat_from_file_extension:
            options.set_format_from_filename(filename)

        return self.layout.write(filename, options)

    def top_kcells(self) -> list[KCell]:
        """Return the top KCells."""
        return [self[tc.cell_index()] for tc in self.top_cells()]

    def top_kcell(self) -> KCell:
        """Return the top KCell if there is a single one."""
        return self[self.top_cell().cell_index()]

    def clear_kcells(self) -> None:
        """Clears all cells in the Layout object."""
        for kc in self.kcells.values():
            kc.locked = False
        for tc in self.top_kcells():
            tc.kdb_cell.prune_cell()
        self.tkcells = {}

    def get_enclosure(
        self, enclosure: str | LayerEnclosure | LayerEnclosureSpec
    ) -> LayerEnclosure:
        """Gets a layer enclosure by name specification or the layerenclosure itself."""
        return self.layer_enclosures.get_enclosure(enclosure, self)

    def get_symmetrical_cross_section(
        self,
        cross_section: str
        | SymmetricalCrossSection
        | CrossSectionSpec
        | DCrossSectionSpec
        | DSymmetricalCrossSection,
    ) -> SymmetricalCrossSection:
        """Get a cross section by name or specification."""
        return self.cross_sections.get_cross_section(cross_section)

    def get_icross_section(
        self,
        cross_section: str
        | SymmetricalCrossSection
        | CrossSectionSpec
        | DCrossSectionSpec
        | DCrossSection
        | DSymmetricalCrossSection
        | CrossSection,
    ) -> CrossSection:
        """Get a cross section by name or specification."""
        return CrossSection(
            kcl=self, base=self.cross_sections.get_cross_section(cross_section)
        )

    def get_dcross_section(
        self,
        cross_section: str
        | SymmetricalCrossSection
        | CrossSectionSpec
        | DCrossSectionSpec
        | DSymmetricalCrossSection
        | CrossSection
        | DCrossSection,
    ) -> DCrossSection:
        """Get a cross section by name or specification."""
        return DCrossSection(
            kcl=self, base=self.cross_sections.get_cross_section(cross_section)
        )

    def __repr__(self) -> str:
        return f"{self.__class__.__name__}({self.name}, n={len(self.kcells)})"

    def delete(self) -> None:
        del kcls[self.name]
        self.library.delete()

    def routing_strategy(
        self,
        f: Callable[
            Concatenate[
                ProtoTKCell[Any],
                Sequence[Sequence[ProtoPort[Any]]],
                ...,
            ],
            list[ManhattanRoute],
        ],
    ) -> Callable[
        Concatenate[
            ProtoTKCell[Any],
            Sequence[Sequence[ProtoPort[Any]]],
            ...,
        ],
        list[ManhattanRoute],
    ]:
        self.routing_strategies[get_function_name(f)] = f
        return f

dbu property

dbu: float

Get the database unit.

dkcells cached property

dkcells: DKCells

DKCells is a mapping of int to DKCell.

factories_locked property

factories_locked: bool

Whether both the real and virtual factory collections are locked.

kcells cached property

kcells: KCells

KCells is a mapping of int to KCell.

__getattr__

__getattr__(name: str) -> Any

If KCLayout doesn't have an attribute, look in the KLayout Cell.

Source code in kfactory/layout.py
1647
1648
1649
1650
1651
def __getattr__(self, name: str) -> Any:
    """If KCLayout doesn't have an attribute, look in the KLayout Cell."""
    if name != "_name" and name not in self.__class__.model_fields:
        return self.layout.__getattribute__(name)
    return None

__getitem__

__getitem__(obj: str | int) -> KCell

Retrieve a cell by name(str) or index(int).

Attrs

obj: name of cell or cell_index

Source code in kfactory/layout.py
1820
1821
1822
1823
1824
1825
1826
def __getitem__(self, obj: str | int) -> KCell:
    """Retrieve a cell by name(str) or index(int).

    Attrs:
        obj: name of cell or cell_index
    """
    return self.get_cell(obj)

__init__

__init__(
    name: str,
    layer_enclosures: dict[str, LayerEnclosure]
    | LayerEnclosureModel
    | None = None,
    enclosure: KCellEnclosure | None = None,
    infos: type[LayerInfos] | None = None,
    sparameters_path: Path | str | None = None,
    interconnect_cml_path: Path | str | None = None,
    layer_stack: LayerStack | None = None,
    constants: type[Constants] | None = None,
    base_kcl: KCLayout | None = None,
    port_rename_function: Callable[
        ..., None
    ] = rename_clockwise_multi,
    copy_base_kcl_layers: bool = True,
    info: dict[str, MetaData] | None = None,
    default_cell_output_type: type[KCell | DKCell] = KCell,
    connectivity: Sequence[
        tuple[LayerInfo, LayerInfo]
        | tuple[LayerInfo, LayerInfo, LayerInfo]
    ]
    | None = None,
    technology_file: Path | str | None = None,
) -> None

Create a new KCLayout (PDK). Can be based on an old KCLayout.

Parameters:

Name Type Description Default
name str

Name of the PDK.

required
layer_enclosures dict[str, LayerEnclosure] | LayerEnclosureModel | None

Additional KCellEnclosures that should be available except the KCellEnclosure

None
enclosure KCellEnclosure | None

The standard KCellEnclosure of the PDK.

None
infos type[LayerInfos] | None

A LayerInfos describing the layerstack of the PDK.

None
sparameters_path Path | str | None

Path to the sparameters config file.

None
interconnect_cml_path Path | str | None

Path to the interconnect file.

None
layer_stack LayerStack | None

maps name to layer numbers, thickness, zmin, sidewall_angle. if can also contain material properties (refractive index, nonlinear coefficient, sheet resistance ...).

None
constants type[Constants] | None

A model containing all the constants related to the PDK.

None
base_kcl KCLayout | None

an optional basis of the PDK.

None
port_rename_function Callable[..., None]

Which function to use for renaming kcell ports.

rename_clockwise_multi
copy_base_kcl_layers bool

Copy all known layers from the base if any are defined.

True
info dict[str, MetaData] | None

Additional metadata to put into info attribute.

None
Source code in kfactory/layout.py
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
371
372
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
def __init__(
    self,
    name: str,
    layer_enclosures: dict[str, LayerEnclosure] | LayerEnclosureModel | None = None,
    enclosure: KCellEnclosure | None = None,
    infos: type[LayerInfos] | None = None,
    sparameters_path: Path | str | None = None,
    interconnect_cml_path: Path | str | None = None,
    layer_stack: LayerStack | None = None,
    constants: type[Constants] | None = None,
    base_kcl: KCLayout | None = None,
    port_rename_function: Callable[..., None] = rename_clockwise_multi,
    copy_base_kcl_layers: bool = True,
    info: dict[str, MetaData] | None = None,
    default_cell_output_type: type[KCell | DKCell] = KCell,
    connectivity: Sequence[
        tuple[kdb.LayerInfo, kdb.LayerInfo]
        | tuple[kdb.LayerInfo, kdb.LayerInfo, kdb.LayerInfo]
    ]
    | None = None,
    technology_file: Path | str | None = None,
) -> None:
    """Create a new KCLayout (PDK). Can be based on an old KCLayout.

    Args:
        name: Name of the PDK.
        layer_enclosures: Additional KCellEnclosures that should be available
            except the KCellEnclosure
        enclosure: The standard KCellEnclosure of the PDK.
        infos: A LayerInfos describing the layerstack of the PDK.
        sparameters_path: Path to the sparameters config file.
        interconnect_cml_path: Path to the interconnect file.
        layer_stack: maps name to layer numbers, thickness, zmin, sidewall_angle.
            if can also contain material properties
            (refractive index, nonlinear coefficient, sheet resistance ...).
        constants: A model containing all the constants related to the PDK.
        base_kcl: an optional basis of the PDK.
        port_rename_function: Which function to use for renaming kcell ports.
        copy_base_kcl_layers: Copy all known layers from the base if any are
            defined.
        info: Additional metadata to put into info attribute.
    """
    library = kdb.Library()
    layout = library.layout()
    layer_stack = layer_stack or LayerStack()
    constants_ = constants() if constants else Constants()
    infos_ = infos() if infos else LayerInfos()
    if layer_enclosures is not None:
        if isinstance(layer_enclosures, dict):
            layer_enclosures = LayerEnclosureModel(root=layer_enclosures)
    else:
        layer_enclosures = LayerEnclosureModel(root={})
    if technology_file:
        technology_file = Path(technology_file).resolve()
        if not technology_file.is_file():
            raise ValueError(
                f"{technology_file=} is not an existing file."
                " Make sure to link it to the .lyt file."
            )
    super().__init__(
        name=name,
        layer_enclosures=layer_enclosures,
        cross_sections=CrossSectionModel(kcl=self),
        enclosure=KCellEnclosure([]),
        infos=infos_,
        layers=LayerEnum,
        factories=Factories[WrappedKCellFunc[Any, ProtoTKCell[Any]]](),
        virtual_factories=Factories[WrappedVKCellFunc[Any, VKCell]](),
        sparameters_path=sparameters_path,
        interconnect_cml_path=interconnect_cml_path,
        constants=constants_,
        library=library,
        layer_stack=layer_stack,
        layout=layout,
        rename_function=port_rename_function,
        info=Info(**info) if info else Info(),
        future_cell_name=None,
        settings=KCellSettings(
            version=__version__,
            klayout_version=kdb.__version__,  # ty:ignore[unresolved-attribute]
            meta_format="v3",
        ),
        decorators=Decorators(self),
        default_cell_output_type=default_cell_output_type,
        connectivity=connectivity or [],
        technology_file=technology_file,
    )

    self.library.register(self.name)

    enclosure = KCellEnclosure(
        enclosures=[enc.model_copy() for enc in enclosure.enclosures.enclosures]
        if enclosure
        else []
    )
    self.sparameters_path = sparameters_path
    self.enclosure = enclosure
    self.interconnect_cml_path = interconnect_cml_path

    kcls[self.name] = self

__setattr__

__setattr__(name: str, value: Any) -> None

Use a custom setter to automatically set attributes.

If the attribute is not in this object, set it on the Layout object.

Source code in kfactory/layout.py
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
def __setattr__(self, name: str, value: Any) -> None:
    """Use a custom setter to automatically set attributes.

    If the attribute is not in this object, set it on the
    Layout object.
    """
    if name in self.__class__.model_fields:
        super().__setattr__(name, value)
    elif hasattr(self.layout, name):
        self.layout.__setattr__(name, value)

assign

assign(layout: Layout) -> None

Assign a new Layout object to the KCLayout object.

Source code in kfactory/layout.py
1780
1781
1782
1783
1784
def assign(self, layout: kdb.Layout) -> None:
    """Assign a new Layout object to the KCLayout object."""
    with self.thread_lock:
        self.layout.assign(layout)
        self.rebuild()

cell

cell(
    _func: Callable[KCellParams, KC],
) -> Callable[KCellParams, KC]
cell(
    *,
    set_settings: bool = ...,
    set_name: bool = ...,
    check_ports: bool = ...,
    check_pins: bool = ...,
    check_instances: CheckInstances | None = ...,
    check_unnamed_cells: CheckUnnamedCells = ...,
    snap_ports: bool = ...,
    add_port_layers: bool = ...,
    cache: Cache[Hashable, Any]
    | dict[Hashable, Any]
    | None = ...,
    basename: str | None = ...,
    drop_params: list[str] = ...,
    register_factory: bool = ...,
    overwrite_existing: bool | None = ...,
    layout_cache: bool | None = ...,
    info: dict[str, MetaData] | None = ...,
    debug_names: bool | None = ...,
    tags: list[str] | None = ...,
    lvs_equivalent_ports: list[list[str]] | None = None,
    ports: PortsDefinition | None = None,
    schematic_function: Callable[
        KCellParams, TSchematic[Any]
    ],
) -> Callable[
    [Callable[KCellParams, KC]], Callable[KCellParams, KC]
]
cell(
    *,
    set_settings: bool = ...,
    set_name: bool = ...,
    check_ports: bool = ...,
    check_pins: bool = ...,
    check_instances: CheckInstances | None = ...,
    check_unnamed_cells: CheckUnnamedCells = ...,
    snap_ports: bool = ...,
    add_port_layers: bool = ...,
    cache: Cache[Hashable, Any]
    | dict[Hashable, Any]
    | None = ...,
    basename: str | None = ...,
    drop_params: list[str] = ...,
    register_factory: bool = ...,
    overwrite_existing: bool | None = ...,
    layout_cache: bool | None = ...,
    info: dict[str, MetaData] | None = ...,
    debug_names: bool | None = ...,
    tags: list[str] | None = ...,
    lvs_equivalent_ports: list[list[str]] | None = None,
    ports: PortsDefinition | None = None,
    schematic_function: None = None,
) -> Callable[
    [Callable[KCellParams, KC]], Callable[KCellParams, KC]
]
cell(
    *,
    set_settings: bool = ...,
    set_name: bool = ...,
    check_ports: bool = ...,
    check_pins: bool = ...,
    check_instances: CheckInstances | None = ...,
    check_unnamed_cells: CheckUnnamedCells = ...,
    snap_ports: bool = ...,
    add_port_layers: bool = ...,
    cache: Cache[Hashable, Any]
    | dict[Hashable, Any]
    | None = ...,
    basename: str | None = ...,
    drop_params: list[str] = ...,
    register_factory: bool = ...,
    overwrite_existing: bool | None = ...,
    layout_cache: bool | None = ...,
    info: dict[str, MetaData] | None = ...,
    post_process: Iterable[Callable[[KC], None]],
    debug_names: bool | None = ...,
    tags: list[str] | None = ...,
    lvs_equivalent_ports: list[list[str]] | None = None,
    ports: PortsDefinition | None = None,
    schematic_function: Callable[
        KCellParams, TSchematic[Any]
    ],
) -> Callable[
    [Callable[KCellParams, KC]], Callable[KCellParams, KC]
]
cell(
    *,
    set_settings: bool = ...,
    set_name: bool = ...,
    check_ports: bool = ...,
    check_pins: bool = ...,
    check_instances: CheckInstances | None = ...,
    check_unnamed_cells: CheckUnnamedCells = ...,
    snap_ports: bool = ...,
    add_port_layers: bool = ...,
    cache: Cache[Hashable, Any]
    | dict[Hashable, Any]
    | None = ...,
    basename: str | None = ...,
    drop_params: list[str] = ...,
    register_factory: bool = ...,
    overwrite_existing: bool | None = ...,
    layout_cache: bool | None = ...,
    info: dict[str, MetaData] | None = ...,
    post_process: Iterable[Callable[[KC], None]],
    debug_names: bool | None = ...,
    tags: list[str] | None = ...,
    lvs_equivalent_ports: list[list[str]] | None = None,
    ports: PortsDefinition | None = None,
    schematic_function: None = None,
) -> Callable[
    [Callable[KCellParams, KC]], Callable[KCellParams, KC]
]
cell(
    *,
    output_type: type[KC],
    set_settings: bool = ...,
    set_name: bool = ...,
    check_ports: bool = ...,
    check_pins: bool = ...,
    check_instances: CheckInstances | None = ...,
    check_unnamed_cells: CheckUnnamedCells = ...,
    snap_ports: bool = ...,
    add_port_layers: bool = ...,
    cache: Cache[Hashable, Any]
    | dict[Hashable, Any]
    | None = ...,
    basename: str | None = ...,
    drop_params: list[str] = ...,
    register_factory: bool = ...,
    overwrite_existing: bool | None = ...,
    layout_cache: bool | None = ...,
    info: dict[str, MetaData] | None = ...,
    post_process: Iterable[Callable[[KC], None]],
    debug_names: bool | None = ...,
    tags: list[str] | None = ...,
    lvs_equivalent_ports: list[list[str]] | None = None,
    ports: PortsDefinition | None = None,
    schematic_function: Callable[
        KCellParams, TSchematic[Any]
    ],
) -> Callable[
    [Callable[KCellParams, ProtoTKCell[Any]]],
    Callable[KCellParams, KC],
]
cell(
    *,
    output_type: type[KC],
    set_settings: bool = ...,
    set_name: bool = ...,
    check_ports: bool = ...,
    check_pins: bool = ...,
    check_instances: CheckInstances | None = ...,
    check_unnamed_cells: CheckUnnamedCells = ...,
    snap_ports: bool = ...,
    add_port_layers: bool = ...,
    cache: Cache[Hashable, Any]
    | dict[Hashable, Any]
    | None = ...,
    basename: str | None = ...,
    drop_params: list[str] = ...,
    register_factory: bool = ...,
    overwrite_existing: bool | None = ...,
    layout_cache: bool | None = ...,
    info: dict[str, MetaData] | None = ...,
    post_process: Iterable[Callable[[KC], None]],
    debug_names: bool | None = ...,
    tags: list[str] | None = ...,
    lvs_equivalent_ports: list[list[str]] | None = None,
    ports: PortsDefinition | None = None,
    schematic_function: None = None,
) -> Callable[
    [Callable[KCellParams, ProtoTKCell[Any]]],
    Callable[KCellParams, KC],
]
cell(
    *,
    output_type: type[KC],
    set_settings: bool = ...,
    set_name: bool = ...,
    check_ports: bool = ...,
    check_pins: bool = ...,
    check_instances: CheckInstances | None = ...,
    check_unnamed_cells: CheckUnnamedCells = ...,
    snap_ports: bool = ...,
    add_port_layers: bool = ...,
    cache: Cache[Hashable, Any]
    | dict[Hashable, Any]
    | None = ...,
    basename: str | None = ...,
    drop_params: list[str] = ...,
    register_factory: bool = ...,
    overwrite_existing: bool | None = ...,
    layout_cache: bool | None = ...,
    info: dict[str, MetaData] | None = ...,
    debug_names: bool | None = ...,
    tags: list[str] | None = ...,
    lvs_equivalent_ports: list[list[str]] | None = None,
    ports: PortsDefinition | None = None,
    schematic_function: Callable[
        KCellParams, TSchematic[Any]
    ],
) -> Callable[
    [Callable[KCellParams, ProtoTKCell[Any]]],
    Callable[KCellParams, KC],
]
cell(
    *,
    output_type: type[KC],
    set_settings: bool = ...,
    set_name: bool = ...,
    check_ports: bool = ...,
    check_pins: bool = ...,
    check_instances: CheckInstances | None = ...,
    check_unnamed_cells: CheckUnnamedCells = ...,
    snap_ports: bool = ...,
    add_port_layers: bool = ...,
    cache: Cache[Hashable, Any]
    | dict[Hashable, Any]
    | None = ...,
    basename: str | None = ...,
    drop_params: list[str] = ...,
    register_factory: bool = ...,
    overwrite_existing: bool | None = ...,
    layout_cache: bool | None = ...,
    info: dict[str, MetaData] | None = ...,
    debug_names: bool | None = ...,
    tags: list[str] | None = ...,
    lvs_equivalent_ports: list[list[str]] | None = None,
    ports: PortsDefinition | None = None,
    schematic_function: None = None,
) -> Callable[
    [Callable[KCellParams, ProtoTKCell[Any]]],
    Callable[KCellParams, KC],
]
cell(
    _func: Callable[KCellParams, ProtoTKCell[Any]]
    | None = None,
    /,
    *,
    output_type: type[KC] | None = None,
    set_settings: bool = True,
    set_name: bool = True,
    check_ports: bool = True,
    check_pins: bool = True,
    check_instances: CheckInstances | None = None,
    check_unnamed_cells: CheckUnnamedCells | None = None,
    snap_ports: bool = True,
    add_port_layers: bool = True,
    cache: Cache[Hashable, Any]
    | dict[Hashable, Any]
    | None = None,
    basename: str | None = None,
    drop_params: Sequence[str] = ("self", "cls"),
    register_factory: bool = True,
    overwrite_existing: bool | None = None,
    layout_cache: bool | None = None,
    info: dict[str, MetaData] | None = None,
    post_process: Iterable[Callable[[KC], None]]
    | None = None,
    debug_names: bool | None = None,
    tags: list[str] | None = None,
    lvs_equivalent_ports: list[list[str]] | None = None,
    ports: PortsDefinition | None = None,
    schematic_function: Callable[
        KCellParams, TSchematic[Any]
    ]
    | None = None,
) -> (
    Callable[KCellParams, KC]
    | Callable[
        [Callable[KCellParams, ProtoTKCell[Any]]],
        Callable[KCellParams, KC],
    ]
)

Decorator to cache and auto name the cell.

This will use functools.cache to cache the function call. Additionally, if enabled this will set the name and from the args/kwargs of the function and also paste them into a settings dictionary of the KCell.

Parameters:

Name Type Description Default
output_type type[KC] | None

The type of the cell to return.

None
set_settings bool

Copy the args & kwargs into the settings dictionary

True
set_name bool

Auto create the name of the cell to the functionname plus a string created from the args/kwargs

True
check_ports bool

Check uniqueness of port names.

True
check_pins bool

Check uniqueness of pin names.

True
check_instances CheckInstances | None

Check for any complex instances. A complex instance is a an instance that has a magnification != 1 or non-90° rotation. Depending on the setting, an error is raised, the cell is flattened, a VInstance is created instead of a regular instance, or they are ignored.

None
check_unnamed_cells CheckUnnamedCells | None

Check for unnamed child cells (matching Unnamed_\d+). "error" raises, "warning" logs a warning, "ignore" skips the check.

None
snap_ports bool

Snap the centers of the ports onto the grid (only x/y, not angle).

True
add_port_layers bool

Add special layers of KCLayout.netlist_layer_mapping to the ports if the port layer is in the mapping.

True
cache Cache[Hashable, Any] | dict[Hashable, Any] | None

Provide a user defined cache instead of an internal one. This can be used for example to clear the cache. expensive if the cell is called often).

None
basename str | None

Overwrite the name normally inferred from the function or class name.

None
drop_params Sequence[str]

Drop these parameters before writing the settings

('self', 'cls')
register_factory bool

Register the resulting KCell-function to the KCLayout.factories

True
layout_cache bool | None

If true, treat the layout like a cache, if a cell with the same name exists already, pick that one instead of using running the function. This only works if set_name is true. Can be globally configured through config.cell_layout_cache.

None
overwrite_existing bool | None

If cells were created with the same name, delete other cells with the same name. Can be globally configured through config.cell_overwrite_existing.

None
info dict[str, MetaData] | None

Additional metadata to put into info attribute.

None
post_process Iterable[Callable[[KC], None]] | None

List of functions to call after the cell has been created.

None
debug_names bool | None

Check on setting the name whether a cell with this name already exists.

None
tags list[str] | None

Tag cell functions with user defined tags.

None

Returns: A wrapped cell function which caches responses and modifies the cell according to settings.

Source code in kfactory/layout.py
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
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
1306
1307
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
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
def cell[**KCellParams, KC: ProtoTKCell[Any]](
    self,
    _func: Callable[KCellParams, ProtoTKCell[Any]] | None = None,
    /,
    *,
    output_type: type[KC] | None = None,
    set_settings: bool = True,
    set_name: bool = True,
    check_ports: bool = True,
    check_pins: bool = True,
    check_instances: CheckInstances | None = None,
    check_unnamed_cells: CheckUnnamedCells | None = None,
    snap_ports: bool = True,
    add_port_layers: bool = True,
    cache: Cache[Hashable, Any] | dict[Hashable, Any] | None = None,
    basename: str | None = None,
    drop_params: Sequence[str] = ("self", "cls"),
    register_factory: bool = True,
    overwrite_existing: bool | None = None,
    layout_cache: bool | None = None,
    info: dict[str, MetaData] | None = None,
    post_process: Iterable[Callable[[KC], None]] | None = None,
    debug_names: bool | None = None,
    tags: list[str] | None = None,
    lvs_equivalent_ports: list[list[str]] | None = None,
    ports: PortsDefinition | None = None,
    schematic_function: Callable[KCellParams, TSchematic[Any]] | None = None,
) -> (
    Callable[KCellParams, KC]
    | Callable[
        [Callable[KCellParams, ProtoTKCell[Any]]],
        Callable[KCellParams, KC],
    ]
):
    """Decorator to cache and auto name the cell.

    This will use `functools.cache` to cache the function call.
    Additionally, if enabled this will set the name and from the args/kwargs of the
    function and also paste them into a settings dictionary of the
    [KCell][kfactory.kcell.KCell].

    Args:
        output_type: The type of the cell to return.
        set_settings: Copy the args & kwargs into the settings dictionary
        set_name: Auto create the name of the cell to the functionname plus a
            string created from the args/kwargs
        check_ports: Check uniqueness of port names.
        check_pins: Check uniqueness of pin names.
        check_instances: Check for any complex instances. A complex instance is a an
            instance that has a magnification != 1 or non-90° rotation.
            Depending on the setting, an error is raised, the cell is flattened,
            a VInstance is created instead of a regular instance, or they are
            ignored.
        check_unnamed_cells: Check for unnamed child cells (matching
            ``Unnamed_\\d+``). ``"error"`` raises, ``"warning"`` logs a warning,
            ``"ignore"`` skips the check.
        snap_ports: Snap the centers of the ports onto the grid
            (only x/y, not angle).
        add_port_layers: Add special layers of `KCLayout.netlist_layer_mapping`
            to the ports if the port layer is in the mapping.
        cache: Provide a user defined cache instead of an internal one. This
            can be used for example to clear the cache.
            expensive if the cell is called often).
        basename: Overwrite the name normally inferred from the function or class
            name.
        drop_params: Drop these parameters before writing the
            [settings][kfactory.kcell.KCell.settings]
        register_factory: Register the resulting KCell-function to the
            `KCLayout.factories`
        layout_cache: If true, treat the layout like a cache, if a cell with the
            same name exists already, pick that one instead of using running the
            function. This only works if `set_name` is true. Can be globally
            configured through `config.cell_layout_cache`.
        overwrite_existing: If cells were created with the same name, delete other
            cells with the same name. Can be globally configured through
            `config.cell_overwrite_existing`.
        info: Additional metadata to put into info attribute.
        post_process: List of functions to call after the cell has been created.
        debug_names: Check on setting the name whether a cell with this name already
            exists.
        tags: Tag cell functions with user defined tags.
    Returns:
        A wrapped cell function which caches responses and modifies the cell
        according to settings.
    """
    if check_instances is None:
        check_instances = config.check_instances
    if check_unnamed_cells is None:
        check_unnamed_cells = config.check_unnamed_cells
    if overwrite_existing is None:
        overwrite_existing = config.cell_overwrite_existing
    if layout_cache is None:
        layout_cache = config.cell_layout_cache
    if debug_names is None:
        debug_names = config.debug_names
    if post_process is None:
        post_process = []

    def decorator_autocell(
        f: Callable[KCellParams, KCIN],
    ) -> Callable[KCellParams, KC]:
        sig = inspect.signature(f)
        if output_type is not None:
            output_cell_type_: type[KC | ProtoTKCell[Any]] = output_type
        elif sig.return_annotation is not inspect.Signature.empty:
            # Use get_type_hints to resolve string annotations
            try:
                type_hints = get_type_hints(f, globalns=f.__globals__)  # ty:ignore[unresolved-attribute]
                output_cell_type_ = type_hints.get("return", sig.return_annotation)

            except Exception:
                # Fallback to raw annotation if get_type_hints fails
                logger.opt(depth=2).warning(
                    "Cannot determine output type ((D)KCell type)"
                    f"from annotation {sig.return_annotation!r}. "
                    "Trying to continue but likely this will fail.",
                )
                output_cell_type_ = sig.return_annotation
        else:
            output_cell_type_ = self.default_cell_output_type

        output_cell_type__ = cast("type[KC]", output_cell_type_)

        cache_: Cache[Hashable, Any] | dict[Hashable, Any] = cache or Cache(
            maxsize=float("inf")
        )
        wrapper_autocell: WrappedKCellFunc[KCellParams, KC] = WrappedKCellFunc[
            KCellParams, KC
        ](
            kcl=self,
            f=f,
            sig=sig,
            output_type=output_cell_type__,
            cache=cache_,
            set_settings=set_settings,
            set_name=set_name,
            check_ports=check_ports,
            check_pins=check_pins,
            check_instances=check_instances,
            check_unnamed_cells=check_unnamed_cells,
            snap_ports=snap_ports,
            add_port_layers=add_port_layers,
            basename=basename,
            drop_params=drop_params,
            overwrite_existing=overwrite_existing,
            layout_cache=layout_cache,
            info=info,
            post_process=post_process,  # ty:ignore[invalid-argument-type]
            debug_names=debug_names,
            tags=tags,
            lvs_equivalent_ports=lvs_equivalent_ports,
            ports=ports,
            schematic_function=schematic_function,
        )

        if register_factory:
            with self.thread_lock:
                if wrapper_autocell.name is None:
                    raise ValueError(f"Function {f} has no name.")
                self.factories.add(wrapper_autocell)

        @functools.wraps(f)
        def func(*args: KCellParams.args, **kwargs: KCellParams.kwargs) -> KC:
            return wrapper_autocell(*args, **kwargs)

        return func

    return decorator_autocell if _func is None else decorator_autocell(_func)

clear

clear(keep_layers: bool = True) -> None

Clear the Layout.

If the layout is cleared, all the LayerEnums and

Source code in kfactory/layout.py
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
def clear(self, keep_layers: bool = True) -> None:
    """Clear the Layout.

    If the layout is cleared, all the LayerEnums and
    """
    for c in self.layout.cells("*"):
        c.locked = False
    self.layout.clear()
    self.tkcells = {}

    if keep_layers:
        self.layers = self.layerenum_from_dict(layers=self.infos)
    else:
        self.layers = self.layerenum_from_dict(layers=LayerInfos())

clear_kcells

clear_kcells() -> None

Clears all cells in the Layout object.

Source code in kfactory/layout.py
2157
2158
2159
2160
2161
2162
2163
def clear_kcells(self) -> None:
    """Clears all cells in the Layout object."""
    for kc in self.kcells.values():
        kc.locked = False
    for tc in self.top_kcells():
        tc.kdb_cell.prune_cell()
    self.tkcells = {}

create_cell

create_cell(
    name: str, *args: str, allow_duplicate: bool = False
) -> kdb.Cell

Create a new cell in the library.

This shouldn't be called manually. The constructor of KCell will call this method.

Parameters:

Name Type Description Default
name str

The (initial) name of the cell.

required
allow_duplicate bool

Allow the creation of a cell with the same name which already is registered in the Layout. This will create a cell with the name name + $1 or 2..n increasing by the number of existing duplicates

False
args str

additional arguments passed to klayout.db.Layout.create_cell

()

Returns:

Type Description
Cell

klayout.db.Cell: klayout.db.Cell object created in the Layout

Source code in kfactory/layout.py
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
def create_cell(
    self,
    name: str,
    *args: str,
    allow_duplicate: bool = False,
) -> kdb.Cell:
    """Create a new cell in the library.

    This shouldn't be called manually.
    The constructor of KCell will call this method.

    Args:
        name: The (initial) name of the cell.
        allow_duplicate: Allow the creation of a cell with the same name which
            already is registered in the Layout.
            This will create a cell with the name `name` + `$1` or `2..n`
            increasing by the number of existing duplicates
        args: additional arguments passed to
            `klayout.db.Layout.create_cell`

    Returns:
        klayout.db.Cell: klayout.db.Cell object created in the Layout

    """
    with self.thread_lock:
        if allow_duplicate or (self.layout_cell(name) is None):
            return self.layout.create_cell(name, *args)
        raise ValueError(
            f"Cellname {name} already exists in the layout/KCLayout. "
            "Please make sure the cellname is"
            " unique or pass `allow_duplicate` when creating the library"
        )

create_layer_enclosure

create_layer_enclosure(
    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,
) -> LayerEnclosure

Create a new LayerEnclosure in the KCLayout.

Source code in kfactory/layout.py
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
def create_layer_enclosure(
    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,
) -> LayerEnclosure:
    """Create a new LayerEnclosure in the KCLayout."""
    if name is None and main_layer is not None and main_layer.name != "":
        name = main_layer.name
    enc = LayerEnclosure(
        sections=sections,
        dsections=dsections,
        name=name,
        main_layer=main_layer,
        kcl=self,
    )

    self.layer_enclosures[enc.name] = enc
    return enc

delete_cell

delete_cell(cell: AnyTKCell | int) -> None

Delete a cell in the kcl object.

Source code in kfactory/layout.py
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
def delete_cell(self, cell: AnyTKCell | int) -> None:
    """Delete a cell in the kcl object."""
    with self.thread_lock:
        if isinstance(cell, int):
            self.layout.cell(cell).locked = False
            self.layout.delete_cell(cell)
            self.tkcells.pop(cell, None)
        else:
            ci = cell.cell_index()
            self.layout.cell(ci).locked = False
            self.layout.delete_cell(ci)
            self.tkcells.pop(ci, None)

delete_cell_rec

delete_cell_rec(cell_index: int) -> None

Deletes a KCell plus all subcells.

Source code in kfactory/layout.py
1765
1766
1767
1768
1769
def delete_cell_rec(self, cell_index: int) -> None:
    """Deletes a KCell plus all subcells."""
    with self.thread_lock:
        self.layout.delete_cell_rec(cell_index)
        self.rebuild()

delete_cells

delete_cells(cell_index_list: Sequence[int]) -> None

Delete a sequence of cell by indexes.

Source code in kfactory/layout.py
1771
1772
1773
1774
1775
1776
1777
1778
def delete_cells(self, cell_index_list: Sequence[int]) -> None:
    """Delete a sequence of cell by indexes."""
    with self.thread_lock:
        for ci in cell_index_list:
            self.layout.cell(ci).locked = False
            self.tkcells.pop(ci, None)
        self.layout.delete_cells(cell_index_list)
        self.rebuild()

dkcell

dkcell(
    name: str | None = None, ports: DPorts | None = None
) -> DKCell

Create a new cell based ont he pdk's layout object.

Source code in kfactory/layout.py
1635
1636
1637
def dkcell(self, name: str | None = None, ports: DPorts | None = None) -> DKCell:
    """Create a new cell based ont he pdk's layout object."""
    return DKCell(name=name, kcl=self, ports=ports)

dup

dup(init_cells: bool = True) -> KCLayout

Create a duplication of the ~KCLayout object.

Parameters:

Name Type Description Default
init_cells bool

initialize the all cells in the new KCLayout object

True

Returns:

Type Description
KCLayout

Copy of itself

Source code in kfactory/layout.py
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
def dup(self, init_cells: bool = True) -> KCLayout:
    """Create a duplication of the `~KCLayout` object.

    Args:
        init_cells: initialize the all cells in the new KCLayout object

    Returns:
        Copy of itself
    """
    kcl = KCLayout(self.name + "_DUPLICATE")
    kcl.layout.assign(self.layout.dup())
    if init_cells:
        for i, kc in self.tkcells.items():
            kcl.tkcells[i] = kc.model_copy(
                update={"kdb_cell": kc.kdb_cell, "kcl": kcl}
            )
    kcl.rename_function = self.rename_function
    return kcl

find_layer

find_layer(name: str) -> LayerEnum
find_layer(info: LayerInfo) -> LayerEnum
find_layer(layer: int, datatype: int) -> LayerEnum
find_layer(
    layer: int, dataytpe: int, name: str
) -> LayerEnum
find_layer(
    name: str,
    *,
    allow_undefined_layers: Literal[True] = True,
) -> LayerEnum | int
find_layer(
    info: LayerInfo,
    *,
    allow_undefined_layers: Literal[True] = True,
) -> LayerEnum | int
find_layer(
    layer: int,
    datatype: int,
    *,
    allow_undefined_layers: Literal[True] = True,
) -> LayerEnum | int
find_layer(
    layer: int,
    dataytpe: int,
    name: str,
    allow_undefined_layers: Literal[True] = True,
) -> LayerEnum | int
find_layer(
    *args: int | str | LayerInfo,
    **kwargs: int | str | LayerInfo | bool,
) -> LayerEnum | int

Try to find a registered layer. Throws a KeyError if it cannot find it.

Can find a layer either by name, layer and datatype (two args), LayerInfo, or all three of layer, datatype, and name.

Source code in kfactory/layout.py
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
def find_layer(
    self,
    *args: int | str | kdb.LayerInfo,
    **kwargs: int | str | kdb.LayerInfo | bool,
) -> LayerEnum | int:
    """Try to find a registered layer. Throws a KeyError if it cannot find it.

    Can find a layer either by name, layer and datatype (two args), LayerInfo, or
    all three of layer, datatype, and name.
    """
    allow_undefined_layers = kwargs.pop(
        "allow_undefined_layers", config.allow_undefined_layers
    )
    info = self.layout.get_info(self.layout.layer(*args, **kwargs))
    try:
        return self.layers[info.name]
    except KeyError as e:
        if allow_undefined_layers:
            return self.layout.layer(info)
        raise KeyError(
            f"Layer '{args=}, {kwargs=}' has not been defined in the KCLayout. "
            "Have you defined the layer and set it in KCLayout.info?"
        ) from e

get_cell

get_cell(
    obj: str | int,
    cell_type: type[KC] = KCell,
    error_search_limit: int | None = 10,
) -> KC

Retrieve a cell by name(str) or index(int).

Attrs

obj: name of cell or cell_index cell_type: type of cell to return

Source code in kfactory/layout.py
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
def get_cell[KC: ProtoTKCell[Any]](
    self,
    obj: str | int,
    cell_type: type[KC] = KCell,  # ty:ignore[invalid-parameter-default]
    error_search_limit: int | None = 10,
) -> KC:
    """Retrieve a cell by name(str) or index(int).

    Attrs:
        obj: name of cell or cell_index
        cell_type: type of cell to return
    """
    if isinstance(obj, int):
        # search by index
        try:
            return cell_type(base=self.tkcells[obj])
        except KeyError:
            kdb_c = self.layout_cell(obj)
            if kdb_c is None:
                raise
            return cell_type(name=kdb_c.name, kcl=self, kdb_cell=kdb_c)
    # search by name/key
    kdb_c = self.layout_cell(obj)
    if kdb_c is not None:
        try:
            return cell_type(base=self.tkcells[kdb_c.cell_index()])
        except KeyError:
            c = cell_type(name=kdb_c.name, kcl=self, kdb_cell=kdb_c)
            c.get_meta_data()
            return c
    if error_search_limit:
        # limit the print of available cells
        # and throw closest names with fuzzy search
        from rapidfuzz import process

        closest_names = [
            result[0]
            for result in process.extract(
                obj,
                (cell.name for cell in self.kcells.values()),
                limit=error_search_limit,
            )
        ]
        raise ValueError(
            f"Library doesn't have a KCell named {obj},"
            f" closest {error_search_limit} are: \n"
            f"{pformat(closest_names)}"
        )

    raise ValueError(
        f"Library doesn't have a KCell named {obj},"
        " available KCells are"
        f"{pformat(sorted([cell.name for cell in self.kcells.values()]))}"
    )

get_dcross_section

get_dcross_section(
    cross_section: str
    | SymmetricalCrossSection
    | CrossSectionSpec
    | DCrossSectionSpec
    | DSymmetricalCrossSection
    | CrossSection
    | DCrossSection,
) -> DCrossSection

Get a cross section by name or specification.

Source code in kfactory/layout.py
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
def get_dcross_section(
    self,
    cross_section: str
    | SymmetricalCrossSection
    | CrossSectionSpec
    | DCrossSectionSpec
    | DSymmetricalCrossSection
    | CrossSection
    | DCrossSection,
) -> DCrossSection:
    """Get a cross section by name or specification."""
    return DCrossSection(
        kcl=self, base=self.cross_sections.get_cross_section(cross_section)
    )

get_enclosure

get_enclosure(
    enclosure: str | LayerEnclosure | LayerEnclosureSpec,
) -> LayerEnclosure

Gets a layer enclosure by name specification or the layerenclosure itself.

Source code in kfactory/layout.py
2165
2166
2167
2168
2169
def get_enclosure(
    self, enclosure: str | LayerEnclosure | LayerEnclosureSpec
) -> LayerEnclosure:
    """Gets a layer enclosure by name specification or the layerenclosure itself."""
    return self.layer_enclosures.get_enclosure(enclosure, self)

get_icross_section

get_icross_section(
    cross_section: str
    | SymmetricalCrossSection
    | CrossSectionSpec
    | DCrossSectionSpec
    | DCrossSection
    | DSymmetricalCrossSection
    | CrossSection,
) -> CrossSection

Get a cross section by name or specification.

Source code in kfactory/layout.py
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
def get_icross_section(
    self,
    cross_section: str
    | SymmetricalCrossSection
    | CrossSectionSpec
    | DCrossSectionSpec
    | DCrossSection
    | DSymmetricalCrossSection
    | CrossSection,
) -> CrossSection:
    """Get a cross section by name or specification."""
    return CrossSection(
        kcl=self, base=self.cross_sections.get_cross_section(cross_section)
    )

get_meta_data

get_meta_data() -> tuple[dict[str, Any], dict[str, Any]]

Read KCLayout meta info from the KLayout object.

Source code in kfactory/layout.py
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
def get_meta_data(self) -> tuple[dict[str, Any], dict[str, Any]]:
    """Read KCLayout meta info from the KLayout object."""
    settings: dict[str, Any] = {}
    info: dict[str, Any] = {}
    cross_sections: list[dict[str, Any]] = []
    for meta in self.layout.each_meta_info():
        if meta.name.startswith("kfactory:info"):
            info[meta.name.removeprefix("kfactory:info:")] = meta.value
        elif meta.name.startswith("kfactory:settings"):
            settings[meta.name.removeprefix("kfactory:settings:")] = meta.value
        elif meta.name.startswith("kfactory:layer_enclosure:"):
            self.get_enclosure(
                LayerEnclosure(
                    **meta.value,
                )
            )
        elif meta.name.startswith("kfactory:cross_section:"):
            cross_sections.append(
                {
                    "name": meta.name.removeprefix("kfactory:cross_section:"),
                    **meta.value,
                }
            )

    for cs in cross_sections:
        self.get_symmetrical_cross_section(
            SymmetricalCrossSection(
                width=cs["width"],
                enclosure=self.get_enclosure(cs["layer_enclosure"]),
                name=cs["name"],
            )
        )

    return info, settings

get_symmetrical_cross_section

get_symmetrical_cross_section(
    cross_section: str
    | SymmetricalCrossSection
    | CrossSectionSpec
    | DCrossSectionSpec
    | DSymmetricalCrossSection,
) -> SymmetricalCrossSection

Get a cross section by name or specification.

Source code in kfactory/layout.py
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
def get_symmetrical_cross_section(
    self,
    cross_section: str
    | SymmetricalCrossSection
    | CrossSectionSpec
    | DCrossSectionSpec
    | DSymmetricalCrossSection,
) -> SymmetricalCrossSection:
    """Get a cross section by name or specification."""
    return self.cross_sections.get_cross_section(cross_section)

kcell

kcell(
    name: str | None = None, ports: Ports | None = None
) -> KCell

Create a new cell based ont he pdk's layout object.

Source code in kfactory/layout.py
1631
1632
1633
def kcell(self, name: str | None = None, ports: Ports | None = None) -> KCell:
    """Create a new cell based ont he pdk's layout object."""
    return KCell(name=name, kcl=self, ports=ports)

layerenum_from_dict

layerenum_from_dict(
    name: str = "LAYER", *, layers: LayerInfos
) -> type[LayerEnum]

Create a new LayerEnum from this KCLayout.

Source code in kfactory/layout.py
1664
1665
1666
1667
1668
def layerenum_from_dict(
    self, name: str = "LAYER", *, layers: LayerInfos
) -> type[LayerEnum]:
    """Create a new [LayerEnum][kfactory.kcell.LayerEnum] from this KCLayout."""
    return layerenum_from_dict(layers=layers, name=name, layout=self.layout)

layout_cell

layout_cell(name: str | int) -> kdb.Cell | None

Get a cell by name or index from the Layout object.

Source code in kfactory/layout.py
1704
1705
1706
def layout_cell(self, name: str | int) -> kdb.Cell | None:
    """Get a cell by name or index from the Layout object."""
    return self.layout.cell(name)

lock_factories

lock_factories() -> None

Prevent further factories (real and virtual) from being registered.

This is irreversible: once locked, a KCLayout will reject any new factory registrations (e.g. via @kcl.cell / @kcl.vcell or direct factories.add calls). Use this to seal a PDK after registering all of its pcell functions.

Source code in kfactory/layout.py
437
438
439
440
441
442
443
444
445
446
def lock_factories(self) -> None:
    """Prevent further factories (real and virtual) from being registered.

    This is irreversible: once locked, a `KCLayout` will reject any new
    factory registrations (e.g. via `@kcl.cell` / `@kcl.vcell` or direct
    `factories.add` calls). Use this to seal a PDK after registering all
    of its pcell functions.
    """
    self.factories.lock()
    self.virtual_factories.lock()

read

read(
    filename: str | Path,
    options: LoadLayoutOptions | None = None,
    register_cells: bool | None = None,
    test_merge: bool = True,
    update_kcl_meta_data: Literal[
        "overwrite", "skip", "drop"
    ] = "skip",
    meta_format: Literal["v1", "v2", "v3"] | None = None,
) -> kdb.LayerMap

Read a GDS file into the existing Layout.

Any existing meta info (KCell.info and KCell.settings) will be overwritten if a KCell already exists. Instead of overwriting the cells, they can also be loaded into new cells by using the corresponding cell_conflict_resolution.

This will fail if any of the read cells try to load into a locked KCell.

Layout meta infos are ignored from the loaded layout.

Parameters:

Name Type Description Default
filename str | Path

Path of the GDS file.

required
options LoadLayoutOptions | None

KLayout options to load from the GDS. Can determine how merge conflicts are handled for example. See https://www.klayout.de/doc-qt5/code/class_LoadLayoutOptions.html

None
register_cells bool | None

If True create KCells for all cells in the GDS.

None
test_merge bool

Check the layouts first whether they are compatible (no differences).

True
update_kcl_meta_data Literal['overwrite', 'skip', 'drop']

How to treat loaded KCLayout info. overwrite: overwrite existing info entries skip: keep existing info values drop: don't add any new info

'skip'
meta_format Literal['v1', 'v2', 'v3'] | None

How to read KCell metainfo from the gds. v1 had stored port transformations as strings, never versions have them stored and loaded in their native KLayout formats.

None
Source code in kfactory/layout.py
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
def read(
    self,
    filename: str | Path,
    options: kdb.LoadLayoutOptions | None = None,
    register_cells: bool | None = None,
    test_merge: bool = True,
    update_kcl_meta_data: Literal["overwrite", "skip", "drop"] = "skip",
    meta_format: Literal["v1", "v2", "v3"] | None = None,
) -> kdb.LayerMap:
    """Read a GDS file into the existing Layout.

    Any existing meta info (KCell.info and KCell.settings) will be overwritten if
    a KCell already exists. Instead of overwriting the cells, they can also be
    loaded into new cells by using the corresponding cell_conflict_resolution.

    This will fail if any of the read cells try to load into a locked KCell.

    Layout meta infos are ignored from the loaded layout.

    Args:
        filename: Path of the GDS file.
        options: KLayout options to load from the GDS. Can determine how merge
            conflicts are handled for example. See
            https://www.klayout.de/doc-qt5/code/class_LoadLayoutOptions.html
        register_cells: If `True` create KCells for all cells in the GDS.
        test_merge: Check the layouts first whether they are compatible
            (no differences).
        update_kcl_meta_data: How to treat loaded KCLayout info.
            overwrite: overwrite existing info entries
            skip: keep existing info values
            drop: don't add any new info
        meta_format: How to read KCell metainfo from the gds. `v1` had stored port
            transformations as strings, never versions have them stored and loaded
            in their native KLayout formats.
    """
    if options is None:
        options = load_layout_options()
    with self.thread_lock:
        if meta_format is None:
            meta_format = config.meta_format
        if register_cells is None:
            register_cells = meta_format == config.meta_format
        layout_b = kdb.Layout()
        layout_b.read(str(filename), options)
        if (
            self.cells() > 0
            and test_merge
            and (
                options.cell_conflict_resolution
                != kdb.LoadLayoutOptions.CellConflictResolution.RenameCell
            )
        ):
            self.set_meta_data()
            for kcell in self.kcells.values():
                kcell.set_meta_data()
            diff = MergeDiff(
                layout_a=self.layout,
                layout_b=layout_b,
                name_a=self.name,
                name_b=Path(filename).stem,
            )
            diff.compare()
            if diff.dbu_differs:
                raise MergeError(
                    "Layouts' DBU differ. Check the log for more info."
                )
            if diff.diff_xor.cells() > 0:
                diff_kcl = KCLayout(self.name + "_XOR")
                diff_kcl.layout.assign(diff.diff_xor)
                show(diff_kcl)

                err_msg = (
                    f"Layout {self.name} cannot merge with layout "
                    f"{Path(filename).stem} safely. See the error messages "
                    f"or check with KLayout."
                )

                if diff.layout_meta_diff:
                    yaml = ruamel.yaml.YAML(typ=["rt", "string"])
                    err_msg += (
                        "\nLayout Meta Diff:\n```\n"
                        + yaml.dumps(dict(diff.layout_meta_diff))  # ty:ignore[unresolved-attribute]
                        + "\n```"
                    )
                if diff.cells_meta_diff:
                    yaml = ruamel.yaml.YAML(typ=["rt", "string"])
                    err_msg += (
                        "\nLayout Meta Diff:\n```\n"
                        + yaml.dumps(dict(diff.cells_meta_diff))  # ty:ignore[unresolved-attribute]
                        + "\n```"
                    )

                raise MergeError(err_msg)

        cells = set(self.cells("*"))
        saveopts = save_layout_options()
        saveopts.gds2_max_cellname_length = (
            kdb.SaveLayoutOptions().gds2_max_cellname_length
        )
        binary_layout = layout_b.write_bytes(saveopts)
        locked_cells = [
            kdb_cell for kdb_cell in self.layout.each_cell() if kdb_cell.locked
        ]
        for kdb_cell in locked_cells:
            kdb_cell.locked = False
        lm = self.layout.read_bytes(binary_layout, options)
        for kdb_cell in locked_cells:
            kdb_cell.locked = True
        info, settings = self.get_meta_data()

        match update_kcl_meta_data:
            case "overwrite":
                for k, v in info.items():
                    self.info[k] = v
            case "skip":
                info_ = self.info.model_dump()

                info.update(info_)
                self.info = Info(**info)

            case "drop":
                pass
            case _:
                raise ValueError(
                    f"Unknown meta update strategy {update_kcl_meta_data=}"
                    ", available strategies are 'overwrite', 'skip', or 'drop'"
                )
        meta_format = settings.get("meta_format") or config.meta_format
        load_cells = {
            cell
            for c in layout_b.cells("*")
            if (cell := self.layout_cell(c.name)) is not None
        }
        new_cells = load_cells - cells

        if register_cells:
            for c in sorted(new_cells, key=lambda _c: _c.hierarchy_levels()):
                kc = KCell(kdb_cell=c, kcl=self)
                kc.get_meta_data(
                    meta_format=meta_format,
                )

        for c in load_cells & cells:
            kc = self.kcells[c.cell_index()]
            kc.get_meta_data(meta_format=meta_format)

        return lm

rebuild

rebuild() -> None

Rebuild the KCLayout based on the Layout object.

Source code in kfactory/layout.py
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
def rebuild(self) -> None:
    """Rebuild the KCLayout based on the Layout object."""
    kcells2delete: list[int] = []
    with self.thread_lock:
        for ci, c in self.tkcells.items():
            if c.kdb_cell._destroyed():
                kcells2delete.append(ci)

        for ci in kcells2delete:
            del self.tkcells[ci]

        for cell in self.cells("*"):
            if cell.cell_index() not in self.tkcells:
                self.tkcells[cell.cell_index()] = self.get_cell(
                    cell.cell_index(), KCell
                ).base

register_cell

register_cell(
    kcell: AnyTKCell, allow_reregister: bool = False
) -> None

Register an existing cell in the KCLayout object.

Parameters:

Name Type Description Default
kcell AnyTKCell

KCell 56 be registered in the KCLayout

required
allow_reregister bool

Overwrite the existing KCell registration with this one. Doesn't allow name duplication.

False
Source code in kfactory/layout.py
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
def register_cell(self, kcell: AnyTKCell, allow_reregister: bool = False) -> None:
    """Register an existing cell in the KCLayout object.

    Args:
        kcell: KCell 56 be registered in the KCLayout
        allow_reregister: Overwrite the existing KCell registration with this one.
            Doesn't allow name duplication.
    """
    with self.thread_lock:
        if (kcell.cell_index() not in self.tkcells) or allow_reregister:
            self.tkcells[kcell.cell_index()] = kcell.base
        else:
            raise ValueError(
                f"Cannot register {kcell} if it has been registered already"
                " exists in the library"
            )

set_layers_from_infos

set_layers_from_infos(
    name: str, layers: LayerInfos
) -> type[LayerEnum]

Create a new LAYER enum based on the pdk's kcl.

Source code in kfactory/layout.py
1643
1644
1645
def set_layers_from_infos(self, name: str, layers: LayerInfos) -> type[LayerEnum]:
    """Create a new LAYER enum based on the pdk's kcl."""
    return layerenum_from_dict(name=name, layers=layers, layout=self.layout)

set_meta_data

set_meta_data() -> None

Set the info/settings of the KCLayout.

Source code in kfactory/layout.py
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
def set_meta_data(self) -> None:
    """Set the info/settings of the KCLayout."""
    if config.write_kfactory_settings:
        for name, setting in self.settings.model_dump().items():
            self.add_meta_info(
                kdb.LayoutMetaInfo(f"kfactory:settings:{name}", setting, None, True)
            )
    for name, info in self.info.model_dump().items():
        self.add_meta_info(
            kdb.LayoutMetaInfo(f"kfactory:info:{name}", info, None, True)
        )
    for enclosure in self.layer_enclosures.root.values():
        self.add_meta_info(
            kdb.LayoutMetaInfo(
                f"kfactory:layer_enclosure:{enclosure.name}",
                enclosure.model_dump(),
                None,
                True,
            )
        )
    for cross_section in self.cross_sections.cross_sections.values():
        self.add_meta_info(
            kdb.LayoutMetaInfo(
                f"kfactory:cross_section:{cross_section.name}",
                {
                    "width": cross_section.width,
                    "layer_enclosure": cross_section.enclosure.name,
                },
                None,
                True,
            )
        )

to_dbu

to_dbu(other: None) -> None
to_dbu(other: float) -> int
to_dbu(other: DPoint) -> kdb.Point
to_dbu(other: DVector) -> kdb.Vector
to_dbu(other: DBox) -> kdb.Box
to_dbu(other: DPolygon) -> kdb.Polygon
to_dbu(other: DPath) -> kdb.Path
to_dbu(other: DText) -> kdb.Text
to_dbu(
    other: float
    | DPoint
    | DVector
    | DBox
    | DPolygon
    | DPath
    | DText
    | None,
) -> (
    int
    | kdb.Point
    | kdb.Vector
    | kdb.Box
    | kdb.Polygon
    | kdb.Path
    | kdb.Text
    | None
)

Convert Shapes or values in dbu to DShapes or floats in um.

Source code in kfactory/layout.py
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
def to_dbu(
    self,
    other: float
    | kdb.DPoint
    | kdb.DVector
    | kdb.DBox
    | kdb.DPolygon
    | kdb.DPath
    | kdb.DText
    | None,
) -> (
    int
    | kdb.Point
    | kdb.Vector
    | kdb.Box
    | kdb.Polygon
    | kdb.Path
    | kdb.Text
    | None
):
    """Convert Shapes or values in dbu to DShapes or floats in um."""
    if other is None:
        return None
    return kdb.CplxTrans(self.layout.dbu).inverted() * other

to_um

to_um(other: None) -> None
to_um(other: int) -> float
to_um(other: Point) -> kdb.DPoint
to_um(other: Vector) -> kdb.DVector
to_um(other: Box) -> kdb.DBox
to_um(other: Polygon) -> kdb.DPolygon
to_um(other: Path) -> kdb.DPath
to_um(other: Text) -> kdb.DText
to_um(
    other: int
    | Point
    | Vector
    | Box
    | Polygon
    | Path
    | Text
    | None,
) -> (
    float
    | kdb.DPoint
    | kdb.DVector
    | kdb.DBox
    | kdb.DPolygon
    | kdb.DPath
    | kdb.DText
    | None
)

Convert Shapes or values in dbu to DShapes or floats in um.

Source code in kfactory/layout.py
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
def to_um(
    self,
    other: int
    | kdb.Point
    | kdb.Vector
    | kdb.Box
    | kdb.Polygon
    | kdb.Path
    | kdb.Text
    | None,
) -> (
    float
    | kdb.DPoint
    | kdb.DVector
    | kdb.DBox
    | kdb.DPolygon
    | kdb.DPath
    | kdb.DText
    | None
):
    """Convert Shapes or values in dbu to DShapes or floats in um."""
    if other is None:
        return None
    return kdb.CplxTrans(self.layout.dbu) * other

top_kcell

top_kcell() -> KCell

Return the top KCell if there is a single one.

Source code in kfactory/layout.py
2153
2154
2155
def top_kcell(self) -> KCell:
    """Return the top KCell if there is a single one."""
    return self[self.top_cell().cell_index()]

top_kcells

top_kcells() -> list[KCell]

Return the top KCells.

Source code in kfactory/layout.py
2149
2150
2151
def top_kcells(self) -> list[KCell]:
    """Return the top KCells."""
    return [self[tc.cell_index()] for tc in self.top_cells()]

vcell

vcell(
    _func: Callable[KCellParams, VK],
) -> Callable[KCellParams, VK]
vcell(
    *,
    set_settings: bool = True,
    set_name: bool = True,
    add_port_layers: bool = True,
    cache: Cache[Hashable, Any]
    | dict[Hashable, Any]
    | None = None,
    basename: str | None = None,
    drop_params: Sequence[str] = ("self", "cls"),
    register_factory: bool = True,
    info: dict[str, MetaData] | None = None,
    check_ports: bool = True,
    check_pins: bool = True,
    check_unnamed_cells: CheckUnnamedCells = ...,
    tags: list[str] | None = None,
    lvs_equivalent_ports: list[list[str]] | None = None,
    ports: PortsDefinition | None = None,
) -> Callable[
    [Callable[KCellParams, VK]], Callable[KCellParams, VK]
]
vcell(
    *,
    set_settings: bool = True,
    set_name: bool = True,
    add_port_layers: bool = True,
    cache: Cache[Hashable, Any]
    | dict[Hashable, Any]
    | None = None,
    basename: str | None = None,
    drop_params: Sequence[str] = ("self", "cls"),
    register_factory: bool = True,
    post_process: Iterable[Callable[[VKCell], None]],
    info: dict[str, MetaData] | None = None,
    check_ports: bool = True,
    check_pins: bool = True,
    check_unnamed_cells: CheckUnnamedCells = ...,
    tags: list[str] | None = None,
    lvs_equivalent_ports: list[list[str]] | None = None,
    ports: PortsDefinition | None = None,
) -> Callable[
    [Callable[KCellParams, VK]], Callable[KCellParams, VK]
]
vcell(
    *,
    output_type: type[VK],
    set_settings: bool = True,
    set_name: bool = True,
    add_port_layers: bool = True,
    cache: Cache[Hashable, Any]
    | dict[Hashable, Any]
    | None = None,
    basename: str | None = None,
    drop_params: Sequence[str] = ("self", "cls"),
    register_factory: bool = True,
    info: dict[str, MetaData] | None = None,
    check_ports: bool = True,
    check_pins: bool = True,
    check_unnamed_cells: CheckUnnamedCells = ...,
    tags: list[str] | None = None,
    lvs_equivalent_ports: list[list[str]] | None = None,
    ports: PortsDefinition | None = None,
) -> Callable[
    [Callable[KCellParams, VKCell]],
    Callable[KCellParams, VK],
]
vcell(
    *,
    output_type: type[VK],
    set_settings: bool = True,
    set_name: bool = True,
    add_port_layers: bool = True,
    cache: Cache[Hashable, Any]
    | dict[Hashable, Any]
    | None = None,
    basename: str | None = None,
    drop_params: Sequence[str] = ("self", "cls"),
    register_factory: bool = True,
    post_process: Iterable[Callable[[VKCell], None]],
    info: dict[str, MetaData] | None = None,
    check_ports: bool = True,
    check_pins: bool = True,
    check_unnamed_cells: CheckUnnamedCells = ...,
    tags: list[str] | None = None,
    lvs_equivalent_ports: list[list[str]] | None = None,
    ports: PortsDefinition | None = None,
) -> Callable[
    [Callable[KCellParams, VKCell]],
    Callable[KCellParams, VK],
]
vcell(
    _func: Callable[KCellParams, VKCell] | None = None,
    /,
    *,
    output_type: type[VK] | None = None,
    set_settings: bool = True,
    set_name: bool = True,
    add_port_layers: bool = True,
    cache: Cache[Hashable, Any]
    | dict[Hashable, Any]
    | None = None,
    basename: str | None = None,
    drop_params: Sequence[str] = ("self", "cls"),
    register_factory: bool = True,
    post_process: Iterable[Callable[[VKCell], None]]
    | None = None,
    info: dict[str, MetaData] | None = None,
    check_ports: bool = True,
    check_pins: bool = True,
    check_unnamed_cells: CheckUnnamedCells = CheckUnnamedCells.WARNING,
    tags: list[str] | None = None,
    lvs_equivalent_ports: list[list[str]] | None = None,
    ports: PortsDefinition | None = None,
) -> (
    Callable[KCellParams, VK]
    | Callable[
        [Callable[KCellParams, VK]],
        Callable[KCellParams, VK],
    ]
)

Decorator to cache and auto name the cell.

This will use functools.cache to cache the function call. Additionally, if enabled this will set the name and from the args/kwargs of the function and also paste them into a settings dictionary of the KCell.

Parameters:

Name Type Description Default
set_settings bool

Copy the args & kwargs into the settings dictionary

True
set_name bool

Auto create the name of the cell to the functionname plus a string created from the args/kwargs

True
check_ports bool

Check uniqueness of port names.

True
check_pins bool

Check uniqueness of pin names.

True
check_unnamed_cells CheckUnnamedCells

Check for unnamed child cells (matching Unnamed_\d+). "error" raises, "warning" logs a warning, "ignore" skips the check.

WARNING
add_port_layers bool

Add special layers of KCLayout.netlist_layer_mapping to the ports if the port layer is in the mapping.

True
cache Cache[Hashable, Any] | dict[Hashable, Any] | None

Provide a user defined cache instead of an internal one. This can be used for example to clear the cache.

None
basename str | None

Overwrite the name normally inferred from the function or class name.

None
drop_params Sequence[str]

Drop these parameters before writing the settings

('self', 'cls')
register_factory bool

Register the resulting KCell-function to the KCLayout.factories

True
info dict[str, MetaData] | None

Additional metadata to put into info attribute.

None
post_process Iterable[Callable[[VKCell], None]] | None

List of functions to call after the cell has been created.

None

Returns: A wrapped vcell function which caches responses and modifies the VKCell according to settings.

Source code in kfactory/layout.py
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
def vcell[**KCellParams, VK: VKCell](
    self,
    _func: Callable[KCellParams, VKCell] | None = None,
    /,
    *,
    output_type: type[VK] | None = None,
    set_settings: bool = True,
    set_name: bool = True,
    add_port_layers: bool = True,
    cache: Cache[Hashable, Any] | dict[Hashable, Any] | None = None,
    basename: str | None = None,
    drop_params: Sequence[str] = ("self", "cls"),
    register_factory: bool = True,
    post_process: Iterable[Callable[[VKCell], None]] | None = None,
    info: dict[str, MetaData] | None = None,
    check_ports: bool = True,
    check_pins: bool = True,
    check_unnamed_cells: CheckUnnamedCells = CheckUnnamedCells.WARNING,
    tags: list[str] | None = None,
    lvs_equivalent_ports: list[list[str]] | None = None,
    ports: PortsDefinition | None = None,
) -> (
    Callable[KCellParams, VK]
    | Callable[[Callable[KCellParams, VK]], Callable[KCellParams, VK]]
):
    """Decorator to cache and auto name the cell.

    This will use `functools.cache` to cache the function call.
    Additionally, if enabled this will set the name and from the args/kwargs of the
    function and also paste them into a settings dictionary of the
    [KCell][kfactory.kcell.KCell].

    Args:
        set_settings: Copy the args & kwargs into the settings dictionary
        set_name: Auto create the name of the cell to the functionname plus a
            string created from the args/kwargs
        check_ports: Check uniqueness of port names.
        check_pins: Check uniqueness of pin names.
        check_unnamed_cells: Check for unnamed child cells (matching
            ``Unnamed_\\d+``). ``"error"`` raises, ``"warning"`` logs a warning,
            ``"ignore"`` skips the check.
        add_port_layers: Add special layers of `KCLayout.netlist_layer_mapping`
            to the ports if the port layer is in the mapping.
        cache: Provide a user defined cache instead of an internal one. This
            can be used for example to clear the cache.
        basename: Overwrite the name normally inferred from the function or class
            name.
        drop_params: Drop these parameters before writing the
            [settings][kfactory.kcell.KCell.settings]
        register_factory: Register the resulting KCell-function to the
            `KCLayout.factories`
        info: Additional metadata to put into info attribute.
        post_process: List of functions to call after the cell has been created.
    Returns:
        A wrapped vcell function which caches responses and modifies the VKCell
        according to settings.
    """
    if check_unnamed_cells is None:
        check_unnamed_cells = config.check_unnamed_cells
    if post_process is None:
        post_process = ()

    def decorator_autocell(
        f: Callable[KCellParams, VKCell],
    ) -> Callable[KCellParams, VK]:
        sig = inspect.signature(f)
        output_cell_type_: type[VK | VKCell]
        if output_type is not None:
            output_cell_type_ = output_type
        elif sig.return_annotation is not inspect.Signature.empty:
            # Use get_type_hints to resolve string annotations
            try:
                type_hints = get_type_hints(f, globalns=f.__globals__)  # ty:ignore[unresolved-attribute]
                output_cell_type_ = type_hints.get("return", sig.return_annotation)

            except Exception:
                # Fallback to raw annotation if get_type_hints fails
                logger.opt(depth=2).warning(
                    "Cannot determine output type ((D)KCell type)"
                    f"from annotation {sig.return_annotation!r}. "
                    "Trying to continue but likely this will fail.",
                )
                output_cell_type_ = sig.return_annotation
        else:
            output_cell_type_ = self.default_vcell_output_type

        output_cell_type__ = cast("type[VK]", output_cell_type_)
        # previously was a KCellCache, but dict should do for most case
        cache_: Cache[Hashable, VK] | dict[Hashable, VK] = cache or Cache(
            maxsize=float("inf")
        )

        wrapper_autocell = WrappedVKCellFunc(
            kcl=self,
            f=f,
            sig=sig,
            cache=cache_,
            set_settings=set_settings,
            set_name=set_name,
            add_port_layers=add_port_layers,
            basename=basename,
            drop_params=drop_params,
            post_process=post_process,
            output_type=output_cell_type__,
            info=info,
            check_ports=check_ports,
            check_pins=check_pins,
            check_unnamed_cells=check_unnamed_cells,
            tags=tags,
            lvs_equivalent_ports=lvs_equivalent_ports,
            ports=ports,
        )

        if register_factory:
            if wrapper_autocell.name is None:
                raise ValueError(f"Function {f} has no name.")
            self.virtual_factories.add(wrapper_autocell)  # ty:ignore[invalid-argument-type]

        @functools.wraps(f)
        def func(*args: KCellParams.args, **kwargs: KCellParams.kwargs) -> VK:
            return wrapper_autocell(*args, **kwargs)

        return func

    return decorator_autocell if _func is None else decorator_autocell(_func)

vkcell

vkcell(name: str | None = None) -> VKCell

Create a new cell based ont he pdk's layout object.

Source code in kfactory/layout.py
1639
1640
1641
def vkcell(self, name: str | None = None) -> VKCell:
    """Create a new cell based ont he pdk's layout object."""
    return VKCell(name=name, kcl=self)

write

write(
    filename: str | Path,
    options: SaveLayoutOptions | None = None,
    set_meta_data: bool = True,
    convert_external_cells: bool = False,
    autoformat_from_file_extension: bool = True,
) -> None

Write a GDS file into the existing Layout.

Parameters:

Name Type Description Default
filename str | Path

Path of the GDS file.

required
options SaveLayoutOptions | None

KLayout options to load from the GDS. Can determine how merge conflicts are handled for example. See https://www.klayout.de/doc-qt5/code/class_LoadLayoutOptions.html

None
set_meta_data bool

Make sure all the cells have their metadata set

True
convert_external_cells bool

Whether to make KCells not in this KCLayout to

False
autoformat_from_file_extension bool

Set the format of the output file automatically from the file extension of filename. This is necessary for the options. If not set, this will default to GDSII.

True
Source code in kfactory/layout.py
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
def write(
    self,
    filename: str | Path,
    options: kdb.SaveLayoutOptions | None = None,
    set_meta_data: bool = True,
    convert_external_cells: bool = False,
    autoformat_from_file_extension: bool = True,
) -> None:
    """Write a GDS file into the existing Layout.

    Args:
        filename: Path of the GDS file.
        options: KLayout options to load from the GDS. Can determine how merge
            conflicts are handled for example. See
            https://www.klayout.de/doc-qt5/code/class_LoadLayoutOptions.html
        set_meta_data: Make sure all the cells have their metadata set
        convert_external_cells: Whether to make KCells not in this KCLayout to
        autoformat_from_file_extension: Set the format of the output file
            automatically from the file extension of `filename`. This is necessary
            for the options. If not set, this will default to `GDSII`.
    """
    if options is None:
        options = save_layout_options()
    if isinstance(filename, Path):
        filename = str(filename.resolve())
    for kc in list(self.kcells.values()):
        kc.insert_vinsts()
    match (set_meta_data, convert_external_cells):
        case (True, True):
            self.set_meta_data()
            for kcell in self.kcells.values():
                if not kcell.destroyed():
                    kcell.set_meta_data()
                    if kcell.is_library_cell():
                        kcell.convert_to_static(recursive=True)
        case (True, False):
            self.set_meta_data()
            for kcell in self.kcells.values():
                if not kcell.destroyed():
                    kcell.set_meta_data()
        case (False, True):
            for kcell in self.kcells.values():
                if kcell.is_library_cell() and not kcell.destroyed():
                    kcell.convert_to_static(recursive=True)

    if autoformat_from_file_extension:
        options.set_format_from_filename(filename)

    return self.layout.write(filename, options)

get_default_kcl

get_default_kcl() -> KCLayout

Utility function to get the default kcl object.

Source code in kfactory/layout.py
107
108
109
def get_default_kcl() -> KCLayout:
    """Utility function to get the default kcl object."""
    return kcl