Skip to content

Electrical

electrical

Utilities for automatically routing electrical connections.

place_dual_rails

place_dual_rails(
    c: KCell,
    p1: Port,
    p2: Port,
    pts: Sequence[Point],
    route_width: int | None = None,
    layer_info: LayerInfo | None = None,
    separation_rails: int | None = None,
    **kwargs: Any,
) -> ManhattanRoute

Placer function for a single wire.

Parameters:

Name Type Description Default
c KCell

KCell to place the route in.

required
p1 Port

Start port.

required
p2 Port

End port.

required
pts Sequence[Point]

Route backbone.

required
route_width int | None

Overwrite automatic detection of wire width. Total width of all rails.

None
layer_info LayerInfo | None

Place on a specific layer. Otherwise, use p1.layer_info.

None
separation_rails int | None

Separation between the two rails.

None
kwargs Any

Compatibility for type checkers. Throws an error if not empty.

{}
Source code in kfactory/routing/electrical.py
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
def place_dual_rails(
    c: KCell,
    p1: Port,
    p2: Port,
    pts: Sequence[kdb.Point],
    route_width: int | None = None,
    layer_info: kdb.LayerInfo | None = None,
    separation_rails: int | None = None,
    **kwargs: Any,
) -> ManhattanRoute:
    """Placer function for a single wire.

    Args:
        c: KCell to place the route in.
        p1: Start port.
        p2: End port.
        pts: Route backbone.
        route_width: Overwrite automatic detection of wire width.
            Total width of all rails.
        layer_info: Place on a specific layer. Otherwise, use
            `p1.layer_info`.
        separation_rails: Separation between the two rails.
        kwargs: Compatibility for type checkers. Throws an error if not empty.
    """
    if kwargs:
        raise ValueError(
            f"Additional kwargs aren't supported in route_dual_rails {kwargs=}"
        )
    if layer_info is None:
        layer_info = p1.layer_info
    if route_width is None:
        route_width = p1.width
    if separation_rails is None:
        raise ValueError("Must specify a separation between the two rails.")
    if separation_rails >= route_width:
        raise ValueError(f"{separation_rails=} must be smaller than the {route_width}")

    region = kdb.Region(kdb.Path(pts, route_width)) - kdb.Region(
        kdb.Path(pts, separation_rails)
    )

    shapes = [
        c.shapes(c.layer(layer_info)).insert(region[0]).polygon,
        c.shapes(c.layer(layer_info)).insert(region[1]).polygon,
    ]

    return ManhattanRoute(
        backbone=list(pts),
        start_port=p1,
        end_port=p2,
        taper_length=0,
        bend90_radius=0,
        polygons={layer_info: shapes},
        instances=[],
    )

place_rf_rails

