Skip to content

optical

optical

Optical routing allows the creation of photonic (or any route using bends).

get_radius

get_radius(ports: Sequence[ProtoPort[Any]]) -> dbu

Calculates a radius between two ports.

This can be used to determine the radius of two bend ports.

Parameters:

Name Type Description Default
ports Sequence[ProtoPort[Any]]

A sequence of exactly two ports.

required

Returns:

Type Description
dbu

Radius in dbu.

Raises:

Type Description
ValueError

Radius cannot be determined

Source code in kfactory/routing/generic.py
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
def get_radius(ports: Sequence[ProtoPort[Any]]) -> dbu:
    """Calculates a radius between two ports.

    This can be used to determine the radius of two bend ports.

    Args:
        ports: A sequence of exactly two ports.

    Returns:
        Radius in dbu.

    Raises:
        ValueError: Radius cannot be determined
    """
    ports_ = tuple(p.to_itype() for p in ports)
    if len(ports_) != PORTS_FOR_RADIUS:
        raise ValueError(
            "Cannot determine the maximal radius of a bend with more than two ports."
        )
    p1, p2 = ports_
    if p1.angle == p2.angle:
        return int((p1.trans.disp - p2.trans.disp).length())
    p = kdb.Point(1, 0)
    e1 = kdb.Edge(p1.trans.disp.to_p(), p1.trans * p)
    e2 = kdb.Edge(p2.trans.disp.to_p(), p2.trans * p)

    center = e1.cut_point(e2)
    if center is None:
        raise ValueError("Could not determine the radius. Something went very wrong.")
    return int(
        max((p1.trans.disp - center).length(), (p2.trans.disp - center).length())
    )

place_manhattan

place_manhattan(c: ProtoTKCell[Any], p1: Port, p2: Port, pts: Sequence[Point], route_width: dbu | None = None, straight_factory: StraightFactoryDBU | None = None, bend90_cell: ProtoTKCell[Any] | None = None, taper_cell: ProtoTKCell[Any] | None = None, port_type: str = 'optical', min_straight_taper: dbu = 0, allow_small_routes: bool = False, allow_width_mismatch: bool | None = None, allow_layer_mismatch: bool | None = None, allow_type_mismatch: bool | None = None, purpose: str | None = 'routing', **kwargs: Any) -> ManhattanRoute

Place a symmetric backbone using straight or tapered segments and 90° bends.

Bend geometry and taper ports are resolved once. Each connection between bends uses the same segment selection, including the final connection. Symmetric connection rules and area-based route length are preserved.

Source code in kfactory/routing/optical.py
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
def place_manhattan(
    c: ProtoTKCell[Any],
    p1: Port,
    p2: Port,
    pts: Sequence[kdb.Point],
    route_width: dbu | None = None,
    straight_factory: StraightFactoryDBU | None = None,
    bend90_cell: ProtoTKCell[Any] | None = None,
    taper_cell: ProtoTKCell[Any] | None = None,
    port_type: str = "optical",
    min_straight_taper: dbu = 0,
    allow_small_routes: bool = False,
    allow_width_mismatch: bool | None = None,
    allow_layer_mismatch: bool | None = None,
    allow_type_mismatch: bool | None = None,
    purpose: str | None = "routing",
    **kwargs: Any,
) -> ManhattanRoute:
    """Place a symmetric backbone using straight or tapered segments and 90° bends.

    Bend geometry and taper ports are resolved once. Each connection between
    bends uses the same segment selection, including the final connection.
    Symmetric connection rules and area-based route length are preserved.
    """
    # configure and set up route and placers
    c = KCell(base=c.base)
    if len(kwargs) > 0:
        raise ValueError(
            f"Additional args and kwargs are not allowed for route_smart.{kwargs=}"
        )
    if allow_width_mismatch is None:
        allow_width_mismatch = config.allow_width_mismatch
    if allow_layer_mismatch is None:
        allow_layer_mismatch = config.allow_layer_mismatch
    if allow_type_mismatch is None:
        allow_type_mismatch = config.allow_type_mismatch
    if straight_factory is None:
        raise ValueError(
            "place_manhattan needs to have a straight_factory set. Please pass a "
            "straight_factory which takes kwargs 'width: int' and 'length: int'."
        )
    if bend90_cell is None:
        raise ValueError(
            "place_manhattan needs to be passed a fixed bend90 cell with two optical"
            " ports which are 90° apart from each other with port_type 'port_type'."
        )
    route_start_port = p1.copy()
    route_end_port = p2.copy()
    if p1.base.trans is None:
        logger.warning(
            f"{p1=} is not a manhattan port (either off-grid or angle not a multiple of"
            " 90 degrees). Forcing port to be manhattan."
        )
        route_start_port.trans = route_start_port.trans
    if p2.base.trans is None:
        logger.warning(
            f"{p2=} is not a manhattan port (either off-grid or angle not a multiple of"
            " 90 degrees). Forcing port to be manhattan."
        )
        route_end_port.trans = route_end_port.trans
    route_start_port.name = "route_start"
    route_start_port.trans.angle = (route_start_port.angle + 2) % 4
    route_end_port.name = "route_end"
    route_end_port.trans.angle = (route_end_port.angle + 2) % 4

    b90p1, b90p2, b90c = _bend90_geometry(bend90_cell, port_type)
    # Symmetric placement historically follows the bend port's mirror flag.
    b90c.mirror = b90p1.mirror
    b90r = round(
        max(
            (b90p1.trans.disp - b90c.disp).length(),
            (b90p2.trans.disp - b90c.disp).length(),
        )
    )
    route = ManhattanRoute(
        backbone=list(pts),
        start_port=route_start_port,
        end_port=route_end_port,
        instances=[],
        bend90_radius=b90r,
    )
    if taper_cell is not None:
        taper_cell = KCell(base=taper_cell.base)
        taper_ports = [p for p in taper_cell.ports if p.port_type == port_type]
        if (
            len(taper_ports) != NUM_PORTS_FOR_ROUTING
            or (taper_ports[1].trans.angle + 2) % 4 != taper_ports[0].trans.angle
        ):
            raise AttributeError(
                "Taper must have only two optical ports that are 180° oriented to each"
                " other"
            )
        if taper_ports[1].width == b90p1.width:
            taperp2, taperp1 = taper_ports
        elif taper_ports[0].width == b90p1.width:
            taperp1, taperp2 = taper_ports
        else:
            raise AttributeError(
                "At least one of the taper's optical ports must be the same width as"
                " the bend's ports"
            )
        route.taper_length = int((taperp1.trans.disp - taperp2.trans.disp).length())
    w = route_width or p1.width

    def segment(
        start: Port, end: Port, *, width_override: int | None = route_width
    ) -> tuple[Port, Port]:
        """Place one connection, selecting tapers only when they fit."""
        length = int((end.trans.disp - start.trans.disp).length())
        if (
            taper_cell is not None
            and length >= 2 * route.taper_length + min_straight_taper
        ):
            return _place_tapered_straight(
                c=c,
                straight_factory=straight_factory,
                taper_cell=taper_cell,
                purpose=purpose,
                route=route,
                p1=start,
                p2=end,
                route_width=width_override,
                taper_ports=(taperp1, taperp2),
                port_type=port_type,
                allow_width_mismatch=allow_width_mismatch,
                allow_layer_mismatch=allow_layer_mismatch,
                allow_type_mismatch=allow_type_mismatch,
            )
        return _place_straight(
            c=c,
            straight_factory=straight_factory,
            purpose=purpose,
            w=w,
            route=route,
            p1=start,
            p2=end,
            route_width=width_override,
            port_type=port_type,
            allow_width_mismatch=allow_width_mismatch,
            allow_layer_mismatch=allow_layer_mismatch,
            allow_type_mismatch=allow_type_mismatch,
        )

    # placing
    if not pts or len(pts) < MIN_POINTS_FOR_PLACEMENT:
        # Nothing to be placed
        return route
    old_pt = pts[0]
    old_bend_port = p1
    # the solution should be just a straight
    if len(pts) == MIN_POINTS_FOR_PLACEMENT:
        p1_, p2_ = segment(
            route.start_port.copy_polar(), route.end_port.copy_polar(), width_override=w
        )
        p1_.name = "route_start"
        p2_.name = "route_end"
        route.start_port = p1
        route.end_port = p2
        return route

    # in other cases, place the bend and then route
    for i in range(1, len(pts) - 1):
        pt = pts[i]
        new_pt = pts[i + 1]

        if (pt.distance(old_pt) < b90r) and not allow_small_routes:
            raise ValueError(
                f"distance between points {old_pt!s} and {pt!s} is too small to"
                f" safely place bends {pt.to_s()=}, {old_pt.to_s()=},"
                f" {pt.distance(old_pt)=} < {b90r=}"
            )
        if (
            pt.distance(old_pt) < 2 * b90r
            and i not in {1, len(pts) - 1}
            and not allow_small_routes
        ):
            raise ValueError(
                f"distance between points {old_pt!s} and {pt!s} is too small to"
                f" safely place bends {pt=!s}, {old_pt=!s},"
                f" {pt.distance(old_pt)=} < {2 * b90r=}"
            )

        vec = pt - old_pt
        vec_n = new_pt - pt

        bend90 = c << bend90_cell
        bend90.purpose = purpose
        route.n_bend90 += 1
        mirror = (vec_angle(vec_n) - vec_angle(vec)) % 4 != ANGLE_270
        if (vec.y != 0) and (vec.x != 0):
            raise ValueError(
                f"The vector between manhattan points is not manhattan {old_pt}, {pt}"
            )
        ang = (vec_angle(vec) + 2) % 4
        bend90.transform(kdb.Trans(ang, mirror, pt.x, pt.y) * b90c.inverted())
        new_bend_port = bend90.ports[b90p1.name]
        length = int((new_bend_port.trans.disp - old_bend_port.trans.disp).length())
        if length > 0:
            p1_, _ = segment(old_bend_port, new_bend_port)
            if i == 1:
                route.start_port = p1_
        route.instances.append(bend90)
        old_pt = pt
        old_bend_port = bend90.ports[b90p2.name]
    length = int((bend90.ports[b90p2.name].trans.disp - p2.trans.disp).length())
    if length > 0:
        _, p2_ = segment(old_bend_port, p2)
        route.end_port = p2_.copy()
    else:
        route.end_port = old_bend_port.copy()
    route.start_port.name = "route_start"
    route.end_port.name = "route_end"
    return route

