Skip to content

Schematic

schematic

This is still experimental.

Caution is advised when using this, as the API might suddenly change. In order to fix bugs etc.

Schematic (dbu based schematic) class diagram: Schematic's class diagram

DSchematic (um based schematic) class diagram: DSchematic's class diagram

Anchor pydantic-model

Bases: BaseModel

Base class for placement anchors.

Subclasses (e.g. FixedAnchor, PortAnchor) define reference points used to align an instance during placement. Anchors allow to place instances relative to to their bounding box or port positions.

Source code in kfactory/schematic.py
140
141
142
143
144
145
146
class Anchor(BaseModel):
    """Base class for placement anchors.

    Subclasses (e.g. `FixedAnchor`, `PortAnchor`) define reference points used
    to align an instance during placement. Anchors allow to place instances relative to
    to their bounding box or port positions.
    """

Array pydantic-model

Bases: BaseModel

General 2D array parameterization using two pitch vectors.

Attributes:

Name Type Description
na int

Repetition count along vector A. This vector needs to have a positive x component.

nb int

Repetition count along vector B. This vector needs to have a positive y component

pitch_a tuple[Annotated[T, AfterValidator(_gez)], T]

(dx, dy) pitch for vector A. dx must be >= 0.

pitch_b tuple[T, Annotated[T, AfterValidator(_gez)]]

(dx, dy) pitch for vector B. dy must be >= 0.

Fields:

  • na (int)
  • nb (int)
  • pitch_a (tuple[Annotated[T, AfterValidator(_gez)], T])
  • pitch_b (tuple[T, Annotated[T, AfterValidator(_gez)]])
Source code in kfactory/schematic.py
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
class Array[T: (int, float)](BaseModel, extra="forbid"):
    """General 2D array parameterization using two pitch vectors.

    Attributes:
        na: Repetition count along vector A. This vector
            needs to have a positive x component.
        nb: Repetition count along vector B. This vector
            needs to have a positive y component
        pitch_a: (dx, dy) pitch for vector A. dx must be >= 0.
        pitch_b: (dx, dy) pitch for vector B. dy must be >= 0.
    """

    na: int = Field(gt=1, default=1)
    nb: int = Field(gt=0, default=1)
    pitch_a: tuple[Annotated[T, AfterValidator(_gez)], T]
    pitch_b: tuple[T, Annotated[T, AfterValidator(_gez)]]

Connection pydantic-model

Bases: SchematicNet[T]

Hard connection between two ports.

Enforced as {PortRef | PortArrayRef | Port} x {PortRef | PortArrayRef}. Two Port objects (cell ports) cannot be connected directly.

Raises:

Type Description
TypeError

If connection attempts to join two Port objects.

Fields:

  • net (tuple[PortArrayRef | PortRef | Port[T], PortArrayRef | PortRef])

Validators:

  • _sort_and_validate_netnet
Source code in kfactory/schematic.py
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
class Connection[T: (int, float)](SchematicNet[T]):
    """Hard connection between two ports.

    Enforced as {PortRef | PortArrayRef | Port} x {PortRef | PortArrayRef}.
    Two `Port` objects (cell ports) cannot be connected directly.

    Raises:
        TypeError: If connection attempts to join two `Port` objects.
    """

    net: tuple[PortArrayRef | PortRef | Port[T], PortArrayRef | PortRef] = Field(
        frozen=True
    )

    @field_validator("net", mode="before")
    @classmethod
    def _sort_and_validate_net(
        cls,
        v: tuple[PortArrayRef | PortRef | Port[T], ...],
    ) -> tuple[PortArrayRef | PortRef | Port[T], ...]:
        # Allow list/iterable input; normalize to a 2-tuple
        if not isinstance(v, tuple):
            v = tuple(v)
        if len(v) != 2:
            raise TypeError("net must contain exactly two endpoints")

        a, b = v

        # Sort without mutating the model instance (important for frozen fields/models)
        net_sorted = tuple(sorted((a, b)))

        # After sorting, ensure the RHS isn't a cell Port (your original invariant)
        if isinstance(net_sorted[1], Port):
            raise TypeError(
                "Two cell ports cannot be connected together. This would cause an "
                "invalid netlist."
            )

        return net_sorted

    @classmethod
    def from_list(
        cls, data: list[Any] | tuple[Any, ...] | dict[str, Any]
    ) -> Connection[T]:
        """Parse a Connection from a compact list/tuple/dict representation.

        Used for parsing legacy gdsfactory like connections.

        Supports array addressing like `( (inst, (ia, ib)), port )`.
        """
        if isinstance(data, list | tuple):
            if isinstance(data[0][0], list | tuple):
                p1 = {
                    "instance": data[0][0][0],
                    "port": data[0][1],
                    "ia": data[0][0][1][0],
                    "ib": data[0][0][1][1],
                }
            else:
                p1 = {"instance": data[0][0], "port": data[0][1]}
            if isinstance(data[1][0], list | tuple):
                p2 = {
                    "instance": data[1][0][0],
                    "port": data[1][1],
                    "ia": data[1][0][1][0],
                    "ib": data[1][0][1][1],
                }
            else:
                p2 = {"instance": data[1][0], "port": data[1][1]}

            return Connection[T].model_validate({"net": (p1, p2)})
        return Connection[T](**data)

from_list classmethod

from_list(
    data: list[Any] | tuple[Any, ...] | dict[str, Any],
) -> Connection[T]

Parse a Connection from a compact list/tuple/dict representation.

Used for parsing legacy gdsfactory like connections.

Supports array addressing like ( (inst, (ia, ib)), port ).

Source code in kfactory/schematic.py
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
@classmethod
def from_list(
    cls, data: list[Any] | tuple[Any, ...] | dict[str, Any]
) -> Connection[T]:
    """Parse a Connection from a compact list/tuple/dict representation.

    Used for parsing legacy gdsfactory like connections.

    Supports array addressing like `( (inst, (ia, ib)), port )`.
    """
    if isinstance(data, list | tuple):
        if isinstance(data[0][0], list | tuple):
            p1 = {
                "instance": data[0][0][0],
                "port": data[0][1],
                "ia": data[0][0][1][0],
                "ib": data[0][0][1][1],
            }
        else:
            p1 = {"instance": data[0][0], "port": data[0][1]}
        if isinstance(data[1][0], list | tuple):
            p2 = {
                "instance": data[1][0][0],
                "port": data[1][1],
                "ia": data[1][0][1][0],
                "ib": data[1][0][1][1],
            }
        else:
            p2 = {"instance": data[1][0], "port": data[1][1]}

        return Connection[T].model_validate({"net": (p1, p2)})
    return Connection[T](**data)

Constraint pydantic-model

Bases: BaseModel, ABC

Base class for schematic constraints.

Constraints operate in two phases:

  1. enforce — called by the routing function during the post-process phase, before instances are placed. Receives the ManhattanRouter objects and routing context kwargs (e.g. separation, bend90_radius).

  2. check — called by TSchematic.create_cell after routing is complete. Receives the materialized cell, the schematic, the resolved Instance objects for instance_names, and the ManhattanRoute results for route_names.

Attributes:

Name Type Description
route_names list[str]

Names of the routes this constraint applies to.

instance_names list[str]

Names of the instances this constraint applies to.

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

Behaviour when check returns False. "error" raises a ValueError. "show_error" additionally opens the cell in KLayout with an lyrdb marker database. None silently ignores failures.

Fields:

  • route_names (list[str])
  • instance_names (list[str])
  • on_failure (Literal['error', 'show_error'] | None)
Source code in kfactory/schematic.py
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
class Constraint(BaseModel, ABC, arbitrary_types_allowed=True):
    """Base class for schematic constraints.

    Constraints operate in two phases:

    1. **enforce** — called by the routing function during the post-process phase,
       before instances are placed. Receives the `ManhattanRouter` objects and routing
       context kwargs (e.g. ``separation``, ``bend90_radius``).

    2. **check** — called by `TSchematic.create_cell` after routing is complete.
       Receives the materialized cell, the schematic, the resolved `Instance` objects
       for `instance_names`, and the `ManhattanRoute` results for `route_names`.

    Attributes:
        route_names: Names of the routes this constraint applies to.
        instance_names: Names of the instances this constraint applies to.
        on_failure: Behaviour when `check` returns False. ``"error"`` raises a
            `ValueError`. ``"show_error"`` additionally opens the cell in KLayout
            with an lyrdb marker database. ``None`` silently ignores failures.
    """

    route_names: list[str]
    instance_names: list[str] = Field(default=[])
    on_failure: Literal["error", "show_error"] | None = "error"
    _routes: dict[str | None, list[ManhattanRoute]] = PrivateAttr(default={})
    _routers: dict[str | None, list[ManhattanRouter]] = PrivateAttr(default={})

    @abstractmethod
    def enforce(
        self,
        c: KCell,
        routers: Sequence[ManhattanRouter],
        route_name: str | None,
    ) -> None:
        """Enforce the constraint on the routers before placement.

        Called by the routing function. ``**kwargs`` contains routing context
        such as ``separation`` and ``bend90_radius``.
        """
        ...

    @abstractmethod
    def check(
        self,
        c: KCell,
        schematic: TSchematic[Any],
        instances: dict[str, Instance],
        routes: dict[str, list[ManhattanRoute]],
    ) -> bool:
        """Return True if the constraint is satisfied after routing."""
        ...

    def lyrdb_markers(
        self,
        c: KCell,
        schematic: TSchematic[Any],
        instances: dict[str, Instance],
        routes: dict[str, list[ManhattanRoute]],
    ) -> rdb.ReportDatabase:
        """Build an lyrdb marker database for failing routes.

        The default implementation highlights route backbones. Override for
        constraint-specific visualisation.
        """
        from klayout import rdb as _rdb

        db = _rdb.ReportDatabase(f"{self.__class__.__name__} Constraint Failure")
        cat = db.create_category("Failing Routes")
        cell = db.create_cell(c.name)
        for name in self.route_names:
            for route in routes.get(name, []):
                if len(route.backbone) >= 2:
                    item = db.create_item(cell, cat)
                    item.add_value(
                        kdb.DPath(
                            [kdb.DPoint(p) * c.kcl.dbu for p in route.backbone],
                            route.start_port.dwidth,
                        ).polygon()
                    )
        return db

check abstractmethod

check(
    c: KCell,
    schematic: TSchematic[Any],
    instances: dict[str, Instance],
    routes: dict[str, list[ManhattanRoute]],
) -> bool

Return True if the constraint is satisfied after routing.

Source code in kfactory/schematic.py
858
859
860
861
862
863
864
865
866
867
@abstractmethod
def check(
    self,
    c: KCell,
    schematic: TSchematic[Any],
    instances: dict[str, Instance],
    routes: dict[str, list[ManhattanRoute]],
) -> bool:
    """Return True if the constraint is satisfied after routing."""
    ...

enforce abstractmethod

enforce(
    c: KCell,
    routers: Sequence[ManhattanRouter],
    route_name: str | None,
) -> None

Enforce the constraint on the routers before placement.

Called by the routing function. **kwargs contains routing context such as separation and bend90_radius.

Source code in kfactory/schematic.py
844
845
846
847
848
849
850
851
852
853
854
855
856
@abstractmethod
def enforce(
    self,
    c: KCell,
    routers: Sequence[ManhattanRouter],
    route_name: str | None,
) -> None:
    """Enforce the constraint on the routers before placement.

    Called by the routing function. ``**kwargs`` contains routing context
    such as ``separation`` and ``bend90_radius``.
    """
    ...

lyrdb_markers

lyrdb_markers(
    c: KCell,
    schematic: TSchematic[Any],
    instances: dict[str, Instance],
    routes: dict[str, list[ManhattanRoute]],
) -> rdb.ReportDatabase

Build an lyrdb marker database for failing routes.

The default implementation highlights route backbones. Override for constraint-specific visualisation.

Source code in kfactory/schematic.py
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
def lyrdb_markers(
    self,
    c: KCell,
    schematic: TSchematic[Any],
    instances: dict[str, Instance],
    routes: dict[str, list[ManhattanRoute]],
) -> rdb.ReportDatabase:
    """Build an lyrdb marker database for failing routes.

    The default implementation highlights route backbones. Override for
    constraint-specific visualisation.
    """
    from klayout import rdb as _rdb

    db = _rdb.ReportDatabase(f"{self.__class__.__name__} Constraint Failure")
    cat = db.create_category("Failing Routes")
    cell = db.create_cell(c.name)
    for name in self.route_names:
        for route in routes.get(name, []):
            if len(route.backbone) >= 2:
                item = db.create_item(cell, cat)
                item.add_value(
                    kdb.DPath(
                        [kdb.DPoint(p) * c.kcl.dbu for p in route.backbone],
                        route.start_port.dwidth,
                    ).polygon()
                )
    return db

DSchema pydantic-model

Bases: DSchematic

Deprecated alias for DSchematic (will be removed in kfactory 2.0).

Fields:

Validators:

  • _validate_schematic
  • assign_backrefs
Source code in kfactory/schematic.py
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
class DSchema(DSchematic):
    """Deprecated alias for `DSchematic` (will be removed in kfactory 2.0)."""

    def __init__(self, **data: Any) -> None:
        logger.warning(
            "DSchema is deprecated, please use DSchematic. "
            "It will be removed in kfactory 2.0"
        )
        if "unit" in data:
            raise ValueError(
                "Cannot set the unit direct. It needs to be set by the class init."
            )
        super().__init__(**data)

DSchematic pydantic-model

Bases: TSchematic[um]

Schematic with a base unit of um for placements.

Fields:

Validators:

  • _validate_schematic
  • assign_backrefs
Source code in kfactory/schematic.py
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
class DSchematic(TSchematic[um]):
    """Schematic with a base unit of um for placements."""

    unit: Literal["um"] = "um"

    def __init__(self, **data: Any) -> None:
        if "unit" in data:
            raise ValueError(
                "Cannot set the unit direct. It needs to be set by the class init."
            )
        super().__init__(unit="um", **data)

FixedAnchor pydantic-model

Bases: Anchor

Anchor an instance to a fixed point of its own bounding box.

Attributes:

Name Type Description
x Literal['left', 'center', 'right'] | None

Horizontal anchor relative to the instance bbox ("left", "center", "right").

y Literal['bottom', 'center', 'top'] | None

Vertical anchor relative to the instance bbox ("bottom", "center", "top").

Fields:

  • x (Literal['left', 'center', 'right'] | None)
  • y (Literal['bottom', 'center', 'top'] | None)
Source code in kfactory/schematic.py
149
150
151
152
153
154
155
156
157
158
class FixedAnchor(Anchor):
    """Anchor an instance to a fixed point of its own bounding box.

    Attributes:
        x: Horizontal anchor relative to the instance bbox ("left", "center", "right").
        y: Vertical anchor relative to the instance bbox ("bottom", "center", "top").
    """

    x: Literal["left", "center", "right"] | None = None
    y: Literal["bottom", "center", "top"] | None = None

MirrorPlacement pydantic-model

Bases: BaseModel

Mirror-only placement toggle for an instance.

Mirror only placements are used for connections. This ensures that the schematic can keep track of the relative mirror in case its placement is defined through connections only (i.e. purely relative to neighboring instances).

Attributes:

Name Type Description
mirror bool

Whether the instance should be mirrored horizontally.

Fields:

  • mirror (bool)
Source code in kfactory/schematic.py
126
127
128
129
130
131
132
133
134
135
136
137
class MirrorPlacement(BaseModel, extra="forbid"):
    """Mirror-only placement toggle for an instance.

    Mirror only placements are used for connections. This ensures that the schematic can
    keep track of the relative mirror in case its placement is defined through
    connections only (i.e. purely relative to neighboring instances).

    Attributes:
        mirror: Whether the instance should be mirrored horizontally.
    """

    mirror: bool = False

PathLengthMatch pydantic-model

Bases: Constraint

Constraint that equalises optical path lengths across a set of routes.

Uses the loop-based path-length matching already built into the optical router. The enforce method injects meander loops into the shorter routers so that all routes reach the same length before instances are placed. The check method verifies the final ManhattanRoute lengths are within tolerance of each other.

Attributes:

Name Type Description
loops int

Number of meander loops to use per route.

loop_side int

Which side of the route to place the loop on.

loop_position int

Where along the route to place the loop.

element int

Index of the straight segment to insert the loop into.

tolerance int

Maximum allowed length difference after enforcement.

Fields:

  • route_names (list[str])
  • instance_names (list[str])
  • on_failure (Literal['error', 'show_error'] | None)
  • loops (int)
  • loop_side (int)
  • loop_position (int)
  • element (int)
  • tolerance (int)
  • length (int | None)
  • all (bool)