place_rf_rails(
    c: KCell,
    p1: Port,
    p2: Port,
    pts: Sequence[Point],
    route_width: int | None = None,
    *,
    center_trans: Trans | None = None,
    layer_info: LayerInfo | None = None,
    enclosure: LayerEnclosure | None = None,
    center_radius: dbu = 0,
    bend_factory: BendFactory | None = None,
    wire_factory: WireFactory | None = None,
    port_type: str = "electrical",
    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

Placer function for a single wire.

Parameters:

Name Type Description Default
c KCell

KCell to place the route in.

required
p1 Port

Start port.

required
p2 Port

End port.

required
pts Sequence[Point]

Route backbone.

required
route_width int | None

Overwrite automatic detection of wire width. Total width of all rails.

None
layer_info LayerInfo | None

Place on a specific layer. Otherwise, use p1.layer_info.

None
enclosure LayerEnclosure | None

Apply an enclosure to the rail.

None
center_radius dbu

The radius at the center of the rails.

0
bend_factory BendFactory | None

The function to call to create the rail bends.

None
wire_factory WireFactory | None

The function to call to create the straights of the rails.

None
port_type str

Which port_type to filter the bend for.

'electrical'
allow_small_routes bool

Proceed with placing even if there is not enough space.

False
allow_width_mismatch bool | None

Allow to place even if port widths do not match.

None
allow_layer_mismatch bool | None

Allow to place even if port layers do not match.

None
allow_type_mismatch bool | None

Allow to place even if port port_type do not match.

None
purpose str | None

Which Instance.purpose to assign to the created instances of the placer.

'routing'
kwargs Any

Compatibility for type checkers. Throws an error if not empty.

{}
Source code in kfactory/routing/electrical.py
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
def place_rf_rails(
    c: KCell,
    p1: Port,
    p2: Port,
    pts: Sequence[kdb.Point],
    route_width: int | None = None,
    *,
    center_trans: kdb.Trans | None = None,
    layer_info: kdb.LayerInfo | None = None,
    enclosure: LayerEnclosure | None = None,
    center_radius: dbu = 0,
    bend_factory: BendFactory | None = None,
    wire_factory: WireFactory | None = None,
    port_type: str = "electrical",
    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:
    """Placer function for a single wire.

    Args:
        c: KCell to place the route in.
        p1: Start port.
        p2: End port.
        pts: Route backbone.
        route_width: Overwrite automatic detection of wire width.
            Total width of all rails.
        layer_info: Place on a specific layer. Otherwise, use
            `p1.layer_info`.
        enclosure: Apply an enclosure to the rail.
        center_radius: The radius at the center of the rails.
        bend_factory: The function to call to create the rail bends.
        wire_factory: The function to call to create the straights of the rails.
        port_type: Which port_type to filter the bend for.
        allow_small_routes: Proceed with placing even if there is not enough space.
        allow_width_mismatch: Allow to place even if port widths do not match.
        allow_layer_mismatch: Allow to place even if port layers do not match.
        allow_type_mismatch: Allow to place even if port port_type do not match.
        purpose: Which `Instance.purpose` to assign to the created instances of the
            placer.
        kwargs: Compatibility for type checkers. Throws an error if not empty.
    """
    if kwargs:
        raise ValueError(
            f"Additional kwargs aren't supported in route_dual_rails {kwargs=}"
        )

    if center_trans is None:
        raise ValueError("For placing rf rails, center_radius must be defined")
    if wire_factory is None:
        raise ValueError("for placing rf rails a wire factory must be supplied")
    if bend_factory is None:
        raise ValueError("for placing rf rails a bend factory must be supplied")

    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 wire_factory is None:
        raise ValueError(
            "place_rf_rails needs to have a wire_factory set. Please pass a "
            "wire_factory which takes kwargs 'width: int' and 'length: int'."
        )
    cross_section = p1.kcl.get_icross_section(
        SymmetricalCrossSection(
            width=p1.width,
            enclosure=enclosure or LayerEnclosure(sections=[], main_layer=layer_info),
        )
    )
    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

    old_pt = pts[0]
    old_bend_port = p1

    offset = (center_trans.inverted() * p1.trans).disp.y
    inner_radius = center_radius - abs(offset)
    if inner_radius < 0:
        raise ValueError(
            "Radius for inner turns is below 0. Please increase center radius to get"
            " a radius >= 0."
        )
    outer_radius = center_radius + abs(offset)

    bend90_inner = bend_factory(cross_section=cross_section, radius=inner_radius)
    bend90_outer = bend_factory(cross_section=cross_section, radius=outer_radius)

    bend90_inner_ports = [p for p in bend90_inner.ports if p.port_type == port_type]
    bend90_outer_ports = [p for p in bend90_outer.ports if p.port_type == port_type]

    # test for outer same port names
    bend_outer_ports = [p for p in bend90_outer.ports if p.port_type == port_type]
    for p_in, p_out in zip(bend90_inner_ports, bend_outer_ports, strict=True):
        if not p_in.name == p_out.name:
            raise ValueError(
                "The bend port names and order must be consistent for different radii"
            )
        if not p_in.angle == p_out.angle:
            raise ValueError(
                "The bend port angles must be consistent for different radii"
            )

    if len(bend90_inner_ports) != NUM_PORTS_FOR_ROUTING:
        raise AttributeError(
            f"{bend90_inner.name} should have 2 ports but has "
            f"{len(bend90_inner_ports)} ports"
            f"with {port_type=}"
        )
    if (
        abs((bend90_inner_ports[0].trans.angle - bend90_inner_ports[1].trans.angle) % 4)
        != 1
    ):
        raise AttributeError(
            f"{bend90_inner.name} bend ports should be 90° apart from each other"
        )

    if (
        bend90_inner_ports[1].trans.angle - bend90_inner_ports[0].trans.angle
    ) % 4 == ANGLE_270:
        b90p1_inner = bend90_inner_ports[1]
        b90p2_inner = bend90_inner_ports[0]
    else:
        b90p1_inner = bend90_inner_ports[0]
        b90p2_inner = bend90_inner_ports[1]
    assert b90p1_inner.name is not None, logger.error(
        "bend90 needs named ports, {}", b90p1_inner
    )
    assert b90p2_inner.name is not None, logger.error(
        "bend90 needs named ports, {}", b90p2_inner
    )
    b90c_inner = kdb.Trans(
        b90p1_inner.trans.rot,
        b90p1_inner.trans.is_mirror(),
        b90p1_inner.trans.disp.x
        if b90p1_inner.trans.angle % 2
        else b90p2_inner.trans.disp.x,
        b90p2_inner.trans.disp.y
        if b90p1_inner.trans.angle % 2
        else b90p1_inner.trans.disp.y,
    )
    if (
        bend90_outer_ports[1].trans.angle - bend90_outer_ports[0].trans.angle
    ) % 4 == ANGLE_270:
        b90p1_outer = bend90_outer_ports[1]
        b90p2_outer = bend90_outer_ports[0]
    else:
        b90p1_outer = bend90_outer_ports[0]
        b90p2_outer = bend90_outer_ports[1]
    b90c_outer = kdb.Trans(
        b90p1_outer.trans.rot,
        b90p1_outer.trans.is_mirror(),
        b90p1_outer.trans.disp.x
        if b90p1_outer.trans.angle % 2
        else b90p2_outer.trans.disp.x,
        b90p2_outer.trans.disp.y
        if b90p1_outer.trans.angle % 2
        else b90p1_outer.trans.disp.y,
    )
    b90r_inner = round(
        max(
            (b90p1_inner.trans.disp - b90c_inner.disp).length(),
            (b90p2_inner.trans.disp - b90c_inner.disp).length(),
        )
    )
    b90r_outer = round(
        max(
            (b90p1_outer.trans.disp - b90c_outer.disp).length(),
            (b90p2_outer.trans.disp - b90c_outer.disp).length(),
        )
    )
    route = ManhattanRoute(
        backbone=list(pts).copy(),
        start_port=route_start_port,
        end_port=route_end_port,
        instances=[],
        bend90_radius=center_radius,
        taper_length=0,
    )

    if not pts or len(pts) < MIN_POINTS_FOR_PLACEMENT:
        # Nothing to be placed
        return route

    if len(pts) == MIN_POINTS_FOR_PLACEMENT:
        length = int((pts[1] - pts[0]).length())
        wg = c << wire_factory(
            cross_section=cross_section, length=int((pts[1] - pts[0]).length())
        )
        wg.purpose = purpose
        wg_p1, wg_p2 = (v for v in wg.ports if v.port_type == port_type)
        wg.connect(
            wg_p1,
            p1,
            allow_width_mismatch=route_width is not None or allow_width_mismatch,
            allow_layer_mismatch=allow_layer_mismatch,
            allow_type_mismatch=allow_type_mismatch,
        )
        route.instances.append(wg)
        route.start_port = Port(base=wg_p1.base.transformed())
        route.start_port.name = "route_start"
        route.length_straights += int(length)
        return route
    for i in range(1, len(pts) - 1):
        pt = pts[i]
        new_pt = pts[i + 1]

        if (pt.distance(old_pt) < b90r_inner) 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_inner=}"
            )
        if (
            pt.distance(old_pt) < b90r_inner + b90r_outer
            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)=} < {b90r_inner + b90r_outer=}"
            )

        vec = pt - old_pt
        vec_n = new_pt - pt
        old_angle = vec_angle(vec)
        angle = vec_angle(vec_n)

        sign = int(np.sign(offset)) or 1

        d_angle = (sign * (angle - old_angle)) % 4
        if d_angle == 1:
            bend90 = c << bend_factory(cross_section=cross_section, radius=inner_radius)
            b90c = b90c_inner
        elif d_angle == 3:
            bend90 = c << bend_factory(cross_section=cross_section, radius=outer_radius)
            b90c = b90c_outer
        else:
            raise ValueError(
                "Points are not clean. Make sure to clean the points before supplying "
                "them to the multi rail placer"
            )

        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
        if ang is None:
            raise ValueError(
                f"The vector between manhattan points is not manhattan {old_pt}, {pt}"
            )
        bend90.transform(kdb.Trans(ang, mirror, pt.x, pt.y) * b90c.inverted())
        length = int(
            (
                bend90.ports[b90p1_inner.name].trans.disp - old_bend_port.trans.disp
            ).length()
        )
        if length > 0:
            wg = c << wire_factory(cross_section=cross_section, length=length)
            wg.purpose = purpose
            wg_p1, wg_p2 = (v for v in wg.ports if v.port_type == port_type)
            wg.connect(
                wg_p1,
                bend90,
                b90p1_inner.name,
                allow_width_mismatch=allow_width_mismatch,
                allow_layer_mismatch=allow_layer_mismatch,
                allow_type_mismatch=allow_type_mismatch,
            )
            route.instances.append(wg)
            route.length_straights += int(length)
        route.instances.append(bend90)
        old_pt = pt
        old_bend_port = bend90.ports[b90p2_inner.name]
    length = int((bend90.ports[b90p2_inner.name].trans.disp - p2.trans.disp).length())
    if length > 0:
        wg = c << wire_factory(cross_section=cross_section, length=length)
        wg.purpose = purpose
        wg_p1, wg_p2 = (v for v in wg.ports if v.port_type == port_type)
        wg.connect(
            wg_p1.name,
            bend90,
            b90p2_inner.name,
            allow_width_mismatch=allow_width_mismatch,
            allow_layer_mismatch=allow_layer_mismatch,
            allow_type_mismatch=allow_type_mismatch,
        )
        route.instances.append(wg)
        route.end_port = wg.ports[wg_p2.name].copy()
        route.end_port.name = "route_end"
        route.length_straights += int(length)

    else:
        route.end_port = old_bend_port.copy()
        route.end_port.name = "route_end"
    return route