place_manhattan_asymmetric

place_manhattan_asymmetric(c: ProtoTKCell[Any], p1: Port, p2: Port, pts: Sequence[Point], route_width: dbu | None = None, *, straight_factory: StraightFactoryDBU | None = None, bend90_cell: tuple[ProtoTKCell[Any], ProtoTKCell[Any]] | None = None, taper_cell: ProtoTKCell[Any] | None = None, port_type: str = 'optical', min_straight_taper: dbu = 0, allow_small_routes: bool = False, allow_width_mismatch: bool | None = None, allow_layer_mismatch: bool | None = None, allow_type_mismatch: bool | None = None, purpose: str | None = 'routing', **kwargs: Any) -> ManhattanRoute

Place an asymmetric profile using two opposite-handed 90° bends.

Both bends must carry the endpoint cross section and have the same radius. Classify the bends once by input orientation, then select directly at each corner to preserve the incoming transverse profile. Straight and taper connections preserve all bands, not just the core width. Width/profile changes require explicit transitions; mismatch flags cannot override profile compatibility. S-bend factories are not supported here. The returned route's default length is its Manhattan backbone length, not optical path length: area divided by core width is invalid for these profiles.

Source code in kfactory/routing/optical.py
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
def place_manhattan_asymmetric(
    c: ProtoTKCell[Any],
    p1: Port,
    p2: Port,
    pts: Sequence[kdb.Point],
    route_width: dbu | None = None,
    *,
    straight_factory: StraightFactoryDBU | None = None,
    bend90_cell: tuple[ProtoTKCell[Any], ProtoTKCell[Any]] | None = None,
    taper_cell: ProtoTKCell[Any] | None = None,
    port_type: str = "optical",
    min_straight_taper: dbu = 0,
    allow_small_routes: bool = False,
    allow_width_mismatch: bool | None = None,
    allow_layer_mismatch: bool | None = None,
    allow_type_mismatch: bool | None = None,
    purpose: str | None = "routing",
    **kwargs: Any,
) -> ManhattanRoute:
    """Place an asymmetric profile using two opposite-handed 90° bends.

    Both bends must carry the endpoint cross section and have the same radius.
    Classify the bends once by input orientation, then select directly at each
    corner to preserve the incoming transverse profile.
    Straight and taper connections preserve all bands, not just the core width.
    Width/profile changes require explicit transitions; mismatch flags cannot
    override profile compatibility. S-bend factories are not supported here.
    The returned route's default length is its Manhattan backbone length, not
    optical path length: area divided by core width is invalid for these profiles.
    """
    if kwargs:
        raise ValueError(f"Unsupported asymmetric placer arguments: {kwargs.keys()}")
    if not isinstance(bend90_cell, tuple) or len(bend90_cell) != 2:
        raise ValueError("Asymmetric placement requires two opposite-handed bends.")
    if straight_factory is None:
        raise ValueError("Asymmetric placement requires a straight_factory.")
    c = KCell(base=c.base)
    xs = p1.base.asymmetric_cross_section
    if xs is None:
        raise ValueError("Asymmetric placement requires asymmetric cross sections.")
    _check_cross_section_compatibility(p1, p2)
    if route_width is not None and route_width != p1.width:
        raise ValueError("Changing an asymmetric route width requires a transition.")
    if p1.kcl is not c.kcl or p2.kcl is not c.kcl:
        raise ValueError(
            "Asymmetric route ports must share the target cell's KCLayout."
        )
    if (
        len(pts) < 2
        or pts[0] != p1.trans.disp.to_p()
        or pts[-1] != p2.trans.disp.to_p()
    ):
        raise ValueError("The backbone must start and end at the route ports.")
    if (
        vec_angle(pts[1] - pts[0]) != p1.angle
        or (vec_angle(pts[-1] - pts[-2]) + 2) % 4 != p2.angle
    ):
        raise ValueError("The backbone must respect the route ports' angles.")
    radius = 0
    bends: dict[bool, tuple[ProtoTKCell[Any], Port, Port, kdb.Trans]] = {}
    for bend in bend90_cell:
        if bend.kcl is not c.kcl:
            raise ValueError("Asymmetric bends must share the target cell's KCLayout.")
        bp1, bp2, corner = _bend90_geometry(bend, port_type)
        if any(p.base.asymmetric_cross_section != xs for p in (bp1, bp2)):
            raise ValueError("Both bend ports must carry the route cross section.")
        bend_radius = get_radius([bp1, bp2])
        if radius and radius != bend_radius:
            raise ValueError("Asymmetric route bends must have the same radius.")
        radius = bend_radius
        bends[bp1.mirror] = bend, bp1, bp2, corner.inverted()
    if len(bends) != 2:
        raise ValueError("Asymmetric placement requires two opposite-handed bends.")
    route = ManhattanRoute(
        backbone=list(pts),
        start_port=p1.copy_polar(mirror=True),
        end_port=p2.copy_polar(mirror=True),
        instances=[],
        bend90_radius=radius,
        length_function=get_length_from_backbone,
    )
    taper_ports = None
    if taper_cell is not None:
        ports = KCell(base=taper_cell.base).ports.filter(port_type=port_type)
        if len(ports) != 2 or (ports[1].angle - ports[0].angle) % 4 != 2:
            raise ValueError("A taper must have two opposite ports.")
        if ports[1].base.asymmetric_cross_section == xs:
            ports = ports[::-1]
        if ports[0].base.asymmetric_cross_section != xs or ports[1].is_symmetric():
            raise ValueError(
                "Taper ports must connect the route to an asymmetric profile."
            )
        taper_ports = ports
        route.taper_length = round((ports[1].trans.disp - ports[0].trans.disp).length())

    def connect(cell: ProtoTKCell[Any], name: str | None, target: Port) -> Instance:
        if cell.kcl is not c.kcl:
            raise ValueError(
                "Asymmetric route cells must share the target cell's KCLayout."
            )
        inst = c << cell
        inst.purpose = purpose
        inst.connect(
            name,
            target,
            mirror=True,
            use_mirror=True,
            allow_width_mismatch=allow_width_mismatch,
            allow_layer_mismatch=allow_layer_mismatch,
            allow_type_mismatch=allow_type_mismatch,
        )
        _check_cross_section_compatibility(inst.ports[name], target)
        route.instances.append(inst)
        return inst

    def straight(start: Port, end: Port) -> tuple[Port, Port]:
        length = round((end.trans.disp - start.trans.disp).length())
        if not length:
            _check_cross_section_compatibility(start, end)
            return end.copy(), start.copy()
        cell = straight_factory(width=start.width, length=length)
        ports = KCell(base=cell.base).ports.filter(port_type=port_type)
        if len(ports) != 2:
            raise ValueError("A straight must have two routing ports.")
        inst = connect(cell, ports[0].name, start)
        first, last = inst.ports[ports[0].name], inst.ports[ports[1].name]
        _check_cross_section_compatibility(last, end)
        if last.trans.disp != end.trans.disp or (last.angle - end.angle) % 4 != 2:
            raise ValueError("The asymmetric straight does not reach its destination.")
        route.length_straights += length
        return first, last

    def segment(start: Port, end: Port) -> tuple[Port, Port]:
        length = (end.trans.disp - start.trans.disp).length()
        if taper_ports is None or length < 2 * route.taper_length + min_straight_taper:
            return straight(start, end)
        assert taper_cell is not None
        outer, inner = taper_ports
        t1 = connect(taper_cell, outer.name, start)
        t2 = connect(taper_cell, outer.name, end)
        straight(t1.ports[inner.name], t2.ports[inner.name])
        route.n_taper += 2
        return t1.ports[outer.name], t2.ports[outer.name]

    previous = p1
    for i in range(1, len(pts) - 1):
        incoming, outgoing = pts[i] - pts[i - 1], pts[i + 1] - pts[i]
        if not _is_manhattan(incoming) or not _is_manhattan(outgoing):
            raise ValueError("Asymmetric placement requires a Manhattan backbone.")
        if not allow_small_routes and (
            incoming.length() < radius * (1 if i == 1 else 2)
            or outgoing.length() < radius
        ):
            raise ValueError("Not enough space to place asymmetric route bends.")
        turn = (vec_angle(outgoing) - vec_angle(incoming)) % 4
        if turn not in (1, 3):
            raise ValueError("Bend waypoints must describe 90° turns.")
        position = kdb.Trans((vec_angle(incoming) + 2) % 4, turn == 1, pts[i].to_v())
        # The placed input must have the opposite mirror flag to the previous port.
        bend_cell, bp1, bp2, corner_inverse = bends[position.mirror == previous.mirror]
        bend = c << bend_cell
        bend.purpose = purpose
        bend.trans = position * corner_inverse
        bend_in, bend_out = bend.ports[bp1.name], bend.ports[bp2.name]
        first, _ = segment(previous, bend_in)
        if i == 1:
            route.start_port = first
        route.instances.append(bend)
        route.n_bend90 += 1
        previous = bend_out
    first, route.end_port = segment(previous, p2)
    if not route.n_bend90:
        route.start_port = first
    route.start_port.name, route.end_port.name = "route_start", "route_end"
    return route