Source code in kfactory/schematic.py
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
class PathLengthMatch(Constraint):
    """Constraint that equalises optical path lengths across a set of routes.

    Uses the loop-based path-length matching already built into the optical
    router.  The `enforce` method injects meander loops into the shorter
    routers so that all routes reach the same length before instances are
    placed.  The `check` method verifies the final `ManhattanRoute` lengths
    are within `tolerance` of each other.

    Attributes:
        loops: Number of meander loops to use per route.
        loop_side: Which side of the route to place the loop on.
        loop_position: Where along the route to place the loop.
        element: Index of the straight segment to insert the loop into.
        tolerance: Maximum allowed length difference after enforcement.
    """

    loops: int = 1
    loop_side: int = -1  # LoopSide.left
    loop_position: int = -1  # LoopPosition.start
    element: int = -1
    tolerance: int = 0
    length: int | None = None
    all: bool = False

    def enforce(
        self,
        c: KCell,
        routers: Sequence[ManhattanRouter],
        route_name: str | None,
    ) -> None:
        from .routing.optical import LoopPosition, LoopSide, path_length_match

        if self.all or (len(self.route_names) - len(self._routers)) == 1:
            path_length_match(
                routers=routers,
                element=self.element,
                loops=self.loops,
                loop_side=LoopSide(self.loop_side),
                loop_position=LoopPosition(self.loop_position),
                path_length=self.length,
            )

        self._routers[route_name] = list(routers)

    def check(
        self,
        c: KCell,
        schematic: TSchematic[Any],
        instances: dict[str, Instance],
        routes: dict[str, list[ManhattanRoute]],
    ) -> bool:
        all_routes = [r for name in self.route_names for r in routes.get(name, [])]
        if not all_routes:
            return True
        lengths = [r.length for r in all_routes]
        return (max(lengths) - min(lengths)) <= self.tolerance

    def lyrdb_markers(
        self,
        c: KCell,
        schematic: TSchematic[Any],
        instances: dict[str, Instance],
        routes: dict[str, list[ManhattanRoute]],
    ) -> rdb.ReportDatabase:
        from klayout import rdb as _rdb

        all_routes = [r for name in self.route_names for r in routes.get(name, [])]
        lengths = [r.length for r in all_routes] if all_routes else []
        target = max(lengths) if lengths else 0

        db = _rdb.ReportDatabase("PathLengthMatch Constraint Failure")
        cat = db.create_category("Length Mismatch")
        cell = db.create_cell(c.name)
        for name in self.route_names:
            for route in routes.get(name, []):
                delta = target - route.length
                if delta > self.tolerance and len(route.backbone) >= 2:
                    item = db.create_item(cell, cat)
                    item.add_value(
                        kdb.DPath(
                            [kdb.DPoint(p) * c.kcl.dbu for p in route.backbone],
                            route.start_port.dwidth,
                        ).polygon()
                    )
                    item.add_value(f"length={route.length}, delta={delta}")
        return db

check

check(
    c: KCell,
    schematic: TSchematic[Any],
    instances: dict[str, Instance],
    routes: dict[str, list[ManhattanRoute]],
) -> bool

Return True if the constraint is satisfied after routing.

Source code in kfactory/schematic.py
944
945
946
947
948
949
950
951
952
953
954
955
def check(
    self,
    c: KCell,
    schematic: TSchematic[Any],
    instances: dict[str, Instance],
    routes: dict[str, list[ManhattanRoute]],
) -> bool:
    all_routes = [r for name in self.route_names for r in routes.get(name, [])]
    if not all_routes:
        return True
    lengths = [r.length for r in all_routes]
    return (max(lengths) - min(lengths)) <= self.tolerance

enforce

enforce(
    c: KCell,
    routers: Sequence[ManhattanRouter],
    route_name: str | None,
) -> None

Enforce the constraint on the routers before placement.

Called by the routing function. **kwargs contains routing context such as separation and bend90_radius.

Source code in kfactory/schematic.py
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
def enforce(
    self,
    c: KCell,
    routers: Sequence[ManhattanRouter],
    route_name: str | None,
) -> None:
    from .routing.optical import LoopPosition, LoopSide, path_length_match

    if self.all or (len(self.route_names) - len(self._routers)) == 1:
        path_length_match(
            routers=routers,
            element=self.element,
            loops=self.loops,
            loop_side=LoopSide(self.loop_side),
            loop_position=LoopPosition(self.loop_position),
            path_length=self.length,
        )

    self._routers[route_name] = list(routers)

lyrdb_markers

lyrdb_markers(
    c: KCell,
    schematic: TSchematic[Any],
    instances: dict[str, Instance],
    routes: dict[str, list[ManhattanRoute]],
) -> rdb.ReportDatabase

Build an lyrdb marker database for failing routes.

The default implementation highlights route backbones. Override for constraint-specific visualisation.

Source code in kfactory/schematic.py
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
def lyrdb_markers(
    self,
    c: KCell,
    schematic: TSchematic[Any],
    instances: dict[str, Instance],
    routes: dict[str, list[ManhattanRoute]],
) -> rdb.ReportDatabase:
    from klayout import rdb as _rdb

    all_routes = [r for name in self.route_names for r in routes.get(name, [])]
    lengths = [r.length for r in all_routes] if all_routes else []
    target = max(lengths) if lengths else 0

    db = _rdb.ReportDatabase("PathLengthMatch Constraint Failure")
    cat = db.create_category("Length Mismatch")
    cell = db.create_cell(c.name)
    for name in self.route_names:
        for route in routes.get(name, []):
            delta = target - route.length
            if delta > self.tolerance and len(route.backbone) >= 2:
                item = db.create_item(cell, cat)
                item.add_value(
                    kdb.DPath(
                        [kdb.DPoint(p) * c.kcl.dbu for p in route.backbone],
                        route.start_port.dwidth,
                    ).polygon()
                )
                item.add_value(f"length={route.length}, delta={delta}")
    return db

Pin pydantic-model

Bases: BaseModel

A schematic-level pin grouping one or more schematic-level ports.

The pin will be materialized on the resulting cell at create_cell time as a :class:kfactory.Pin. The ports list references entries in :attr:TSchematic.ports by name.

Attributes:

Name Type Description
name str

Pin name (key in :attr:TSchematic.pins).

ports list[str]

Names of schematic-level ports that belong to this pin.

pin_type str

Pin type (default "DC").

info dict[str, JSONSerializable]

Free-form info attached to the pin.

Fields:

  • name (str)
  • ports (list[str])
  • pin_type (str)
  • info (dict[str, JSONSerializable])
Source code in kfactory/schematic.py
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
class Pin(BaseModel, extra="forbid"):
    """A schematic-level pin grouping one or more schematic-level ports.

    The pin will be materialized on the resulting cell at ``create_cell``
    time as a :class:`kfactory.Pin`. The ``ports`` list references entries
    in :attr:`TSchematic.ports` by name.

    Attributes:
        name: Pin name (key in :attr:`TSchematic.pins`).
        ports: Names of schematic-level ports that belong to this pin.
        pin_type: Pin type (default ``"DC"``).
        info: Free-form info attached to the pin.
    """

    name: str = Field(exclude=True)
    ports: list[str]
    pin_type: str = "DC"
    info: dict[str, JSONSerializable] = Field(default_factory=dict)

PinRef pydantic-model

Bases: BaseModel

Reference to a pin on a schematic instance.

Produced by inst.pins["name"] and used as the pin argument of :meth:TSchematic.add_pin to expose an instance pin as a top-level schematic pin.

Fields:

  • instance (str)
  • pin (str)
Source code in kfactory/schematic.py
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
class PinRef(BaseModel, extra="forbid"):
    """Reference to a pin on a schematic instance.

    Produced by ``inst.pins["name"]`` and used as the ``pin`` argument of
    :meth:`TSchematic.add_pin` to expose an instance pin as a top-level
    schematic pin.
    """

    instance: str
    pin: str

    @property
    def name(self) -> str:
        return self.pin

    def __lt__(self, other: PinRef) -> bool:
        return (self.instance, self.pin) < (other.instance, other.pin)

    def __hash__(self) -> int:
        return hash((self.instance, self.pin))

    def __eq__(self, other: object) -> bool:
        return (
            isinstance(other, PinRef)
            and self.instance == other.instance
            and self.pin == other.pin
        )

    def as_python_str(self, inst_name: str | None = None) -> str:
        return f"{inst_name or self.instance}.pins[{self.pin!r}]"

Pins

Indexer for an instance's pins to produce PinRef.

Example

inst.pins["dc"] -> PinRef

Source code in kfactory/schematic.py
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
class Pins[T: (int, float)]:
    """Indexer for an instance's pins to produce `PinRef`.

    Example:
        `inst.pins["dc"]` -> `PinRef`
    """

    __slots__ = ("instance",)

    def __init__(self, instance: SchematicInstance[T]) -> None:
        self.instance = instance

    def __getitem__(self, key: str) -> PinRef:
        """Return a pin reference."""
        return PinRef(instance=self.instance.name, pin=key)

__getitem__

__getitem__(key: str) -> PinRef

Return a pin reference.

Source code in kfactory/schematic.py
351
352
353
def __getitem__(self, key: str) -> PinRef:
    """Return a pin reference."""
    return PinRef(instance=self.instance.name, pin=key)

Placement pydantic-model

Bases: MirrorPlacement

Absolute placement and orientation for an instance.

Coordinates may be absolute (x, y) with relative offsets (dx, dy), and can reference other instance ports via PortRef/PortArrayRef. These are still considered absolute placements, but allow relative

Attributes:

Name Type Description
x int | T | PortRef | PortArrayRef | AnchorRefX

x position or a port reference providing the x coordinate.

dx int | T

Relative X offset added to x.

y int | T | PortRef | PortArrayRef | AnchorRefY

y position or a port reference providing the y coordinate.

dy int | T

Relative Y offset added to y.

orientation float | PortRef

Rotation in degrees (0, 90, 180, 270). Can be a reference to another instance's port.

anchor FixedAnchor | PortAnchor | None

Optional FixedAnchor/PortAnchor to align the instance relative to its bounding box or one of its ports.

mirror bool

Whether the instance is to be mirrored or not.

Fields:

  • mirror (bool)
  • x (int | T | PortRef | PortArrayRef | AnchorRefX)
  • dx (int | T)
  • y (int | T | PortRef | PortArrayRef | AnchorRefY)
  • dy (int | T)
  • orientation (float | PortRef)
  • anchor (FixedAnchor | PortAnchor | None)

Validators:

  • _replace_rotation_orientation
Source code in kfactory/schematic.py
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
class Placement[T: (int, float)](MirrorPlacement, extra="forbid"):
    """Absolute placement and orientation for an instance.

    Coordinates may be absolute (`x`, `y`) with
    relative offsets (`dx`, `dy`), and can reference other instance ports via
    `PortRef`/`PortArrayRef`. These are still considered absolute placements, but
    allow relative

    Attributes:
        x: x position or a port reference providing the x coordinate.
        dx: Relative X offset added to `x`.
        y: y position or a port reference providing the y coordinate.
        dy: Relative Y offset added to `y`.
        orientation: Rotation in degrees (0, 90, 180, 270). Can be a reference
            to another instance's port.
        anchor: Optional `FixedAnchor`/`PortAnchor` to align the instance relative
            to its bounding box or one of its ports.
        mirror: Whether the instance is to be mirrored or not.
    """

    x: int | T | PortRef | PortArrayRef | AnchorRefX = 0
    dx: int | T = 0
    y: int | T | PortRef | PortArrayRef | AnchorRefY = 0
    dy: int | T = 0
    orientation: float | PortRef = 0
    anchor: FixedAnchor | PortAnchor | None = None

    @model_validator(mode="before")
    @classmethod
    def _replace_rotation_orientation(cls, data: dict[str, Any]) -> dict[str, Any]:
        if "rotation" in data:
            data["orientation"] = data.pop("rotation")
        return data

    def is_placeable(self, placed_instances: set[str], placed_ports: set[str]) -> bool:
        """Return True if all referenced instances/ports are already placed.

        If true, this means this instance can be placed now.
        """
        placeable = True
        if isinstance(self.x, PortRef):
            placeable = self.x.instance in placed_instances
        elif isinstance(self.x, Port):
            placeable = placeable and self.x.name in placed_ports
        elif isinstance(self.x, AnchorRefX):
            placeable = placeable and self.x.instance in placed_instances
        if isinstance(self.y, PortRef):
            placeable = placeable and self.y.instance in placed_instances
        elif isinstance(self.y, Port):
            placeable = placeable and self.y.name in placed_ports
        elif isinstance(self.y, AnchorRefY):
            placeable = placeable and self.y.instance in placed_instances
        if isinstance(self.orientation, PortRef):
            placeable = placeable and self.orientation.instance in placed_instances
        return placeable

is_placeable

is_placeable(
    placed_instances: set[str], placed_ports: set[str]
) -> bool

Return True if all referenced instances/ports are already placed.

If true, this means this instance can be placed now.

Source code in kfactory/schematic.py
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
def is_placeable(self, placed_instances: set[str], placed_ports: set[str]) -> bool:
    """Return True if all referenced instances/ports are already placed.

    If true, this means this instance can be placed now.
    """
    placeable = True
    if isinstance(self.x, PortRef):
        placeable = self.x.instance in placed_instances
    elif isinstance(self.x, Port):
        placeable = placeable and self.x.name in placed_ports
    elif isinstance(self.x, AnchorRefX):
        placeable = placeable and self.x.instance in placed_instances
    if isinstance(self.y, PortRef):
        placeable = placeable and self.y.instance in placed_instances
    elif isinstance(self.y, Port):
        placeable = placeable and self.y.name in placed_ports
    elif isinstance(self.y, AnchorRefY):
        placeable = placeable and self.y.instance in placed_instances
    if isinstance(self.orientation, PortRef):
        placeable = placeable and self.orientation.instance in placed_instances
    return placeable

Port pydantic-model

Bases: BaseModel

A schematic-level, placeable port.

This port is on the Schematic's cell's level, i.e. equivalent of (D)KCell.ports (or Component.ports).

The port position/orientation can be absolute or derived from other placed instance ports via PortRef/PortArrayRef.

Attributes:

Name Type Description
name str

Port name (key in schematic).

x T | PortRef | AnchorRefX

x position or PortRef.

y T | PortRef | AnchorRefY

y position or PortRef.

dx T

Relative x offset.

dy T

Relative y offset.

cross_section str

Name of the cross-section to apply.

orientation Literal[0, 90, 180, 270] | PortRef

Orientation in degrees or PortRef.

Methods:

Name Description
is_placeable

True if all references resolve to already placed instances.

Fields:

  • name (str)
  • x (T | PortRef | AnchorRefX)
  • y (T | PortRef | AnchorRefY)
  • dx (T)
  • dy (T)
  • cross_section (str)
  • orientation (Literal[0, 90, 180, 270] | PortRef)
Source code in kfactory/schematic.py
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
class Port[T: (int, float)](BaseModel, extra="forbid"):
    """A schematic-level, placeable port.

    This port is on the Schematic's cell's level, i.e. equivalent of `(D)KCell.ports`
    (or `Component.ports`).

    The port position/orientation can be absolute or derived from other placed
    instance ports via `PortRef`/`PortArrayRef`.

    Attributes:
        name: Port name (key in schematic).
        x: x position or `PortRef`.
        y: y position or `PortRef`.
        dx: Relative x offset.
        dy: Relative y offset.
        cross_section: Name of the cross-section to apply.
        orientation: Orientation in degrees or `PortRef`.

    Methods:
        is_placeable: True if all references resolve to already placed instances.
    """

    name: str = Field(exclude=True)
    x: T | PortRef | AnchorRefX
    y: T | PortRef | AnchorRefY
    dx: T = 0
    dy: T = 0
    cross_section: str
    orientation: Literal[0, 90, 180, 270] | PortRef

    def __lt__(self, other: Port[T] | PortRef) -> bool:
        if not isinstance(other, Port):
            return True
        if self.name != other.name:
            return self.name < other.name
        x = self.x
        ox = other.x
        if _is_real(x):
            if _is_real(ox):
                return x < ox
            if x != ox:
                return False
        elif _is_port_ref(x):
            if _is_real(ox):
                return False
            if _is_port_ref(ox):
                return x < ox
            return True
        else:
            if _is_real(ox) or _is_port_ref(ox):
                return False
            return x < ox  # ty:ignore[unsupported-operator]
        y = self.y
        oy = other.y
        if _is_real(y):
            if _is_real(oy):
                return y < oy
            if y != oy:
                return False
        elif _is_port_ref(y):
            if _is_real(oy):
                return False
            if _is_port_ref(oy):
                return y < oy
            return True
        else:
            if _is_real(oy) or _is_port_ref(oy):
                return False
            return y < oy  # ty:ignore[unsupported-operator]

        if self.dx != other.dx:
            return self.dx < other.dx
        if self.dy != other.dy:
            return self.dy < other.dy
        if self.cross_section != other.cross_section:
            return self.cross_section < other.cross_section
        if isinstance(self.orientation, int | float):
            if isinstance(other, int | float):
                return self.orientation < other.orientation
            return False
        if isinstance(other.orientation, PortRef):
            return self.orientation < other.orientation

        return True

    def is_placeable(self, placed_instances: set[str]) -> bool:
        placeable = True
        if isinstance(self.x, PortRef | AnchorRefX):
            placeable = self.x.instance in placed_instances
        if isinstance(self.y, PortRef | AnchorRefY):
            placeable = placeable and self.y.instance in placed_instances
        if isinstance(self.orientation, PortRef):
            placeable = placeable and self.orientation.instance in placed_instances
        return placeable

    def __str__(self) -> str:
        return self.as_python_str()

    def as_call(self) -> str:
        port_str = f"x={self.x}, y={self.y}"
        if self.dx:
            port_str += f", {self.dx}"
        if self.dy:
            port_str += f", {self.dy}"

        return port_str

    def as_python_str(self, schematic_name: str = "schematic") -> str:
        return f"{schematic_name}.ports[{self.name!r}]"

PortAnchor pydantic-model

Bases: Anchor

Anchor an instance using one of its ports.

Attributes:

Name Type Description
port str

Name of the port on the instance to use as the anchor point.

Fields:

  • port (str)
Source code in kfactory/schematic.py
161
162
163
164
165
166
167
168
class PortAnchor(Anchor):
    """Anchor an instance using one of its ports.

    Attributes:
        port: Name of the port on the instance to use as the anchor point.
    """

    port: str

Ports

Indexer for an instance's ports to produce PortRef/PortArrayRef.

Example

inst.ports["out"] -> PortRef inst.ports["out", 1, 0] -> PortArrayRef (requires instance array)