place_single_wire

place_single_wire(
    c: KCell,
    p1: Port,
    p2: Port,
    pts: Sequence[Point],
    route_width: int | None = None,
    layer_info: LayerInfo | None = None,
    **kwargs: Any,
) -> ManhattanRoute

Placer function for a single wire.

Parameters:

Name Type Description Default
c KCell

KCell to place the route in.

required
p1 Port

Start port.

required
p2 Port

End port.

required
pts Sequence[Point]

Route backbone.

required
route_width int | None

Overwrite automatic detection of wire width.

None
layer_info LayerInfo | None

Place on a specific layer. Otherwise, use p1.layer_info.

None
kwargs Any

Compatibility for type checkers. Throws an error if not empty.

{}
Source code in kfactory/routing/electrical.py
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
def place_single_wire(
    c: KCell,
    p1: Port,
    p2: Port,
    pts: Sequence[kdb.Point],
    route_width: int | None = None,
    layer_info: kdb.LayerInfo | None = None,
    **kwargs: Any,
) -> ManhattanRoute:
    """Placer function for a single wire.

    Args:
        c: KCell to place the route in.
        p1: Start port.
        p2: End port.
        pts: Route backbone.
        route_width: Overwrite automatic detection of wire width.
        layer_info: Place on a specific layer. Otherwise, use
            `p1.layer_info`.
        kwargs: Compatibility for type checkers. Throws an error if not empty.
    """
    if layer_info is None:
        layer_info = p1.layer_info
    if route_width is None:
        route_width = p1.width
    if kwargs:
        raise ValueError(
            f"Additional kwargs aren't supported in route_single_wire {kwargs=}"
        )

    shape = (
        c.shapes(c.layer(layer_info))
        .insert(kdb.Path(pts, width=route_width).polygon())
        .polygon
    )

    length = 0.0
    pt1 = pts[0]
    for pt2 in pts[1:]:
        length += (pt2 - pt1).length()

    return ManhattanRoute(
        backbone=list(pts),
        start_port=p1,
        end_port=p2,
        taper_length=0,
        bend90_radius=0,
        polygons={layer_info: [shape]},
        instances=[],
        length_straights=round(length),
        length_function=get_length_from_backbone,
    )