place_manhattan_with_sbends

place_manhattan_with_sbends(c: ProtoTKCell[Any], p1: Port, p2: Port, pts: Sequence[Point], route_width: dbu | None = None, straight_factory: StraightFactoryDBU | None = None, bend90_cell: ProtoTKCell[Any] | None = None, taper_cell: ProtoTKCell[Any] | None = None, port_type: str = 'optical', min_straight_taper: dbu = 0, allow_small_routes: bool = False, allow_width_mismatch: bool | None = None, allow_layer_mismatch: bool | None = None, allow_type_mismatch: bool | None = None, purpose: str | None = 'routing', *, sbend_factory: SBendFactoryDBU | None = None, **kwargs: Any) -> ManhattanRoute

Place a symmetric backbone using straight, tapered and S-bend segments.

Bend geometry and taper ports are resolved once. Each connection between bends uses the same segment selection, including the final connection. Symmetric connection rules and area-based route length are preserved.

Source code in kfactory/routing/optical.py
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
def place_manhattan_with_sbends(
    c: ProtoTKCell[Any],
    p1: Port,
    p2: Port,
    pts: Sequence[kdb.Point],
    route_width: dbu | None = None,
    straight_factory: StraightFactoryDBU | None = None,
    bend90_cell: ProtoTKCell[Any] | None = None,
    taper_cell: ProtoTKCell[Any] | None = None,
    port_type: str = "optical",
    min_straight_taper: dbu = 0,
    allow_small_routes: bool = False,
    allow_width_mismatch: bool | None = None,
    allow_layer_mismatch: bool | None = None,
    allow_type_mismatch: bool | None = None,
    purpose: str | None = "routing",
    *,
    sbend_factory: SBendFactoryDBU | None = None,
    **kwargs: Any,
) -> ManhattanRoute:
    """Place a symmetric backbone using straight, tapered and S-bend segments.

    Bend geometry and taper ports are resolved once. Each connection between
    bends uses the same segment selection, including the final connection.
    Symmetric connection rules and area-based route length are preserved.
    """
    # configure and set up route and placers
    c = KCell(base=c.base)
    if len(kwargs) > 0:
        raise ValueError(
            f"Additional args and kwargs are not allowed for route_smart.{kwargs=}"
        )
    if allow_width_mismatch is None:
        allow_width_mismatch = config.allow_width_mismatch
    if allow_layer_mismatch is None:
        allow_layer_mismatch = config.allow_layer_mismatch
    if allow_type_mismatch is None:
        allow_type_mismatch = config.allow_type_mismatch
    if straight_factory is None:
        raise ValueError(
            "place_manhattan_with_sbends needs to have a straight_factory set. Please "
            "pass a straight_factory which takes kwargs 'width: int' and 'length: int'."
        )
    if bend90_cell is None:
        raise ValueError(
            "place_manhattan_with_sbends needs to be passed a fixed bend90 cell with "
            "two optical ports which are 90° apart from each other with port_type "
            "'port_type'."
        )
    if sbend_factory is None:
        raise ValueError(
            "place_manhattan_with_sbends needs to be passed a sbend_function."
        )
    route_start_port = p1.copy()
    route_start_port.name = "route_start"
    route_start_port.trans.angle = (route_start_port.angle + 2) % 4
    route_end_port = p2.copy()
    route_end_port.name = "route_end"
    route_end_port.trans.angle = (route_end_port.angle + 2) % 4

    b90p1, b90p2, b90c = _bend90_geometry(bend90_cell, port_type)
    # Symmetric placement historically follows the bend port's mirror flag.
    b90c.mirror = b90p1.mirror
    b90r = round(
        max(
            (b90p1.trans.disp - b90c.disp).length(),
            (b90p2.trans.disp - b90c.disp).length(),
        )
    )
    route = ManhattanRoute(
        backbone=list(pts),
        start_port=route_start_port,
        end_port=route_end_port,
        instances=[],
        bend90_radius=b90r,
    )
    if taper_cell is not None:
        taper_cell = KCell(base=taper_cell.base)
        taper_ports = [p for p in taper_cell.ports if p.port_type == "optical"]
        if (
            len(taper_ports) != NUM_PORTS_FOR_ROUTING
            or (taper_ports[1].trans.angle + 2) % 4 != taper_ports[0].trans.angle
        ):
            raise AttributeError(
                "Taper must have only two optical ports that are 180° oriented to each"
                " other"
            )
        if taper_ports[1].width == b90p1.width:
            taperp2, taperp1 = taper_ports
        elif taper_ports[0].width == b90p1.width:
            taperp1, taperp2 = taper_ports
        else:
            raise AttributeError(
                "At least one of the taper's optical ports must be the same width as"
                " the bend's ports"
            )
        route.taper_length = int((taperp1.trans.disp - taperp2.trans.disp).length())
    w = route_width or p1.width

    def segment(
        start: Port, end: Port, *, width_override: int | None = route_width
    ) -> tuple[Port, Port]:
        """Place one connection, selecting tapers only when they fit."""
        length = int((end.trans.disp - start.trans.disp).length())
        if (
            taper_cell is not None
            and length >= 2 * route.taper_length + min_straight_taper
        ):
            return _place_tapered_straight(
                c=c,
                straight_factory=straight_factory,
                taper_cell=taper_cell,
                purpose=purpose,
                route=route,
                p1=start,
                p2=end,
                route_width=width_override,
                taper_ports=(taperp1, taperp2),
                port_type=port_type,
                allow_width_mismatch=allow_width_mismatch,
                allow_layer_mismatch=allow_layer_mismatch,
                allow_type_mismatch=allow_type_mismatch,
            )
        return _place_straight(
            c=c,
            straight_factory=straight_factory,
            purpose=purpose,
            w=w,
            route=route,
            p1=start,
            p2=end,
            route_width=width_override,
            port_type=port_type,
            allow_width_mismatch=allow_width_mismatch,
            allow_layer_mismatch=allow_layer_mismatch,
            allow_type_mismatch=allow_type_mismatch,
        )

    # placing
    if not pts or len(pts) < MIN_POINTS_FOR_PLACEMENT:
        # Nothing to be placed
        return route
    old_pt = pts[0]
    old_bend_port = p1
    # the solution should be just a straight
    if len(pts) == MIN_POINTS_FOR_PLACEMENT:
        vec = pts[1] - pts[0]
        if _is_sbend_vec(vec):
            sbend_vec = (kdb.Trans(-p1.angle, False, 0, 0) * vec.to_p()).to_v()
            _place_sbend(
                c=c,
                sbend_factory=sbend_factory,
                purpose=purpose,
                w=w,
                route=route,
                p1=old_bend_port,
                p2=old_bend_port.copy_polar(d=sbend_vec.x, d_orth=sbend_vec.y, angle=2),
                allow_width_mismatch=allow_width_mismatch,
                allow_layer_mismatch=allow_layer_mismatch,
                allow_type_mismatch=allow_type_mismatch,
            )
        else:
            segment(
                route.start_port.copy_polar(),
                route.end_port.copy_polar(),
                width_override=w,
            )
        p1.name = "route_start"
        p2.name = "route_end"
        route.start_port = p1
        route.end_port = p2
        return route

    # in other cases, place the bend and then route
    for i in range(1, len(pts) - 1):
        pt = pts[i]
        new_pt = pts[i + 1]
        old_angle = old_bend_port.angle

        vec = pt - old_pt
        if _is_sbend_vec(vec):
            sbend_vec = (kdb.Trans(-old_angle, False, 0, 0) * vec.to_p()).to_v()
            bend_port = old_bend_port.copy_polar(
                d=sbend_vec.x, d_orth=sbend_vec.y, angle=2
            )
            p1_, p2_ = _place_sbend(
                c=c,
                sbend_factory=sbend_factory,
                purpose=purpose,
                w=w,
                route=route,
                p1=old_bend_port,
                p2=bend_port,
                allow_width_mismatch=allow_width_mismatch,
                allow_layer_mismatch=allow_layer_mismatch,
                allow_type_mismatch=allow_type_mismatch,
            )
            old_pt = pt
            old_bend_port = p2_
            if i == 1:
                route.start_port = p1_
            continue

        vec_n = new_pt - pt

        if _is_sbend_vec(vec_n):
            new_bend_port = old_bend_port.copy_polar(int(vec.length()))
            length = int((new_bend_port.trans.disp - old_bend_port.trans.disp).length())
            if length > 0:
                _, p2_ = segment(old_bend_port, new_bend_port)
            old_pt = pt
            old_bend_port = p2_
            continue

        if (pt.distance(old_pt) < b90r) and not allow_small_routes:
            raise ValueError(
                f"distance between points {old_pt!s} and {pt!s} is too small to"
                f" safely place bends {pt.to_s()=}, {old_pt.to_s()=},"
                f" {pt.distance(old_pt)=} < {b90r=}"
            )
        if (
            pt.distance(old_pt) < 2 * b90r
            and i not in {1, len(pts) - 1}
            and not allow_small_routes
        ):
            raise ValueError(
                f"distance between points {old_pt!s} and {pt!s} is too small to"
                f" safely place bends {pt=!s}, {old_pt=!s},"
                f" {pt.distance(old_pt)=} < {2 * b90r=}"
            )

        bend90 = c << bend90_cell
        bend90.purpose = purpose
        route.n_bend90 += 1
        mirror = (vec_angle(vec_n) - vec_angle(vec)) % 4 != ANGLE_270
        if (vec.y != 0) and (vec.x != 0):
            raise ValueError(
                f"The vector between manhattan points is not manhattan {old_pt}, {pt}"
            )
        ang = (vec_angle(vec) + 2) % 4
        bend90.transform(kdb.Trans(ang, mirror, pt.x, pt.y) * b90c.inverted())
        new_bend_port = bend90.ports[b90p1.name]
        length = int((new_bend_port.trans.disp - old_bend_port.trans.disp).length())
        if length > 0:
            p1_, p2_ = segment(old_bend_port, new_bend_port)
            if i == 1:
                route.start_port = p1_
        route.instances.append(bend90)
        old_pt = pt
        old_bend_port = bend90.ports[b90p2.name]
    vec = pts[-1] - pts[-2]
    if _is_sbend_vec(vec):
        sbend_vec = (old_bend_port.trans.inverted() * pts[-1]).to_v()
        bend_port = old_bend_port.copy_polar(d=sbend_vec.x, d_orth=sbend_vec.y, angle=2)
        _place_sbend(
            c=c,
            sbend_factory=sbend_factory,
            purpose=purpose,
            w=w,
            route=route,
            p1=old_bend_port,
            p2=bend_port,
            allow_width_mismatch=allow_width_mismatch,
            allow_layer_mismatch=allow_layer_mismatch,
            allow_type_mismatch=allow_type_mismatch,
        )
        route.end_port = bend_port
    else:
        length = int((old_bend_port.trans.disp - p2.trans.disp).length())
        if length > 0:
            _, p2_ = segment(old_bend_port, p2)
            route.end_port = p2_.copy()
        else:
            route.end_port = old_bend_port.copy()
    route.start_port.name = "route_start"
    route.end_port.name = "route_end"
    return route