Source code in kfactory/schematic.py
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
class Ports[T: (int, float)]:
    """Indexer for an instance's ports to produce `PortRef`/`PortArrayRef`.

    Example:
        `inst.ports["out"]` -> `PortRef`
        `inst.ports["out", 1, 0]` -> `PortArrayRef` (requires instance array)
    """

    __slots__ = ("instance",)

    def __init__(self, instance: SchematicInstance[T]) -> None:
        self.instance = instance

    def __getitem__(self, key: str | tuple[str, int, int]) -> PortRef | PortArrayRef:
        """Return a port reference for a (standard or array) port."""
        if isinstance(key, tuple):
            if self.instance.array is None:
                raise ValueError(
                    "Cannot use an array port reference if the schema"
                    " instance is not an Array."
                )
            return PortArrayRef(
                instance=self.instance.name, port=key[0], ia=key[1], ib=key[2]
            )
        return PortRef(instance=self.instance.name, port=key)

__getitem__

__getitem__(
    key: str | tuple[str, int, int],
) -> PortRef | PortArrayRef

Return a port reference for a (standard or array) port.

Source code in kfactory/schematic.py
325
326
327
328
329
330
331
332
333
334
335
336
def __getitem__(self, key: str | tuple[str, int, int]) -> PortRef | PortArrayRef:
    """Return a port reference for a (standard or array) port."""
    if isinstance(key, tuple):
        if self.instance.array is None:
            raise ValueError(
                "Cannot use an array port reference if the schema"
                " instance is not an Array."
            )
        return PortArrayRef(
            instance=self.instance.name, port=key[0], ia=key[1], ib=key[2]
        )
    return PortRef(instance=self.instance.name, port=key)

RegularArray pydantic-model

Bases: BaseModel

Rectangular array with uniform row/column pitch.

Attributes:

Name Type Description
columns int

Number of columns (> 0).

column_pitch T

Distance between columns.

rows int

Number of rows (> 0).

row_pitch T

Distance between rows.

Fields:

  • columns (int)
  • column_pitch (T)
  • rows (int)
  • row_pitch (T)
Source code in kfactory/schematic.py
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
class RegularArray[T: (int, float)](BaseModel, extra="forbid"):
    """Rectangular array with uniform row/column pitch.

    Attributes:
        columns: Number of columns (> 0).
        column_pitch: Distance between columns.
        rows: Number of rows (> 0).
        row_pitch: Distance between rows.
    """

    columns: int = Field(gt=0, default=1)
    column_pitch: T
    rows: int = Field(gt=0, default=1)
    row_pitch: T

    def __repr__(self) -> str:
        return f"RegularArray(columns={self.columns}, columns_pitch=)"

Route pydantic-model

Bases: BaseModel

Bundle of Links routed using a named strategy.

Attributes:

Name Type Description
name str

Route identifier (key in (D)Schematic.routes).

routing_strategy str

Name of routing function registered on the Schematic.create_cell or registered in KCLayout if none are given.

settings dict[str, JSONSerializable]

Keyword arguments forwarded to the routing strategy.

Fields:

  • name (str)
  • routing_strategy (str)
  • settings (dict[str, JSONSerializable])

Validators:

  • _parse_nets
Source code in kfactory/schematic.py
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
class Route[T: (int, float)](BaseModel, extra="forbid"):
    """Bundle of `Link`s routed using a named strategy.

    Attributes:
        name: Route identifier (key in `(D)Schematic.routes`).
        routing_strategy: Name of routing function registered on the
            `Schematic.create_cell` or registered in `KCLayout` if none are given.
        settings: Keyword arguments forwarded to the routing strategy.
    """

    name: str = Field(exclude=True)
    routing_strategy: str = "route_bundle"
    settings: dict[str, JSONSerializable]

    @model_validator(mode="before")
    @classmethod
    def _parse_nets(cls, data: dict[str, Any]) -> dict[str, Any]:
        if "settings" not in data:
            data["settings"] = {}
        return data

RouteNet pydantic-model

Bases: SchematicNet[T]

Undirected association between two ports (refs or schematic ports).

The pair is stored in sorted order to ensure stable equality and hashing.

Fields:

  • route (str)
  • net (tuple[PortRef, ...])
Source code in kfactory/schematic.py
718
719
720
721
722
723
724
725
class RouteNet[T: (int, float)](SchematicNet[T]):
    """Undirected association between two ports (refs or schematic ports).

    The pair is stored in sorted order to ensure stable equality and hashing.
    """

    route: str
    net: tuple[PortRef, ...]

Schema pydantic-model

Bases: Schematic

Deprecated alias for Schematic (will be removed in kfactory 2.0).

Fields:

Validators:

  • _validate_schematic
  • assign_backrefs
Source code in kfactory/schematic.py
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
class Schema(Schematic):
    """Deprecated alias for `Schematic` (will be removed in kfactory 2.0)."""

    def __init__(self, **data: Any) -> None:
        logger.warning(
            "Schema is deprecated, please use Schematic. "
            "It will be removed in kfactory 2.0"
        )
        if "unit" in data:
            raise ValueError(
                "Cannot set the unit direct. It needs to be set by the class init."
            )
        super().__init__(**data)

Schematic pydantic-model

Bases: TSchematic[dbu]

Schematic with a base unit of dbu for placements.

Fields:

Validators:

  • _validate_schematic
  • assign_backrefs
Source code in kfactory/schematic.py
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
class Schematic(TSchematic[dbu]):
    """Schematic with a base unit of dbu for placements."""

    unit: Literal["dbu"] = "dbu"

    def __init__(self, **data: Any) -> None:
        if "unit" in data:
            raise ValueError(
                "Cannot set the unit direct. It needs to be set by the class init."
            )
        super().__init__(unit="dbu", **data)

SchematicInstance pydantic-model

Bases: BaseModel

Instance record within a schematic.

Attributes:

Name Type Description
name str

Instance name (unique within the schematic).

component str

Factory (cell function) name used to create the underlying cell.

settings dict[str, JSONSerializable]

Parameters passed to the factory.

array RegularArray[T] | Array[T] | None

Optional array specification (RegularArray or Array).

kcl KCLayout

Layout context (KCLayout) to build the instance from. Defaults to default object.

virtual bool

If True, create a virtual instance (VInstance/ComponentAllAngle).

placement Placement[T] | MirrorPlacement | None

Reference to a placement if the instance has a corresponding one.

Properties

parent_schematic: (D)Schematic owning this instance. ports: Accessing PortRef/PortArrayRef resulting from this instance.

Methods:

Name Description
place

Declare a placement, saved in the schematic owning this instance.

connect

Create and register a Connection from one of my ports.

Fields:

  • name (str)
  • component (str)
  • settings (dict[str, JSONSerializable])
  • array (RegularArray[T] | Array[T] | None)
  • kcl (KCLayout)
  • virtual (bool)

Validators:

  • _find_kclkcl
Source code in kfactory/schematic.py
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
class SchematicInstance[T: (int, float)](
    BaseModel, extra="forbid", arbitrary_types_allowed=True
):
    """Instance record within a schematic.

    Attributes:
        name: Instance name (unique within the schematic).
        component: Factory (cell function) name used to create the underlying cell.
        settings: Parameters passed to the factory.
        array: Optional array specification (`RegularArray` or `Array`).
        kcl: Layout context (`KCLayout`) to build the instance from. Defaults to
            default object.
        virtual: If True, create a virtual instance (VInstance/ComponentAllAngle).
        placement: Reference to a placement if the instance has a corresponding one.

    Properties:
        parent_schematic: `(D)Schematic` owning this instance.
        ports: Accessing `PortRef`/`PortArrayRef` resulting from this instance.

    Methods:
        place: Declare a placement, saved in the schematic owning this instance.
        connect: Create and register a `Connection` from one of my ports.
    """

    name: str = Field(exclude=True, frozen=True)
    component: str
    settings: dict[str, JSONSerializable] = Field(default_factory=dict)
    array: RegularArray[T] | Array[T] | None = None
    kcl: KCLayout = Field(default_factory=get_default_kcl)
    virtual: bool = False
    _schematic: TSchematic[T] = PrivateAttr()

    @field_validator("kcl", mode="before")
    @classmethod
    def _find_kcl(cls, value: str | KCLayout) -> KCLayout:
        if isinstance(value, str):
            return kcls[value]
        return value

    @field_serializer("kcl")
    def _serialize_kcl(self, kcl: KCLayout) -> str:
        return kcl.name

    @property
    def parent_schematic(self) -> TSchematic[T]:
        if self._schematic is None:
            raise RuntimeError("Schematic instance has no parent set.")
        return self._schematic

    @property
    def placement(self) -> Placement[T] | MirrorPlacement | None:
        return self.parent_schematic.placements.get(self.name)

    def get_placement(self) -> Placement[T] | MirrorPlacement:
        placement = self.placement
        if placement is None:
            raise ValueError(
                f"SchematicInstance {self.name!r} does not have a placement"
            )
        return placement

    def place(
        self,
        x: T | PortRef | AnchorRefX = 0,
        y: T | PortRef | AnchorRefY = 0,
        dx: T = 0,
        dy: T = 0,
        orientation: float | PortRef = 0,
        mirror: bool = False,
        anchor: FixedAnchorDict | PortAnchorDict | None = None,
    ) -> Placement[T]:
        """Declare placement/orientation/mirroring for this instance.

        Returns:
            The created `Placement` (also stored under `self.placement` which references
            `self.parent_schematic.placements`).
        """
        placement = Placement[T](
            x=x,
            y=y,
            dx=dx,
            dy=dy,
            orientation=orientation,
            mirror=mirror,
        )
        if anchor is not None:
            if _is_portdict(anchor):
                placement.anchor = PortAnchor(port=anchor["port"])
            else:
                fixed = cast("FixedAnchorDict", anchor)
                placement.anchor = FixedAnchor(x=fixed["x"], y=fixed["y"])
        self.parent_schematic.placements[self.name] = placement
        return placement

    @overload
    def __getitem__(self, value: str) -> PortRef: ...
    @overload
    def __getitem__(self, value: tuple[str, int, int]) -> PortArrayRef: ...

    def __getitem__(self, value: str | tuple[str, int, int]) -> PortRef:
        if isinstance(value, str):
            return PortRef(instance=self.name, port=value)
        return PortArrayRef(instance=self.name, port=value[0], ia=value[1], ib=value[2])

    def connect(
        self,
        port: str | tuple[str, int, int],
        other: Port[T] | PortRef,
    ) -> Connection[T]:
        """Connect one of my ports to `other` and register it on the schematic."""
        if isinstance(port, str):
            pref = PortRef(instance=self.name, port=port)
        else:
            pref = PortArrayRef(
                instance=self.name, port=port[0], ia=port[1], ib=port[2]
            )
        conn = Connection[T](net=(other, pref))
        self.parent_schematic.nets.append(conn)
        return conn

    @property
    def mirror(self) -> bool:
        if self.placement is None:
            return False
        return self.placement.mirror

    @mirror.setter
    def mirror(self, value: bool) -> None:
        if self.placement is None:
            if value:
                self.parent_schematic.placements[self.name] = MirrorPlacement(
                    mirror=True
                )
        else:
            self.placement.mirror = value

    @cached_property
    def ports(self) -> Ports[T]:
        return Ports(instance=self)

    @cached_property
    def pins(self) -> Pins[T]:
        return Pins(instance=self)

    @property
    def xmin(self) -> AnchorRefX:
        return AnchorRefX(instance=self.name, x="left")

    @property
    def xmax(self) -> AnchorRefX:
        return AnchorRefX(instance=self.name, x="left")

    @property
    def ymin(self) -> AnchorRefY:
        return AnchorRefY(instance=self.name, y="bottom")

    @property
    def ymax(self) -> AnchorRefY:
        return AnchorRefY(instance=self.name, y="top")

    @property
    def center(self) -> tuple[AnchorRefX, AnchorRefY]:
        return (
            AnchorRefX(instance=self.name, x="center"),
            AnchorRefY(instance=self.name, y="center"),
        )

connect

connect(
    port: str | tuple[str, int, int],
    other: Port[T] | PortRef,
) -> Connection[T]

Connect one of my ports to other and register it on the schematic.

Source code in kfactory/schematic.py
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
def connect(
    self,
    port: str | tuple[str, int, int],
    other: Port[T] | PortRef,
) -> Connection[T]:
    """Connect one of my ports to `other` and register it on the schematic."""
    if isinstance(port, str):
        pref = PortRef(instance=self.name, port=port)
    else:
        pref = PortArrayRef(
            instance=self.name, port=port[0], ia=port[1], ib=port[2]
        )
    conn = Connection[T](net=(other, pref))
    self.parent_schematic.nets.append(conn)
    return conn

place

place(
    x: T | PortRef | AnchorRefX = 0,
    y: T | PortRef | AnchorRefY = 0,
    dx: T = 0,
    dy: T = 0,
    orientation: float | PortRef = 0,
    mirror: bool = False,
    anchor: FixedAnchorDict | PortAnchorDict | None = None,
) -> Placement[T]

Declare placement/orientation/mirroring for this instance.

Returns:

Type Description
Placement[T]

The created Placement (also stored under self.placement which references

Placement[T]

self.parent_schematic.placements).

Source code in kfactory/schematic.py
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
def place(
    self,
    x: T | PortRef | AnchorRefX = 0,
    y: T | PortRef | AnchorRefY = 0,
    dx: T = 0,
    dy: T = 0,
    orientation: float | PortRef = 0,
    mirror: bool = False,
    anchor: FixedAnchorDict | PortAnchorDict | None = None,
) -> Placement[T]:
    """Declare placement/orientation/mirroring for this instance.

    Returns:
        The created `Placement` (also stored under `self.placement` which references
        `self.parent_schematic.placements`).
    """
    placement = Placement[T](
        x=x,
        y=y,
        dx=dx,
        dy=dy,
        orientation=orientation,
        mirror=mirror,
    )
    if anchor is not None:
        if _is_portdict(anchor):
            placement.anchor = PortAnchor(port=anchor["port"])
        else:
            fixed = cast("FixedAnchorDict", anchor)
            placement.anchor = FixedAnchor(x=fixed["x"], y=fixed["y"])
    self.parent_schematic.placements[self.name] = placement
    return placement

SchematicNet pydantic-model

Bases: BaseModel

Undirected association between two ports (refs or schematic ports).

The pair is stored in sorted order to ensure stable equality and hashing.

Fields:

  • net (tuple[PortRef | Port[T], PortRef | Port[T]])
Source code in kfactory/schematic.py
709
710
711
712
713
714
715
class SchematicNet[T: (int, float)](BaseModel):
    """Undirected association between two ports (refs or schematic ports).

    The pair is stored in sorted order to ensure stable equality and hashing.
    """

    net: tuple[PortRef | Port[T], PortRef | Port[T]]

TSchematic pydantic-model

Bases: BaseModel

Schematic of a cell / component.

Attributes:

Name Type Description
name str | None

Optional schematic name.

instances dict[str, SchematicInstance[T]]

Mapping of instance name -> SchematicInstance.

placements dict[str, Placement[T] | MirrorPlacement]

Mapping of instance name -> Placement/MirrorPlacement.

connections list[Connection[T]]

List of Connections.

routes dict[str, Route[T]]

Mapping of route name -> Route.

ports dict[str, Port[T] | PortRef | PortArrayRef]

Mapping of port name -> Port/PortRef/PortArrayRef.

pins dict[str, Pin | PinRef]

Mapping of pin name -> Pin/PinRef. Pins are top-level groupings of schematic ports (purely structural — they do not participate in nets/connections).

info dict[str, JSONSerializable]

dict which will be mapped to KCell.info (or any other derivate like Component).

unit Literal['dbu', 'um']

Base coordinate unit ("dbu" or "um"). Fixed by subclass.

kcl KCLayout

KCLayout context (excluded from model serialization). Needed for referencing and creation of the cell.

Fields:

Validators:

  • _validate_schematic
  • assign_backrefs