route_bundle

route_bundle(
    c: KCell,
    start_ports: Sequence[Port],
    end_ports: Sequence[Port],
    separation: dbu,
    place_layer: LayerInfo | None = None,
    route_width: dbu | list[dbu] | None = None,
    bboxes: Sequence[Box] | None = None,
    bbox_routing: Literal["minimal", "full"] = "minimal",
    sort_ports: 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",
    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",
    constraints: Sequence[Constraint] | None = None,
    route_debug: RouteDebug | None = None,
) -> list[ManhattanRoute]
route_bundle(
    c: DKCell,
    start_ports: Sequence[DPort],
    end_ports: Sequence[DPort],
    separation: um,
    place_layer: LayerInfo | None = None,
    route_width: um | list[um] | None = None,
    bboxes: Sequence[DBox] | None = None,
    bbox_routing: Literal["minimal", "full"] = "minimal",
    sort_ports: 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",
    waypoints: DTrans | 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",
    constraints: Sequence[Constraint] | None = None,
    route_debug: RouteDebug | None = None,
) -> list[ManhattanRoute]
route_bundle(
    c: KCell | DKCell,
    start_ports: Sequence[Port] | Sequence[DPort],
    end_ports: Sequence[Port] | Sequence[DPort],
    separation: dbu | um,
    place_layer: LayerInfo | None = None,
    route_width: dbu
    | um
    | list[dbu]
    | list[um]
    | None = None,
    bboxes: Sequence[Box] | Sequence[DBox] | None = None,
    bbox_routing: Literal["minimal", "full"] = "minimal",
    sort_ports: 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",
    waypoints: Trans
    | list[Point]
    | DTrans
    | 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",
    constraints: Sequence[Constraint] | None = None,
    route_debug: RouteDebug | None = None,
) -> list[ManhattanRoute]