route_bundle

route_bundle(c: KCell, start_ports: Sequence[Port], end_ports: Sequence[Port], separation: dbu, straight_factory: StraightFactoryDBU, bend90_cell: KCell | tuple[KCell, KCell], taper_cell: KCell | None = None, min_straight_taper: dbu = 0, place_port_type: str = 'optical', place_allow_small_routes: bool = False, collision_check_layers: Sequence[LayerInfo] | None = None, on_collision: Literal['error', 'show_error'] | None = 'show_error', on_placer_error: Literal['error', 'show_error'] | None = 'show_error', bboxes: list[Box] | None = None, allow_width_mismatch: bool | None = None, allow_layer_mismatch: bool | None = None, allow_type_mismatch: bool | None = None, route_width: dbu | list[dbu] | None = None, sort_ports: bool = False, bbox_routing: Literal['minimal', 'full'] = 'minimal', waypoints: Trans | list[Point] | None = None, starts: dbu | list[dbu] | list[Step] | list[list[Step]] | None = None, ends: dbu | list[dbu] | list[Step] | list[list[Step]] | None = None, start_angles: int | list[int] | None = None, end_angles: int | list[int] | None = None, purpose: str | None = 'routing', sbend_factory: SBendFactoryDBU | None = None, constraints: Sequence[Constraint] | None = None, route_debug: RouteDebug | None = None, route_name: str | None = None) -> list[ManhattanRoute]
route_bundle(c: DKCell, start_ports: Sequence[DPort], end_ports: Sequence[DPort], separation: um, straight_factory: StraightFactoryUM, bend90_cell: DKCell | tuple[DKCell, DKCell], taper_cell: DKCell | None = None, min_straight_taper: um = 0, place_port_type: str = 'optical', place_allow_small_routes: bool = False, collision_check_layers: Sequence[LayerInfo] | None = None, on_collision: Literal['error', 'show_error'] | None = 'show_error', on_placer_error: Literal['error', 'show_error'] | None = 'show_error', bboxes: list[DBox] | None = None, allow_width_mismatch: bool | None = None, allow_layer_mismatch: bool | None = None, allow_type_mismatch: bool | None = None, route_width: um | list[um] | None = None, sort_ports: bool = False, bbox_routing: Literal['minimal', 'full'] = 'minimal', waypoints: Trans | list[DPoint] | None = None, starts: um | list[um] | list[Step] | list[list[Step]] | None = None, ends: um | list[um] | list[Step] | list[list[Step]] | None = None, start_angles: float | list[float] | None = None, end_angles: float | list[float] | None = None, purpose: str | None = 'routing', sbend_factory: SBendFactoryUM | None = None, constraints: Sequence[Constraint] | None = None, route_debug: RouteDebug | None = None, route_name: str | None = None) -> list[ManhattanRoute]
route_bundle(c: KCell | DKCell, start_ports: Sequence[Port] | Sequence[DPort], end_ports: Sequence[Port] | Sequence[DPort], separation: dbu | um, straight_factory: StraightFactoryDBU | StraightFactoryUM, bend90_cell: KCell | DKCell | tuple[KCell, KCell] | tuple[DKCell, DKCell], taper_cell: KCell | DKCell | None = None, min_straight_taper: dbu | float = 0, place_port_type: str = 'optical', place_allow_small_routes: bool = False, collision_check_layers: Sequence[LayerInfo] | None = None, on_collision: Literal['error', 'show_error'] | None = 'show_error', on_placer_error: Literal['error', 'show_error'] | None = 'show_error', bboxes: list[Box] | list[DBox] | None = None, allow_width_mismatch: bool | None = None, allow_layer_mismatch: bool | None = None, allow_type_mismatch: bool | None = None, route_width: dbu | list[dbu] | um | list[um] | None = None, sort_ports: bool = False, bbox_routing: Literal['minimal', 'full'] = 'minimal', waypoints: Trans | list[Point] | DCplxTrans | list[DPoint] | None = None, starts: dbu | list[dbu] | um | list[um] | list[Step] | list[list[Step]] | None = None, ends: dbu | list[dbu] | um | list[um] | list[Step] | list[list[Step]] | None = None, start_angles: list[int] | float | list[float] | None = None, end_angles: list[int] | float | list[float] | None = None, purpose: str | None = 'routing', sbend_factory: SBendFactoryDBU | SBendFactoryUM | None = None, constraints: Sequence[Constraint] | None = None, route_debug: RouteDebug | None = None, route_name: str | None = None) -> list[ManhattanRoute]