Source code in kfactory/schematic.py
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
class TSchematic[T: (int, float)](BaseModel, extra="forbid"):
    """Schematic of a cell / component.

    Attributes:
        name: Optional schematic name.
        instances: Mapping of instance name -> `SchematicInstance`.
        placements: Mapping of instance name -> `Placement`/`MirrorPlacement`.
        connections: List of `Connection`s.
        routes: Mapping of route name -> `Route`.
        ports: Mapping of port name -> `Port`/`PortRef`/`PortArrayRef`.
        pins: Mapping of pin name -> `Pin`/`PinRef`. Pins are top-level
            groupings of schematic ports (purely structural — they do not
            participate in nets/connections).
        info: dict which will be mapped to `KCell.info` (or any other derivate like
            Component).
        unit: Base coordinate unit ("dbu" or "um"). Fixed by subclass.
        kcl: `KCLayout` context (excluded from model serialization). Needed for
            referencing and creation of the cell.
    """

    name: str | None = None
    instances: dict[str, SchematicInstance[T]] = Field(default_factory=dict)
    placements: dict[str, Placement[T] | MirrorPlacement] = Field(default_factory=dict)
    nets: list[RouteNet[T] | Connection[T] | VirtualConnection[T]] = Field(
        default_factory=list
    )
    routes: dict[str, Route[T]] = Field(default_factory=dict)
    ports: dict[str, Port[T] | PortRef | PortArrayRef] = Field(default_factory=dict)
    pins: dict[str, Pin | PinRef] = Field(default_factory=dict)
    constraints: list[Constraint] = Field(default_factory=list)
    kcl: KCLayout = Field(exclude=True, default_factory=get_default_kcl)
    unit: Literal["dbu", "um"]
    info: dict[str, JSONSerializable] = Field(default_factory=dict)

    def create_inst(
        self,
        name: str,
        component: str,
        settings: dict[str, JSONSerializable] | None = None,
        array: RegularArray[T] | Array[T] | None = None,
        placement: Placement[T] | None = None,
        kcl: KCLayout | None = None,
        virtual: bool = False,
    ) -> SchematicInstance[T]:
        """Create a schema instance.

        This would be an SREF or AREF in the resulting GDS cell.

        Args:
            name: Instance name. In a schematic, each instance must be named,
                unless created through routing functions.
            component: Factory name of the component to instantiate.
            settings: Parameters passed to the factory (optional).
            array: If the instance should create an array instance (AREF),
                this can be passed here as an `Array` class instance.
            placement: Optional placement for the instance. Can also be configured
                with `inst.place(...)` afterwards.
            kcl: Optional `KCLayout` override for this instance.


        Returns:
            Schematic instance representing the args.
        """
        inst = SchematicInstance[T].model_validate(
            {
                "name": name,
                "component": component,
                "settings": settings or {},
                "array": array,
                "kcl": kcl or self.kcl,
                "virtual": virtual,
            }
        )
        inst._schematic = self

        if inst.name in self.instances:
            raise ValueError(
                f"Duplicate instance names are not allowed {inst.name=!r}"
                "already exists."
            )

        self.instances[inst.name] = inst
        if placement:
            self.placements[inst.name] = placement
        return inst

    def add_port(
        self, name: str | None = None, *, port: PortRef | PortArrayRef
    ) -> None:
        """Expose an existing instance port as a schematic top-level port.

        Args:
            name: Name for the schematic port; defaults to the underlying port name.
            port: Port reference to expose.

        Raises:
            ValueError: If a schematic port with `name` already exists.
        """
        name = name or port.port
        if name not in self.ports:
            self.ports[name] = port
            return
        raise ValueError(f"Port with name {name} already exists")

    def create_port(
        self,
        name: str,
        cross_section: str,
        x: PortRef | PortArrayRef | T,
        y: PortRef | PortArrayRef | T,
        dx: T = 0,
        dy: T = 0,
        orientation: Literal[0, 90, 180, 270] = 0,
    ) -> Port[T]:
        """Create a schematic-level, placeable port.

        Returns:
            The created `Port`, also stored in `self.ports`.
        """
        p = Port(
            name=name,
            x=x,
            y=y,
            dx=dx,
            dy=dy,
            cross_section=cross_section,
            orientation=orientation,
        )
        self.ports[p.name] = p
        return p

    def place_port(
        self,
        name: str,
        cell: KCell,
        cross_sections: Mapping[str, CrossSection | DCrossSection],
    ) -> BasePort:
        """Materialize a schematic-level port on `cell`.

        Looks up `self.ports[name]` and dispatches by port type:

        - `PortArrayRef` / `PortRef`: forwards an instance port through
          `cell.add_port` (using `cell.vinsts` for virtual instances).
        - `Port[T]`: resolves `(x, y, orientation)` (which may themselves be
          references), then creates the port via `cell.create_port`.
        """
        port = self.ports[name]
        if isinstance(port, PortArrayRef):
            if self.instances[port.instance].virtual:
                return cell.add_port(
                    port=cell.vinsts[port.instance].ports[port.port, port.ia, port.ib],
                    name=name,
                ).base
            return cell.add_port(
                port=cell.insts[port.instance].ports[port.port, port.ia, port.ib],
                name=name,
            ).base
        if isinstance(port, PortRef):
            if self.instances[port.instance].virtual:
                return cell.add_port(
                    port=cell.vinsts[port.instance].ports[port.port], name=name
                ).base
            return cell.add_port(
                port=cell.insts[port.instance].ports[port.port], name=name
            ).base

        if isinstance(port.x, PortRef):
            if isinstance(port.x, PortArrayRef):
                x: float = (
                    cell.insts[port.x.instance]
                    .ports[port.x.port, port.x.ia, port.x.ib]
                    .x
                )
            else:
                x = cell.insts[port.x.instance].ports[port.x.port].x
        elif isinstance(port.x, AnchorRefX):
            match port.x.x:
                case "left":
                    x = cell.insts[port.x.instance].xmin
                case "center":
                    x = cell.insts[port.x.instance].bbox().center().x
                case "right":
                    x = cell.insts[port.x.instance].xmax
        else:
            x = cast("int | T", port.x)
        x += port.dx
        if isinstance(port.y, PortRef):
            if isinstance(port.y, PortArrayRef):
                y: float = (
                    cell.insts[port.y.instance]
                    .ports[port.y.port, port.y.ia, port.y.ib]
                    .y
                )
            else:
                y = cell.insts[port.y.instance].ports[port.y.port].y
        elif isinstance(port.y, AnchorRefY):
            match port.y.y:
                case "bottom":
                    y = cell.insts[port.y.instance].ymin
                case "center":
                    y = cell.insts[port.y.instance].bbox().center().y
                case "top":
                    y = cell.insts[port.y.instance].ymax
        else:
            y = cast("int | T", port.y)
        y += port.dy
        if isinstance(port.orientation, PortRef):
            orientation = (
                cell.insts[port.orientation.instance]
                .ports[port.orientation.port]
                .orientation
            )
        else:
            orientation = port.orientation

        if self.unit == "dbu":
            return cell.create_port(
                dcplx_trans=kdb.DCplxTrans(
                    rot=orientation,
                    x=cell.kcl.to_um(cast("int", x)),
                    y=cell.kcl.to_um(cast("int", y)),
                ),
                cross_section=cross_sections[port.cross_section],
                name=name,
            ).base

        return cell.create_port(
            dcplx_trans=kdb.DCplxTrans(rot=orientation, x=x, y=y),
            cross_section=cross_sections[port.cross_section],
            name=name,
        ).base

    def create_pin(
        self,
        name: str,
        ports: list[str],
        pin_type: str = "DC",
        info: dict[str, JSONSerializable] | None = None,
    ) -> Pin:
        """Create a schematic-level pin grouping existing schematic ports.

        Args:
            name: Pin name. Must be unique within the schematic.
            ports: Names of schematic ports (entries of ``self.ports``) that
                belong to this pin. Each name must already be registered as a
                schematic port.
            pin_type: Pin type (default ``"DC"``).
            info: Optional info dict attached to the pin.

        Returns:
            The created :class:`Pin`, also stored in :attr:`self.pins`.

        Raises:
            ValueError: If a pin with ``name`` already exists, ``ports`` is
                empty, or any port name is not present in ``self.ports``.
        """
        if name in self.pins:
            raise ValueError(f"Pin with name {name!r} already exists")
        if not ports:
            raise ValueError(
                f"At least one port must be provided to create pin named {name!r}"
            )
        missing = [p for p in ports if p not in self.ports]
        if missing:
            raise ValueError(
                f"Cannot create pin {name!r}: port(s) {missing!r} are not "
                "registered as schematic ports."
            )
        pin = Pin(name=name, ports=list(ports), pin_type=pin_type, info=info or {})
        self.pins[name] = pin
        return pin

    def add_pin(self, name: str | None = None, *, pin: PinRef) -> None:
        """Expose an existing instance pin as a schematic top-level pin.

        Args:
            name: Name for the schematic pin; defaults to the underlying pin name.
            pin: Pin reference to expose.

        Raises:
            ValueError: If a schematic pin with ``name`` already exists.
        """
        name = name or pin.pin
        if name in self.pins:
            raise ValueError(f"Pin with name {name!r} already exists")
        self.pins[name] = pin

    def create_connection(
        self, port1: PortRef | Port[T], port2: PortRef
    ) -> Connection[T]:
        """Create and register a connection between two instance ports.

        Args:
            port1: First instance port.
            port2: Second instance port.

        Raises:
            ValueError: If either referenced instance is unknown.

        Returns:
            The created `Connection`.
        """

        conn = Connection[T](net=(port1, port2))
        if isinstance(port1, PortRef):
            if port1.instance not in self.instances:
                raise ValueError(
                    f"Cannot create connection to unknown instance {port1.instance}"
                )
        elif port1 != self.ports.get(port1.name):
            raise ValueError(f"Unknown port {port1=}")
        if port2.instance not in self.instances:
            raise ValueError(
                f"Cannot create connection to unknown instance {port2.instance}"
            )
        self.nets.append(conn)
        return conn

    def netlist(
        self,
        add_defaults: bool = True,
        factories: dict[str, Callable[..., ProtoTKCell[Any]] | Callable[..., VKCell]]
        | None = None,
        external_factories: dict[
            str, dict[str, Callable[..., ProtoTKCell[Any]] | Callable[..., VKCell]]
        ]
        | None = None,
    ) -> Netlist:
        """Compile the schematic into a `Netlist`.

        Includes nets from `connections`, `routes`, and exposed `ports`. Instances
        are serialized with their `kcl`, component, and settings. The resulting
        netlist is sorted for stable output.
        """

        nets = [
            Net(
                [
                    NetlistPort(name=p.name) if isinstance(p, Port) else p
                    for p in net.net
                ]
            )
            for net in self.nets
        ]

        if self.ports:
            nets.extend(
                [
                    Net([NetlistPort(name=name), p])
                    for name, p in self.ports.items()
                    if isinstance(p, PortRef)
                ]
            )
        if add_defaults:
            if external_factories is None:
                all_factories: dict[
                    str,
                    dict[str, Callable[..., ProtoTKCell[Any]] | Callable[..., VKCell]],
                ] = defaultdict(dict)
                for kcl_ in kcls.values():
                    kcl_factories: dict[
                        str, Callable[..., ProtoTKCell[Any]] | Callable[..., VKCell]
                    ] = {f.name: f._f for f in kcl_.factories._all}
                    kcl_factories.update(
                        {vf.name: vf._f for vf in kcl_.virtual_factories._all}
                    )
                    all_factories[kcl_.name] = kcl_factories
            else:
                all_factories = external_factories.copy()
            if factories is not None:
                all_factories[self.kcl.name] = factories
            nl = Netlist()
            for name in self.ports:
                nl.create_port(name)
            if self.instances:
                for inst in self.instances.values():
                    na, nb = _array_dims(inst.array)
                    nl.create_inst(
                        name=inst.name,
                        kcl=inst.kcl.name,
                        component=inst.component,
                        settings=_get_full_settings(
                            inst.settings,
                            inspect.signature(
                                all_factories[inst.kcl.name][inst.component]
                            ),
                        ),
                        na=na,
                        nb=nb,
                    )
            for net in nets:
                nl.add_net(net)
        else:
            nl = Netlist()
            for name in self.ports:
                nl.create_port(name)
            if self.instances:
                for inst in self.instances.values():
                    na, nb = _array_dims(inst.array)
                    nl.create_inst(
                        name=inst.name,
                        kcl=inst.kcl.name,
                        component=inst.component,
                        settings=inst.settings,
                        na=na,
                        nb=nb,
                    )
            for net in nets:
                nl.add_net(net)
        nl.sort()
        return nl

    @model_validator(mode="before")
    @classmethod
    def _validate_schematic(cls, data: dict[str, Any]) -> dict[str, Any]:
        data.pop("warnings", None)
        if not isinstance(data, dict):
            return data
        if "kcl" in data and isinstance(data["kcl"], str):
            data["kcl"] = kcls[data["kcl"]]
        instances = data.get("instances")
        if instances:
            for name, instance in instances.items():
                instance["name"] = name
                instance.pop("info", None)

        nets: list[dict[str, str]] = data.get("nets", [])
        built_nets: list[RouteNet[T] | Connection[T] | VirtualConnection[T]] = []
        data["nets"] = built_nets
        if nets:
            built_nets.extend(
                [
                    VirtualConnection[T](
                        net=(
                            _get_instance_and_port(net["p1"]),
                            _get_instance_and_port(net["p2"]),
                        )
                    )
                    for net in nets
                ]
            )

        connections = data.pop("connections", None)
        if connections is not None and isinstance(connections, dict):
            built_nets.extend(
                [
                    Connection[T](
                        net=(
                            _get_instance_and_port(conn_ref1),
                            _get_instance_and_port(conn_ref2),
                        )
                    )
                    for conn_ref1, conn_ref2 in connections.items()
                ]
            )
        routes = data.get("routes")
        if routes:
            for name, route in routes.items():
                route["name"] = name
                built_nets.extend(
                    [
                        RouteNet[T](
                            route=name,
                            net=(
                                _get_instance_and_port(link1),
                                _get_instance_and_port(link2),
                            ),
                        )
                        for link1, link2 in route["links"].items()
                    ]
                )
                route.pop("links")
        placements = data.get("placements")
        if placements:
            for placement in placements.values():
                if "port" in placement:
                    port = placement.pop("port")
                    if port in [
                        "ce",
                        "cw",
                        "nc",
                        "ne",
                        "nw",
                        "sc",
                        "se",
                        "sw",
                        "center",
                        "cc",
                    ]:
                        placement["anchor"] = _anchor_mapping[port]
                    else:
                        placement["anchor"] = {"port": port}
                anchor: FixedAnchorDict = placement.get("anchor", {})
                if "xmin" in placement:
                    anchor["x"] = "left"
                    placement["x"] = placement.pop("xmin")
                elif "xmax" in placement:
                    anchor["x"] = "right"
                    placement["y"] = placement.pop("xmax")
                if "ymin" in placement:
                    anchor["y"] = "bottom"
                    placement["y"] = placement.pop("ymin")
                elif "ymax" in placement:
                    anchor["y"] = "top"
                    placement["y"] = placement.pop("ymax")
                if anchor:
                    placement["anchor"] = anchor
                x_ = placement.get("x")
                if isinstance(x_, str):
                    inst, port = x_.rsplit(",", 1)
                    if port in ["east", "center", "west"]:
                        placement["x"] = {
                            "instance": inst,
                            "x": _anchorref_mapping[port],
                        }
                    else:
                        placement["x"] = {"instance": inst, "port": port}
                y_ = placement.get("y")
                if isinstance(y_, str):
                    inst, port = x_.rsplit(",", 1)
                    if port in ["bottom", "center", "top"]:
                        placement["x"] = {
                            "instance": inst,
                            "y": _anchorref_mapping[port],
                        }
                    else:
                        placement["y"] = {"instance": inst, "port": port}

                if isinstance(placement.get("y"), str):
                    raise NotImplementedError
        ports = data.get("ports")
        if ports:
            for name, port_val in ports.items():
                if isinstance(port_val, str):
                    ports[name] = _get_instance_and_port(port_val)
        pins = data.get("pins")
        if pins:
            for name, pin in pins.items():
                if isinstance(pin, str):
                    inst, pname = pin.rsplit(",", 1)
                    pins[name] = {"instance": inst, "pin": pname}
                elif isinstance(pin, dict) and "ports" in pin:
                    pin["name"] = name
        return data

    @field_serializer("placements")
    @classmethod
    def _serialize_placements(
        cls, v: dict[str, Placement[Any] | MirrorPlacement]
    ) -> dict[str, dict[str, Any]]:
        return {k: p.model_dump(warnings=False) for k, p in v.items()}

    @model_validator(mode="after")
    def assign_backrefs(self) -> Self:
        for inst in self.instances.values():
            inst._schematic = self
        return self

    def create_cell(
        self,
        output_type: type[KC],
        factories: Mapping[
            str, Callable[..., KCell] | Callable[..., DKCell] | Callable[..., VKCell]
        ]
        | None = None,
        cross_sections: Mapping[str, CrossSection | DCrossSection] | None = None,
        routing_strategies: dict[
            str,
            Callable[
                Concatenate[
                    ProtoTKCell[Any],
                    Sequence[Sequence[ProtoPort[Any]]],
                    ...,
                ],
                Any,
            ],
        ]
        | None = None,
        place_unknown: bool = False,
        ignore_errors: bool = False,
    ) -> KC:
        """Materialize the schematic into a `KCell`/`DKCell`/`Component`.

        Args:
            output_type: Cell type to return (e.g., `KCell`, `DKCell`).
            factories: Optional mapping from factory name to callable returning a cell.
            cross_sections: Optional mapping of cross-section names to definitions.
                If undefined uses `self.kcl`'s cross sections.
            routing_strategies: Strategy functions keyed by name. If none uses
                `self.kcl`'s routing strategies
            place_unknown: If True, place otherwise unplaceable instances at (0, 0).
                This might cause unintended side effects as the schematic is seemingly
                not fully deterministic, therefore this is disabled by default.

        Returns:
            A cell of type `output_type` with instances, ports, and routes realized.

        Raises:
            ValueError: If placement or connection constraints cannot be satisfied.
        """
        c = KCell(kcl=self.kcl)
        c.info = Info(**self.info)

        if routing_strategies is None:
            routing_strategies = c.kcl.routing_strategies

        if cross_sections is None:
            cross_sections = {
                name: c.kcl.get_icross_section(xs)
                for name, xs in c.kcl.cross_sections.cross_sections.items()
            }

        # calculate islands -- islands are a bunch of directly connected instances and
        # must be isolated from other islands either through no connection at all or
        # routes

        connections = self.connections

        islands, instance_connections = _get_island_connections(
            instances=self.instances, connections=connections
        )

        placed_insts: set[str] = set()
        placed_ports: set[str] = set()

        for name, port in self.ports.items():
            if isinstance(port, PortRef | PortArrayRef):
                continue
            if port.is_placeable(placed_instances=placed_insts):
                p = self.place_port(
                    name,
                    cell=c,
                    cross_sections=cross_sections,
                )
                placed_ports.add(p.name)

        instances: dict[str, Instance | VInstance] = {}
        placed_islands: list[set[str]] = []
        seen_islands: set[int] = set()
        unique_islands: list[set[str]] = []
        for island in islands.values():
            island_id = id(island)
            if island_id not in seen_islands:
                seen_islands.add(island_id)
                unique_islands.append(island)
        for i, island in enumerate(unique_islands):
            logger.debug("Placing island {} of schema {}, {}", i, self.name, island)
            if island not in placed_islands:
                _place_island(
                    c,
                    schematic_island=island,
                    instances=instances,
                    connections=instance_connections,
                    schematic_instances=self.instances,
                    placed_insts=placed_insts,
                    placed_ports=placed_ports,
                    schematic=self,
                    cross_sections=cross_sections,
                    factories=factories,
                    place_unknown=place_unknown,
                )
                placed_islands.append(island)
                placed_insts |= island

        nets_per_route = self.routes_nets()

        # routes
        route_results: dict[str, list[Any]] = {}
        for route in self.routes.values():
            resolved_ports: list[tuple[ProtoPort[Any], ...]] = []
            for net in nets_per_route[route.name]:
                resolved_port_list: list[KCellPort | DKCellPort] = []
                for port_ref in net.net:
                    if isinstance(port_ref, Port):
                        p: KCellPort | DKCellPort = c.ports[port_ref.name]
                    else:
                        inst = self.instances[port_ref.instance]
                        target = (
                            c.vinsts[port_ref.instance]
                            if inst.virtual
                            else c.insts[port_ref.instance]
                        )
                        if isinstance(port_ref, PortArrayRef):
                            p = target.ports[port_ref.port, port_ref.ia, port_ref.ib]
                        else:
                            p = target.ports[port_ref.port]
                    resolved_port_list.append(p)
                resolved_ports.append(tuple(resolved_port_list))
            route_c = output_type(base=c.base)
            relevant_constraints = [
                ct for ct in self.constraints if route.name in ct.route_names
            ]
            extra_kwargs: dict[str, Any] = (
                {"constraints": relevant_constraints} if relevant_constraints else {}
            )
            if isinstance(route_c, KCell):
                result = routing_strategies[route.routing_strategy](
                    output_type(base=c.base),
                    resolved_ports,
                    **route.settings,
                    **extra_kwargs,
                )
            else:
                result = routing_strategies[route.routing_strategy](
                    output_type(base=c.base),
                    [
                        tuple(DKCellPort(base=p.base) for p in net_ports)
                        for net_ports in resolved_ports
                    ],
                    **route.settings,
                    **extra_kwargs,
                )
            route_results[route.name] = result or []

        # check constraints
        if self.constraints:
            failed: list[Constraint] = []
            for ct in self.constraints:
                resolved_instances = {
                    n: c.insts[n] for n in ct.instance_names if n in c.insts
                }
                resolved_routes = {n: route_results.get(n, []) for n in ct.route_names}
                if not ct.check(c, self, resolved_instances, resolved_routes):
                    if ct.on_failure == "show_error":
                        c_ = c.dup()
                        c_.name = c.kcl.future_cell_name or c.name
                        c_.show(
                            lyrdb=ct.lyrdb_markers(
                                c_, self, resolved_instances, resolved_routes
                            )
                        )
                    if ct.on_failure in ("error", "show_error"):
                        failed.append(ct)
            if failed:
                raise ValueError(
                    f"Constraints not satisfied in schematic {self.name!r}:\n"
                    + "\n".join(repr(ct) for ct in failed)
                )

        # verify connections
        port_connection_transformation_errors: list[Connection[T]] = []
        connection_transformation_errors: list[Connection[T]] = []
        for conn in connections:
            c1 = conn.net[0]
            c2 = conn.net[1]
            if isinstance(c1, Port):
                p1 = c.ports[c1.name]
                p2 = c.insts[c2.instance].ports[c2.port]
                if p1.dcplx_trans != p2.dcplx_trans:
                    port_connection_transformation_errors.append(conn)
            else:
                if self.instances[c1.instance].virtual:
                    inst1: Instance | VInstance = c.vinsts[c1.instance]
                else:
                    inst1 = c.insts[c1.instance]
                if self.instances[c2.instance].virtual:
                    inst2: Instance | VInstance = c.vinsts[c2.instance]
                else:
                    inst2 = c.insts[c2.instance]
                if isinstance(c1, PortArrayRef):
                    p1 = inst1.ports[c1.port, c1.ia, c1.ib]
                else:
                    p1 = inst1.ports[c1.port]
                if isinstance(c2, PortArrayRef):
                    p2 = inst2.ports[c2.port, c2.ia, c2.ib]
                else:
                    p2 = inst2.ports[c2.port]

                t1 = p1.dcplx_trans
                t2 = p2.dcplx_trans
                if (t1 != t2 * kdb.DCplxTrans.R180) and (t1 != t2 * kdb.DCplxTrans.M90):
                    connection_transformation_errors.append(conn)

        if not ignore_errors and (
            connection_transformation_errors or port_connection_transformation_errors
        ):
            raise ValueError(
                f"Not all connections in schema {self.name}"
                " could be satisfied. Missing or wrong connections:\n"
                + "\n".join(
                    f"{conn.net[0]} - {conn.net[1]}"
                    for conn in connection_transformation_errors
                    + port_connection_transformation_errors
                )
            )

        # materialize pins on the resulting cell. ports must already be created.
        if self.pins:
            # map (instance, original port name) -> schematic-port key name
            # only PortRef-style schematic ports map to instance ports; cell
            # port names equal the schematic-port keys (see PortRef.place).
            ref_to_schematic_port: dict[tuple[str, str], str] = {}
            for sname, sport in self.ports.items():
                if isinstance(sport, PortRef) and not isinstance(sport, PortArrayRef):
                    ref_to_schematic_port[(sport.instance, sport.port)] = sname

        for pin_name, pin_def in self.pins.items():
            if isinstance(pin_def, PinRef):
                inst = self.instances.get(pin_def.instance)
                if inst is None:
                    raise ValueError(
                        f"Pin {pin_name!r} references unknown instance "
                        f"{pin_def.instance!r}."
                    )
                if inst.virtual:
                    inst_pins = c.vinsts[pin_def.instance].cell.pins
                else:
                    inst_pins = c.insts[pin_def.instance].cell.pins
                if pin_def.pin not in [p.name for p in inst_pins]:
                    raise ValueError(
                        f"Pin {pin_name!r} references unknown pin "
                        f"{pin_def.pin!r} on instance {pin_def.instance!r}."
                    )
                inst_pin = inst_pins[pin_def.pin]
                cell_port_names: list[str] = []
                missing: list[str] = []
                for p in inst_pin.ports:
                    if p.name is None:
                        missing.append("<unnamed>")
                        continue
                    key = (pin_def.instance, p.name)
                    if key not in ref_to_schematic_port:
                        missing.append(p.name)
                    else:
                        cell_port_names.append(ref_to_schematic_port[key])
                if missing:
                    raise ValueError(
                        f"Cannot materialize pin {pin_name!r} from "
                        f"{pin_def.instance!r}.{pin_def.pin!r}: underlying "
                        f"port(s) {missing!r} are not exposed as top-level"
                        " schematic ports (use schematic.add_port for each)."
                    )
                c.create_pin(
                    name=pin_name,
                    ports=[c.ports[n] for n in cell_port_names],
                    pin_type=inst_pin.pin_type,
                    info=inst_pin.info.model_dump(),
                )
            else:
                missing = [p for p in pin_def.ports if p not in c.ports]
                if missing:
                    raise ValueError(
                        f"Cannot materialize pin {pin_name!r}: port(s) "
                        f"{missing!r} are not registered on the cell."
                    )
                c.create_pin(
                    name=pin_name,
                    ports=[c.ports[p] for p in pin_def.ports],
                    pin_type=pin_def.pin_type,
                    info=dict(pin_def.info),
                )

        c.schematic = self
        if self.name:
            c.name = self.name

        return output_type(base=c.base)

    def add_constraint(self, constraint: Constraint) -> Constraint:
        """Register a constraint on this schematic.

        Validates that all ``route_names`` and ``instance_names`` referenced by
        the constraint already exist in the schematic.

        Args:
            constraint: The constraint to add.

        Returns:
            The added constraint (for chaining).

        Raises:
            ValueError: If any referenced route or instance name is unknown.
        """
        missing_routes = [n for n in constraint.route_names if n not in self.routes]
        if missing_routes:
            raise ValueError(
                f"Constraint references unknown route(s): {missing_routes}"
            )
        missing_insts = [
            n for n in constraint.instance_names if n not in self.instances
        ]
        if missing_insts:
            raise ValueError(
                f"Constraint references unknown instance(s): {missing_insts}"
            )
        self.constraints.append(constraint)
        return constraint

    def add_route(
        self,
        name: str,
        nets: Sequence[Sequence[PortRef]],
        routing_strategy: str,
        settings: dict[str, JSONSerializable],
    ) -> Route[T]:
        """Create a multi-link route bundle.

        Args:
            name: Route identifier (must be unique).
            nets: List of net tuples. Each tuple contains 2 or more ports
                that belong to the same net.
            routing_strategy: Name of the routing strategy function.
            **settings: Extra keyword args forwarded to the strategy.

        Returns:
            The created `Route`.

        Raises:
            ValueError: If `name` already exists or a net has fewer than 2 ports.
        """

        if name in self.routes:
            raise ValueError(f"Route with name {name!r} already exists")
        route = Route[T](
            name=name,
            routing_strategy=routing_strategy,
            settings=settings,
        )
        self.routes[name] = route
        for net in nets:
            if len(net) < 2:
                raise ValueError(
                    f"Each route net must have at least 2 ports, got {len(net)} in "
                    f"route {name!r}"
                )
            self.nets.append(RouteNet[T](route=name, net=tuple(net)))
        return route

    @overload
    def connect(
        self,
        port1: PortRef | Port[T],
        port2: PortRef,
        *,
        virtual: Literal[False] = False,
    ) -> Connection[T]: ...

    @overload
    def connect(
        self,
        port1: PortRef | Port[T],
        port2: PortRef | Port[T],
        *ports: PortRef | Port[T],
        virtual: Literal[True] = True,
    ) -> VirtualConnection[T]: ...
    def connect(
        self,
        port1: PortRef | Port[T],
        port2: PortRef | Port[T],
        *ports: PortRef | Port[T],
        virtual: bool = False,
    ) -> Connection[T] | VirtualConnection[T]:
        conn: Connection[T] | VirtualConnection[T]
        if virtual:
            conn = VirtualConnection[T](net=(port1, port2, *ports))
        else:
            assert isinstance(port2, PortRef), (
                "non-virtual connect requires port2 to be a PortRef"
            )
            conn = Connection[T](net=(port1, port2))
        self.nets.append(conn)
        return conn

    def __getitem__(self, key: str) -> Port[T] | PortRef:
        return self.ports[key]

    def code_str(
        self,
        imports: dict[str, str] = _schematic_default_imports,
        kfactory_name: str | None = None,
        ruff_format: bool = True,
    ) -> str:
        """Generate Python code that reconstructs this schematic.

        Args:
            imports: Mapping of module -> alias to emit at top of file.
            kfactory_name: Optional override for the `kfactory` import name.
            ruff_format: If True, format the generated code with `ruff`.

        Returns:
            The generated source code as a string. If `ruff` is unavailable or
            fails, the unformatted string is returned.
        """

        schematic_cell = ""
        indent = 0

        def _ind() -> str:
            nonlocal indent
            return " " * indent

        kf_name = kfactory_name or imports["kfactory"]

        def _kcls(name: str) -> str:
            return f'{kf_name}.kcls["{name}"]'

        for imp, imp_as in imports.items():
            if imp_as is None:
                schematic_cell += f"import {imp}\n"
            else:
                schematic_cell += f"import {imp} as {imp_as}\n"

        if imports:
            schematic_cell += "\n\n"

        schematic_cell += f"kcl = {_kcls(self.kcl.name)}\n\n"

        schematic_cell += f"@kcl.schematic_cell(output_type={kf_name}.DKCell)\n"
        schematic_cell += f"def {self.name}() -> {kf_name}.{self.__class__.__name__}:\n"
        indent = 2

        if isinstance(self, Schematic):
            schematic_cell += f"{_ind()}schematic = {kf_name}.Schematic(kcl=kcl)\n\n"
        else:
            schematic_cell += f"{_ind()}schematic = {kf_name}.DSchematic(kcl=kcl)\n\n"

        schematic_cell += f"{_ind()}# Create the schematic instances\n"

        names: dict[str, str] = {}

        for inst in sorted(self.instances.values(), key=attrgetter("name")):
            inst_name = _valid_varname(inst.name)
            names[inst.name] = inst_name
            schematic_cell += f"{_ind()}{inst_name} = schematic.create_inst(\n"
            indent += 2
            schematic_cell += (
                f"{_ind()}name={inst.name!r},\n"
                f"{_ind()}component={inst.component!r},\n"
                f"{_ind()}settings={inst.settings!r},\n"
            )
            if inst.kcl != self.kcl:
                schematic_cell += f"{_ind()}kcl={_kcls(inst.kcl.name)},\n"
            if inst.virtual:
                schematic_cell += f"{_ind()}virtual=True,\n"
            if inst.array is not None:
                arr = inst.array
                if isinstance(arr, RegularArray):
                    schematic_cell += f"{_ind()}array=RegularArray(\n"
                    indent += 2
                    schematic_cell += (
                        f"{_ind()}columns={arr.columns},\n"
                        f"{_ind()}columns_pitch={arr.column_pitch},\n"
                        f"{_ind()}rows={arr.rows},\n"
                        f"{_ind()}row_pitch={arr.row_pitch}),\n"
                    )
                    indent -= 2
                    schematic_cell += f"{_ind()})\n"
                else:
                    schematic_cell += f"{_ind()}array=Array(\n"
                    indent += 2
                    schematic_cell += (
                        f"{_ind()}na={arr.na},\n"
                        f"{_ind()}nb={arr.nb},\n"
                        f"{_ind()}pitch_a={arr.pitch_a},\n"
                        f"{_ind()}pitch_b={arr.pitch_b}),\n"
                    )
                    indent -= 2
                    schematic_cell += f"{_ind()})\n"
            indent -= 2
            schematic_cell += f"{_ind()})\n"

        if self.ports:
            schematic_cell += f"{_ind()}# Schematic ports\n"

            for name, port in sorted(
                self.ports.items(),
                key=lambda named_port: (
                    named_port[1].__class__.__name__,
                    named_port[0],
                ),
            ):
                if isinstance(port, Port):
                    schematic_cell += f"{_ind()}schematic.create_port(\n"
                    indent += 2
                    schematic_cell += f"{_ind()}name={port.name!r},\n"
                    schematic_cell += f"{_ind()}cross_section={port.cross_section!r},\n"
                    schematic_cell += f"{_ind()}orientation={port.orientation},\n"
                    if isinstance(port.x, PortRef):
                        schematic_cell += (
                            f"{_ind()}x={port.x.as_python_str(names[port.x.name])},\n"
                        )
                    else:
                        schematic_cell += f"{_ind()}x={port.x},\n"
                    if isinstance(port.y, PortRef):
                        schematic_cell += (
                            f"{_ind()}y={port.y.as_python_str(names[port.y.name])},\n"
                        )
                    else:
                        schematic_cell += f"{_ind()}y={port.y},\n"
                    if port.dx:
                        schematic_cell += f"{_ind()}dx={port.dx},\n"
                    if port.dy:
                        schematic_cell += f"{_ind()}dy={port.dy},\n"
                    indent -= 2
                else:
                    schematic_cell += (
                        f"{_ind()}schematic.add_port("
                        f"name={name!r},"
                        f"port={port.as_python_str(names[port.instance])})\n"
                    )
        if self.pins:
            schematic_cell += f"\n{_ind()}# Schematic pins\n"
            for name, pin in sorted(
                self.pins.items(),
                key=lambda named_pin: (
                    named_pin[1].__class__.__name__,
                    named_pin[0],
                ),
            ):
                if isinstance(pin, Pin):
                    schematic_cell += f"{_ind()}schematic.create_pin(\n"
                    indent += 2
                    schematic_cell += f"{_ind()}name={name!r},\n"
                    schematic_cell += f"{_ind()}ports={pin.ports!r},\n"
                    if pin.pin_type != "DC":
                        schematic_cell += f"{_ind()}pin_type={pin.pin_type!r},\n"
                    if pin.info:
                        schematic_cell += f"{_ind()}info={pin.info!r},\n"
                    indent -= 2
                    schematic_cell += f"{_ind()})\n"
                else:
                    schematic_cell += (
                        f"{_ind()}schematic.add_pin("
                        f"name={name!r},"
                        f"pin={pin.as_python_str(names[pin.instance])})\n"
                    )
        if self.placements:
            schematic_cell += f"\n{_ind()}# Schematic instance placements\n"

            for name, placement in sorted(
                self.placements.items(), key=lambda p: (isinstance(p, Placement), p[0])
            ):
                inst_name = names[name]
                if isinstance(placement, Placement):
                    schematic_cell += f"{_ind()}{inst_name}.place(\n"
                    indent += 2
                    if placement.x:
                        schematic_cell += f"{_ind()}x={placement.x},\n"
                    if placement.y:
                        schematic_cell += f"{_ind()}y={placement.y},\n"
                    if placement.dx:
                        schematic_cell += f"{_ind()}dx={placement.dx},\n"
                    if placement.dy:
                        schematic_cell += f"{_ind()}dy={placement.dy},\n"
                    if placement.orientation:
                        schematic_cell += (
                            f"{_ind()}orientation={placement.orientation},\n"
                        )
                    if placement.mirror:
                        schematic_cell += f"{_ind()}mirror={placement.mirror},\n"
                    if placement.anchor:
                        schematic_cell += (
                            f"{_ind()}anchor="
                            f"{placement.anchor.model_dump(exclude_defaults=True)},\n"
                        )
                    indent -= 2
                    schematic_cell += f"{_ind()})\n"
                else:
                    schematic_cell += f"{_ind()}{inst_name}.mirror = True\n"
        connections = self.connections
        if connections:
            schematic_cell += f"\n{_ind()}# Schematic connections\n"

            for connection in connections:
                ref1, ref2 = connection.net
                if isinstance(ref1, PortRef):
                    schematic_cell += f"{_ind()}{names[ref1.instance]}.connect(\n"
                    indent += 2
                    if isinstance(ref1, PortArrayRef):
                        schematic_cell += (
                            f"{_ind()}port=({ref1.port!r},{ref1.ia},{ref1.ib}),\n"
                        )
                    else:
                        schematic_cell += f"{_ind()}port={ref1.port!r},\n"
                    assert isinstance(ref2, PortRef)
                    if isinstance(ref2, PortRef):
                        schematic_cell += f"{_ind()}other={ref2},\n"
                    indent -= 2
                    schematic_cell += f"{_ind()})\n"
                else:
                    assert isinstance(ref2, PortRef)
                    schematic_cell += f"{_ind()}{names[ref2.instance]}.connect(\n"
                    indent += 2
                    if isinstance(ref2, PortArrayRef):
                        schematic_cell += (
                            f"{_ind()}port=({ref2.port!r}, {ref2.ia}, {ref2.ib}),\n"
                        )
                    else:
                        schematic_cell += f"{_ind()}port={ref2.port!r},\n"
                    schematic_cell += f"{_ind()}other={ref1}\n"
                    indent -= 2
                    schematic_cell += f"{_ind()})\n"
        if self.routes:
            nets_per_route = self.routes_nets()
            schematic_cell += f"\n{_ind()}# Schematic routes\n"
            for route in self.routes.values():
                schematic_cell += f"{_ind()}schematic.add_route(\n"
                indent += 2
                # schematic_cell += f"{_ind()}
                schematic_cell += f"{_ind()}name={route.name!r},\n"
                start_ports: list[str] = []
                end_ports: list[str] = []
                for net in nets_per_route[route.name]:
                    p1, p2 = net.net
                    if isinstance(p1, Port):
                        start_ports.append(p1.as_python_str())
                    else:
                        start_ports.append(p1.as_python_str(names[p1.instance]))
                    if isinstance(p2, Port):
                        start_ports.append(p2.as_python_str())
                    else:
                        start_ports.append(p2.as_python_str(names[p2.instance]))

                schematic_cell += f"{_ind()}start_ports=[{', '.join(start_ports)}],\n"
                schematic_cell += f"{_ind()}end_ports=[{', '.join(end_ports)}],\n"
                schematic_cell += (
                    f"{_ind()}routing_strategy={route.routing_strategy!r},\n"
                )
                for key, value in route.settings.items():
                    if isinstance(value, str):
                        schematic_cell += f"{_ind()}{key}={value!r},\n"
                    else:
                        schematic_cell += f"{_ind()}{key}={value},\n"
                indent -= 2
                schematic_cell += f"{_ind()})\n"

        schematic_cell += f"{_ind()}return schematic"

        if ruff_format:
            try:
                result = subprocess.run(
                    ["ruff", "format", "-"],  # noqa: S607
                    input=schematic_cell,
                    text=True,
                    capture_output=True,
                    check=False,
                )
                if result.returncode != 0:
                    logger.warning(
                        "Ruff errored out, returning unmodified string. Ruff errors:\n"
                        + result.stderr
                    )
                    return schematic_cell

                schematic_cell = result.stdout
            except FileNotFoundError:
                logger.warning(
                    "Ruff not found or installed. Returning unformatted string."
                )

        return schematic_cell

    def get_port_positions(
        self,
        factories: dict[
            str,
            WrappedKCellFunc[Any, ProtoTKCell[Any]] | WrappedVKCellFunc[Any, VKCell],
        ],
    ) -> PortDirections:
        sorted_ports: PortDirections = PortDirections(
            right=[], top=[], left=[], bottom=[]
        )

        @cached(cache=Cache(float("inf")))
        def get_port_orientation_function(
            component: str, /, **settings: Any
        ) -> dict[str | None, float]:
            factory = factories[component]
            if isinstance(factory, WrappedKCellFunc):
                is_schematic_inst = factory.schematic_driven()
                if is_schematic_inst:
                    _schematic = factory._f_schematic(**settings)  # ty:ignore[call-top-callable, call-non-callable]
                    port_positions = _schematic.get_port_positions(factories=factories)
                    port_directions: dict[str | None, float] = {}
                    for port_name in port_positions["right"]:
                        port_directions[port_name] = 0
                    for port_name in port_positions["top"]:
                        port_directions[port_name] = 90
                    for port_name in port_positions["left"]:
                        port_directions[port_name] = 180
                    for port_name in port_positions["bottom"]:
                        port_directions[port_name] = 270
                    return port_directions
            cell = factory(**settings)

            return {port.name: port.dcplx_trans.angle for port in cell.ports}

        for port_name, port in self.ports.items():
            if isinstance(port, Port):
                if isinstance(port.orientation, PortRef):
                    inst = self.instances[port.orientation.instance]

                    orientation = _get_instance_orientation(
                        port.orientation.instance,
                        schematic=self,
                        visited_instances=set(),
                        get_port_orientation_f=get_port_orientation_function,
                    )
                    factory = factories[inst.component]
                    if isinstance(factory, WrappedKCellFunc):
                        is_schematic_inst = factory.schematic_driven()
                        if is_schematic_inst:
                            _schematic = factory._f_schematic(**inst.settings)  # ty:ignore[call-top-callable, call-non-callable]
                            inst_ports = _schematic.get_port_positions(
                                factories=factories
                            )
                            found = False

                            port_orientation: float | None = None

                            for inst_port in inst_ports["right"]:
                                if inst_port == port:
                                    port_orientation = 0
                                    found = True
                                    break
                            if not found:
                                for inst_port in inst_ports["top"]:
                                    if inst_port == port:
                                        port_orientation = 90
                                        found = True
                                        break
                            if not found:
                                for inst_port in inst_ports["left"]:
                                    if inst_port == port:
                                        port_orientation = 180
                                        found = True
                                        break
                            if not found:
                                for inst_port in inst_ports["bottom"]:
                                    if inst_port == port:
                                        port_orientation = 270
                                        break
                            if port_orientation is None:
                                raise ValueError(
                                    f"Port {port_name} does not exist for"
                                    f" instance {inst.name} in the schematic\n{self}"
                                )
                        else:
                            cell = factory(**inst.settings)
                            port_orientation = cell.ports[port.name].dcplx_trans.angle
                    if inst.mirror:
                        orientation = (orientation - port_orientation) % 360  # ty:ignore[unsupported-operator]
                    else:
                        orientation = (orientation + port_orientation) % 360  # ty:ignore[unsupported-operator]

                    match orientation:
                        case 0:
                            sorted_ports["right"].append(port_name)
                        case 90:
                            sorted_ports["top"].append(port_name)
                        case 180:
                            sorted_ports["left"].append(port_name)
                        case 270:
                            sorted_ports["bottom"].append(port_name)
                else:
                    match port.orientation:
                        case 0:
                            sorted_ports["right"].append(port_name)
                        case 90:
                            sorted_ports["top"].append(port_name)
                        case 180:
                            sorted_ports["left"].append(port_name)
                        case 270:
                            sorted_ports["bottom"].append(port_name)
            else:
                inst = self.instances[port.instance]

                orientation = _get_instance_orientation(
                    port.instance,
                    schematic=self,
                    visited_instances=set(),
                    get_port_orientation_f=get_port_orientation_function,
                )
                factory = factories[inst.component]
                if isinstance(factory, WrappedKCellFunc):
                    is_schematic_inst = factory.schematic_driven()
                    if is_schematic_inst:
                        _schematic = factory._f_schematic(**inst.settings)  # ty:ignore[call-non-callable, call-top-callable]
                        inst_ports = _schematic.get_port_positions(factories=factories)
                        found = False

                        port_orientation = None

                        for inst_port in inst_ports["right"]:
                            if inst_port == port.port:
                                port_orientation = 0
                                found = True
                                break
                        if not found:
                            for inst_port in inst_ports["top"]:
                                if inst_port == port.port:
                                    port_orientation = 90
                                    found = True
                                    break
                        if not found:
                            for inst_port in inst_ports["left"]:
                                if inst_port == port.port:
                                    port_orientation = 180
                                    found = True
                                    break
                        if not found:
                            for inst_port in inst_ports["bottom"]:
                                if inst_port == port.port:
                                    port_orientation = 270
                                    break
                        if port_orientation is None:
                            raise ValueError(
                                f"Port {port_name!r} does not exist for"
                                f" instance {inst.name!r} in the schematic\n{self}"
                            )
                    else:
                        cell = factory(**inst.settings)
                        port_orientation = cell.ports[port.port].dcplx_trans.angle
                if inst.mirror:
                    orientation = (orientation - port_orientation) % 360  # ty:ignore[unsupported-operator]
                else:
                    orientation = (orientation + port_orientation) % 360  # ty:ignore[unsupported-operator]

                match orientation:
                    case 0:
                        sorted_ports["right"].append(port_name)
                    case 90:
                        sorted_ports["top"].append(port_name)
                    case 180:
                        sorted_ports["left"].append(port_name)
                    case 270:
                        sorted_ports["bottom"].append(port_name)
        for side in ("right", "top", "left", "bottom"):
            sorted_ports[side].sort()
        return sorted_ports

    def routes_nets(self) -> dict[str, list[RouteNet[T]]]:
        nets: dict[str, list[RouteNet[T]]] = defaultdict(list)
        for net in self.nets:
            if isinstance(net, RouteNet):
                nets[net.route].append(net)
        return nets

    @property
    def connections(self) -> list[Connection[T]]:
        return [net for net in self.nets if isinstance(net, Connection)]