Connect multiple input ports to output ports.

This function takes a list of input ports and assume they are all oriented in the same direction (could be any of W, S, E, N). The target ports have the opposite orientation, i.e. if input ports are oriented to north, and target ports should be oriented to south. The function will produce a routing to connect input ports to output ports without any crossings.

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

KCell to place the routes 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

Minimum space between wires. [dbu]

required
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
place_layer LayerInfo | None

Override automatic detection of layers with specific layer.

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

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

None
bboxes Sequence[Box] | Sequence[DBox] | None

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

None
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'
sort_ports bool

Automatically sort ports.

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'
waypoints Trans | list[Point] | DTrans | 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

Purpose of the routes. (Unused)

'routing'
Source code in kfactory/routing/electrical.py
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
def route_bundle(
    c: KCell | DKCell,
    start_ports: Sequence[Port] | Sequence[DPort],
    end_ports: Sequence[Port] | Sequence[DPort],
    separation: dbu | um,
    place_layer: kdb.LayerInfo | None = None,
    route_width: dbu | um | list[dbu] | list[um] | None = None,
    bboxes: Sequence[kdb.Box] | Sequence[kdb.DBox] | None = None,
    bbox_routing: Literal["minimal", "full"] = "minimal",
    sort_ports: 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",
    waypoints: kdb.Trans
    | list[kdb.Point]
    | kdb.DTrans
    | 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",
    constraints: Sequence[Constraint] | None = None,
    route_debug: RouteDebug | None = None,
) -> list[ManhattanRoute]:
    r"""Connect multiple input ports to output ports.

    This function takes a list of input ports and assume they are all oriented in the
    same direction (could be any of W, S, E, N). The target ports have the opposite
    orientation, i.e. if input ports are oriented to north, and target ports should
    be oriented to south. The function will produce a routing to connect input ports
    to output ports without any crossings.

    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: KCell to place the routes in.
        start_ports: List of start ports.
        end_ports: List of end ports.
        separation: Minimum space between wires. [dbu]
        starts: Minimal straight segment after `start_ports`.
        ends: Minimal straight segment before `end_ports`.
        place_layer: Override automatic detection of layers with specific layer.
        route_width: Width of the route. If None, the width of the ports is used.
        bboxes: List of boxes to consider. Currently only boxes overlapping ports will
            be considered.
        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.
        sort_ports: Automatically sort ports.
        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.
        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: Purpose of the routes. (Unused)
    """
    if ends is None:
        ends = []
    if starts is None:
        starts = []
    if bboxes is None:
        bboxes = []

    start_ports_ = [p.base.model_copy() for p in start_ports]
    end_ports_ = [p.base.model_copy() for p in end_ports]

    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),
                routing_function=route_smart,
                routing_kwargs={
                    "separation": separation,
                    "sort_ports": sort_ports,
                    "bbox_routing": bbox_routing,
                    "bboxes": list(bboxes),
                    "bend90_radius": 0,
                    "waypoints": waypoints,
                },
                placer_function=place_single_wire,
                placer_kwargs={
                    "route_width": route_width,
                },
                on_collision=on_collision,
                on_placer_error=on_placer_error,
                collision_check_layers=collision_check_layers,
                start_angles=cast("int | list[int] | None", start_angles),
                end_angles=cast("int | list[int]", end_angles),
                route_width=cast("int", route_width),
                constraints=constraints,
                route_debug=route_debug,
            )
        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 Port(base=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

    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: 30}
    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)
    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)
    try:
        return route_bundle_generic(
            c=c.kcl[c.cell_index()],
            start_ports=start_ports_,
            end_ports=end_ports_,
            starts=starts,
            ends=ends,
            routing_function=route_smart,
            routing_kwargs={
                "separation": c.kcl.to_dbu(separation),
                "sort_ports": sort_ports,
                "bbox_routing": bbox_routing,
                "bboxes": [
                    bb.to_itype(c.kcl.dbu) for bb in cast("list[kdb.DBox]", bboxes)
                ],
                "bend90_radius": 0,
                "waypoints": waypoints,
            },
            placer_function=place_single_wire,
            placer_kwargs={
                "route_width": route_width,
                "layer_info": place_layer,
            },
            on_collision=on_collision,
            on_placer_error=on_placer_error,
            collision_check_layers=collision_check_layers,
            start_angles=start_angles,
            end_angles=end_angles,
            route_width=route_width,
            constraints=constraints,
            route_debug=route_debug,
        )
    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 DPort(base=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_bundle_dual_rails

route_bundle_dual_rails(
    c: KCell,
    start_ports: list[Port],
    end_ports: list[Port],
    separation: dbu,
    place_layer: LayerInfo | None = None,
    width_rails: dbu | None = None,
    separation_rails: dbu | None = None,
    bboxes: list[Box] | None = None,
    bbox_routing: Literal["minimal", "full"] = "minimal",
    sort_ports: 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",
    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,
    constraints: Sequence[Constraint] | None = None,
    route_debug: RouteDebug | None = None,
) -> list[ManhattanRoute]

Connect multiple input ports to output ports.

This function takes a list of input ports and assume they are all oriented in the same direction (could be any of W, S, E, N). The target ports have the opposite orientation, i.e. if input ports are oriented to north, and target ports should be oriented to south. The function will produce a routing to connect input ports to output ports without any crossings.

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

KCell to place the routes in.

required
start_ports list[Port]

List of start ports.

required
end_ports list[Port]

List of end ports.

required
separation dbu

Minimum space between wires. [dbu]

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

Minimal straight segment after start_ports.

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

Minimal straight segment before end_ports.

None
place_layer LayerInfo | None

Override automatic detection of layers with specific layer.

None
width_rails dbu | None

Total width of the rails.

None
separation_rails dbu | None

Separation between the two rails.

None
bboxes list[Box] | None

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

None
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'
sort_ports bool

Automatically sort ports.

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'
waypoints Trans | list[Point] | 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 int | list[int] | 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 int | list[int] | 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
Source code in kfactory/routing/electrical.py
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
def route_bundle_dual_rails(
    c: KCell,
    start_ports: list[Port],
    end_ports: list[Port],
    separation: dbu,
    place_layer: kdb.LayerInfo | None = None,
    width_rails: dbu | None = None,
    separation_rails: dbu | None = None,
    bboxes: list[kdb.Box] | None = None,
    bbox_routing: Literal["minimal", "full"] = "minimal",
    sort_ports: 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",
    waypoints: kdb.Trans | list[kdb.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,
    constraints: Sequence[Constraint] | None = None,
    route_debug: RouteDebug | None = None,
) -> list[ManhattanRoute]:
    r"""Connect multiple input ports to output ports.

    This function takes a list of input ports and assume they are all oriented in the
    same direction (could be any of W, S, E, N). The target ports have the opposite
    orientation, i.e. if input ports are oriented to north, and target ports should
    be oriented to south. The function will produce a routing to connect input ports
    to output ports without any crossings.

    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: KCell to place the routes in.
        start_ports: List of start ports.
        end_ports: List of end ports.
        separation: Minimum space between wires. [dbu]
        starts: Minimal straight segment after `start_ports`.
        ends: Minimal straight segment before `end_ports`.
        place_layer: Override automatic detection of layers with specific layer.
        width_rails: Total width of the rails.
        separation_rails: Separation between the two rails.
        bboxes: List of boxes to consider. Currently only boxes overlapping ports will
            be considered.
        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.
        sort_ports: Automatically sort ports.
        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.
        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).
    """
    if ends is None:
        ends = []
    if starts is None:
        starts = []
    if bboxes is None:
        bboxes = []
    try:
        return route_bundle_generic(
            c=c,
            start_ports=[p.base for p in start_ports],
            end_ports=[p.base for p in end_ports],
            routing_function=route_smart,
            starts=starts,
            ends=ends,
            routing_kwargs={
                "separation": separation,
                "sort_ports": sort_ports,
                "bbox_routing": bbox_routing,
                "bboxes": list(bboxes),
                "bend90_radius": 0,
                "waypoints": waypoints,
            },
            placer_function=place_dual_rails,
            placer_kwargs={
                "separation_rails": separation_rails,
                "route_width": width_rails,
                "layer_info": place_layer,
            },
            on_collision=on_collision,
            on_placer_error=on_placer_error,
            collision_check_layers=collision_check_layers,
            start_angles=start_angles,
            end_angles=end_angles,
            constraints=constraints,
            route_debug=route_debug,
        )
    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 = width_rails or 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

route_bundle_rf

route_bundle_rf(
    c: KCell,
    start_ports: Sequence[Port] | Sequence[DPort],
    end_ports: Sequence[Port] | Sequence[DPort],
    wire_factory: WireFactory,
    bend_factory: BendFactory,
    place_port_type: str = "electrical",
    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",
    allow_width_mismatch: bool | None = None,
    allow_layer_mismatch: bool | None = None,
    allow_type_mismatch: bool | None = None,
    sort_ports: bool = False,
    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",
    minimum_radius: int = 0,
    constraints: Sequence[Constraint] | None = None,
    route_debug: RouteDebug | None = None,
    *,
    layer: LayerInfo,
    enclosure: LayerEnclosure | None = None,
    bboxes: list[Box] | 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

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
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
bend_factory BendFactory

The function to call to create the rail bends.

required
wire_factory WireFactory

The function to call to create the straights of the rails.

required
place_port_type str

Port type to use for the bend90_cell.

'electrical'
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] | 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
sort_ports bool

Automatically sort ports.

False
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/electrical.py
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
def route_bundle_rf(
    c: KCell,
    start_ports: Sequence[Port] | Sequence[DPort],
    end_ports: Sequence[Port] | Sequence[DPort],
    wire_factory: WireFactory,
    bend_factory: BendFactory,
    place_port_type: str = "electrical",
    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",
    allow_width_mismatch: bool | None = None,
    allow_layer_mismatch: bool | None = None,
    allow_type_mismatch: bool | None = None,
    sort_ports: bool = False,
    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",
    minimum_radius: int = 0,
    constraints: Sequence[Constraint] | None = None,
    route_debug: RouteDebug | None = None,
    *,
    layer: kdb.LayerInfo,
    enclosure: LayerEnclosure | None = None,
    bboxes: list[kdb.Box] | 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.
        starts: Minimal straight segment after `start_ports`.
        ends: Minimal straight segment before `end_ports`.
        bend_factory: The function to call to create the rail bends.
        wire_factory: The function to call to create the straights of the rails.
        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).
        sort_ports: Automatically sort ports.
        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.
    """
    p1 = Port(base=start_ports[0].base)
    port_angle = p1.angle

    for port in start_ports[1:]:
        if not port.angle == port_angle:
            raise ValueError(
                "All ports must have the same orientation and separation between their "
                f"core material Orientations: {[p.orientation for p in start_ports]}"
            )
    separation = 0
    if len(start_ports) > 1:
        p2 = Port(base=start_ports[1].base)
        separation = (
            round(p2.trans.disp.to_p().distance(p1.trans.disp.to_p()))
            - (p1.width + p2.width) // 2
        )

    points = [
        p1.trans.inverted() * Port(base=port.base).trans.disp.to_p()
        for port in start_ports
    ]
    min_ = min(points, key=lambda p: p.y)
    max_ = max(points, key=lambda p: p.y)

    center_radius = abs(max_.y - min_.y) // 2 + minimum_radius
    bboxes = bboxes or []
    if ends is None:
        ends = []
    if starts is None:
        starts = []

    start_ports_ = [p.base for p in start_ports]
    end_ports_ = [p.base for p in end_ports]

    p1t = p1.trans
    u = kdb.Vector()
    for p in start_ports:
        u += p.trans.disp
    u /= len(start_ports)
    center_trans = kdb.Trans(rot=p1t.angle, mirrx=p1t.mirror, x=u.x, y=u.y)

    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=None,
        on_collision=on_collision,
        on_placer_error=on_placer_error,
        collision_check_layers=collision_check_layers,
        routing_function=route_smart,
        routing_kwargs={
            "bend90_radius": center_radius,
            "separation": separation,
            "sort_ports": sort_ports,
            "bbox_routing": "minimal",
            "bboxes": list(bboxes),
            "waypoints": waypoints,
        },
        placer_function=place_rf_rails,
        placer_kwargs={
            "center_trans": center_trans,
            "layer_info": layer,
            "enclosure": enclosure,
            "center_radius": center_radius,
            "bend_factory": bend_factory,
            "wire_factory": wire_factory,
            "port_type": "electrical",
            "route_width": None,
            "allow_small_routes": False,
            "allow_width_mismatch": None,
            "allow_layer_mismatch": None,
            "allow_type_mismatch": None,
            "purpose": purpose,
        },
        start_angles=cast("list[int] | int", start_angles),
        end_angles=cast("list[int] | int", end_angles),
        constraints=constraints,
        route_debug=route_debug,
    )

route_dual_rails

route_dual_rails(
    c: KCell,
    p1: Port,
    p2: Port,
    start_straight: dbu | None = None,
    end_straight: dbu | None = None,
    route_path_function: Callable[
        ..., list[Point]
    ] = route_manhattan,
    width: dbu | None = None,
    hole_width: dbu | None = None,
    layer: int | None = None,
) -> None

Connect ports with a dual-wire rail.

Parameters:

Name Type Description Default
c KCell

KCell to place the connection in.

required
p1 Port

Start port.

required
p2 Port

End port.

required
start_straight dbu | None

Minimum straight after the start port.

None
end_straight dbu | None

Minimum straight before end port.

None
route_path_function Callable[..., list[Point]]

Function to calculate the path. Signature: route_path_function(p1, p2, bend90_radius, start_straight, end_straight)

route_manhattan
width dbu | None

Width of the rail (total). [dbu]

None
hole_width dbu | None

Width of the space between the rails. [dbu]

None
layer int | None

layer to place the rail in.

None
Source code in kfactory/routing/electrical.py
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
def route_dual_rails(
    c: KCell,
    p1: Port,
    p2: Port,
    start_straight: dbu | None = None,
    end_straight: dbu | None = None,
    route_path_function: Callable[..., list[kdb.Point]] = route_manhattan,
    width: dbu | None = None,
    hole_width: dbu | None = None,
    layer: int | None = None,
) -> None:
    """Connect ports with a dual-wire rail.

    Args:
        c: KCell to place the connection in.
        p1: Start port.
        p2: End port.
        start_straight: Minimum straight after the start port.
        end_straight: Minimum straight before end port.
        route_path_function: Function to calculate the path. Signature:
            `route_path_function(p1, p2, bend90_radius, start_straight,
            end_straight)`
        width: Width of the rail (total). [dbu]
        hole_width: Width of the space between the rails. [dbu]
        layer: layer to place the rail in.
    """
    width_ = width or p1.width
    hole_width_ = hole_width or p1.width // 2
    layer_ = layer or p1.layer

    pts = route_path_function(
        p1.copy(),
        p2.copy(),
        bend90_radius=0,
        start_steps=[Straight(dist=start_straight)],
        end_steps=[Straight(dist=end_straight)],
    )

    path = kdb.Path(pts, width_)
    hole_path = kdb.Path(pts, hole_width_)
    final_poly = kdb.Region(path.polygon()) - kdb.Region(hole_path.polygon())
    c.shapes(layer_).insert(final_poly)