Route a bundle from starting ports to end_ports.

Waypoints will create a front which will create ports in a 1D array. If waypoints are a transformation it will be like a point with a direction. If multiple points are passed, the direction will be invfered. For orientation of 0 degrees it will create the following front for 4 ports:

      │
      │
      │
      p1 ->
      │
      │
      │


      │
      │
      │
      p2 ->
      │
      │
      │
  ___\waypoint
     /
      │
      │
      │
      p3 ->
      │
      │
      │


      │
      │
      │
      p4 ->
      │
      │
      │

Parameters:

Name Type Description Default
c KCell | DKCell

Cell to place the route in.

required
start_ports Sequence[Port] | Sequence[DPort]

List of start ports.

required
end_ports Sequence[Port] | Sequence[DPort]

List of end ports.

required
separation dbu | um

Separation between the routes.

required
straight_factory StraightFactoryDBU | StraightFactoryUM

Factory function for straight cells. in DBU.

required
bend90_cell KCell | DKCell | tuple[KCell, KCell] | tuple[DKCell, DKCell]

90° bend cell, or a pair of opposite-handed bends with the same cross section and radius. Asymmetric profiles need both hands to support arbitrary turns without swapping their transverse sections.

required
taper_cell KCell | DKCell | None

Taper cell.

None
starts dbu | list[dbu] | um | list[um] | list[Step] | list[list[Step]] | None

Minimal straight segment after start_ports.

None
ends dbu | list[dbu] | um | list[um] | list[Step] | list[list[Step]] | None

Minimal straight segment before end_ports.

None
min_straight_taper dbu | float

Minimum straight [dbu] before attempting to place tapers.

0
place_port_type str

Port type to use for the bend90_cell.

'optical'
place_allow_small_routes bool

Don't throw an error if two corners cannot be placed.

False
collision_check_layers Sequence[LayerInfo] | None

Layers to check for actual errors if manhattan routes detect potential collisions.

None
on_collision Literal['error', 'show_error'] | None

Define what to do on routing collision. Default behaviour is to open send the layout of c to klive and open an error lyrdb with the collisions. "error" will simply raise an error. None will ignore any error.

'show_error'
on_placer_error Literal['error', 'show_error'] | None

If a placing of the components fails, use the strategy above to handle the error. show_error will visualize it in klayout with the intended route along the already placed parts of c. Error will just throw an error. None will ignore the error.

'show_error'
bboxes list[Box] | list[DBox] | None

List of boxes to consider. Currently only boxes overlapping ports will be considered.

None
allow_width_mismatch bool | None

If True, the width of the ports is ignored (config default: False).

None
allow_layer_mismatch bool | None

If True, the layer of the ports is ignored (config default: False).

None
allow_type_mismatch bool | None

If True, the type of the ports is ignored (config default: False).

None
route_width dbu | list[dbu] | um | list[um] | None

Width of the route. If None, the width of the ports is used.

None
sort_ports bool

Automatically sort ports.

False
bbox_routing Literal['minimal', 'full']

"minimal": only route to the bbox so that it can be safely routed around, but start or end bends might encroach on the bounding boxes when leaving them.

'minimal'
waypoints Trans | list[Point] | DCplxTrans | list[DPoint] | None

Bundle the ports and route them with minimal separation through the waypoints. The waypoints can either be a list of at least two points or a single transformation. If it's a transformation, the points will be routed through it as if it were a tunnel with length 0.

None
start_angles list[int] | float | list[float] | None

Overwrite the port orientation of all start_ports together (single value) or each one (list of values which is as long as start_ports).

None
end_angles list[int] | float | list[float] | None

Overwrite the port orientation of all start_ports together (single value) or each one (list of values which is as long as end_ports). If no waypoints are set, the target angles of all ends muts be the same (after the steps).

None
purpose str | None

Set the property "purpose" (at id kf.kcell.PROPID.PURPOSE) to the value. Not set if None.

'routing'

Returns:

Type Description
list[ManhattanRoute]

list[ManhattanRoute]: The route object with the placed components.