add_constraint

add_constraint(constraint: Constraint) -> Constraint

Register a constraint on this schematic.

Validates that all route_names and instance_names referenced by the constraint already exist in the schematic.

Parameters:

Name Type Description Default
constraint Constraint

The constraint to add.

required

Returns:

Type Description
Constraint

The added constraint (for chaining).

Raises:

Type Description
ValueError

If any referenced route or instance name is unknown.

Source code in kfactory/schematic.py
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
def add_constraint(self, constraint: Constraint) -> Constraint:
    """Register a constraint on this schematic.

    Validates that all ``route_names`` and ``instance_names`` referenced by
    the constraint already exist in the schematic.

    Args:
        constraint: The constraint to add.

    Returns:
        The added constraint (for chaining).

    Raises:
        ValueError: If any referenced route or instance name is unknown.
    """
    missing_routes = [n for n in constraint.route_names if n not in self.routes]
    if missing_routes:
        raise ValueError(
            f"Constraint references unknown route(s): {missing_routes}"
        )
    missing_insts = [
        n for n in constraint.instance_names if n not in self.instances
    ]
    if missing_insts:
        raise ValueError(
            f"Constraint references unknown instance(s): {missing_insts}"
        )
    self.constraints.append(constraint)
    return constraint

add_pin

add_pin(name: str | None = None, *, pin: PinRef) -> None

