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
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
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())
    )

route_bundle

route_bundle(
    c: KCell,
    start_ports: Sequence[Port],
    end_ports: Sequence[Port],
    separation: dbu,
    straight_factory: StraightFactoryDBU,
    bend90_cell: 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,
    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,
    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

90° bend cell.

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
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
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,
    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.
        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_radius = get_radius(bend90_cell.ports.filter(port_type=place_port_type))
    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,
            "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,
            "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,
                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.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,
            "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,
            "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,
            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
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
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

    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)

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

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
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
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