Source code in kfactory/routing/optical.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
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
def route_bundle(
    c: KCell | DKCell,
    start_ports: Sequence[Port] | Sequence[DPort],
    end_ports: Sequence[Port] | Sequence[DPort],
    separation: dbu | um,
    straight_factory: StraightFactoryDBU | StraightFactoryUM,
    bend90_cell: KCell | DKCell | tuple[KCell, KCell] | tuple[DKCell, DKCell],
    taper_cell: KCell | DKCell | None = None,
    min_straight_taper: dbu | float = 0,
    place_port_type: str = "optical",
    place_allow_small_routes: bool = False,
    collision_check_layers: Sequence[kdb.LayerInfo] | None = None,
    on_collision: Literal["error", "show_error"] | None = "show_error",
    on_placer_error: Literal["error", "show_error"] | None = "show_error",
    bboxes: list[kdb.Box] | list[kdb.DBox] | None = None,
    allow_width_mismatch: bool | None = None,
    allow_layer_mismatch: bool | None = None,
    allow_type_mismatch: bool | None = None,
    route_width: dbu | list[dbu] | um | list[um] | None = None,
    sort_ports: bool = False,
    bbox_routing: Literal["minimal", "full"] = "minimal",
    waypoints: kdb.Trans
    | list[kdb.Point]
    | kdb.DCplxTrans
    | list[kdb.DPoint]
    | None = None,
    starts: dbu
    | list[dbu]
    | um
    | list[um]
    | list[Step]
    | list[list[Step]]
    | None = None,
    ends: dbu | list[dbu] | um | list[um] | list[Step] | list[list[Step]] | None = None,
    start_angles: list[int] | float | list[float] | None = None,
    end_angles: list[int] | float | list[float] | None = None,
    purpose: str | None = "routing",
    sbend_factory: SBendFactoryDBU | SBendFactoryUM | None = None,
    constraints: Sequence[Constraint] | None = None,
    route_debug: RouteDebug | None = None,
    route_name: str | None = None,
) -> list[ManhattanRoute]:
    r"""Route a bundle from starting ports to end_ports.

    Waypoints will create a front which will create ports in a 1D array. If waypoints
    are a transformation it will be like a point with a direction. If multiple points
    are passed, the direction will be invfered.
    For orientation of 0 degrees it will create the following front for 4 ports:

    ```
          │
          │
          │
          p1 ->
          │
          │
          │


          │
          │
          │
          p2 ->
          │
          │
          │
      ___\waypoint
         /
          │
          │
          │
          p3 ->
          │
          │
          │


          │
          │
          │
          p4 ->
          │
          │
          │
    ```

    Args:
        c: Cell to place the route in.
        start_ports: List of start ports.
        end_ports: List of end ports.
        separation: Separation between the routes.
        straight_factory: Factory function for straight cells. in DBU.
        bend90_cell: 90° bend cell, or a pair of opposite-handed bends with the
            same cross section and radius. Asymmetric profiles need both hands
            to support arbitrary turns without swapping their transverse sections.
        taper_cell: Taper cell.
        starts: Minimal straight segment after `start_ports`.
        ends: Minimal straight segment before `end_ports`.
        min_straight_taper: Minimum straight [dbu] before attempting to place tapers.
        place_port_type: Port type to use for the bend90_cell.
        place_allow_small_routes: Don't throw an error if two corners cannot be placed.
        collision_check_layers: Layers to check for actual errors if manhattan routes
            detect potential collisions.
        on_collision: Define what to do on routing collision. Default behaviour is to
            open send the layout of c to klive and open an error lyrdb with the
            collisions. "error" will simply raise an error. None will ignore any error.
        on_placer_error: If a placing of the components fails, use the strategy above to
            handle the error. show_error will visualize it in klayout with the intended
            route along the already placed parts of c. Error will just throw an error.
            None will ignore the error.
        bboxes: List of boxes to consider. Currently only boxes overlapping ports will
            be considered.
        allow_width_mismatch: If True, the width of the ports is ignored
            (config default: False).
        allow_layer_mismatch: If True, the layer of the ports is ignored
            (config default: False).
        allow_type_mismatch: If True, the type of the ports is ignored
            (config default: False).
        route_width: Width of the route. If None, the width of the ports is used.
        sort_ports: Automatically sort ports.
        bbox_routing: "minimal": only route to the bbox so that it can be safely routed
            around, but start or end bends might encroach on the bounding boxes when
            leaving them.
        waypoints: Bundle the ports and route them with minimal separation through
            the waypoints. The waypoints can either be a list of at least two points
            or a single transformation. If it's a transformation, the points will be
            routed through it as if it were a tunnel with length 0.
        start_angles: Overwrite the port orientation of all start_ports together
            (single value) or each one (list of values which is as long as start_ports).
        end_angles: Overwrite the port orientation of all start_ports together
            (single value) or each one (list of values which is as long as end_ports).
            If no waypoints are set, the target angles of all ends muts be the same
            (after the steps).
        purpose: Set the property "purpose" (at id kf.kcell.PROPID.PURPOSE) to the
            value. Not set if None.

    Returns:
        list[ManhattanRoute]: The route object with the placed components.
    """
    if ends is None:
        ends = []
    if starts is None:
        starts = []
    if bboxes is None:
        bboxes = []
    bend90_cells = bend90_cell if isinstance(bend90_cell, tuple) else (bend90_cell,)
    bend90_radius = get_radius(bend90_cells[0].ports.filter(port_type=place_port_type))
    for bend in bend90_cells[1:]:
        if get_radius(bend.ports.filter(port_type=place_port_type)) != bend90_radius:
            raise ValueError("Route bends must have the same radius.")
    start_ports_ = [p.base.model_copy() for p in start_ports]
    end_ports_ = [p.base.model_copy() for p in end_ports]
    if sbend_factory is None:
        placer: PlacerFunction = place_manhattan
        placer_kwargs: dict[str, Any] = {
            "straight_factory": straight_factory,
            "bend90_cell": bend90_cell[0]
            if isinstance(bend90_cell, tuple)
            else bend90_cell,
            "taper_cell": taper_cell,
            "port_type": place_port_type,
            "min_straight_taper": min_straight_taper,
            "allow_small_routes": place_allow_small_routes,
            "allow_width_mismatch": allow_width_mismatch,
            "allow_layer_mismatch": allow_layer_mismatch,
            "allow_type_mismatch": allow_type_mismatch,
            "purpose": purpose,
            "route_width": route_width,
        }
    else:
        # Not a type error
        placer = place_manhattan_with_sbends
        placer_kwargs = {
            "straight_factory": straight_factory,
            "bend90_cell": bend90_cell[0]
            if isinstance(bend90_cell, tuple)
            else bend90_cell,
            "taper_cell": taper_cell,
            "port_type": place_port_type,
            "min_straight_taper": min_straight_taper,
            "allow_small_routes": place_allow_small_routes,
            "allow_width_mismatch": allow_width_mismatch,
            "allow_layer_mismatch": allow_layer_mismatch,
            "allow_type_mismatch": allow_type_mismatch,
            "purpose": purpose,
            "route_width": route_width,
            "sbend_factory": sbend_factory,
        }
    if isinstance(c, KCell):
        try:
            return route_bundle_generic(
                c=c,
                start_ports=start_ports_,
                end_ports=end_ports_,
                starts=cast("dbu | list[dbu] | list[Step] | list[list[Step]]", starts),
                ends=cast("dbu | list[dbu] | list[Step] | list[list[Step]]", ends),
                route_width=cast("int", route_width),
                on_collision=on_collision,
                on_placer_error=on_placer_error,
                collision_check_layers=collision_check_layers,
                routing_function=route_smart,
                routing_kwargs={
                    "bend90_radius": bend90_radius,
                    "separation": separation,
                    "sort_ports": sort_ports,
                    "bbox_routing": bbox_routing,
                    "bboxes": list(bboxes),
                    "waypoints": waypoints,
                    "allow_sbend": sbend_factory is not None,
                },
                placer_function=placer,
                placer_kwargs=placer_kwargs,
                asymmetric_placer_function=place_manhattan_asymmetric,
                asymmetric_placer_kwargs={**placer_kwargs, "bend90_cell": bend90_cell},
                start_angles=cast("list[int] | int", start_angles),
                end_angles=cast("list[int] | int", end_angles),
                constraints=constraints,
                route_debug=route_debug,
                route_name=route_name,
            )
        except ValueError as e:
            if str(e).startswith("Found non-manhattan waypoints."):
                waypoints = cast("list[kdb.Point]", waypoints)
                wp_old = waypoints[0]
                non_manhattan_wps: list[tuple[kdb.Point, kdb.Point, kdb.Vector]] = []
                for wp in waypoints[1:]:
                    v = wp - wp_old
                    if not _is_manhattan(v):
                        non_manhattan_wps.append((wp_old, wp, v))
                    wp_old = wp
                error_msg = (
                    "Found non-manhattan waypoints. route_smart only supports manhattan"
                    " (orthogonal to the axes) routing.\n Non-manhattan waypoints "
                    "(x,y)[dbu]:\n"
                )
                for error_wp in non_manhattan_wps:
                    error_msg += (
                        f"Start point: {error_wp[0]} End point: {error_wp[1]} "
                        f"Resulting vector (end - start): {error_wp[2]}\n"
                    )
                if on_placer_error == "show_error":
                    c_: KCell | DKCell = c.dup()
                    c_.name = c.kcl._future_cell_name or c.name
                    db = rdb.ReportDatabase("Routing Waypoint Errors")
                    err_cat = db.create_category("Waypoint Error")
                    wp_cat = db.create_category("Waypoints")
                    cell = db.create_cell(c_.name)
                    wp_len = len(waypoints)

                    width = cast("int | None", route_width) or cast(
                        "int", start_ports[0].width
                    )

                    for i, wp in enumerate(waypoints):
                        it = db.create_item(cell=cell, category=wp_cat)
                        it.add_value(f"Waypoint {i + 1}/{wp_len}")
                        it.add_value(
                            kdb.DText(
                                f"Waypoint {i + 1}/{wp_len}",
                                kdb.Trans(wp.to_v()).to_dtype(c.kcl.dbu),
                            )
                        )
                        it.add_value(
                            kdb.Box(width).moved(wp.to_v()).to_dtype(c.kcl.dbu)
                        )
                    for error_wp in non_manhattan_wps:
                        it = db.create_item(cell=cell, category=err_cat)
                        it.add_value(
                            kdb.Path([error_wp[0], error_wp[1]], width)
                            .to_dtype(c.kcl.dbu)
                            .polygon()
                        )
                    c_.show(lyrdb=db)
                raise ValueError(error_msg) from e
            raise
    if route_width is not None:
        if isinstance(route_width, list):
            route_width = [c.kcl.to_dbu(width) for width in route_width]
        else:
            route_width = c.kcl.to_dbu(route_width)
    angles: dict[int | float, int] = {0: 0, 90: 1, 180: 2, 270: 3}
    if start_angles is not None:
        if isinstance(start_angles, list):
            start_angles = [angles[angle] for angle in start_angles]
        else:
            start_angles = angles[start_angles]
    if end_angles is not None:
        if isinstance(end_angles, list):
            end_angles = [angles[angle] for angle in end_angles]
        else:
            end_angles = angles[end_angles]
    if isinstance(starts, int | float):
        starts = c.kcl.to_dbu(starts)
    elif isinstance(starts, list):
        if isinstance(starts[0], int | float):
            starts = [c.kcl.to_dbu(cast("int|float", start)) for start in starts]
        starts = cast("int | list[int] | list[Step] | list[list[Step]]", starts)
    if isinstance(ends, int | float):
        ends = c.kcl.to_dbu(ends)
    elif isinstance(ends, list):
        if isinstance(ends[0], int | float):
            ends = [c.kcl.to_dbu(cast("int|float", end)) for end in ends]
        ends = cast("int | list[int] | list[Step] | list[list[Step]]", ends)

    def _straight_factory(width: int, length: int) -> KCell:
        dkc = cast("StraightFactoryUM", straight_factory)(
            width=c.kcl.to_um(width), length=c.kcl.to_um(length)
        )
        return c.kcl[dkc.cell_index()]

    bend90_cell = (
        (c.kcl[bend90_cell[0].cell_index()], c.kcl[bend90_cell[1].cell_index()])
        if isinstance(bend90_cell, tuple)
        else c.kcl[bend90_cell.cell_index()]
    )
    if taper_cell is not None:
        taper_cell = c.kcl[taper_cell.cell_index()]
    if min_straight_taper:
        min_straight_taper = c.kcl.to_dbu(min_straight_taper)

    bboxes_ = [c.kcl.to_dbu(b) for b in cast("list[kdb.DBox]", bboxes)]
    if waypoints is not None:
        if isinstance(waypoints, list):
            waypoints = [
                p.to_itype(c.kcl.dbu) for p in cast("list[kdb.DPoint]", waypoints)
            ]
        else:
            waypoints = cast("kdb.DCplxTrans", waypoints).s_trans().to_itype(c.kcl.dbu)
    if sbend_factory is None:
        placer = place_manhattan
        placer_kwargs = {
            "straight_factory": _straight_factory,
            "bend90_cell": bend90_cell[0]
            if isinstance(bend90_cell, tuple)
            else bend90_cell,
            "taper_cell": taper_cell,
            "port_type": place_port_type,
            "min_straight_taper": min_straight_taper,
            "allow_small_routes": place_allow_small_routes,
            "allow_width_mismatch": allow_width_mismatch,
            "allow_layer_mismatch": allow_layer_mismatch,
            "allow_type_mismatch": allow_type_mismatch,
            "purpose": purpose,
            "route_width": route_width,
        }
    else:
        sbend_factory = cast("SBendFactoryUM", sbend_factory)

        def _sbend_factory(
            c: ProtoTKCell[Any], offset: dbu, length: dbu, width: dbu
        ) -> ProtoTInstance[Any] | ProtoTInstanceGroup[Any, Any]:
            return sbend_factory(
                c=c,
                offset=c.kcl.to_um(offset),
                length=c.kcl.to_um(length),
                width=c.kcl.to_um(width),
            )

        # Not a type error
        placer = place_manhattan_with_sbends
        placer_kwargs = {
            "straight_factory": _straight_factory,
            "bend90_cell": bend90_cell[0]
            if isinstance(bend90_cell, tuple)
            else bend90_cell,
            "taper_cell": taper_cell,
            "port_type": place_port_type,
            "min_straight_taper": min_straight_taper,
            "allow_small_routes": place_allow_small_routes,
            "allow_width_mismatch": allow_width_mismatch,
            "allow_layer_mismatch": allow_layer_mismatch,
            "allow_type_mismatch": allow_type_mismatch,
            "purpose": purpose,
            "route_width": route_width,
            "sbend_factory": _sbend_factory,
        }
    try:
        return route_bundle_generic(
            c=c.kcl[c.cell_index()],
            start_ports=start_ports_,
            end_ports=end_ports_,
            starts=starts,
            ends=ends,
            route_width=route_width,
            on_collision=on_collision,
            on_placer_error=on_placer_error,
            collision_check_layers=collision_check_layers,
            routing_function=route_smart,
            routing_kwargs={
                "bend90_radius": bend90_radius,
                "separation": c.kcl.to_dbu(separation),
                "sort_ports": sort_ports,
                "bbox_routing": bbox_routing,
                "bboxes": list(bboxes_),
                "waypoints": waypoints,
                "allow_sbend": sbend_factory is not None,
            },
            placer_function=placer,
            placer_kwargs=placer_kwargs,
            asymmetric_placer_function=place_manhattan_asymmetric,
            asymmetric_placer_kwargs={**placer_kwargs, "bend90_cell": bend90_cell},
            constraints=constraints,
            start_angles=start_angles,
            end_angles=end_angles,
            route_debug=route_debug,
            route_name=route_name,
        )
    except ValueError as e:
        if str(e).startswith("Found non-manhattan waypoints."):
            waypoints = cast("list[kdb.DPoint]", waypoints)
            wp_old_d = waypoints[0]
            non_manhattan_wps_d: list[tuple[kdb.DPoint, kdb.DPoint, kdb.DVector]] = []
            for wp_d in waypoints[1:]:
                v_d = wp_d - wp_old_d
                if not _is_manhattan(v_d):
                    non_manhattan_wps_d.append((wp_old_d, wp_d, v_d))
                wp_old_d = wp_d
            error_msg = (
                "Found non-manhattan waypoints. route_smart only supports manhattan"
                " (orthogonal to the axes) routing.\n Non-manhattan waypoints "
                "(x,y)[dbu]:\n"
            )
            for error_wp_d in non_manhattan_wps_d:
                error_msg += (
                    f"Start point: {error_wp_d[0]} End point: {error_wp_d[1]} "
                    f"Resulting vector (end - start): {error_wp_d[2]}\n"
                )
            if on_placer_error == "show_error":
                c_ = c.dup()
                c_.name = c.kcl._future_cell_name or c.name
                db = rdb.ReportDatabase("Routing Waypoint Errors")
                err_cat = db.create_category("Waypoint Error")
                wp_cat = db.create_category("Waypoints")
                cell = db.create_cell(c_.name)
                wp_len = len(waypoints)

                width_d = cast("float | None", route_width) or start_ports[0].width

                for i, wp_d in enumerate(waypoints):
                    it = db.create_item(cell=cell, category=wp_cat)
                    it.add_value(f"Waypoint {i + 1}/{wp_len}")
                    it.add_value(
                        kdb.DText(f"Waypoint {i + 1}/{wp_len}", kdb.DTrans(wp_d.to_v()))
                    )
                    it.add_value(kdb.DBox(width_d).moved(wp_d.to_v()))
                for error_wp_d in non_manhattan_wps_d:
                    it = db.create_item(cell=cell, category=err_cat)
                    it.add_value(
                        kdb.DPath([error_wp_d[0], error_wp_d[1]], width_d).polygon()
                    )
                c_.show(lyrdb=db)
            raise ValueError(error_msg) from e
        raise