Expose an existing instance pin as a schematic top-level pin.

Parameters:

Name Type Description Default
name str | None

Name for the schematic pin; defaults to the underlying pin name.

None
pin PinRef

Pin reference to expose.

required

Raises:

Type Description
ValueError

If a schematic pin with name already exists.

Source code in kfactory/schematic.py
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
def add_pin(self, name: str | None = None, *, pin: PinRef) -> None:
    """Expose an existing instance pin as a schematic top-level pin.

    Args:
        name: Name for the schematic pin; defaults to the underlying pin name.
        pin: Pin reference to expose.

    Raises:
        ValueError: If a schematic pin with ``name`` already exists.
    """
    name = name or pin.pin
    if name in self.pins:
        raise ValueError(f"Pin with name {name!r} already exists")
    self.pins[name] = pin

add_port

add_port(
    name: str | None = None, *, port: PortRef | PortArrayRef
) -> None

Expose an existing instance port as a schematic top-level port.

Parameters:

Name Type Description Default
name str | None

Name for the schematic port; defaults to the underlying port name.

None
port PortRef | PortArrayRef

Port reference to expose.

required

Raises:

Type Description
ValueError

If a schematic port with name already exists.

Source code in kfactory/schematic.py
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
def add_port(
    self, name: str | None = None, *, port: PortRef | PortArrayRef
) -> None:
    """Expose an existing instance port as a schematic top-level port.

    Args:
        name: Name for the schematic port; defaults to the underlying port name.
        port: Port reference to expose.

    Raises:
        ValueError: If a schematic port with `name` already exists.
    """
    name = name or port.port
    if name not in self.ports:
        self.ports[name] = port
        return
    raise ValueError(f"Port with name {name} already exists")

add_route

add_route(
    name: str,
    nets: Sequence[Sequence[PortRef]],
    routing_strategy: str,
    settings: dict[str, JSONSerializable],
) -> Route[T]

Create a multi-link route bundle.

Parameters:

Name Type Description Default
name str

Route identifier (must be unique).

required
nets Sequence[Sequence[PortRef]]

List of net tuples. Each tuple contains 2 or more ports that belong to the same net.

required
routing_strategy str

Name of the routing strategy function.

required
**settings dict[str, JSONSerializable]

Extra keyword args forwarded to the strategy.

required

Returns:

Type Description
Route[T]

The created Route.

Raises:

Type Description
ValueError

If name already exists or a net has fewer than 2 ports.

Source code in kfactory/schematic.py
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
def add_route(
    self,
    name: str,
    nets: Sequence[Sequence[PortRef]],
    routing_strategy: str,
    settings: dict[str, JSONSerializable],
) -> Route[T]:
    """Create a multi-link route bundle.

    Args:
        name: Route identifier (must be unique).
        nets: List of net tuples. Each tuple contains 2 or more ports
            that belong to the same net.
        routing_strategy: Name of the routing strategy function.
        **settings: Extra keyword args forwarded to the strategy.

    Returns:
        The created `Route`.

    Raises:
        ValueError: If `name` already exists or a net has fewer than 2 ports.
    """

    if name in self.routes:
        raise ValueError(f"Route with name {name!r} already exists")
    route = Route[T](
        name=name,
        routing_strategy=routing_strategy,
        settings=settings,
    )
    self.routes[name] = route
    for net in nets:
        if len(net) < 2:
            raise ValueError(
                f"Each route net must have at least 2 ports, got {len(net)} in "
                f"route {name!r}"
            )
        self.nets.append(RouteNet[T](route=name, net=tuple(net)))
    return route

code_str

code_str(
    imports: dict[str, str] = _schematic_default_imports,
    kfactory_name: str | None = None,
    ruff_format: bool = True,
) -> str

Generate Python code that reconstructs this schematic.

Parameters:

Name Type Description Default
imports dict[str, str]

Mapping of module -> alias to emit at top of file.

_schematic_default_imports
kfactory_name str | None

Optional override for the kfactory import name.

None
ruff_format bool

If True, format the generated code with ruff.

True

Returns:

Type Description
str

The generated source code as a string. If ruff is unavailable or

str

fails, the unformatted string is returned.