route_loopback

route_loopback(port1: Port | Trans, port2: Port | Trans, bend90_radius: dbu, bend180_radius: dbu | None = None, start_straight: dbu = 0, end_straight: dbu = 0, d_loop: dbu = 200000, inside: bool = False) -> list[kdb.Point]

Create a loopback on two parallel ports.

inside == False
╭----╮            ╭----╮
|    |            |    |
|  -----        -----  |
|  port1        port2  |
╰----------------------╯
inside == True
    ╭---╮     ╭---╮
    |   |     |   |
  ----- |     | -----
  port1 |     | port2
        ╰-----╯

Parameters:

Name Type Description Default
port1 Port | Trans

Start port.

required
port2 Port | Trans

End port.

required
bend90_radius dbu

Radius of 90° bend. [dbu]

required
bend180_radius dbu | None

Optional use of 180° bend, distance between two parallel ports. [dbu]

None
start_straight dbu

Minimal straight segment after p1.

0
end_straight dbu

Minimal straight segment before p2.

0
d_loop dbu

Distance of the (vertical) offset of the back of the ports

200000
inside bool

Route the loopback inside the array or outside

False

Returns:

Name Type Description
points list[Point]

List of the calculated points (starting/ending at p1/p2).

Raises:

Type Description
ValueError