Source code in kfactory/schematic.py
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
def code_str(
    self,
    imports: dict[str, str] = _schematic_default_imports,
    kfactory_name: str | None = None,
    ruff_format: bool = True,
) -> str:
    """Generate Python code that reconstructs this schematic.

    Args:
        imports: Mapping of module -> alias to emit at top of file.
        kfactory_name: Optional override for the `kfactory` import name.
        ruff_format: If True, format the generated code with `ruff`.

    Returns:
        The generated source code as a string. If `ruff` is unavailable or
        fails, the unformatted string is returned.
    """

    schematic_cell = ""
    indent = 0

    def _ind() -> str:
        nonlocal indent
        return " " * indent

    kf_name = kfactory_name or imports["kfactory"]

    def _kcls(name: str) -> str:
        return f'{kf_name}.kcls["{name}"]'

    for imp, imp_as in imports.items():
        if imp_as is None:
            schematic_cell += f"import {imp}\n"
        else:
            schematic_cell += f"import {imp} as {imp_as}\n"

    if imports:
        schematic_cell += "\n\n"

    schematic_cell += f"kcl = {_kcls(self.kcl.name)}\n\n"

    schematic_cell += f"@kcl.schematic_cell(output_type={kf_name}.DKCell)\n"
    schematic_cell += f"def {self.name}() -> {kf_name}.{self.__class__.__name__}:\n"
    indent = 2

    if isinstance(self, Schematic):
        schematic_cell += f"{_ind()}schematic = {kf_name}.Schematic(kcl=kcl)\n\n"
    else:
        schematic_cell += f"{_ind()}schematic = {kf_name}.DSchematic(kcl=kcl)\n\n"

    schematic_cell += f"{_ind()}# Create the schematic instances\n"

    names: dict[str, str] = {}

    for inst in sorted(self.instances.values(), key=attrgetter("name")):
        inst_name = _valid_varname(inst.name)
        names[inst.name] = inst_name
        schematic_cell += f"{_ind()}{inst_name} = schematic.create_inst(\n"
        indent += 2
        schematic_cell += (
            f"{_ind()}name={inst.name!r},\n"
            f"{_ind()}component={inst.component!r},\n"
            f"{_ind()}settings={inst.settings!r},\n"
        )
        if inst.kcl != self.kcl:
            schematic_cell += f"{_ind()}kcl={_kcls(inst.kcl.name)},\n"
        if inst.virtual:
            schematic_cell += f"{_ind()}virtual=True,\n"
        if inst.array is not None:
            arr = inst.array
            if isinstance(arr, RegularArray):
                schematic_cell += f"{_ind()}array=RegularArray(\n"
                indent += 2
                schematic_cell += (
                    f"{_ind()}columns={arr.columns},\n"
                    f"{_ind()}columns_pitch={arr.column_pitch},\n"
                    f"{_ind()}rows={arr.rows},\n"
                    f"{_ind()}row_pitch={arr.row_pitch}),\n"
                )
                indent -= 2
                schematic_cell += f"{_ind()})\n"
            else:
                schematic_cell += f"{_ind()}array=Array(\n"
                indent += 2
                schematic_cell += (
                    f"{_ind()}na={arr.na},\n"
                    f"{_ind()}nb={arr.nb},\n"
                    f"{_ind()}pitch_a={arr.pitch_a},\n"
                    f"{_ind()}pitch_b={arr.pitch_b}),\n"
                )
                indent -= 2
                schematic_cell += f"{_ind()})\n"
        indent -= 2
        schematic_cell += f"{_ind()})\n"

    if self.ports:
        schematic_cell += f"{_ind()}# Schematic ports\n"

        for name, port in sorted(
            self.ports.items(),
            key=lambda named_port: (
                named_port[1].__class__.__name__,
                named_port[0],
            ),
        ):
            if isinstance(port, Port):
                schematic_cell += f"{_ind()}schematic.create_port(\n"
                indent += 2
                schematic_cell += f"{_ind()}name={port.name!r},\n"
                schematic_cell += f"{_ind()}cross_section={port.cross_section!r},\n"
                schematic_cell += f"{_ind()}orientation={port.orientation},\n"
                if isinstance(port.x, PortRef):
                    schematic_cell += (
                        f"{_ind()}x={port.x.as_python_str(names[port.x.name])},\n"
                    )
                else:
                    schematic_cell += f"{_ind()}x={port.x},\n"
                if isinstance(port.y, PortRef):
                    schematic_cell += (
                        f"{_ind()}y={port.y.as_python_str(names[port.y.name])},\n"
                    )
                else:
                    schematic_cell += f"{_ind()}y={port.y},\n"
                if port.dx:
                    schematic_cell += f"{_ind()}dx={port.dx},\n"
                if port.dy:
                    schematic_cell += f"{_ind()}dy={port.dy},\n"
                indent -= 2
            else:
                schematic_cell += (
                    f"{_ind()}schematic.add_port("
                    f"name={name!r},"
                    f"port={port.as_python_str(names[port.instance])})\n"
                )
    if self.pins:
        schematic_cell += f"\n{_ind()}# Schematic pins\n"
        for name, pin in sorted(
            self.pins.items(),
            key=lambda named_pin: (
                named_pin[1].__class__.__name__,
                named_pin[0],
            ),
        ):
            if isinstance(pin, Pin):
                schematic_cell += f"{_ind()}schematic.create_pin(\n"
                indent += 2
                schematic_cell += f"{_ind()}name={name!r},\n"
                schematic_cell += f"{_ind()}ports={pin.ports!r},\n"
                if pin.pin_type != "DC":
                    schematic_cell += f"{_ind()}pin_type={pin.pin_type!r},\n"
                if pin.info:
                    schematic_cell += f"{_ind()}info={pin.info!r},\n"
                indent -= 2
                schematic_cell += f"{_ind()})\n"
            else:
                schematic_cell += (
                    f"{_ind()}schematic.add_pin("
                    f"name={name!r},"
                    f"pin={pin.as_python_str(names[pin.instance])})\n"
                )
    if self.placements:
        schematic_cell += f"\n{_ind()}# Schematic instance placements\n"

        for name, placement in sorted(
            self.placements.items(), key=lambda p: (isinstance(p, Placement), p[0])
        ):
            inst_name = names[name]
            if isinstance(placement, Placement):
                schematic_cell += f"{_ind()}{inst_name}.place(\n"
                indent += 2
                if placement.x:
                    schematic_cell += f"{_ind()}x={placement.x},\n"
                if placement.y:
                    schematic_cell += f"{_ind()}y={placement.y},\n"
                if placement.dx:
                    schematic_cell += f"{_ind()}dx={placement.dx},\n"
                if placement.dy:
                    schematic_cell += f"{_ind()}dy={placement.dy},\n"
                if placement.orientation:
                    schematic_cell += (
                        f"{_ind()}orientation={placement.orientation},\n"
                    )
                if placement.mirror:
                    schematic_cell += f"{_ind()}mirror={placement.mirror},\n"
                if placement.anchor:
                    schematic_cell += (
                        f"{_ind()}anchor="
                        f"{placement.anchor.model_dump(exclude_defaults=True)},\n"
                    )
                indent -= 2
                schematic_cell += f"{_ind()})\n"
            else:
                schematic_cell += f"{_ind()}{inst_name}.mirror = True\n"
    connections = self.connections
    if connections:
        schematic_cell += f"\n{_ind()}# Schematic connections\n"

        for connection in connections:
            ref1, ref2 = connection.net
            if isinstance(ref1, PortRef):
                schematic_cell += f"{_ind()}{names[ref1.instance]}.connect(\n"
                indent += 2
                if isinstance(ref1, PortArrayRef):
                    schematic_cell += (
                        f"{_ind()}port=({ref1.port!r},{ref1.ia},{ref1.ib}),\n"
                    )
                else:
                    schematic_cell += f"{_ind()}port={ref1.port!r},\n"
                assert isinstance(ref2, PortRef)
                if isinstance(ref2, PortRef):
                    schematic_cell += f"{_ind()}other={ref2},\n"
                indent -= 2
                schematic_cell += f"{_ind()})\n"
            else:
                assert isinstance(ref2, PortRef)
                schematic_cell += f"{_ind()}{names[ref2.instance]}.connect(\n"
                indent += 2
                if isinstance(ref2, PortArrayRef):
                    schematic_cell += (
                        f"{_ind()}port=({ref2.port!r}, {ref2.ia}, {ref2.ib}),\n"
                    )
                else:
                    schematic_cell += f"{_ind()}port={ref2.port!r},\n"
                schematic_cell += f"{_ind()}other={ref1}\n"
                indent -= 2
                schematic_cell += f"{_ind()})\n"
    if self.routes:
        nets_per_route = self.routes_nets()
        schematic_cell += f"\n{_ind()}# Schematic routes\n"
        for route in self.routes.values():
            schematic_cell += f"{_ind()}schematic.add_route(\n"
            indent += 2
            # schematic_cell += f"{_ind()}
            schematic_cell += f"{_ind()}name={route.name!r},\n"
            start_ports: list[str] = []
            end_ports: list[str] = []
            for net in nets_per_route[route.name]:
                p1, p2 = net.net
                if isinstance(p1, Port):
                    start_ports.append(p1.as_python_str())
                else:
                    start_ports.append(p1.as_python_str(names[p1.instance]))
                if isinstance(p2, Port):
                    start_ports.append(p2.as_python_str())
                else:
                    start_ports.append(p2.as_python_str(names[p2.instance]))

            schematic_cell += f"{_ind()}start_ports=[{', '.join(start_ports)}],\n"
            schematic_cell += f"{_ind()}end_ports=[{', '.join(end_ports)}],\n"
            schematic_cell += (
                f"{_ind()}routing_strategy={route.routing_strategy!r},\n"
            )
            for key, value in route.settings.items():
                if isinstance(value, str):
                    schematic_cell += f"{_ind()}{key}={value!r},\n"
                else:
                    schematic_cell += f"{_ind()}{key}={value},\n"
            indent -= 2
            schematic_cell += f"{_ind()})\n"

    schematic_cell += f"{_ind()}return schematic"

    if ruff_format:
        try:
            result = subprocess.run(
                ["ruff", "format", "-"],  # noqa: S607
                input=schematic_cell,
                text=True,
                capture_output=True,
                check=False,
            )
            if result.returncode != 0:
                logger.warning(
                    "Ruff errored out, returning unmodified string. Ruff errors:\n"
                    + result.stderr
                )
                return schematic_cell

            schematic_cell = result.stdout
        except FileNotFoundError:
            logger.warning(
                "Ruff not found or installed. Returning unformatted string."
            )

    return schematic_cell

create_cell

create_cell(
    output_type: type[KC],
    factories: Mapping[
        str,
        Callable[..., KCell]
        | Callable[..., DKCell]
        | Callable[..., VKCell],
    ]
    | None = None,
    cross_sections: Mapping[
        str, CrossSection | DCrossSection
    ]
    | None = None,
    routing_strategies: dict[
        str,
        Callable[
            Concatenate[
                ProtoTKCell[Any],
                Sequence[Sequence[ProtoPort[Any]]],
                ...,
            ],
            Any,
        ],
    ]
    | None = None,
    place_unknown: bool = False,
    ignore_errors: bool = False,
) -> KC

Materialize the schematic into a KCell/DKCell/Component.

Parameters:

Name Type Description Default
output_type type[KC]

Cell type to return (e.g., KCell, DKCell).

required
factories Mapping[str, Callable[..., KCell] | Callable[..., DKCell] | Callable[..., VKCell]] | None

Optional mapping from factory name to callable returning a cell.

None
cross_sections Mapping[str, CrossSection | DCrossSection] | None

Optional mapping of cross-section names to definitions. If undefined uses self.kcl's cross sections.

None
routing_strategies dict[str, Callable[Concatenate[ProtoTKCell[Any], Sequence[Sequence[ProtoPort[Any]]], ...], Any]] | None

Strategy functions keyed by name. If none uses self.kcl's routing strategies

None
place_unknown bool

If True, place otherwise unplaceable instances at (0, 0). This might cause unintended side effects as the schematic is seemingly not fully deterministic, therefore this is disabled by default.

False

Returns:

Type Description
KC

A cell of type output_type with instances, ports, and routes realized.

Raises:

Type Description
ValueError

If placement or connection constraints cannot be satisfied.

Source code in kfactory/schematic.py
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
def create_cell(
    self,
    output_type: type[KC],
    factories: Mapping[
        str, Callable[..., KCell] | Callable[..., DKCell] | Callable[..., VKCell]
    ]
    | None = None,
    cross_sections: Mapping[str, CrossSection | DCrossSection] | None = None,
    routing_strategies: dict[
        str,
        Callable[
            Concatenate[
                ProtoTKCell[Any],
                Sequence[Sequence[ProtoPort[Any]]],
                ...,
            ],
            Any,
        ],
    ]
    | None = None,
    place_unknown: bool = False,
    ignore_errors: bool = False,
) -> KC:
    """Materialize the schematic into a `KCell`/`DKCell`/`Component`.

    Args:
        output_type: Cell type to return (e.g., `KCell`, `DKCell`).
        factories: Optional mapping from factory name to callable returning a cell.
        cross_sections: Optional mapping of cross-section names to definitions.
            If undefined uses `self.kcl`'s cross sections.
        routing_strategies: Strategy functions keyed by name. If none uses
            `self.kcl`'s routing strategies
        place_unknown: If True, place otherwise unplaceable instances at (0, 0).
            This might cause unintended side effects as the schematic is seemingly
            not fully deterministic, therefore this is disabled by default.

    Returns:
        A cell of type `output_type` with instances, ports, and routes realized.

    Raises:
        ValueError: If placement or connection constraints cannot be satisfied.
    """
    c = KCell(kcl=self.kcl)
    c.info = Info(**self.info)

    if routing_strategies is None:
        routing_strategies = c.kcl.routing_strategies

    if cross_sections is None:
        cross_sections = {
            name: c.kcl.get_icross_section(xs)
            for name, xs in c.kcl.cross_sections.cross_sections.items()
        }

    # calculate islands -- islands are a bunch of directly connected instances and
    # must be isolated from other islands either through no connection at all or
    # routes

    connections = self.connections

    islands, instance_connections = _get_island_connections(
        instances=self.instances, connections=connections
    )

    placed_insts: set[str] = set()
    placed_ports: set[str] = set()

    for name, port in self.ports.items():
        if isinstance(port, PortRef | PortArrayRef):
            continue
        if port.is_placeable(placed_instances=placed_insts):
            p = self.place_port(
                name,
                cell=c,
                cross_sections=cross_sections,
            )
            placed_ports.add(p.name)

    instances: dict[str, Instance | VInstance] = {}
    placed_islands: list[set[str]] = []
    seen_islands: set[int] = set()
    unique_islands: list[set[str]] = []
    for island in islands.values():
        island_id = id(island)
        if island_id not in seen_islands:
            seen_islands.add(island_id)
            unique_islands.append(island)
    for i, island in enumerate(unique_islands):
        logger.debug("Placing island {} of schema {}, {}", i, self.name, island)
        if island not in placed_islands:
            _place_island(
                c,
                schematic_island=island,
                instances=instances,
                connections=instance_connections,
                schematic_instances=self.instances,
                placed_insts=placed_insts,
                placed_ports=placed_ports,
                schematic=self,
                cross_sections=cross_sections,
                factories=factories,
                place_unknown=place_unknown,
            )
            placed_islands.append(island)
            placed_insts |= island

    nets_per_route = self.routes_nets()

    # routes
    route_results: dict[str, list[Any]] = {}
    for route in self.routes.values():
        resolved_ports: list[tuple[ProtoPort[Any], ...]] = []
        for net in nets_per_route[route.name]:
            resolved_port_list: list[KCellPort | DKCellPort] = []
            for port_ref in net.net:
                if isinstance(port_ref, Port):
                    p: KCellPort | DKCellPort = c.ports[port_ref.name]
                else:
                    inst = self.instances[port_ref.instance]
                    target = (
                        c.vinsts[port_ref.instance]
                        if inst.virtual
                        else c.insts[port_ref.instance]
                    )
                    if isinstance(port_ref, PortArrayRef):
                        p = target.ports[port_ref.port, port_ref.ia, port_ref.ib]
                    else:
                        p = target.ports[port_ref.port]
                resolved_port_list.append(p)
            resolved_ports.append(tuple(resolved_port_list))
        route_c = output_type(base=c.base)
        relevant_constraints = [
            ct for ct in self.constraints if route.name in ct.route_names
        ]
        extra_kwargs: dict[str, Any] = (
            {"constraints": relevant_constraints} if relevant_constraints else {}
        )
        if isinstance(route_c, KCell):
            result = routing_strategies[route.routing_strategy](
                output_type(base=c.base),
                resolved_ports,
                **route.settings,
                **extra_kwargs,
            )
        else:
            result = routing_strategies[route.routing_strategy](
                output_type(base=c.base),
                [
                    tuple(DKCellPort(base=p.base) for p in net_ports)
                    for net_ports in resolved_ports
                ],
                **route.settings,
                **extra_kwargs,
            )
        route_results[route.name] = result or []

    # check constraints
    if self.constraints:
        failed: list[Constraint] = []
        for ct in self.constraints:
            resolved_instances = {
                n: c.insts[n] for n in ct.instance_names if n in c.insts
            }
            resolved_routes = {n: route_results.get(n, []) for n in ct.route_names}
            if not ct.check(c, self, resolved_instances, resolved_routes):
                if ct.on_failure == "show_error":
                    c_ = c.dup()
                    c_.name = c.kcl.future_cell_name or c.name
                    c_.show(
                        lyrdb=ct.lyrdb_markers(
                            c_, self, resolved_instances, resolved_routes
                        )
                    )
                if ct.on_failure in ("error", "show_error"):
                    failed.append(ct)
        if failed:
            raise ValueError(
                f"Constraints not satisfied in schematic {self.name!r}:\n"
                + "\n".join(repr(ct) for ct in failed)
            )

    # verify connections
    port_connection_transformation_errors: list[Connection[T]] = []
    connection_transformation_errors: list[Connection[T]] = []
    for conn in connections:
        c1 = conn.net[0]
        c2 = conn.net[1]
        if isinstance(c1, Port):
            p1 = c.ports[c1.name]
            p2 = c.insts[c2.instance].ports[c2.port]
            if p1.dcplx_trans != p2.dcplx_trans:
                port_connection_transformation_errors.append(conn)
        else:
            if self.instances[c1.instance].virtual:
                inst1: Instance | VInstance = c.vinsts[c1.instance]
            else:
                inst1 = c.insts[c1.instance]
            if self.instances[c2.instance].virtual:
                inst2: Instance | VInstance = c.vinsts[c2.instance]
            else:
                inst2 = c.insts[c2.instance]
            if isinstance(c1, PortArrayRef):
                p1 = inst1.ports[c1.port, c1.ia, c1.ib]
            else:
                p1 = inst1.ports[c1.port]
            if isinstance(c2, PortArrayRef):
                p2 = inst2.ports[c2.port, c2.ia, c2.ib]
            else:
                p2 = inst2.ports[c2.port]

            t1 = p1.dcplx_trans
            t2 = p2.dcplx_trans
            if (t1 != t2 * kdb.DCplxTrans.R180) and (t1 != t2 * kdb.DCplxTrans.M90):
                connection_transformation_errors.append(conn)

    if not ignore_errors and (
        connection_transformation_errors or port_connection_transformation_errors
    ):
        raise ValueError(
            f"Not all connections in schema {self.name}"
            " could be satisfied. Missing or wrong connections:\n"
            + "\n".join(
                f"{conn.net[0]} - {conn.net[1]}"
                for conn in connection_transformation_errors
                + port_connection_transformation_errors
            )
        )

    # materialize pins on the resulting cell. ports must already be created.
    if self.pins:
        # map (instance, original port name) -> schematic-port key name
        # only PortRef-style schematic ports map to instance ports; cell
        # port names equal the schematic-port keys (see PortRef.place).
        ref_to_schematic_port: dict[tuple[str, str], str] = {}
        for sname, sport in self.ports.items():
            if isinstance(sport, PortRef) and not isinstance(sport, PortArrayRef):
                ref_to_schematic_port[(sport.instance, sport.port)] = sname

    for pin_name, pin_def in self.pins.items():
        if isinstance(pin_def, PinRef):
            inst = self.instances.get(pin_def.instance)
            if inst is None:
                raise ValueError(
                    f"Pin {pin_name!r} references unknown instance "
                    f"{pin_def.instance!r}."
                )
            if inst.virtual:
                inst_pins = c.vinsts[pin_def.instance].cell.pins
            else:
                inst_pins = c.insts[pin_def.instance].cell.pins
            if pin_def.pin not in [p.name for p in inst_pins]:
                raise ValueError(
                    f"Pin {pin_name!r} references unknown pin "
                    f"{pin_def.pin!r} on instance {pin_def.instance!r}."
                )
            inst_pin = inst_pins[pin_def.pin]
            cell_port_names: list[str] = []
            missing: list[str] = []
            for p in inst_pin.ports:
                if p.name is None:
                    missing.append("<unnamed>")
                    continue
                key = (pin_def.instance, p.name)
                if key not in ref_to_schematic_port:
                    missing.append(p.name)
                else:
                    cell_port_names.append(ref_to_schematic_port[key])
            if missing:
                raise ValueError(
                    f"Cannot materialize pin {pin_name!r} from "
                    f"{pin_def.instance!r}.{pin_def.pin!r}: underlying "
                    f"port(s) {missing!r} are not exposed as top-level"
                    " schematic ports (use schematic.add_port for each)."
                )
            c.create_pin(
                name=pin_name,
                ports=[c.ports[n] for n in cell_port_names],
                pin_type=inst_pin.pin_type,
                info=inst_pin.info.model_dump(),
            )
        else:
            missing = [p for p in pin_def.ports if p not in c.ports]
            if missing:
                raise ValueError(
                    f"Cannot materialize pin {pin_name!r}: port(s) "
                    f"{missing!r} are not registered on the cell."
                )
            c.create_pin(
                name=pin_name,
                ports=[c.ports[p] for p in pin_def.ports],
                pin_type=pin_def.pin_type,
                info=dict(pin_def.info),
            )

    c.schematic = self
    if self.name:
        c.name = self.name

    return output_type(base=c.base)