If the ports are not parallel or point in the same direction.

Source code in kfactory/routing/optical.py
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
def route_loopback(
    port1: Port | kdb.Trans,
    port2: Port | kdb.Trans,
    bend90_radius: dbu,
    bend180_radius: dbu | None = None,
    start_straight: dbu = 0,
    end_straight: dbu = 0,
    d_loop: dbu = 200000,
    inside: bool = False,
) -> list[kdb.Point]:
    r"""Create a loopback on two parallel ports.

        inside == False
        ╭----╮            ╭----╮
        |    |            |    |
        |  -----        -----  |
        |  port1        port2  |
        ╰----------------------╯
        inside == True
            ╭---╮     ╭---╮
            |   |     |   |
          ----- |     | -----
          port1 |     | port2
                ╰-----╯


    Args:
        port1: Start port.
        port2: End port.
        bend90_radius: Radius of 90° bend. [dbu]
        bend180_radius: Optional use of 180° bend, distance between two parallel ports.
            [dbu]
        start_straight: Minimal straight segment after `p1`.
        end_straight: Minimal straight segment before `p2`.
        d_loop: Distance of the (vertical) offset of the back of the ports
        inside: Route the loopback inside the array or outside

    Returns:
        points: List of the calculated points (starting/ending at p1/p2).

    Raises:
        ValueError: If the ports are not parallel or point in the same direction.
    """
    t1 = port1 if isinstance(port1, kdb.Trans) else port1.trans
    t2 = port2 if isinstance(port2, kdb.Trans) else port2.trans

    (t1, port1_), (t2, _) = sorted(
        [(t1, port1), (t2, port2)], key=lambda t: -(t1.inverted() * t[0]).disp.y
    )

    if (t1.angle != t2.angle) and (
        (t1.disp.x == t2.disp.x) or (t1.disp.y == t2.disp.y)
    ):
        raise ValueError(
            "for a standard loopback the ports must point in the same direction and"
            "have to be parallel"
        )

    pz = kdb.Point(0, 0)

    if (start_straight > 0 and bend180_radius is None) or (
        start_straight <= 0 and bend180_radius is None
    ):
        pts_start = [
            t1 * pz,
            t1 * kdb.Trans(0, False, start_straight + bend90_radius, 0) * pz,
        ]
    elif start_straight > 0:
        pts_start = [t1 * pz, t1 * kdb.Trans(0, False, start_straight, 0) * pz]
    else:
        pts_start = [t1 * pz]
    if (end_straight > 0 and bend180_radius is None) or (
        end_straight <= 0 and bend180_radius is None
    ):
        pts_end = [
            t2 * kdb.Trans(0, False, end_straight + bend90_radius, 0) * pz,
            t2 * pz,
        ]
    elif end_straight > 0:
        pts_end = [t2 * kdb.Trans(0, False, end_straight, 0) * pz, t2 * pz]
    else:
        pts_end = [t2 * pz]

    if inside:
        if bend180_radius is not None:
            t1 *= kdb.Trans(2, False, start_straight, -bend180_radius)
            t2 *= kdb.Trans(2, False, end_straight, bend180_radius)
        else:
            t1 *= kdb.Trans(
                2, False, start_straight + bend90_radius, -2 * bend90_radius
            )
            t2 *= kdb.Trans(2, False, end_straight + bend90_radius, 2 * bend90_radius)
    elif bend180_radius is not None:
        t1 *= kdb.Trans(2, False, start_straight, bend180_radius)
        t2 *= kdb.Trans(2, False, end_straight, -bend180_radius)
    else:
        t1 *= kdb.Trans(2, False, start_straight + bend90_radius, 2 * bend90_radius)
        t2 *= kdb.Trans(2, False, end_straight + bend90_radius, -2 * bend90_radius)

    pts = (
        pts_start
        + route_manhattan(
            t1,
            t2,
            bend90_radius,
            start_steps=[Straight(dist=start_straight + d_loop)],
        )
        + pts_end
    )

    if port1_ == port1:
        return pts
    return list(reversed(pts))

vec_angle

vec_angle(v: Vector) -> int

Determine vector angle in increments of 90°.

Returns:

Type Description
int

The angle of the vector in increments of 90° (0, 1, 2, 3).

Raises:

Type Description
ValueError

If the vector is not a manhattan vector.

Source code in kfactory/routing/optical.py
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
def vec_angle(v: kdb.Vector) -> int:
    """Determine vector angle in increments of 90°.

    Returns:
        The angle of the vector in increments of 90° (0, 1, 2, 3).

    Raises:
        ValueError: If the vector is not a manhattan vector.
    """
    if v.x != 0 and v.y != 0:
        raise ValueError("Non-manhattan vectors are not supported")

    match (v.x, v.y):
        case (x, 0) if x > 0:
            return 0
        case (x, 0) if x < 0:
            return 2
        case (0, y) if y > 0:
            return 1
        case (0, y) if y < 0:
            return 3
        case _:
            logger.warning(f"{v} is not a manhattan, cannot determine direction")
    return -1