create_connection

create_connection(
    port1: PortRef | Port[T], port2: PortRef
) -> Connection[T]

Create and register a connection between two instance ports.

Parameters:

Name Type Description Default
port1 PortRef | Port[T]

First instance port.

required
port2 PortRef

Second instance port.

required

Raises:

Type Description
ValueError

If either referenced instance is unknown.

Returns:

Type Description
Connection[T]

The created Connection.

Source code in kfactory/schematic.py
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
def create_connection(
    self, port1: PortRef | Port[T], port2: PortRef
) -> Connection[T]:
    """Create and register a connection between two instance ports.

    Args:
        port1: First instance port.
        port2: Second instance port.

    Raises:
        ValueError: If either referenced instance is unknown.

    Returns:
        The created `Connection`.
    """

    conn = Connection[T](net=(port1, port2))
    if isinstance(port1, PortRef):
        if port1.instance not in self.instances:
            raise ValueError(
                f"Cannot create connection to unknown instance {port1.instance}"
            )
    elif port1 != self.ports.get(port1.name):
        raise ValueError(f"Unknown port {port1=}")
    if port2.instance not in self.instances:
        raise ValueError(
            f"Cannot create connection to unknown instance {port2.instance}"
        )
    self.nets.append(conn)
    return conn

create_inst

create_inst(
    name: str,
    component: str,
    settings: dict[str, JSONSerializable] | None = None,
    array: RegularArray[T] | Array[T] | None = None,
    placement: Placement[T] | None = None,
    kcl: KCLayout | None = None,
    virtual: bool = False,
) -> SchematicInstance[T]

Create a schema instance.

This would be an SREF or AREF in the resulting GDS cell.

Parameters:

Name Type Description Default
name str

Instance name. In a schematic, each instance must be named, unless created through routing functions.

required
component str

Factory name of the component to instantiate.

required
settings dict[str, JSONSerializable] | None

Parameters passed to the factory (optional).

None
array RegularArray[T] | Array[T] | None

If the instance should create an array instance (AREF), this can be passed here as an Array class instance.

None
placement Placement[T] | None

Optional placement for the instance. Can also be configured with inst.place(...) afterwards.

None
kcl KCLayout | None

Optional KCLayout override for this instance.

None

Returns:

Type Description
SchematicInstance[T]

Schematic instance representing the args.

Source code in kfactory/schematic.py
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
def create_inst(
    self,
    name: str,
    component: str,
    settings: dict[str, JSONSerializable] | None = None,
    array: RegularArray[T] | Array[T] | None = None,
    placement: Placement[T] | None = None,
    kcl: KCLayout | None = None,
    virtual: bool = False,
) -> SchematicInstance[T]:
    """Create a schema instance.

    This would be an SREF or AREF in the resulting GDS cell.

    Args:
        name: Instance name. In a schematic, each instance must be named,
            unless created through routing functions.
        component: Factory name of the component to instantiate.
        settings: Parameters passed to the factory (optional).
        array: If the instance should create an array instance (AREF),
            this can be passed here as an `Array` class instance.
        placement: Optional placement for the instance. Can also be configured
            with `inst.place(...)` afterwards.
        kcl: Optional `KCLayout` override for this instance.


    Returns:
        Schematic instance representing the args.
    """
    inst = SchematicInstance[T].model_validate(
        {
            "name": name,
            "component": component,
            "settings": settings or {},
            "array": array,
            "kcl": kcl or self.kcl,
            "virtual": virtual,
        }
    )
    inst._schematic = self

    if inst.name in self.instances:
        raise ValueError(
            f"Duplicate instance names are not allowed {inst.name=!r}"
            "already exists."
        )

    self.instances[inst.name] = inst
    if placement:
        self.placements[inst.name] = placement
    return inst

create_pin

create_pin(
    name: str,
    ports: list[str],
    pin_type: str = "DC",
    info: dict[str, JSONSerializable] | None = None,
) -> Pin

Create a schematic-level pin grouping existing schematic ports.

Parameters:

Name Type Description Default
name str

Pin name. Must be unique within the schematic.

required
ports list[str]

Names of schematic ports (entries of self.ports) that belong to this pin. Each name must already be registered as a schematic port.

required
pin_type str

Pin type (default "DC").

'DC'
info dict[str, JSONSerializable] | None

Optional info dict attached to the pin.

None

Returns:

Type Description
Pin

The created :class:Pin, also stored in :attr:self.pins.

Raises:

Type Description
ValueError

If a pin with name already exists, ports is empty, or any port name is not present in self.ports.

Source code in kfactory/schematic.py
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
def create_pin(
    self,
    name: str,
    ports: list[str],
    pin_type: str = "DC",
    info: dict[str, JSONSerializable] | None = None,
) -> Pin:
    """Create a schematic-level pin grouping existing schematic ports.

    Args:
        name: Pin name. Must be unique within the schematic.
        ports: Names of schematic ports (entries of ``self.ports``) that
            belong to this pin. Each name must already be registered as a
            schematic port.
        pin_type: Pin type (default ``"DC"``).
        info: Optional info dict attached to the pin.

    Returns:
        The created :class:`Pin`, also stored in :attr:`self.pins`.

    Raises:
        ValueError: If a pin with ``name`` already exists, ``ports`` is
            empty, or any port name is not present in ``self.ports``.
    """
    if name in self.pins:
        raise ValueError(f"Pin with name {name!r} already exists")
    if not ports:
        raise ValueError(
            f"At least one port must be provided to create pin named {name!r}"
        )
    missing = [p for p in ports if p not in self.ports]
    if missing:
        raise ValueError(
            f"Cannot create pin {name!r}: port(s) {missing!r} are not "
            "registered as schematic ports."
        )
    pin = Pin(name=name, ports=list(ports), pin_type=pin_type, info=info or {})
    self.pins[name] = pin
    return pin

create_port

create_port(
    name: str,
    cross_section: str,
    x: PortRef | PortArrayRef | T,
    y: PortRef | PortArrayRef | T,
    dx: T = 0,
    dy: T = 0,
    orientation: Literal[0, 90, 180, 270] = 0,
) -> Port[T]

Create a schematic-level, placeable port.

Returns:

Type Description
Port[T]

The created Port, also stored in self.ports.

Source code in kfactory/schematic.py
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
def create_port(
    self,
    name: str,
    cross_section: str,
    x: PortRef | PortArrayRef | T,
    y: PortRef | PortArrayRef | T,
    dx: T = 0,
    dy: T = 0,
    orientation: Literal[0, 90, 180, 270] = 0,
) -> Port[T]:
    """Create a schematic-level, placeable port.

    Returns:
        The created `Port`, also stored in `self.ports`.
    """
    p = Port(
        name=name,
        x=x,
        y=y,
        dx=dx,
        dy=dy,
        cross_section=cross_section,
        orientation=orientation,
    )
    self.ports[p.name] = p
    return p

netlist

netlist(
    add_defaults: bool = True,
    factories: dict[
        str,
        Callable[..., ProtoTKCell[Any]]
        | Callable[..., VKCell],
    ]
    | None = None,
    external_factories: dict[
        str,
        dict[
            str,
            Callable[..., ProtoTKCell[Any]]
            | Callable[..., VKCell],
        ],
    ]
    | None = None,
) -> Netlist

Compile the schematic into a Netlist.

Includes nets from connections, routes, and exposed ports. Instances are serialized with their kcl, component, and settings. The resulting netlist is sorted for stable output.

Source code in kfactory/schematic.py
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
def netlist(
    self,
    add_defaults: bool = True,
    factories: dict[str, Callable[..., ProtoTKCell[Any]] | Callable[..., VKCell]]
    | None = None,
    external_factories: dict[
        str, dict[str, Callable[..., ProtoTKCell[Any]] | Callable[..., VKCell]]
    ]
    | None = None,
) -> Netlist:
    """Compile the schematic into a `Netlist`.

    Includes nets from `connections`, `routes`, and exposed `ports`. Instances
    are serialized with their `kcl`, component, and settings. The resulting
    netlist is sorted for stable output.
    """

    nets = [
        Net(
            [
                NetlistPort(name=p.name) if isinstance(p, Port) else p
                for p in net.net
            ]
        )
        for net in self.nets
    ]

    if self.ports:
        nets.extend(
            [
                Net([NetlistPort(name=name), p])
                for name, p in self.ports.items()
                if isinstance(p, PortRef)
            ]
        )
    if add_defaults:
        if external_factories is None:
            all_factories: dict[
                str,
                dict[str, Callable[..., ProtoTKCell[Any]] | Callable[..., VKCell]],
            ] = defaultdict(dict)
            for kcl_ in kcls.values():
                kcl_factories: dict[
                    str, Callable[..., ProtoTKCell[Any]] | Callable[..., VKCell]
                ] = {f.name: f._f for f in kcl_.factories._all}
                kcl_factories.update(
                    {vf.name: vf._f for vf in kcl_.virtual_factories._all}
                )
                all_factories[kcl_.name] = kcl_factories
        else:
            all_factories = external_factories.copy()
        if factories is not None:
            all_factories[self.kcl.name] = factories
        nl = Netlist()
        for name in self.ports:
            nl.create_port(name)
        if self.instances:
            for inst in self.instances.values():
                na, nb = _array_dims(inst.array)
                nl.create_inst(
                    name=inst.name,
                    kcl=inst.kcl.name,
                    component=inst.component,
                    settings=_get_full_settings(
                        inst.settings,
                        inspect.signature(
                            all_factories[inst.kcl.name][inst.component]
                        ),
                    ),
                    na=na,
                    nb=nb,
                )
        for net in nets:
            nl.add_net(net)
    else:
        nl = Netlist()
        for name in self.ports:
            nl.create_port(name)
        if self.instances:
            for inst in self.instances.values():
                na, nb = _array_dims(inst.array)
                nl.create_inst(
                    name=inst.name,
                    kcl=inst.kcl.name,
                    component=inst.component,
                    settings=inst.settings,
                    na=na,
                    nb=nb,
                )
        for net in nets:
            nl.add_net(net)
    nl.sort()
    return nl

place_port

place_port(
    name: str,
    cell: KCell,
    cross_sections: Mapping[
        str, CrossSection | DCrossSection
    ],
) -> BasePort

Materialize a schematic-level port on cell.

Looks up self.ports[name] and dispatches by port type:

  • PortArrayRef / PortRef: forwards an instance port through cell.add_port (using cell.vinsts for virtual instances).
  • Port[T]: resolves (x, y, orientation) (which may themselves be references), then creates the port via cell.create_port.
Source code in kfactory/schematic.py
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
def place_port(
    self,
    name: str,
    cell: KCell,
    cross_sections: Mapping[str, CrossSection | DCrossSection],
) -> BasePort:
    """Materialize a schematic-level port on `cell`.

    Looks up `self.ports[name]` and dispatches by port type:

    - `PortArrayRef` / `PortRef`: forwards an instance port through
      `cell.add_port` (using `cell.vinsts` for virtual instances).
    - `Port[T]`: resolves `(x, y, orientation)` (which may themselves be
      references), then creates the port via `cell.create_port`.
    """
    port = self.ports[name]
    if isinstance(port, PortArrayRef):
        if self.instances[port.instance].virtual:
            return cell.add_port(
                port=cell.vinsts[port.instance].ports[port.port, port.ia, port.ib],
                name=name,
            ).base
        return cell.add_port(
            port=cell.insts[port.instance].ports[port.port, port.ia, port.ib],
            name=name,
        ).base
    if isinstance(port, PortRef):
        if self.instances[port.instance].virtual:
            return cell.add_port(
                port=cell.vinsts[port.instance].ports[port.port], name=name
            ).base
        return cell.add_port(
            port=cell.insts[port.instance].ports[port.port], name=name
        ).base

    if isinstance(port.x, PortRef):
        if isinstance(port.x, PortArrayRef):
            x: float = (
                cell.insts[port.x.instance]
                .ports[port.x.port, port.x.ia, port.x.ib]
                .x
            )
        else:
            x = cell.insts[port.x.instance].ports[port.x.port].x
    elif isinstance(port.x, AnchorRefX):
        match port.x.x:
            case "left":
                x = cell.insts[port.x.instance].xmin
            case "center":
                x = cell.insts[port.x.instance].bbox().center().x
            case "right":
                x = cell.insts[port.x.instance].xmax
    else:
        x = cast("int | T", port.x)
    x += port.dx
    if isinstance(port.y, PortRef):
        if isinstance(port.y, PortArrayRef):
            y: float = (
                cell.insts[port.y.instance]
                .ports[port.y.port, port.y.ia, port.y.ib]
                .y
            )
        else:
            y = cell.insts[port.y.instance].ports[port.y.port].y
    elif isinstance(port.y, AnchorRefY):
        match port.y.y:
            case "bottom":
                y = cell.insts[port.y.instance].ymin
            case "center":
                y = cell.insts[port.y.instance].bbox().center().y
            case "top":
                y = cell.insts[port.y.instance].ymax
    else:
        y = cast("int | T", port.y)
    y += port.dy
    if isinstance(port.orientation, PortRef):
        orientation = (
            cell.insts[port.orientation.instance]
            .ports[port.orientation.port]
            .orientation
        )
    else:
        orientation = port.orientation

    if self.unit == "dbu":
        return cell.create_port(
            dcplx_trans=kdb.DCplxTrans(
                rot=orientation,
                x=cell.kcl.to_um(cast("int", x)),
                y=cell.kcl.to_um(cast("int", y)),
            ),
            cross_section=cross_sections[port.cross_section],
            name=name,
        ).base

    return cell.create_port(
        dcplx_trans=kdb.DCplxTrans(rot=orientation, x=x, y=y),
        cross_section=cross_sections[port.cross_section],
        name=name,
    ).base

read_schematic

read_schematic(
    file: Path | str, unit: Literal["dbu"] = "dbu"
) -> Schematic
read_schematic(
    file: Path | str, unit: Literal["um"]
) -> DSchematic
read_schematic(
    file: Path | str, unit: Literal["dbu", "um"] = "dbu"
) -> Schematic | DSchematic

Read a schematic from a YAML file.

Parameters:

Name Type Description Default
file Path | str

Path to a YAML file.

required
unit Literal['dbu', 'um']

Target coordinate unit; controls which subclass is constructed.

'dbu'

Returns:

Type Description
Schematic | DSchematic

Schematic when unit="dbu", else DSchematic.

Raises:

Type Description
ValueError

If file does not exist or is not a file.

Source code in kfactory/schematic.py
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
def read_schematic(
    file: Path | str, unit: Literal["dbu", "um"] = "dbu"
) -> Schematic | DSchematic:
    """Read a schematic from a YAML file.

    Args:
        file: Path to a YAML file.
        unit: Target coordinate unit; controls which subclass is constructed.

    Returns:
        `Schematic` when `unit="dbu"`, else `DSchematic`.

    Raises:
        ValueError: If `file` does not exist or is not a file.
    """

    file = Path(file).resolve()
    if not file.is_file():
        raise ValueError(f"{file=} is either not a file or does not exist.")
    with file.open(mode="rt") as f:
        yaml_dict = yaml.load(f)
        if unit == "dbu":
            return Schematic.model_validate(yaml_dict, strict=True)
        return DSchematic.model_validate(yaml_dict)