Skip to content

Kcell

kcell

Core module of kfactory.

Defines the KCell providing klayout Cells with Ports and other convenience functions.

Instance are the kfactory instances used to also acquire ports and other inf from instances.

BaseKCell pydantic-model

Bases: BaseModel, ABC

KLayout cell and change its class to KCell.

A KCell is a dynamic proxy for kdb.Cell. It has all the attributes of the official KLayout class. Some attributes have been adjusted to return KCell specific sub classes. If the function is listed here in the docs, they have been adjusted for KFactory specifically. This object will transparently proxy to kdb.Cell. Meaning any attribute not directly defined in this class that are available from the KLayout counter part can still be accessed. The pure KLayout object can be accessed with kdb_cell.

Attributes:

Name Type Description
yaml_tag

Tag for yaml serialization.

ports list[BasePort]

Manages the ports of the cell.

settings KCellSettings

A dictionary containing settings populated by the cell decorator.

info Info

Dictionary for storing additional info if necessary. This is not passed to the GDS and therefore not reversible.

d Info

UMKCell object for easy access to the KCell in um units.

kcl KCLayout

Library object that is the manager of the KLayout

boundary KCLayout

Boundary of the cell.

insts KCLayout

List of instances in the cell.

vinsts VInstances

List of virtual instances in the cell.

size_info VInstances

Size information of the cell.

function_name str | None

Name of the function that created the cell.

Fields:

Source code in kfactory/kcell.py
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
class BaseKCell(BaseModel, ABC, arbitrary_types_allowed=True):
    """KLayout cell and change its class to KCell.

    A KCell is a dynamic proxy for kdb.Cell. It has all the
    attributes of the official KLayout class. Some attributes have been adjusted
    to return KCell specific sub classes. If the function is listed here in the
    docs, they have been adjusted for KFactory specifically. This object will
    transparently proxy to kdb.Cell. Meaning any attribute not directly
    defined in this class that are available from the KLayout counter part can
    still be accessed. The pure KLayout object can be accessed with
    `kdb_cell`.

    Attributes:
        yaml_tag: Tag for yaml serialization.
        ports: Manages the ports of the cell.
        settings: A dictionary containing settings populated by the
            [cell][kfactory.layout.KCLayout.cell] decorator.
        info: Dictionary for storing additional info if necessary. This is not
            passed to the GDS and therefore not reversible.
        d: UMKCell object for easy access to the KCell in um units.
        kcl: Library object that is the manager of the KLayout
        boundary: Boundary of the cell.
        insts: List of instances in the cell.
        vinsts: List of virtual instances in the cell.
        size_info: Size information of the cell.
        function_name: Name of the function that created the cell.
    """

    ports: list[BasePort] = Field(default_factory=list)
    pins: list[BasePin] = Field(default_factory=list)
    settings: KCellSettings = Field(default_factory=KCellSettings)
    settings_units: KCellSettingsUnits = Field(default_factory=KCellSettingsUnits)
    vinsts: VInstances
    info: Info
    kcl: KCLayout
    function_name: str | None = None
    basename: str | None = None

    @property
    @abstractmethod
    def locked(self) -> bool:
        """If set the cell shouldn't be modified anymore."""
        ...

    @locked.setter
    @abstractmethod
    def locked(self, value: bool) -> None: ...

    def lock(self) -> None:
        """Lock the cell."""
        self.locked = True

    @property
    @abstractmethod
    def name(self) -> str | None: ...

    @name.setter
    @abstractmethod
    def name(self, value: str) -> None: ...

locked abstractmethod property writable

locked: bool

If set the cell shouldn't be modified anymore.

lock

lock() -> None

Lock the cell.

Source code in kfactory/kcell.py
189
190
191
def lock(self) -> None:
    """Lock the cell."""
    self.locked = True

DKCell

Bases: ProtoTKCell[float], UMGeometricObject, DCreatePort

Cell with floating point units.

Source code in kfactory/kcell.py
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
class DKCell(ProtoTKCell[float], UMGeometricObject, DCreatePort):
    """Cell with floating point units."""

    yaml_tag: ClassVar[str] = "!DKCell"

    @overload
    def __init__(self, *, base: TKCell) -> None: ...

    @overload
    def __init__(
        self,
        name: str | None = None,
        kcl: KCLayout | None = None,
        kdb_cell: kdb.Cell | None = None,
        ports: Iterable[ProtoPort[Any]] | None = None,
        info: dict[str, Any] | None = None,
        settings: dict[str, Any] | None = None,
        pins: Iterable[ProtoPin[Any]] | None = None,
    ) -> None: ...

    def __init__(
        self,
        name: str | None = None,
        kcl: KCLayout | None = None,
        kdb_cell: kdb.Cell | None = None,
        ports: Iterable[ProtoPort[Any]] | None = None,
        info: dict[str, Any] | None = None,
        settings: dict[str, Any] | None = None,
        pins: Iterable[ProtoPin[Any]] | None = None,
        *,
        base: TKCell | None = None,
    ) -> None:
        """Constructor of KCell.

        Args:
            base: If not `None`, a KCell will be created from and existing
                KLayout Cell
            name: Name of the cell, if None will autogenerate name to
                "Unnamed_<cell_index>".
            kcl: KCLayout the cell should be attached to.
            kdb_cell: If not `None`, a KCell will be created from and existing
                KLayout Cell
            ports: Attach an existing [Ports][kfactory.ports.Ports] object to the KCell,
                if `None` create an empty one.
            info: Info object to attach to the KCell.
            settings: KCellSettings object to attach to the KCell.
        """
        super().__init__(
            base=base,
            name=name,
            kcl=kcl,
            kdb_cell=kdb_cell,
            ports=ports,
            info=info,
            settings=settings,
            pins=pins,
        )

    @property
    def ports(self) -> DPorts:
        """Ports associated with the cell."""
        return DPorts(kcl=self.kcl, bases=self._base.ports)

    @ports.setter
    def ports(self, new_ports: Iterable[ProtoPort[Any]]) -> None:
        if self.locked:
            raise LockedError(self)
        self._base.ports = [port.base for port in new_ports]

    @property
    def pins(self) -> DPins:
        """Pins associated with the cell."""
        return DPins(kcl=self.kcl, bases=self._base.pins)

    @pins.setter
    def pins(self, new_pins: Iterable[ProtoPin[Any]]) -> None:
        if self.locked:
            raise LockedError(self)
        self._base.pins = [pin.base for pin in new_pins]

    @property
    def insts(self) -> DInstances:
        """Instances associated with the cell."""
        return DInstances(cell=self._base)

    def __lshift__(self, cell: AnyTKCell) -> DInstance:
        """Convenience function for `DKCell.create_inst`.

        Args:
            cell: The cell to be added as an instance
        """
        return DInstance(kcl=self.kcl, instance=self.create_inst(cell).instance)

    def add_port(
        self,
        *,
        port: ProtoPort[Any],
        name: str | None = None,
        keep_mirror: bool = False,
    ) -> DPort:
        """Create a port in the cell."""
        if self.locked:
            raise LockedError(self)

        return self.ports.add_port(
            port=port,
            name=name,
            keep_mirror=keep_mirror,
        )

    def create_pin(
        self,
        *,
        name: str,
        ports: Iterable[ProtoPort[Any]],
        pin_type: str = "DC",
        info: dict[str, MetaData] | None = None,
    ) -> DPin:
        """Create a pin in the cell."""
        return self.pins.create_pin(
            name=name, ports=ports, pin_type=pin_type, info=info
        )

    def __getitem__(self, key: int | str | None) -> DPort:
        """Returns port from instance."""
        return self.ports[key]

    def create_inst(
        self,
        cell: ProtoTKCell[Any] | int,
        trans: kdb.DTrans | kdb.DVector | kdb.DCplxTrans | None = None,
        *,
        a: kdb.DVector | None = None,
        b: kdb.DVector | None = None,
        na: int = 1,
        nb: int = 1,
        libcell_as_static: bool = False,
        static_name_separator: str = "__",
    ) -> DInstance:  # ty:ignore[invalid-method-override]
        return DInstance(
            kcl=self.kcl,
            instance=self.dcreate_inst(
                cell,
                trans or kdb.DTrans(),
                a=a,
                b=b,
                na=na,
                nb=nb,
                libcell_as_static=libcell_as_static,
                static_name_separator=static_name_separator,
            ).instance,
        )

    def get_cross_section(
        self,
        cross_section: str
        | dict[str, Any]
        | Callable[..., CrossSection | DCrossSection]
        | SymmetricalCrossSection,
        **cross_section_kwargs: Any,
    ) -> DCrossSection:
        if isinstance(cross_section, str):
            return DCrossSection(
                kcl=self.kcl, base=self.kcl.cross_sections[cross_section]
            )
        if isinstance(cross_section, SymmetricalCrossSection):
            return DCrossSection(kcl=self.kcl, base=cross_section)
        if callable(cross_section):
            any_cross_section = cross_section(**cross_section_kwargs)  # ty:ignore[call-top-callable]
            return DCrossSection(kcl=self.kcl, base=any_cross_section._base)
        if isinstance(cross_section, dict):
            return DCrossSection(
                kcl=self.kcl,
                name=cross_section.get("name"),
                **cross_section["settings"],
            )
        raise ValueError(
            "Cannot create a cross section from "
            f"{type(cross_section)=} and {cross_section_kwargs=}"
        )

    @property
    def library_cell(self) -> DKCell:
        if self.kdb_cell.is_library_cell():
            lib_cell = self.base._library_cell
            assert lib_cell is not None
            return DKCell(base=lib_cell.base)
        raise ValueError(
            "This is not a proxy cell referencing a library cell. Please check"
            " with `.is_library_cell()` first if unsure."
        )

insts property

insts: DInstances

Instances associated with the cell.

pins property writable

pins: DPins

Pins associated with the cell.

ports property writable

ports: DPorts

Ports associated with the cell.

__getitem__

__getitem__(key: int | str | None) -> DPort

Returns port from instance.

Source code in kfactory/kcell.py
2859
2860
2861
def __getitem__(self, key: int | str | None) -> DPort:
    """Returns port from instance."""
    return self.ports[key]

__init__

__init__(*, base: TKCell) -> None
__init__(
    name: str | None = None,
    kcl: KCLayout | None = None,
    kdb_cell: Cell | None = None,
    ports: Iterable[ProtoPort[Any]] | None = None,
    info: dict[str, Any] | None = None,
    settings: dict[str, Any] | None = None,
    pins: Iterable[ProtoPin[Any]] | None = None,
) -> None
__init__(
    name: str | None = None,
    kcl: KCLayout | None = None,
    kdb_cell: Cell | None = None,
    ports: Iterable[ProtoPort[Any]] | None = None,
    info: dict[str, Any] | None = None,
    settings: dict[str, Any] | None = None,
    pins: Iterable[ProtoPin[Any]] | None = None,
    *,
    base: TKCell | None = None,
) -> None

Constructor of KCell.

Parameters:

Name Type Description Default
base TKCell | None

If not None, a KCell will be created from and existing KLayout Cell

None
name str | None

Name of the cell, if None will autogenerate name to "Unnamed_".

None
kcl KCLayout | None

KCLayout the cell should be attached to.

None
kdb_cell Cell | None

If not None, a KCell will be created from and existing KLayout Cell

None
ports Iterable[ProtoPort[Any]] | None

Attach an existing Ports object to the KCell, if None create an empty one.

None
info dict[str, Any] | None

Info object to attach to the KCell.

None
settings dict[str, Any] | None

KCellSettings object to attach to the KCell.

None
Source code in kfactory/kcell.py
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
def __init__(
    self,
    name: str | None = None,
    kcl: KCLayout | None = None,
    kdb_cell: kdb.Cell | None = None,
    ports: Iterable[ProtoPort[Any]] | None = None,
    info: dict[str, Any] | None = None,
    settings: dict[str, Any] | None = None,
    pins: Iterable[ProtoPin[Any]] | None = None,
    *,
    base: TKCell | None = None,
) -> None:
    """Constructor of KCell.

    Args:
        base: If not `None`, a KCell will be created from and existing
            KLayout Cell
        name: Name of the cell, if None will autogenerate name to
            "Unnamed_<cell_index>".
        kcl: KCLayout the cell should be attached to.
        kdb_cell: If not `None`, a KCell will be created from and existing
            KLayout Cell
        ports: Attach an existing [Ports][kfactory.ports.Ports] object to the KCell,
            if `None` create an empty one.
        info: Info object to attach to the KCell.
        settings: KCellSettings object to attach to the KCell.
    """
    super().__init__(
        base=base,
        name=name,
        kcl=kcl,
        kdb_cell=kdb_cell,
        ports=ports,
        info=info,
        settings=settings,
        pins=pins,
    )

__lshift__

__lshift__(cell: AnyTKCell) -> DInstance

Convenience function for DKCell.create_inst.

Parameters:

Name Type Description Default
cell AnyTKCell

The cell to be added as an instance

required
Source code in kfactory/kcell.py
2821
2822
2823
2824
2825
2826
2827
def __lshift__(self, cell: AnyTKCell) -> DInstance:
    """Convenience function for `DKCell.create_inst`.

    Args:
        cell: The cell to be added as an instance
    """
    return DInstance(kcl=self.kcl, instance=self.create_inst(cell).instance)

add_port

add_port(
    *,
    port: ProtoPort[Any],
    name: str | None = None,
    keep_mirror: bool = False,
) -> DPort

Create a port in the cell.

Source code in kfactory/kcell.py
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
def add_port(
    self,
    *,
    port: ProtoPort[Any],
    name: str | None = None,
    keep_mirror: bool = False,
) -> DPort:
    """Create a port in the cell."""
    if self.locked:
        raise LockedError(self)

    return self.ports.add_port(
        port=port,
        name=name,
        keep_mirror=keep_mirror,
    )

create_pin

create_pin(
    *,
    name: str,
    ports: Iterable[ProtoPort[Any]],
    pin_type: str = "DC",
    info: dict[str, MetaData] | None = None,
) -> DPin

Create a pin in the cell.

Source code in kfactory/kcell.py
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
def create_pin(
    self,
    *,
    name: str,
    ports: Iterable[ProtoPort[Any]],
    pin_type: str = "DC",
    info: dict[str, MetaData] | None = None,
) -> DPin:
    """Create a pin in the cell."""
    return self.pins.create_pin(
        name=name, ports=ports, pin_type=pin_type, info=info
    )

KCell

Bases: ProtoTKCell[int], DBUGeometricObject, ICreatePort

Cell with integer units.

Source code in kfactory/kcell.py
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
class KCell(ProtoTKCell[int], DBUGeometricObject, ICreatePort):
    """Cell with integer units."""

    yaml_tag: ClassVar[str] = "!KCell"

    @overload
    def __init__(self, *, base: TKCell) -> None: ...

    @overload
    def __init__(
        self,
        name: str | None = None,
        kcl: KCLayout | None = None,
        kdb_cell: kdb.Cell | None = None,
        ports: Iterable[ProtoPort[Any]] | None = None,
        info: dict[str, Any] | None = None,
        settings: dict[str, Any] | None = None,
        pins: Iterable[ProtoPin[Any]] | None = None,
    ) -> None: ...

    def __init__(
        self,
        name: str | None = None,
        kcl: KCLayout | None = None,
        kdb_cell: kdb.Cell | None = None,
        ports: Iterable[ProtoPort[Any]] | None = None,
        info: dict[str, Any] | None = None,
        settings: dict[str, Any] | None = None,
        pins: Iterable[ProtoPin[Any]] | None = None,
        *,
        base: TKCell | None = None,
    ) -> None:
        """Constructor of KCell.

        Args:
            base: If not `None`, a KCell will be created from and existing
                KLayout Cell
            name: Name of the cell, if None will autogenerate name to
                "Unnamed_<cell_index>".
            kcl: KCLayout the cell should be attached to.
            kdb_cell: If not `None`, a KCell will be created from and existing
                KLayout Cell
            ports: Attach an existing [Ports][kfactory.ports.Ports] object to the KCell,
                if `None` create an empty one.
            info: Info object to attach to the KCell.
            settings: KCellSettings object to attach to the KCell.
        """
        super().__init__(
            base=base,
            name=name,
            kcl=kcl,
            kdb_cell=kdb_cell,
            ports=ports,
            info=info,
            settings=settings,
            pins=pins,
        )

    @property
    def ports(self) -> Ports:
        """Ports associated with the cell."""
        return Ports(kcl=self.kcl, bases=self._base.ports)

    @ports.setter
    def ports(self, new_ports: Iterable[ProtoPort[Any]]) -> None:
        if self.locked:
            raise LockedError(self)
        self._base.ports = [port.base for port in new_ports]

    @property
    def pins(self) -> Pins:
        """Pins associated with the cell."""
        return Pins(kcl=self.kcl, bases=self._base.pins)

    @pins.setter
    def pins(self, new_pins: Iterable[ProtoPin[Any]]) -> None:
        if self.locked:
            raise LockedError(self)
        self._base.pins = [pin.base for pin in new_pins]

    @property
    def insts(self) -> Instances:
        """Instances associated with the cell."""
        return Instances(cell=self._base)

    @property
    def library_cell(self) -> KCell:
        if self.kdb_cell.is_library_cell():
            lib_cell = self.base._library_cell
            assert lib_cell is not None
            return lib_cell
        raise ValueError(
            "This is not a proxy cell referencing a library cell. Please check"
            " with `.is_library_cell()` first if unsure."
        )

    def __lshift__(self, cell: AnyTKCell) -> Instance:
        """Convenience function for `KCell.create_inst`.

        Args:
            cell: The cell to be added as an instance
        """
        return self.create_inst(cell)

    def add_port(
        self,
        *,
        port: ProtoPort[Any],
        name: str | None = None,
        keep_mirror: bool = False,
    ) -> Port:
        """Create a port in the cell."""
        if self.locked:
            raise LockedError(self)

        return self.ports.add_port(
            port=port,
            name=name,
            keep_mirror=keep_mirror,
        )

    def create_pin(
        self,
        *,
        name: str,
        ports: Iterable[ProtoPort[Any]],
        pin_type: str = "DC",
        info: dict[str, MetaData] | None = None,
    ) -> Pin:
        """Create a pin in the cell."""
        return self.pins.create_pin(
            name=name, ports=ports, pin_type=pin_type, info=info
        )

    def __getitem__(self, key: int | str | None) -> Port:
        """Returns port from instance."""
        return self.ports[key]

    def create_inst(
        self,
        cell: AnyTKCell | int,
        trans: kdb.Trans | kdb.Vector | kdb.ICplxTrans | None = None,
        *,
        a: kdb.Vector | None = None,
        b: kdb.Vector | None = None,
        na: int = 1,
        nb: int = 1,
        libcell_as_static: bool = False,
        static_name_separator: str = "__",
    ) -> Instance:  # ty:ignore[invalid-method-override]
        return Instance(
            kcl=self.kcl,
            instance=self.icreate_inst(
                cell,
                trans or kdb.Trans(),
                a=a,
                b=b,
                na=na,
                nb=nb,
                libcell_as_static=libcell_as_static,
                static_name_separator=static_name_separator,
            ).instance,
        )

    @classmethod
    def from_yaml(
        cls,
        constructor: SafeConstructor,
        node: Any,
        verbose: bool = False,
    ) -> Self:
        """Internal function used by the placer to convert yaml to a KCell."""
        d = SafeConstructor.construct_mapping(
            constructor,
            node,
            deep=True,
        )
        cell = cls(name=d["name"])
        if verbose:
            logger.info(f"Building {d['name']}")
        for _d in d.get("ports", Ports(ports=[], kcl=cell.kcl)):
            layer_as_string = (
                str(_d["layer"]).replace("[", "").replace("]", "").replace(", ", "/")
            )
            if "dcplx_trans" in _d:
                cell.create_port(
                    name=str(_d["name"]),
                    dcplx_trans=kdb.DCplxTrans.from_s(_d["dcplx_trans"]),
                    width=_d["dwidth"],
                    layer=cell.kcl.layer(kdb.LayerInfo.from_string(layer_as_string)),
                    port_type=_d["port_type"],
                )
            else:
                cell.create_port(
                    name=str(_d["name"]),
                    trans=kdb.Trans.from_s(_d["trans"]),
                    width=int(_d["width"]),
                    layer=cell.kcl.layer(kdb.LayerInfo.from_string(layer_as_string)),
                    port_type=_d["port_type"],
                )
        cell.settings = KCellSettings(
            **{
                name: deserialize_setting(setting)
                for name, setting in d.get("settings", {}).items()
            }
        )
        cell.info = Info(
            **{
                name: deserialize_setting(setting)
                for name, setting in d.get("info", {}).items()
            }
        )
        for inst in d.get("insts", []):
            if "cellname" in inst:
                cell_ = cell.kcl[inst["cellname"]]
            elif "cellfunction" in inst:
                module_name, fname = inst["cellfunction"].rsplit(".", 1)
                module = importlib.import_module(module_name)
                cellf = getattr(module, fname)
                cell_ = cellf(**inst["settings"])
                del module
            else:
                raise NotImplementedError(
                    'To define an instance, either a "cellfunction" or'
                    ' a "cellname" needs to be defined'
                )
            t = inst.get("trans", {})
            if isinstance(t, str):
                cell.create_inst(
                    cell_,
                    kdb.Trans.from_s(inst["trans"]),
                )
            else:
                angle = t.get("angle", 0)
                mirror = t.get("mirror", False)

                kinst = cell.create_inst(
                    cell_,
                    kdb.Trans(angle, mirror, 0, 0),
                )

                x0_yml = t.get("x0", DEFAULT_TRANS["x0"])
                y0_yml = t.get("y0", DEFAULT_TRANS["y0"])
                x_yml = t.get("x", DEFAULT_TRANS["x"])
                y_yml = t.get("y", DEFAULT_TRANS["y"])
                margin = t.get("margin", DEFAULT_TRANS["margin"])
                margin_x = margin.get(
                    "x",
                    DEFAULT_TRANS["margin"]["x"],  # ty:ignore[not-subscriptable, invalid-argument-type]
                )
                margin_y = margin.get(
                    "y",
                    DEFAULT_TRANS["margin"]["y"],  # ty:ignore[not-subscriptable, invalid-argument-type]
                )
                margin_x0 = margin.get(
                    "x0",
                    DEFAULT_TRANS["margin"]["x0"],  # ty:ignore[not-subscriptable, invalid-argument-type]
                )
                margin_y0 = margin.get(
                    "y0",
                    DEFAULT_TRANS["margin"]["y0"],  # ty:ignore[not-subscriptable, invalid-argument-type]
                )
                ref_yml = t.get("ref", DEFAULT_TRANS["ref"])
                if isinstance(ref_yml, str):
                    i: Instance
                    for i in reversed(cell.insts):
                        if i.cell.name == ref_yml:
                            ref = i
                            break
                    else:
                        raise IndexError(
                            f"No instance with cell name: <{ref_yml}> found"
                        )
                elif isinstance(ref_yml, int) and len(cell.insts) > 1:
                    ref = cell.insts[ref_yml]

                # margins for x0/y0 need to be in with opposite sign of
                # x/y due to them being subtracted later

                # x0
                match x0_yml:
                    case "W":
                        x0 = kinst.bbox().left - margin_x0
                    case "E":
                        x0 = kinst.bbox().right + margin_x0
                    case _:
                        if isinstance(x0_yml, int):
                            x0 = x0_yml
                        else:
                            raise NotImplementedError("unknown format for x0")
                # y0
                match y0_yml:
                    case "S":
                        y0 = kinst.bbox().bottom - margin_y0
                    case "N":
                        y0 = kinst.bbox().top + margin_y0
                    case _:
                        if isinstance(y0_yml, int):
                            y0 = y0_yml
                        else:
                            raise NotImplementedError("unknown format for y0")
                # x
                match x_yml:
                    case "W":
                        if len(cell.insts) > 1:
                            x = ref.bbox().left
                            if x_yml != x0_yml:
                                x -= margin_x
                        else:
                            x = margin_x
                    case "E":
                        if len(cell.insts) > 1:
                            x = ref.bbox().right
                            if x_yml != x0_yml:
                                x += margin_x
                        else:
                            x = margin_x
                    case _:
                        if isinstance(x_yml, int):
                            x = x_yml
                        else:
                            raise NotImplementedError("unknown format for x")
                # y
                match y_yml:
                    case "S":
                        if len(cell.insts) > 1:
                            y = ref.bbox().bottom
                            if y_yml != y0_yml:
                                y -= margin_y
                        else:
                            y = margin_y
                    case "N":
                        if len(cell.insts) > 1:
                            y = ref.bbox().top
                            if y_yml != y0_yml:
                                y += margin_y
                        else:
                            y = margin_y
                    case _:
                        if isinstance(y_yml, int):
                            y = y_yml
                        else:
                            raise NotImplementedError("unknown format for y")
                kinst.transform(kdb.Trans(0, False, x - x0, y - y0))
        type_to_class: dict[
            str,
            Callable[
                [str],
                kdb.Box
                | kdb.DBox
                | kdb.Polygon
                | kdb.DPolygon
                | kdb.Edge
                | kdb.DEdge
                | kdb.Text
                | kdb.DText,
            ],
        ] = {
            "box": kdb.Box.from_s,
            "polygon": kdb.Polygon.from_s,
            "edge": kdb.Edge.from_s,
            "text": kdb.Text.from_s,
            "dbox": kdb.DBox.from_s,
            "dpolygon": kdb.DPolygon.from_s,
            "dedge": kdb.DEdge.from_s,
            "dtext": kdb.DText.from_s,
        }

        for layer, shapes in dict(d.get("shapes", {})).items():
            linfo = kdb.LayerInfo.from_string(layer)
            for shape in shapes:
                shapetype, shapestring = shape.split(" ", 1)
                cell.shapes(cell.layout().layer(linfo)).insert(
                    type_to_class[shapetype](shapestring)
                )

        return cell

    @classmethod
    def to_yaml(cls, representer: BaseRepresenter, node: Self) -> MappingNode:
        """Internal function to convert the cell to yaml."""
        d: dict[str, Any] = {"name": node.name}

        insts = [
            {"cellname": inst.cell.name, "trans": inst.instance.trans.to_s()}
            for inst in node.insts
        ]
        shapes = {
            node.layout().get_info(layer).to_s(): [
                shape.to_s() for shape in node.shapes(layer).each()
            ]
            for layer in node.layout().layer_indexes()
            if not node.shapes(layer).is_empty()
        }
        ports: list[dict[str, Any]] = []
        for port in node.ports:
            l_ = node.kcl.get_info(port.layer)
            p: dict[str, Any] = {
                "name": port.name,
                "layer": [l_.layer, l_.datatype],
                "port_type": port.port_type,
            }
            if port.base.trans:
                p["trans"] = port.base.trans.to_s()
                p["width"] = port.width
            else:
                assert port.base.dcplx_trans is not None
                p["dcplx_trans"] = port.base.dcplx_trans.to_s()
                p["dwidth"] = port.dwidth
            p["info"] = {
                name: serialize_setting(setting)
                for name, setting in node.info.model_dump().items()
            }
            ports.append(p)

        d["ports"] = ports

        if insts:
            d["insts"] = insts
        if shapes:
            d["shapes"] = shapes
        d["settings"] = {
            name: serialize_setting(setting)
            for name, setting in node.settings.model_dump().items()
        }
        d["info"] = {
            name: serialize_setting(info)
            for name, info in node.info.model_dump().items()
        }
        return representer.represent_mapping(cls.yaml_tag, d)

    def get_cross_section(
        self,
        cross_section: str
        | dict[str, Any]
        | Callable[..., CrossSection | DCrossSection]
        | SymmetricalCrossSection,
        **cross_section_kwargs: Any,
    ) -> CrossSection:
        if isinstance(cross_section, str):
            return CrossSection(
                kcl=self.kcl, base=self.kcl.cross_sections[cross_section]
            )
        if isinstance(cross_section, SymmetricalCrossSection):
            return CrossSection(kcl=self.kcl, base=cross_section)
        if callable(cross_section):
            any_cross_section = cross_section(**cross_section_kwargs)  # ty:ignore[call-top-callable]
            return CrossSection(kcl=self.kcl, base=any_cross_section._base)
        if isinstance(cross_section, dict):
            return CrossSection(
                kcl=self.kcl,
                name=cross_section.get("name"),
                **cross_section["settings"],
            )
        raise ValueError(
            "Cannot create a cross section from "
            f"{type(cross_section)=} and {cross_section_kwargs=}"
        )

    def __getattr__(self, name: str) -> Any:
        """If KCell doesn't have an attribute, look in the KLayout Cell."""
        try:
            return ProtoTKCell.__getattr__(self, name)
        except Exception:
            return getattr(self._base, name)

insts property

insts: Instances

Instances associated with the cell.

pins property writable

pins: Pins

Pins associated with the cell.

ports property writable

ports: Ports

Ports associated with the cell.

__getattr__

__getattr__(name: str) -> Any

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

Source code in kfactory/kcell.py
3388
3389
3390
3391
3392
3393
def __getattr__(self, name: str) -> Any:
    """If KCell doesn't have an attribute, look in the KLayout Cell."""
    try:
        return ProtoTKCell.__getattr__(self, name)
    except Exception:
        return getattr(self._base, name)

__getitem__

__getitem__(key: int | str | None) -> Port

Returns port from instance.

Source code in kfactory/kcell.py
3063
3064
3065
def __getitem__(self, key: int | str | None) -> Port:
    """Returns port from instance."""
    return self.ports[key]

__init__

__init__(*, base: TKCell) -> None
__init__(
    name: str | None = None,
    kcl: KCLayout | None = None,
    kdb_cell: Cell | None = None,
    ports: Iterable[ProtoPort[Any]] | None = None,
    info: dict[str, Any] | None = None,
    settings: dict[str, Any] | None = None,
    pins: Iterable[ProtoPin[Any]] | None = None,
) -> None
__init__(
    name: str | None = None,
    kcl: KCLayout | None = None,
    kdb_cell: Cell | None = None,
    ports: Iterable[ProtoPort[Any]] | None = None,
    info: dict[str, Any] | None = None,
    settings: dict[str, Any] | None = None,
    pins: Iterable[ProtoPin[Any]] | None = None,
    *,
    base: TKCell | None = None,
) -> None

Constructor of KCell.

Parameters:

Name Type Description Default
base TKCell | None

If not None, a KCell will be created from and existing KLayout Cell

None
name str | None

Name of the cell, if None will autogenerate name to "Unnamed_".

None
kcl KCLayout | None

KCLayout the cell should be attached to.

None
kdb_cell Cell | None

If not None, a KCell will be created from and existing KLayout Cell

None
ports Iterable[ProtoPort[Any]] | None

Attach an existing Ports object to the KCell, if None create an empty one.

None
info dict[str, Any] | None

Info object to attach to the KCell.

None
settings dict[str, Any] | None

KCellSettings object to attach to the KCell.

None
Source code in kfactory/kcell.py
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
def __init__(
    self,
    name: str | None = None,
    kcl: KCLayout | None = None,
    kdb_cell: kdb.Cell | None = None,
    ports: Iterable[ProtoPort[Any]] | None = None,
    info: dict[str, Any] | None = None,
    settings: dict[str, Any] | None = None,
    pins: Iterable[ProtoPin[Any]] | None = None,
    *,
    base: TKCell | None = None,
) -> None:
    """Constructor of KCell.

    Args:
        base: If not `None`, a KCell will be created from and existing
            KLayout Cell
        name: Name of the cell, if None will autogenerate name to
            "Unnamed_<cell_index>".
        kcl: KCLayout the cell should be attached to.
        kdb_cell: If not `None`, a KCell will be created from and existing
            KLayout Cell
        ports: Attach an existing [Ports][kfactory.ports.Ports] object to the KCell,
            if `None` create an empty one.
        info: Info object to attach to the KCell.
        settings: KCellSettings object to attach to the KCell.
    """
    super().__init__(
        base=base,
        name=name,
        kcl=kcl,
        kdb_cell=kdb_cell,
        ports=ports,
        info=info,
        settings=settings,
        pins=pins,
    )

__lshift__

__lshift__(cell: AnyTKCell) -> Instance

Convenience function for KCell.create_inst.

Parameters:

Name Type Description Default
cell AnyTKCell

The cell to be added as an instance

required
Source code in kfactory/kcell.py
3025
3026
3027
3028
3029
3030
3031
def __lshift__(self, cell: AnyTKCell) -> Instance:
    """Convenience function for `KCell.create_inst`.

    Args:
        cell: The cell to be added as an instance
    """
    return self.create_inst(cell)

add_port

add_port(
    *,
    port: ProtoPort[Any],
    name: str | None = None,
    keep_mirror: bool = False,
) -> Port

Create a port in the cell.

Source code in kfactory/kcell.py
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
def add_port(
    self,
    *,
    port: ProtoPort[Any],
    name: str | None = None,
    keep_mirror: bool = False,
) -> Port:
    """Create a port in the cell."""
    if self.locked:
        raise LockedError(self)

    return self.ports.add_port(
        port=port,
        name=name,
        keep_mirror=keep_mirror,
    )

create_pin

create_pin(
    *,
    name: str,
    ports: Iterable[ProtoPort[Any]],
    pin_type: str = "DC",
    info: dict[str, MetaData] | None = None,
) -> Pin

Create a pin in the cell.

Source code in kfactory/kcell.py
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
def create_pin(
    self,
    *,
    name: str,
    ports: Iterable[ProtoPort[Any]],
    pin_type: str = "DC",
    info: dict[str, MetaData] | None = None,
) -> Pin:
    """Create a pin in the cell."""
    return self.pins.create_pin(
        name=name, ports=ports, pin_type=pin_type, info=info
    )

from_yaml classmethod

from_yaml(
    constructor: SafeConstructor,
    node: Any,
    verbose: bool = False,
) -> Self

Internal function used by the placer to convert yaml to a KCell.

Source code in kfactory/kcell.py
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
@classmethod
def from_yaml(
    cls,
    constructor: SafeConstructor,
    node: Any,
    verbose: bool = False,
) -> Self:
    """Internal function used by the placer to convert yaml to a KCell."""
    d = SafeConstructor.construct_mapping(
        constructor,
        node,
        deep=True,
    )
    cell = cls(name=d["name"])
    if verbose:
        logger.info(f"Building {d['name']}")
    for _d in d.get("ports", Ports(ports=[], kcl=cell.kcl)):
        layer_as_string = (
            str(_d["layer"]).replace("[", "").replace("]", "").replace(", ", "/")
        )
        if "dcplx_trans" in _d:
            cell.create_port(
                name=str(_d["name"]),
                dcplx_trans=kdb.DCplxTrans.from_s(_d["dcplx_trans"]),
                width=_d["dwidth"],
                layer=cell.kcl.layer(kdb.LayerInfo.from_string(layer_as_string)),
                port_type=_d["port_type"],
            )
        else:
            cell.create_port(
                name=str(_d["name"]),
                trans=kdb.Trans.from_s(_d["trans"]),
                width=int(_d["width"]),
                layer=cell.kcl.layer(kdb.LayerInfo.from_string(layer_as_string)),
                port_type=_d["port_type"],
            )
    cell.settings = KCellSettings(
        **{
            name: deserialize_setting(setting)
            for name, setting in d.get("settings", {}).items()
        }
    )
    cell.info = Info(
        **{
            name: deserialize_setting(setting)
            for name, setting in d.get("info", {}).items()
        }
    )
    for inst in d.get("insts", []):
        if "cellname" in inst:
            cell_ = cell.kcl[inst["cellname"]]
        elif "cellfunction" in inst:
            module_name, fname = inst["cellfunction"].rsplit(".", 1)
            module = importlib.import_module(module_name)
            cellf = getattr(module, fname)
            cell_ = cellf(**inst["settings"])
            del module
        else:
            raise NotImplementedError(
                'To define an instance, either a "cellfunction" or'
                ' a "cellname" needs to be defined'
            )
        t = inst.get("trans", {})
        if isinstance(t, str):
            cell.create_inst(
                cell_,
                kdb.Trans.from_s(inst["trans"]),
            )
        else:
            angle = t.get("angle", 0)
            mirror = t.get("mirror", False)

            kinst = cell.create_inst(
                cell_,
                kdb.Trans(angle, mirror, 0, 0),
            )

            x0_yml = t.get("x0", DEFAULT_TRANS["x0"])
            y0_yml = t.get("y0", DEFAULT_TRANS["y0"])
            x_yml = t.get("x", DEFAULT_TRANS["x"])
            y_yml = t.get("y", DEFAULT_TRANS["y"])
            margin = t.get("margin", DEFAULT_TRANS["margin"])
            margin_x = margin.get(
                "x",
                DEFAULT_TRANS["margin"]["x"],  # ty:ignore[not-subscriptable, invalid-argument-type]
            )
            margin_y = margin.get(
                "y",
                DEFAULT_TRANS["margin"]["y"],  # ty:ignore[not-subscriptable, invalid-argument-type]
            )
            margin_x0 = margin.get(
                "x0",
                DEFAULT_TRANS["margin"]["x0"],  # ty:ignore[not-subscriptable, invalid-argument-type]
            )
            margin_y0 = margin.get(
                "y0",
                DEFAULT_TRANS["margin"]["y0"],  # ty:ignore[not-subscriptable, invalid-argument-type]
            )
            ref_yml = t.get("ref", DEFAULT_TRANS["ref"])
            if isinstance(ref_yml, str):
                i: Instance
                for i in reversed(cell.insts):
                    if i.cell.name == ref_yml:
                        ref = i
                        break
                else:
                    raise IndexError(
                        f"No instance with cell name: <{ref_yml}> found"
                    )
            elif isinstance(ref_yml, int) and len(cell.insts) > 1:
                ref = cell.insts[ref_yml]

            # margins for x0/y0 need to be in with opposite sign of
            # x/y due to them being subtracted later

            # x0
            match x0_yml:
                case "W":
                    x0 = kinst.bbox().left - margin_x0
                case "E":
                    x0 = kinst.bbox().right + margin_x0
                case _:
                    if isinstance(x0_yml, int):
                        x0 = x0_yml
                    else:
                        raise NotImplementedError("unknown format for x0")
            # y0
            match y0_yml:
                case "S":
                    y0 = kinst.bbox().bottom - margin_y0
                case "N":
                    y0 = kinst.bbox().top + margin_y0
                case _:
                    if isinstance(y0_yml, int):
                        y0 = y0_yml
                    else:
                        raise NotImplementedError("unknown format for y0")
            # x
            match x_yml:
                case "W":
                    if len(cell.insts) > 1:
                        x = ref.bbox().left
                        if x_yml != x0_yml:
                            x -= margin_x
                    else:
                        x = margin_x
                case "E":
                    if len(cell.insts) > 1:
                        x = ref.bbox().right
                        if x_yml != x0_yml:
                            x += margin_x
                    else:
                        x = margin_x
                case _:
                    if isinstance(x_yml, int):
                        x = x_yml
                    else:
                        raise NotImplementedError("unknown format for x")
            # y
            match y_yml:
                case "S":
                    if len(cell.insts) > 1:
                        y = ref.bbox().bottom
                        if y_yml != y0_yml:
                            y -= margin_y
                    else:
                        y = margin_y
                case "N":
                    if len(cell.insts) > 1:
                        y = ref.bbox().top
                        if y_yml != y0_yml:
                            y += margin_y
                    else:
                        y = margin_y
                case _:
                    if isinstance(y_yml, int):
                        y = y_yml
                    else:
                        raise NotImplementedError("unknown format for y")
            kinst.transform(kdb.Trans(0, False, x - x0, y - y0))
    type_to_class: dict[
        str,
        Callable[
            [str],
            kdb.Box
            | kdb.DBox
            | kdb.Polygon
            | kdb.DPolygon
            | kdb.Edge
            | kdb.DEdge
            | kdb.Text
            | kdb.DText,
        ],
    ] = {
        "box": kdb.Box.from_s,
        "polygon": kdb.Polygon.from_s,
        "edge": kdb.Edge.from_s,
        "text": kdb.Text.from_s,
        "dbox": kdb.DBox.from_s,
        "dpolygon": kdb.DPolygon.from_s,
        "dedge": kdb.DEdge.from_s,
        "dtext": kdb.DText.from_s,
    }

    for layer, shapes in dict(d.get("shapes", {})).items():
        linfo = kdb.LayerInfo.from_string(layer)
        for shape in shapes:
            shapetype, shapestring = shape.split(" ", 1)
            cell.shapes(cell.layout().layer(linfo)).insert(
                type_to_class[shapetype](shapestring)
            )

    return cell

to_yaml classmethod

to_yaml(
    representer: BaseRepresenter, node: Self
) -> MappingNode

Internal function to convert the cell to yaml.

Source code in kfactory/kcell.py
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
@classmethod
def to_yaml(cls, representer: BaseRepresenter, node: Self) -> MappingNode:
    """Internal function to convert the cell to yaml."""
    d: dict[str, Any] = {"name": node.name}

    insts = [
        {"cellname": inst.cell.name, "trans": inst.instance.trans.to_s()}
        for inst in node.insts
    ]
    shapes = {
        node.layout().get_info(layer).to_s(): [
            shape.to_s() for shape in node.shapes(layer).each()
        ]
        for layer in node.layout().layer_indexes()
        if not node.shapes(layer).is_empty()
    }
    ports: list[dict[str, Any]] = []
    for port in node.ports:
        l_ = node.kcl.get_info(port.layer)
        p: dict[str, Any] = {
            "name": port.name,
            "layer": [l_.layer, l_.datatype],
            "port_type": port.port_type,
        }
        if port.base.trans:
            p["trans"] = port.base.trans.to_s()
            p["width"] = port.width
        else:
            assert port.base.dcplx_trans is not None
            p["dcplx_trans"] = port.base.dcplx_trans.to_s()
            p["dwidth"] = port.dwidth
        p["info"] = {
            name: serialize_setting(setting)
            for name, setting in node.info.model_dump().items()
        }
        ports.append(p)

    d["ports"] = ports

    if insts:
        d["insts"] = insts
    if shapes:
        d["shapes"] = shapes
    d["settings"] = {
        name: serialize_setting(setting)
        for name, setting in node.settings.model_dump().items()
    }
    d["info"] = {
        name: serialize_setting(info)
        for name, info in node.info.model_dump().items()
    }
    return representer.represent_mapping(cls.yaml_tag, d)

ProtoCells

Bases: Mapping[int, KC_co], ABC

Source code in kfactory/kcell.py
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
class ProtoCells(Mapping[int, KC_co], ABC):
    _kcl: KCLayout

    def __init__(self, kcl: KCLayout) -> None:
        self._kcl = kcl

    @abstractmethod
    def __getitem__(self, key: int | str) -> KC_co: ...

    def __delitem__(self, key: int | str) -> None:
        """Delete a cell by key (name or index)."""
        if isinstance(key, int):
            del self._kcl.tkcells[key]
        else:
            cell_index = self._kcl[key].cell_index()
            del self._kcl.tkcells[cell_index]

    @abstractmethod
    def _generate_dict(self) -> dict[int, KC_co]: ...

    def __iter__(self) -> Iterator[int]:
        return iter(self._kcl.tkcells)

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

    def items(self) -> ItemsView[int, KC_co]:
        return self._generate_dict().items()

    def values(self) -> ValuesView[KC_co]:
        return self._generate_dict().values()

    def keys(self) -> KeysView[int]:
        return self._generate_dict().keys()

    def __contains__(self, key: object) -> bool:
        if isinstance(key, int | str):
            return key in self._kcl.tkcells
        return False

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

    def __str__(self) -> str:
        return (
            f"{self.__class__.__name__}({self._kcl.name}, {self._kcl.tkcells})".replace(
                "TKCell", (self.__class__.__name__).replace("Cells", "Cell")
            )
        )

__delitem__

__delitem__(key: int | str) -> None

Delete a cell by key (name or index).

Source code in kfactory/kcell.py
4051
4052
4053
4054
4055
4056
4057
def __delitem__(self, key: int | str) -> None:
    """Delete a cell by key (name or index)."""
    if isinstance(key, int):
        del self._kcl.tkcells[key]
    else:
        cell_index = self._kcl[key].cell_index()
        del self._kcl.tkcells[cell_index]

ProtoKCell

Bases: GeometricObject[T], ABC

Source code in kfactory/kcell.py
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
class ProtoKCell[T: (int, float), TB: BaseKCell[Any]](GeometricObject[T], ABC):
    _base: TB

    @property
    def locked(self) -> bool:
        return self._base.locked

    @locked.setter
    def locked(self, value: bool) -> None:
        self._base.locked = value

    def lock(self) -> None:
        self._base.lock()

    @property
    def name(self) -> str | None:
        return self._base.name

    @name.setter
    def name(self, value: str) -> None:
        self._base.name = value

    @abstractmethod
    def dup(self) -> Self: ...

    @abstractmethod
    def write(
        self,
        filename: str | Path,
        save_options: kdb.SaveLayoutOptions = ...,
        convert_external_cells: bool = ...,
        set_meta_data: bool = ...,
        autoformat_from_file_extension: bool = ...,
    ) -> None: ...

    @property
    def info(self) -> Info:
        return self._base.info

    @info.setter
    def info(self, value: Info) -> None:
        self._base.info = value

    @property
    def settings(self) -> KCellSettings:
        """Settings dictionary set by the `kfactory.layout.KCLayout.vcell` decorator."""
        return self._base.settings

    @settings.setter
    def settings(self, value: KCellSettings) -> None:
        self._base.settings = value

    @property
    def settings_units(self) -> KCellSettingsUnits:
        """Dictionary containing the units of the settings.

        Set by the [@cell][kfactory.layout.KCLayout.cell] decorator.
        """
        return self._base.settings_units

    @settings_units.setter
    def settings_units(self, value: KCellSettingsUnits) -> None:
        self._base.settings_units = value

    @property
    def function_name(self) -> str | None:
        return self._base.function_name

    @function_name.setter
    def function_name(self, value: str | None) -> None:
        self._base.function_name = value

    @property
    def basename(self) -> str | None:
        return self._base.basename

    @basename.setter
    def basename(self, value: str | None) -> None:
        self._base.basename = value

    @property
    def vinsts(self) -> VInstances:
        return self._base.vinsts

    @property
    def base(self) -> TBaseCell_co:
        return self._base

    @property
    @abstractmethod
    def insts(self) -> ProtoInstances[T, ProtoInstance[T]]: ...

    @abstractmethod
    def shapes(self, layer: int | kdb.LayerInfo) -> kdb.Shapes | VShapes: ...

    @property
    @abstractmethod
    def ports(self) -> ProtoPorts[T]: ...

    @ports.setter
    @abstractmethod
    def ports(self, new_ports: Iterable[ProtoPort[Any]]) -> None: ...

    @property
    @abstractmethod
    def pins(self) -> ProtoPins[T]: ...

    @pins.setter
    @abstractmethod
    def pins(self, new_ports: Iterable[ProtoPin[Any]]) -> None: ...

    def add_port(
        self,
        *,
        port: ProtoPort[Any],
        name: str | None = None,
        keep_mirror: bool = False,
    ) -> ProtoPort[T]:
        """Add an existing port. E.g. from an instance to propagate the port.

        Args:
            port: The port to add.
            name: Overwrite the name of the port
            keep_mirror: Keep the mirror part of the transformation of a port if
                `True`, else set the mirror flag to `False`.
        """
        if self.locked:
            raise LockedError(self)

        return self.ports.add_port(port=port, name=name, keep_mirror=keep_mirror)

    def add_ports(
        self,
        ports: Iterable[ProtoPort[Any]],
        prefix: str = "",
        suffix: str = "",
        keep_mirror: bool = False,
    ) -> None:
        """Add a sequence of ports to the cell.

        Can be useful to add all ports of a instance for example.

        Args:
            ports: list/tuple (anything iterable) of ports.
            prefix: string to add in front of all the port names
            suffix: string to add at the end of all the port names
            keep_mirror: Keep the mirror part of the transformation of a port if
                `True`, else set the mirror flag to `False`.
        """
        if self.locked:
            raise LockedError(self)

        self.ports.add_ports(
            ports=ports, prefix=prefix, suffix=suffix, keep_mirror=keep_mirror
        )

    def layer(self, *args: Any, **kwargs: Any) -> int:
        """Get the layer info, convenience for `klayout.db.Layout.layer`."""
        return self._base.kcl.layout.layer(*args, **kwargs)

    @property
    def factory_name(self) -> str:
        """Return the name under which the factory was registered."""
        factory_name = self._base.basename or self._base.function_name
        if factory_name is not None:
            return factory_name
        raise ValueError(
            f"{self.__class__.__name__} {self.name} has most likely not been registered"
            " automatically as a factory. Therefore it doesn't have an associated name."
        )

    def has_factory_name(self) -> bool:
        return bool(self._base.basename or self._base.function_name)

    def create_vinst(
        self,
        cell: AnyKCell,
        *,
        a: kdb.DVector = kdb.DVector(0, 0),  # noqa: B008
        b: kdb.DVector = kdb.DVector(0, 0),  # noqa: B008
        na: int = 1,
        nb: int = 1,
    ) -> VInstance:
        """Insert the KCell as a VInstance into a VKCell or KCell."""
        if self.locked:
            raise LockedError(self)
        vi = VInstance(cell, a=a.dup(), b=b.dup(), na=na, nb=nb)
        self._base.vinsts.append(vi)
        return vi

    @property
    def kcl(self) -> KCLayout:
        return self._base.kcl

    def __repr__(self) -> str:
        """Return a string representation of the Cell."""
        port_names = [p.name for p in self.ports]
        pin_names = [pin.name for pin in self.pins]
        instances = [inst.name for inst in self.insts]
        return (
            f"{self.__class__.__name__}(name={self.name}, ports={port_names}, "
            f"pins={pin_names}, "
            f"instances={instances}, locked={self.locked}, kcl={self.kcl.name})"
        )

factory_name property

factory_name: str

Return the name under which the factory was registered.

settings property writable

settings: KCellSettings

Settings dictionary set by the kfactory.layout.KCLayout.vcell decorator.

settings_units property writable

settings_units: KCellSettingsUnits

Dictionary containing the units of the settings.

Set by the @cell decorator.

__repr__

__repr__() -> str

Return a string representation of the Cell.

Source code in kfactory/kcell.py
396
397
398
399
400
401
402
403
404
405
def __repr__(self) -> str:
    """Return a string representation of the Cell."""
    port_names = [p.name for p in self.ports]
    pin_names = [pin.name for pin in self.pins]
    instances = [inst.name for inst in self.insts]
    return (
        f"{self.__class__.__name__}(name={self.name}, ports={port_names}, "
        f"pins={pin_names}, "
        f"instances={instances}, locked={self.locked}, kcl={self.kcl.name})"
    )

add_port

add_port(
    *,
    port: ProtoPort[Any],
    name: str | None = None,
    keep_mirror: bool = False,
) -> ProtoPort[T]

Add an existing port. E.g. from an instance to propagate the port.

Parameters:

Name Type Description Default
port ProtoPort[Any]

The port to add.

required
name str | None

Overwrite the name of the port

None
keep_mirror bool

Keep the mirror part of the transformation of a port if True, else set the mirror flag to False.

False
Source code in kfactory/kcell.py
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
def add_port(
    self,
    *,
    port: ProtoPort[Any],
    name: str | None = None,
    keep_mirror: bool = False,
) -> ProtoPort[T]:
    """Add an existing port. E.g. from an instance to propagate the port.

    Args:
        port: The port to add.
        name: Overwrite the name of the port
        keep_mirror: Keep the mirror part of the transformation of a port if
            `True`, else set the mirror flag to `False`.
    """
    if self.locked:
        raise LockedError(self)

    return self.ports.add_port(port=port, name=name, keep_mirror=keep_mirror)

add_ports

add_ports(
    ports: Iterable[ProtoPort[Any]],
    prefix: str = "",
    suffix: str = "",
    keep_mirror: bool = False,
) -> None

Add a sequence of ports to the cell.

Can be useful to add all ports of a instance for example.

Parameters:

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

list/tuple (anything iterable) of ports.

required
prefix str

string to add in front of all the port names

''
suffix str

string to add at the end of all the port names

''
keep_mirror bool

Keep the mirror part of the transformation of a port if True, else set the mirror flag to False.

False
Source code in kfactory/kcell.py
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
def add_ports(
    self,
    ports: Iterable[ProtoPort[Any]],
    prefix: str = "",
    suffix: str = "",
    keep_mirror: bool = False,
) -> None:
    """Add a sequence of ports to the cell.

    Can be useful to add all ports of a instance for example.

    Args:
        ports: list/tuple (anything iterable) of ports.
        prefix: string to add in front of all the port names
        suffix: string to add at the end of all the port names
        keep_mirror: Keep the mirror part of the transformation of a port if
            `True`, else set the mirror flag to `False`.
    """
    if self.locked:
        raise LockedError(self)

    self.ports.add_ports(
        ports=ports, prefix=prefix, suffix=suffix, keep_mirror=keep_mirror
    )

create_vinst

create_vinst(
    cell: AnyKCell,
    *,
    a: DVector = kdb.DVector(0, 0),
    b: DVector = kdb.DVector(0, 0),
    na: int = 1,
    nb: int = 1,
) -> VInstance

Insert the KCell as a VInstance into a VKCell or KCell.

Source code in kfactory/kcell.py
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
def create_vinst(
    self,
    cell: AnyKCell,
    *,
    a: kdb.DVector = kdb.DVector(0, 0),  # noqa: B008
    b: kdb.DVector = kdb.DVector(0, 0),  # noqa: B008
    na: int = 1,
    nb: int = 1,
) -> VInstance:
    """Insert the KCell as a VInstance into a VKCell or KCell."""
    if self.locked:
        raise LockedError(self)
    vi = VInstance(cell, a=a.dup(), b=b.dup(), na=na, nb=nb)
    self._base.vinsts.append(vi)
    return vi

layer

layer(*args: Any, **kwargs: Any) -> int

Get the layer info, convenience for klayout.db.Layout.layer.

Source code in kfactory/kcell.py
358
359
360
def layer(self, *args: Any, **kwargs: Any) -> int:
    """Get the layer info, convenience for `klayout.db.Layout.layer`."""
    return self._base.kcl.layout.layer(*args, **kwargs)

ProtoTKCell

Bases: ProtoKCell[T, TKCell], ABC

Source code in kfactory/kcell.py
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
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
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
class ProtoTKCell[T: (int, float)](ProtoKCell[T, TKCell], ABC):
    _base: TKCell

    def __init__(
        self,
        *,
        base: TKCell | None = None,
        name: str | None = None,
        kcl: KCLayout | None = None,
        kdb_cell: kdb.Cell | None = None,
        ports: Iterable[ProtoPort[Any]] | None = None,
        pins: Iterable[ProtoPin[Any]] | None = None,
        info: dict[str, Any] | None = None,
        settings: dict[str, Any] | None = None,
    ) -> None:
        if base is not None:
            self._base = base
            return

        from .layout import get_default_kcl, kcls

        kcl_ = kcl or get_default_kcl()

        if name is None:
            name_ = "Unnamed_!" if kdb_cell is None else kdb_cell.name
        else:
            name_ = name
            if kdb_cell is not None:
                kdb_cell.name = name
        kdb_cell_ = kdb_cell or kcl_.create_cell(name_)
        if name_ == "Unnamed_!":
            kdb_cell_.name = f"Unnamed_{kdb_cell_.cell_index()}"

        self._base = TKCell(
            kcl=kcl_,
            info=Info(**(info or {})),
            settings=KCellSettings(**(settings or {})),
            kdb_cell=kdb_cell_,
            ports=[port.base for port in ports] if ports else [],
            pins=[pin.base for pin in pins] if pins else [],
            vinsts=VInstances(),
        )
        if kdb_cell_.is_library_cell():
            if ports or info or settings or pins:
                raise ValueError(
                    "If a TKCell is created from a library cell (separate PDK/layout), "
                    "ports, info, settings, and pins must not be set."
                    f"Cell {kdb_cell_.name} in {kcl_.name}: {ports=}, {pins=}, {info=},"
                    f" {settings=}"
                )
            lib_cell = kcls[kdb_cell_.library().name()][kdb_cell_.library_cell_index()]
            lib_cell.set_meta_data()
            self.get_meta_data()
            self._base._library_cell = lib_cell
        self.kcl.register_cell(self)

    @property
    def schematic(self) -> TSchematic[Any] | None:
        return self._base.schematic

    @schematic.setter
    def schematic(self, value: TSchematic[Any] | None) -> None:
        self._base.schematic = value

    @abstractmethod
    def __getitem__(self, key: int | str | None) -> ProtoPort[T]:
        """Returns port from instance."""
        ...

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

    @name.setter
    def name(self, value: str) -> None:
        self._base.name = value

    @property
    def virtual(self) -> bool:
        if self.kdb_cell.is_library_cell():
            return self.library_cell.virtual
        return self._base.virtual

    @property
    @abstractmethod
    def pins(self) -> ProtoPins[T]: ...

    @pins.setter
    @abstractmethod
    def pins(self, new_pins: Iterable[ProtoPin[Any]]) -> None: ...

    def __hash__(self) -> int:
        """Hash the KCell."""
        return hash((self._base.kcl.library.name(), self._base.kdb_cell.cell_index()))

    def __eq__(self, other: object) -> bool:
        if not isinstance(other, ProtoTKCell):
            return False
        return self._base is other._base

    @property
    def prop_id(self) -> int:
        """Gets the properties ID associated with the cell."""
        return self._base.kdb_cell.prop_id

    @prop_id.setter
    def prop_id(self, value: int) -> None:
        if self.locked:
            raise LockedError(self)
        self._base.kdb_cell.prop_id = value

    @property
    def ghost_cell(self) -> bool:
        """Returns a value indicating whether the cell is a "ghost cell"."""
        return self._base.kdb_cell.ghost_cell

    @ghost_cell.setter
    def ghost_cell(self, value: bool) -> None:
        if self.locked:
            raise LockedError(self)
        self._base.kdb_cell.ghost_cell = value

    def __getattr__(self, name: str) -> Any:
        """If KCell doesn't have an attribute, look in the KLayout Cell."""
        try:
            return ProtoKCell.__getattribute__(self, name)
        except Exception:
            return getattr(self._base, name)

    def cell_index(self) -> int:
        """Gets the cell index."""
        return self._base.kdb_cell.cell_index()

    def called_cells(self) -> list[int]:
        """Cell indices for every cell transitively instantiated inside this cell."""
        return self._base.kdb_cell.called_cells()

    def is_library_cell(self) -> bool:
        """True if this cell is imported from a klayout library."""
        return self._base.kdb_cell.is_library_cell()

    def shapes(self, layer: int | kdb.LayerInfo) -> kdb.Shapes:
        return self._base.kdb_cell.shapes(layer)

    @property
    @abstractmethod
    def insts(self) -> ProtoTInstances[T]: ...

    def __copy__(self) -> Self:
        """Enables use of `copy.copy` and `copy.deep_copy`."""
        return self.dup()

    def dup(self, new_name: str | None = None) -> Self:
        """Copy the full cell.

        Sets `_locked` to `False`

        Returns:
            cell: Exact copy of the current cell.
                The name will have `$1` as duplicate names are not allowed
        """
        kdb_copy = self._kdb_copy()
        if new_name:
            if new_name == self.name:
                if config.debug_names:
                    raise ValueError(
                        "When duplicating a Cell, avoid giving the duplicate the same "
                        "name, as this can cause naming conflicts and may render the "
                        "GDS/OASIS file unwritable. If you're using a @cell function, "
                        "ensure that the function has a different name than the one "
                        "being called."
                    )
                logger.error(
                    "When duplicating a Cell, avoid giving the duplicate the same "
                    "name, as this can cause naming conflicts and may render the "
                    "GDS/OASIS file unwritable. If you're using a @cell function, "
                    "ensure that the function has a different name than the one being "
                    "called."
                )
            kdb_copy.name = new_name

        c = self.__class__(kcl=self.kcl, kdb_cell=kdb_copy)
        c.ports = self.ports.copy()

        if self.pins:
            port_mapping = {id(p): i for i, p in enumerate(c.ports)}
            c._base.pins = [
                BasePin(
                    name=p.name,
                    kcl=self.kcl,
                    ports=[c.base.ports[port_mapping[id(port)]] for port in p.ports],
                    pin_type=p.pin_type,
                    info=p.info,
                )
                for p in self._base.pins
            ]

        c._base.settings = self.settings.model_copy()
        c._base.settings_units = self.settings_units.model_copy()
        c._base.info = self.info.model_copy()
        c._base.vinsts = self._base.vinsts.dup()

        return c

    def get_original_kcell(self) -> KCell:
        if self.is_library_cell():
            return self.library_cell.get_original_kcell()
        return KCell(base=self.base)

    @property
    def kdb_cell(self) -> kdb.Cell:
        return self._base.kdb_cell

    def destroyed(self) -> bool:
        return self._base.kdb_cell._destroyed()

    @property
    def boundary(self) -> kdb.DPolygon | None:
        return self._base.boundary

    @boundary.setter
    def boundary(self, boundary: kdb.DPolygon | None) -> None:
        self._base.boundary = boundary

    def to_itype(self) -> KCell:
        """Convert the kcell to a dbu kcell."""
        return KCell(base=self._base)

    def to_dtype(self) -> DKCell:
        """Convert the kcell to a um kcell."""
        return DKCell(base=self._base)

    def show(
        self,
        lyrdb: rdb.ReportDatabase | Path | str | None = None,
        l2n: kdb.LayoutToNetlist | Path | str | None = None,
        keep_position: bool = True,
        save_options: kdb.SaveLayoutOptions | None = None,
        use_libraries: bool = True,
        library_save_options: kdb.SaveLayoutOptions | None = None,
        technology: str | None = None,
        markers: list[tuple[DShapeLike, MarkerConfig]] | None = None,
    ) -> None:
        """Stream the gds to klive.

        Will create a temporary file of the gds and load it in KLayout via klive
        """
        if save_options is None:
            save_options = save_layout_options()
        if library_save_options is None:
            library_save_options = save_layout_options()
        show_f: ShowFunction = config.show_function or show

        kwargs: dict[str, Any] = {}
        if technology is not None:
            kwargs["technology"] = technology
        if l2n is not None:
            kwargs["l2n"] = l2n
        if lyrdb is not None:
            kwargs["lyrdb"] = lyrdb

        show_f(
            self,
            keep_position=keep_position,
            save_options=save_options,
            use_libraries=use_libraries,
            library_save_options=library_save_options,
            markers=markers,
            **kwargs,
        )

    def plot(
        self,
        lyrdb: Path | str | None = None,
        display_type: Literal["image", "widget"] | None = None,
    ) -> None:
        """Display cell.

        Args:
            lyrdb: Path to the lyrdb file.
            display_type: Type of display. Options are "widget" or "image".

        """
        from .widgets.interactive import display_kcell

        display_kcell(self, lyrdb=lyrdb, display_type=display_type)

    def _ipython_display_(self) -> None:
        """Display a cell in a Jupyter Cell.

        Usage: Pass the kcell variable as an argument in the cell at the end
        """
        self.plot()

    def delete(self) -> None:
        """Delete the cell."""
        ci = self.cell_index()
        self._base.kdb_cell.locked = False
        self.kcl.delete_cell(ci)

    @abstractmethod
    def add_port(
        self,
        *,
        port: ProtoPort[Any],
        name: str | None = None,
        keep_mirror: bool = False,
    ) -> ProtoPort[Any]: ...

    @abstractmethod
    def create_pin(
        self,
        *,
        name: str,
        ports: Iterable[ProtoPort[Any]],
        pin_type: str = "DC",
        info: dict[str, MetaData] | None = None,
    ) -> ProtoPin[T]: ...

    @overload
    @abstractmethod
    def create_inst(
        self: ProtoTKCell[int],
        cell: ProtoTKCell[Any] | int,
        trans: kdb.Trans | kdb.Vector | kdb.ICplxTrans | None = None,
        *,
        a: kdb.Vector | None = None,
        b: kdb.Vector | None = None,
        na: int = 1,
        nb: int = 1,
        libcell_as_static: bool = False,
        static_name_separator: str = "__",
    ) -> Instance: ...

    @overload
    @abstractmethod
    def create_inst(
        self: ProtoTKCell[float],
        cell: ProtoTKCell[Any] | int,
        trans: kdb.DTrans | kdb.DVector | kdb.DCplxTrans | None = None,
        *,
        a: kdb.DVector | None = None,
        b: kdb.DVector | None = None,
        na: int = 1,
        nb: int = 1,
        libcell_as_static: bool = False,
        static_name_separator: str = "__",
    ) -> DInstance: ...

    @abstractmethod
    def create_inst(
        self,
        cell: ProtoTKCell[Any] | int,
        trans: kdb.Trans
        | kdb.Vector
        | kdb.ICplxTrans
        | kdb.DTrans
        | kdb.DVector
        | kdb.DCplxTrans
        | None = None,
        *,
        a: kdb.Vector | kdb.DVector | None = None,
        b: kdb.Vector | kdb.DVector | None = None,
        na: int = 1,
        nb: int = 1,
        libcell_as_static: bool = False,
        static_name_separator: str = "__",
    ) -> Instance | DInstance: ...

    def _get_ci(
        self,
        cell: ProtoTKCell[Any],
        libcell_as_static: bool = False,
        static_name_separator: str = "__",
    ) -> int:
        if cell.layout() == self.layout():
            return cell.cell_index()
        assert cell.layout().library() is not None
        lib_ci = self.kcl.layout.add_lib_cell(cell.kcl.library, cell.cell_index())
        if lib_ci not in self.kcl.tkcells:
            kcell = self.kcl[lib_ci]
            kcell.basename = cell.basename
            kcell.function_name = cell.function_name
            kcell.base._library_cell = KCell(base=cell.base)
        if libcell_as_static:
            cell.set_meta_data()
            ci = self.kcl.layout.convert_cell_to_static(lib_ci)
            if ci not in self.kcl.tkcells:
                kcell = self.kcl[ci]
                kcell.copy_meta_info(cell.kdb_cell)
                kcell.name = cell.kcl.name + static_name_separator + cell.name
                kcell.base.virtual = cell.virtual
                if cell.kcl.dbu != self.kcl.dbu:
                    for port, lib_port in zip(kcell.ports, cell.ports, strict=False):
                        port.cross_section = CrossSection(
                            kcl=kcell.kcl,
                            base=cell.kcl.get_symmetrical_cross_section(
                                lib_port.cross_section.base.to_dtype(cell.kcl)
                            ),
                        )
            return ci
        return lib_ci

    def icreate_inst(
        self,
        cell: ProtoTKCell[Any] | int,
        trans: kdb.Trans | kdb.Vector | kdb.ICplxTrans | None = None,
        *,
        a: kdb.Vector | None = None,
        b: kdb.Vector | None = None,
        na: int = 1,
        nb: int = 1,
        libcell_as_static: bool = False,
        static_name_separator: str = "__",
    ) -> Instance:
        """Add an instance of another KCell.

        Args:
            cell: The cell to be added
            trans: The integer transformation applied to the reference
            a: Vector for the array.
                Needs to be in positive X-direction. Usually this is only a
                Vector in x-direction. Some foundries won't allow other Vectors.
            b: Vector for the array.
                Needs to be in positive Y-direction. Usually this is only a
                Vector in x-direction. Some foundries won't allow other Vectors.
            na: Number of elements in direction of `a`
            nb: Number of elements in direction of `b`
            libcell_as_static: If the cell is a Library cell
                (different KCLayout object), convert it to a static cell. This can cause
                name collisions that are automatically resolved by appending $1[..n] on
                the newly created cell.
            static_name_separator: Stringt to separate the KCLayout name from the cell
                name when converting library cells (other KCLayout object than the one
                of this KCell) to static cells (copy them into this KCell's KCLayout).

        Returns:
            The created instance
        """
        if trans is None:
            trans = kdb.Trans()
        if isinstance(cell, int):
            ci = cell
        else:
            ci = self._get_ci(cell, libcell_as_static, static_name_separator)

        if a is None:
            inst = self._base.kdb_cell.insert(kdb.CellInstArray(ci, trans))
        else:
            if b is None:
                b = kdb.Vector()
            inst = self._base.kdb_cell.insert(
                kdb.CellInstArray(ci, trans, a, b, na, nb)
            )
        return Instance(kcl=self.kcl, instance=inst)

    def dcreate_inst(
        self,
        cell: ProtoTKCell[Any] | int,
        trans: kdb.DTrans | kdb.DVector | kdb.DCplxTrans | None = None,
        *,
        a: kdb.DVector | None = None,
        b: kdb.DVector | None = None,
        na: int = 1,
        nb: int = 1,
        libcell_as_static: bool = False,
        static_name_separator: str = "__",
    ) -> DInstance:
        """Add an instance of another KCell.

        Args:
            cell: The cell to be added
            trans: The integer transformation applied to the reference
            a: Vector for the array.
                Needs to be in positive X-direction. Usually this is only a
                Vector in x-direction. Some foundries won't allow other Vectors.
            b: Vector for the array.
                Needs to be in positive Y-direction. Usually this is only a
                Vector in x-direction. Some foundries won't allow other Vectors.
            na: Number of elements in direction of `a`
            nb: Number of elements in direction of `b`
            libcell_as_static: If the cell is a Library cell
                (different KCLayout object), convert it to a static cell. This can cause
                name collisions that are automatically resolved by appending $1[..n] on
                the newly created cell.
            static_name_separator: Stringt to separate the KCLayout name from the cell
                name when converting library cells (other KCLayout object than the one
                of this KCell) to static cells (copy them into this KCell's KCLayout).

        Returns:
            The created instance
        """
        if trans is None:
            trans = kdb.DTrans()
        if isinstance(cell, int):
            ci = cell
        else:
            ci = self._get_ci(cell, libcell_as_static, static_name_separator)

        if a is None:
            inst = self._base.kdb_cell.insert(kdb.DCellInstArray(ci, trans))
        else:
            if b is None:
                b = kdb.DVector()
            inst = self._base.kdb_cell.insert(
                kdb.DCellInstArray(ci, trans, a, b, na, nb)
            )
        return DInstance(kcl=self.kcl, instance=inst)

    def _kdb_copy(self) -> kdb.Cell:
        return self._base.kdb_cell.dup()

    def layout(self) -> kdb.Layout:
        return self._base.kdb_cell.layout()

    def library(self) -> kdb.LibraryBase:
        return self._base.kdb_cell.library()

    @property
    @abstractmethod
    def library_cell(self) -> ProtoTKCell[T]: ...

    @abstractmethod
    def __lshift__(self, cell: AnyTKCell) -> ProtoTInstance[T]: ...

    def auto_rename_ports(self, rename_func: Callable[..., None] | None = None) -> None:
        """Rename the ports with the schema angle -> "NSWE" and sort by x and y.

        Args:
            rename_func: Function that takes Iterable[Port] and renames them.
                This can of course contain a filter and only rename some of the ports
        """
        if self.locked:
            raise LockedError(self)
        if rename_func is None:
            self.kcl.rename_function(self.ports)
        else:
            rename_func(self.ports)

    def flatten(self, merge: bool = True) -> None:
        """Flatten the cell.

        Args:
            merge: Merge the shapes on all layers.
        """
        if self.locked:
            raise LockedError(self)
        for vinst in self._base.vinsts:
            vinst.insert_into_flat(self)
        self._base.vinsts = VInstances()
        self._base.kdb_cell.flatten(False)

        if merge:
            for layer in self.kcl.layout.layer_indexes():
                reg = kdb.Region(self.shapes(layer))
                reg = reg.merge()
                texts = kdb.Texts(self.shapes(layer))
                self.kdb_cell.clear(layer)
                self.shapes(layer).insert(reg)
                self.shapes(layer).insert(texts)

    def convert_to_static(self, recursive: bool = True) -> None:
        """Convert the KCell to a static cell if it is pdk KCell."""
        if self.library().name() == self.kcl.name:
            raise ValueError(f"KCell {self.qname()} is already a static KCell.")
        from .layout import kcls

        lib_cell = kcls[self.library().name()][self.library_cell_index()]
        lib_cell.set_meta_data()
        kdb_cell = self.kcl.layout_cell(
            self.kcl.convert_cell_to_static(self.cell_index())
        )
        assert kdb_cell is not None
        kdb_cell.name = self.qname()
        ci_ = kdb_cell.cell_index()
        old_kdb_cell = self._base.kdb_cell
        kdb_cell.copy_meta_info(lib_cell.kdb_cell)
        self.get_meta_data()

        if recursive:
            for ci in self.called_cells():
                kc = self.kcl[ci]
                if kc.is_library_cell():
                    kc.convert_to_static(recursive=recursive)

        self._base.kdb_cell = kdb_cell
        for ci in old_kdb_cell.caller_cells():
            c = self.kcl.layout_cell(ci)
            assert c is not None
            it = kdb.RecursiveInstanceIterator(self.kcl.layout, c)
            it.targets = [old_kdb_cell.cell_index()]
            it.max_depth = 0
            insts = [instit.current_inst_element().inst() for instit in it.each()]
            locked = c.locked
            c.locked = False
            for inst in insts:
                ca = inst.cell_inst
                ca.cell_index = ci_
                c.replace(inst, ca)
            c.locked = locked

        self.kcl.layout.delete_cell(old_kdb_cell.cell_index())

    def draw_ports(self) -> None:
        """Draw all the ports on their respective layer."""
        locked = self._base.kdb_cell.locked
        self._base.kdb_cell.locked = False
        polys: dict[int, kdb.Region] = {}

        for port in Ports(kcl=self.kcl, bases=self.ports.bases):
            w = port.width

            if w in polys:
                poly = polys[w]
            else:
                poly = kdb.Region()
                poly.insert(
                    kdb.Polygon(
                        [
                            kdb.Point(0, int(-w // 2)),
                            kdb.Point(0, int(w // 2)),
                            kdb.Point(int(w // 2), 0),
                        ]
                    )
                )
                if w > 20:
                    poly -= kdb.Region(
                        kdb.Polygon(
                            [
                                kdb.Point(int(w // 20), 0),
                                kdb.Point(
                                    int(w // 20), int(-w // 2 + int(w * 2.5 // 20))
                                ),
                                kdb.Point(int(w // 2 - int(w * 1.41 / 20)), 0),
                            ]
                        )
                    )
            polys[w] = poly
            if port.base.trans:
                self.shapes(port.layer).insert(poly.transformed(port.trans))
                self.shapes(port.layer).insert(kdb.Text(port.name or "", port.trans))
            else:
                self.shapes(port.layer).insert(poly, port.dcplx_trans)
                self.shapes(port.layer).insert(kdb.Text(port.name or "", port.trans))
        self._base.kdb_cell.locked = locked

    def write(
        self,
        filename: str | Path,
        save_options: kdb.SaveLayoutOptions | None = None,
        convert_external_cells: bool = False,
        set_meta_data: bool = True,
        autoformat_from_file_extension: bool = True,
    ) -> None:
        """Write a KCell to a GDS.

        See [KCLayout.write][kfactory.layout.KCLayout.write] for more info.
        """
        if save_options is None:
            save_options = save_layout_options()
        self.insert_vinsts()
        match set_meta_data, convert_external_cells:
            case True, True:
                self.kcl.set_meta_data()
                for kcell in (self.kcl[ci] for ci in self.called_cells()):
                    if not kcell._destroyed():
                        if kcell.is_library_cell():
                            kcell.convert_to_static(recursive=True)
                        kcell.set_meta_data()
                if self.is_library_cell():
                    self.convert_to_static(recursive=True)
                self.set_meta_data()
            case True, False:
                self.kcl.set_meta_data()
                for kcell in (self.kcl[ci] for ci in self.called_cells()):
                    if not kcell._destroyed():
                        kcell.set_meta_data()
                self.set_meta_data()
            case False, True:
                for kcell in (self.kcl[ci] for ci in self.called_cells()):
                    if kcell.is_library_cell() and not kcell._destroyed():
                        kcell.convert_to_static(recursive=True)
                if self.is_library_cell():
                    self.convert_to_static(recursive=True)
            case _:
                ...

        filename = str(filename)
        if autoformat_from_file_extension:
            save_options.set_format_from_filename(filename)
        self._base.kdb_cell.write(filename, save_options)

    def write_bytes(
        self,
        save_options: kdb.SaveLayoutOptions | None = None,
        convert_external_cells: bool = False,
        set_meta_data: bool = True,
    ) -> bytes:
        """Write a KCell to a binary format as oasis.

        See [KCLayout.write][kfactory.layout.KCLayout.write] for more info.
        """
        if save_options is None:
            save_options = save_layout_options()
        self.insert_vinsts()
        match set_meta_data, convert_external_cells:
            case True, True:
                self.kcl.set_meta_data()
                for kcell in (self.kcl[ci] for ci in self.called_cells()):
                    if not kcell._destroyed():
                        if kcell.is_library_cell():
                            kcell.convert_to_static(recursive=True)
                        kcell.set_meta_data()
                if self.is_library_cell():
                    self.convert_to_static(recursive=True)
                self.set_meta_data()
            case True, False:
                self.kcl.set_meta_data()
                for kcell in (self.kcl[ci] for ci in self.called_cells()):
                    if not kcell._destroyed():
                        kcell.set_meta_data()
                self.set_meta_data()
            case False, True:
                for kcell in (self.kcl[ci] for ci in self.called_cells()):
                    if kcell.is_library_cell() and not kcell._destroyed():
                        kcell.convert_to_static(recursive=True)
                if self.is_library_cell():
                    self.convert_to_static(recursive=True)
            case _:
                ...

        save_options.format = save_options.format or "OASIS"
        save_options.clear_cells()
        save_options.select_cell(self.cell_index())
        return self.kcl.layout.write_bytes(save_options)

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

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

        Layout meta infos are ignored from the loaded layout.

        Args:
            filename: Path of the GDS file.
            options: KLayout options to load from the GDS. Can determine how merge
                conflicts are handled for example. See
                https://www.klayout.de/doc-qt5/code/class_LoadLayoutOptions.html
            register_cells: If `True` create KCells for all cells in the GDS.
            test_merge: Check the layouts first whether they are compatible
                (no differences).
            update_kcl_meta_data: How to treat loaded KCLayout info.
                overwrite: overwrite existing info entries
                skip: keep existing info values
                drop: don't add any new info
            meta_format: How to read KCell metainfo from the gds. `v1` had stored port
                transformations as strings, never versions have them stored and loaded
                in their native KLayout formats.
        """
        # see: wait for KLayout update https://github.com/KLayout/klayout/issues/1609
        logger.critical(
            "KLayout <=0.28.15 (last update 2024-02-02) cannot read LayoutMetaInfo on"
            " 'Cell.read'. kfactory uses these extensively for ports, info, and "
            "settings. Therefore proceed at your own risk."
        )
        if meta_format is None:
            meta_format = config.meta_format
        if options is None:
            options = load_layout_options()
        fn = str(Path(filename).expanduser().resolve())
        if test_merge and (
            options.cell_conflict_resolution
            != kdb.LoadLayoutOptions.CellConflictResolution.RenameCell
        ):
            self.kcl.set_meta_data()
            for kcell in self.kcl.kcells.values():
                kcell.set_meta_data()
            layout_b = kdb.Layout()
            layout_b.read(fn, options)
            layout_a = self.kcl.layout.dup()
            layout_a.delete_cell(layout_a.cell(self.name).cell_index())
            diff = MergeDiff(
                layout_a=layout_a,
                layout_b=layout_b,
                name_a=self.name,
                name_b=Path(filename).stem,
            )
            diff.compare()
            if diff.dbu_differs:
                raise MergeError("Layouts' DBU differ. Check the log for more info.")
            if diff.diff_xor.cells() > 0 or diff.layout_meta_diff:
                diff_kcl = KCLayout(self.name + "_XOR")
                diff_kcl.layout.assign(diff.diff_xor)
                show(diff_kcl)

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

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

                raise MergeError(err_msg)

        cell_ids = self._base.kdb_cell.read(fn, options)
        info, settings = self.kcl.get_meta_data()

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

                info.update(info_)
                self.kcl.info = Info(**info)
            case "drop":
                ...
        meta_format = settings.get("meta_format") or meta_format

        if register_cells:
            new_cis = set(cell_ids)

            for c in new_cis:
                kc = self.kcl[c]
                kc.get_meta_data(meta_format=meta_format)
        else:
            cis = self.kcl.tkcells.keys()
            new_cis = set(cell_ids)

            for c in new_cis & cis:
                kc = self.kcl[c]
                kc.get_meta_data(meta_format=meta_format)

        self.get_meta_data(meta_format=meta_format)

        return cell_ids

    def each_inst(self) -> Iterator[Instance]:
        """Iterates over all child instances (which may actually be instance arrays)."""
        yield from (
            Instance(self.kcl, inst) for inst in self._base.kdb_cell.each_inst()
        )

    def each_overlapping_inst(self, b: kdb.Box | kdb.DBox) -> Iterator[Instance]:
        """Gets the instances overlapping the given rectangle."""
        yield from (
            Instance(self.kcl, inst)
            for inst in self._base.kdb_cell.each_overlapping_inst(b)
        )

    def each_touching_inst(self, b: kdb.Box | kdb.DBox) -> Iterator[Instance]:
        """Gets the instances overlapping the given rectangle."""
        yield from (
            Instance(self.kcl, inst)
            for inst in self._base.kdb_cell.each_touching_inst(b)
        )

    @overload
    def insert(
        self, inst: Instance | kdb.CellInstArray | kdb.DCellInstArray
    ) -> Instance: ...

    @overload
    def insert(
        self, inst: kdb.CellInstArray | kdb.DCellInstArray, property_id: int
    ) -> Instance: ...

    def insert(
        self,
        inst: Instance | kdb.CellInstArray | kdb.DCellInstArray,
        property_id: int | None = None,
    ) -> Instance:
        """Inserts a cell instance given by another reference."""
        if self.locked:
            raise LockedError(self)
        if isinstance(inst, Instance):
            return Instance(self.kcl, self._base.kdb_cell.insert(inst.instance))
        if not property_id:
            return Instance(self.kcl, self._base.kdb_cell.insert(inst))
        assert isinstance(inst, kdb.CellInstArray | kdb.DCellInstArray)
        return Instance(self.kcl, self._base.kdb_cell.insert(inst, property_id))

    @overload
    def transform(
        self,
        inst: kdb.Instance,
        trans: kdb.Trans | kdb.DTrans | kdb.ICplxTrans | kdb.DCplxTrans,
        /,
        *,
        transform_ports: bool = True,
    ) -> Instance: ...

    @overload
    def transform(
        self,
        trans: kdb.Trans | kdb.DTrans | kdb.ICplxTrans | kdb.DCplxTrans,
        /,
        *,
        transform_ports: bool = True,
    ) -> None: ...

    def transform(
        self,
        inst_or_trans: kdb.Instance
        | kdb.Trans
        | kdb.DTrans
        | kdb.ICplxTrans
        | kdb.DCplxTrans,
        trans: kdb.Trans | kdb.DTrans | kdb.ICplxTrans | kdb.DCplxTrans | None = None,
        /,
        *,
        transform_ports: bool = True,
    ) -> Instance | None:
        """Transforms the instance or cell with the transformation given."""
        if trans is not None:
            return Instance(
                self.kcl,
                self._base.kdb_cell.transform(
                    cast("kdb.Instance", inst_or_trans),
                    trans,
                ),
            )
        self._base.kdb_cell.transform(
            cast(
                "kdb.Trans | kdb.DTrans | kdb.ICplxTrans | kdb.DCplxTrans",
                inst_or_trans,
            )
        )
        if transform_ports:
            if isinstance(inst_or_trans, kdb.DTrans):
                inst_or_trans = kdb.DCplxTrans(inst_or_trans)
            elif isinstance(inst_or_trans, kdb.ICplxTrans):
                inst_or_trans = kdb.DCplxTrans(inst_or_trans, self.kcl.dbu)

            if isinstance(inst_or_trans, kdb.Trans):
                for port in self.ports:
                    port.trans = inst_or_trans * port.trans
            else:
                for port in self.ports:
                    port.dcplx_trans = inst_or_trans * port.dcplx_trans  # ty:ignore[unsupported-operator]
        return None

    def set_meta_data(self) -> None:
        """Set metadata of the Cell.

        Currently, ports, settings and info will be set.
        """
        self.clear_meta_info()
        if not self.is_library_cell():
            for i, port in enumerate(self.ports):
                if port.base.trans is not None:
                    meta_info: dict[str, MetaData] = {
                        "name": port.name,
                        "cross_section": port.cross_section.name,
                        "trans": port.base.trans,
                        "port_type": port.port_type,
                        "info": port.info.model_dump(),
                    }

                    self.add_meta_info(
                        kdb.LayoutMetaInfo(f"kfactory:ports:{i}", meta_info, None, True)
                    )
                else:
                    meta_info = {
                        "name": port.name,
                        "cross_section": port.cross_section.name,
                        "dcplx_trans": port.dcplx_trans,
                        "port_type": port.port_type,
                        "info": port.info.model_dump(),
                    }

                    self.add_meta_info(
                        kdb.LayoutMetaInfo(f"kfactory:ports:{i}", meta_info, None, True)
                    )
            for i, pin in enumerate(self.pins):
                meta_info = {
                    "name": pin.name,
                    "pin_type": pin.pin_type,
                    "info": pin.info.model_dump(),
                    "ports": [self.base.ports.index(port.base) for port in pin.ports],
                }
                self.add_meta_info(
                    kdb.LayoutMetaInfo(f"kfactory:pins:{i}", meta_info, None, True)
                )
            settings = self.settings.model_dump()
            if settings:
                self.add_meta_info(
                    kdb.LayoutMetaInfo("kfactory:settings", settings, None, True)
                )
            info = self.info.model_dump()
            if info:
                self.add_meta_info(
                    kdb.LayoutMetaInfo("kfactory:info", info, None, True)
                )
            settings_units = self.settings_units.model_dump()
            if settings_units:
                self.add_meta_info(
                    kdb.LayoutMetaInfo(
                        "kfactory:settings_units",
                        settings_units,
                        None,
                        True,
                    )
                )

            if self.function_name is not None:
                self.add_meta_info(
                    kdb.LayoutMetaInfo(
                        "kfactory:function_name", self.function_name, None, True
                    )
                )

            if self.basename is not None:
                self.add_meta_info(
                    kdb.LayoutMetaInfo("kfactory:basename", self.basename, None, True)
                )

    def get_meta_data(
        self,
        meta_format: Literal["v1", "v2", "v3"] | None = None,
    ) -> None:
        """Read metadata from the KLayout Layout object."""
        if meta_format is None:
            meta_format = config.meta_format
        port_dict: dict[str, Any] = {}
        pin_dict: dict[str, Any] = {}
        ports: dict[str, Port] = {}
        settings: dict[str, MetaData] = {}
        settings_units: dict[str, str] = {}
        from .layout import kcls

        match meta_format:
            case "v3":
                self.ports.clear()
                meta_iter = (
                    kcls[self.library().name()][
                        self.library_cell_index()
                    ].each_meta_info()
                    if self.is_library_cell()
                    else self.each_meta_info()
                )
                for meta in meta_iter:
                    if meta.name.startswith("kfactory:ports"):
                        i = meta.name.removeprefix("kfactory:ports:")
                        port_dict[i] = meta.value
                    elif meta.name.startswith("kfactory:pins"):
                        i = meta.name.removeprefix("kfactory:pins:")
                        pin_dict[i] = meta.value
                    elif meta.name.startswith("kfactory:info"):
                        self._base.info = Info(**meta.value)
                    elif meta.name.startswith("kfactory:settings_units"):
                        self._base.settings_units = KCellSettingsUnits(**meta.value)
                    elif meta.name.startswith("kfactory:settings"):
                        self._base.settings = KCellSettings(**meta.value)
                    elif meta.name == "kfactory:function_name":
                        self._base.function_name = meta.value
                    elif meta.name == "kfactory:basename":
                        self._base.basename = meta.value

                if not self.is_library_cell():
                    for index in sorted(port_dict.keys()):
                        v = port_dict[index]
                        trans_: kdb.Trans | None = v.get("trans")
                        if trans_ is not None:
                            ports[index] = self.create_port(
                                name=v.get("name"),
                                trans=trans_,
                                cross_section=self.kcl.get_symmetrical_cross_section(
                                    v["cross_section"]
                                ),
                                port_type=v["port_type"],
                                info=v["info"],
                            )
                        else:
                            ports[index] = self.create_port(
                                name=v.get("name"),
                                dcplx_trans=v["dcplx_trans"],
                                cross_section=self.kcl.get_symmetrical_cross_section(
                                    v["cross_section"]
                                ),
                                port_type=v["port_type"],
                                info=v["info"],
                            )
                    for index in sorted(pin_dict.keys()):
                        v = pin_dict[index]
                        self.create_pin(
                            name=v.get("name"),
                            ports=[
                                Port(base=ports[str(port_index)].base)
                                for port_index in v["ports"]
                            ],
                            pin_type=v["pin_type"],
                            info=v["info"],
                        )
                else:
                    lib_name = self.library().name()
                    for index in sorted(port_dict.keys()):
                        v = port_dict[index]
                        trans_ = v.get("trans")
                        lib_kcl = kcls[lib_name]
                        cs = self.kcl.get_symmetrical_cross_section(
                            lib_kcl.get_symmetrical_cross_section(
                                v["cross_section"]
                            ).to_dtype(lib_kcl)
                        )

                        if trans_ is not None:
                            ports[index] = self.create_port(
                                name=v.get("name"),
                                trans=trans_.to_dtype(lib_kcl.dbu).to_itype(
                                    self.kcl.dbu
                                ),
                                cross_section=cs,
                                port_type=v["port_type"],
                            )
                        else:
                            ports[index] = self.create_port(
                                name=v.get("name"),
                                dcplx_trans=v["dcplx_trans"],
                                cross_section=cs,
                                port_type=v["port_type"],
                            )
                    for index in sorted(pin_dict):
                        v = pin_dict[index]
                        self.create_pin(
                            name=v.get("name"),
                            ports=[
                                Port(base=ports[str(port_index)].base)
                                for port_index in v["ports"]
                            ],
                            pin_type=v["pin_type"],
                            info=v["info"],
                        )

            case "v2":
                for meta in self.each_meta_info():
                    if meta.name.startswith("kfactory:ports"):
                        i, type_ = meta.name.removeprefix("kfactory:ports:").split(
                            ":", 1
                        )
                        if i not in port_dict:
                            port_dict[i] = {}
                        if not type_.startswith("info"):
                            port_dict[i][type_] = meta.value
                        else:
                            if "info" not in port_dict[i]:
                                port_dict[i]["info"] = {}
                            port_dict[i]["info"][type_.removeprefix("info:")] = (
                                meta.value
                            )
                    elif meta.name.startswith("kfactory:info"):
                        setattr(
                            self.info,
                            meta.name.removeprefix("kfactory:info:"),
                            meta.value,
                        )
                    elif meta.name.startswith("kfactory:settings_units"):
                        settings_units[
                            meta.name.removeprefix("kfactory:settings_units:")
                        ] = meta.value
                    elif meta.name.startswith("kfactory:settings"):
                        settings[meta.name.removeprefix("kfactory:settings:")] = (
                            meta.value
                        )

                    elif meta.name == "kfactory:function_name":
                        self.function_name = meta.value

                    elif meta.name == "kfactory:basename":
                        self.basename = meta.value

                self.settings = KCellSettings(**settings)
                self.settings_units = KCellSettingsUnits(**settings_units)

                self.ports.clear()
                for index in sorted(port_dict.keys()):
                    d = port_dict[index]
                    name = d.get("name", None)
                    port_type = d["port_type"]
                    layer_info = d["layer"]
                    width = d["width"]
                    trans = d.get("trans", None)
                    dcplx_trans = d.get("dcplx_trans", None)
                    port = Port(
                        name=name,
                        width=width,
                        layer_info=layer_info,
                        trans=kdb.Trans.R0,
                        kcl=self.kcl,
                        port_type=port_type,
                        info=d.get("info", {}),
                    )
                    if trans:
                        port.trans = trans
                    elif dcplx_trans:
                        port.dcplx_trans = dcplx_trans

                    self.add_port(port=port, keep_mirror=True)
            case "v1":
                for meta in self.each_meta_info():
                    if meta.name.startswith("kfactory:ports"):
                        i, type_ = meta.name.removeprefix("kfactory:ports:").split(
                            ":", 1
                        )
                        if i not in port_dict:
                            port_dict[i] = {}
                        if not type_.startswith("info"):
                            port_dict[i][type_] = meta.value
                        else:
                            if "info" not in port_dict[i]:
                                port_dict[i]["info"] = {}
                            port_dict[i]["info"][type_.removeprefix("info:")] = (
                                meta.value
                            )
                    elif meta.name.startswith("kfactory:info"):
                        setattr(
                            self.info,
                            meta.name.removeprefix("kfactory:info:"),
                            meta.value,
                        )
                    elif meta.name.startswith("kfactory:settings_units"):
                        settings_units[
                            meta.name.removeprefix("kfactory:settings_units:")
                        ] = meta.value
                    elif meta.name.startswith("kfactory:settings"):
                        settings[meta.name.removeprefix("kfactory:settings:")] = (
                            meta.value
                        )

                    elif meta.name == "kfactory:function_name":
                        self.function_name = meta.value

                    elif meta.name == "kfactory:basename":
                        self.basename = meta.value

                self.settings = KCellSettings(**settings)
                self.settings_units = KCellSettingsUnits(**settings_units)

                self.ports.clear()
                for index in sorted(port_dict.keys()):
                    d = port_dict[index]
                    name = d.get("name", None)
                    port_type = d["port_type"]
                    layer = d["layer"]
                    width = d["width"]
                    trans = d.get("trans", None)
                    dcplx_trans = d.get("dcplx_trans", None)
                    port = Port(
                        name=name,
                        width=width,
                        layer_info=layer,
                        trans=kdb.Trans.R0,
                        kcl=self.kcl,
                        port_type=port_type,
                        info=d.get("info", {}),
                    )
                    if trans:
                        port.trans = kdb.Trans.from_s(trans)
                    elif dcplx_trans:
                        port.dcplx_trans = kdb.DCplxTrans.from_s(dcplx_trans)

                    self.add_port(port=port, keep_mirror=True)

    def ibbox(self, layer: int | None = None) -> kdb.Box:
        if layer is None:
            return self._base.kdb_cell.bbox()
        return self._base.kdb_cell.bbox(layer)

    def dbbox(self, layer: int | None = None) -> kdb.DBox:
        if layer is None:
            return self._base.kdb_cell.dbbox()
        return self._base.kdb_cell.dbbox(layer)

    def l2n_ports(
        self,
        port_types: Iterable[str] = ("optical",),
        exclude_purposes: list[str] | None = None,
        ignore_unnamed: bool = False,
        allow_width_mismatch: bool = False,
    ) -> kdb.LayoutToNetlist:
        """Generate a LayoutToNetlist object from the port types.

        Uses kfactory ports as a basis for extraction.

        Args:
            port_types: The port types to consider for the netlist extraction.
            exclude_purposes: List of purposes, if an instance has that purpose, it will
                be ignored.
            ignore_unnamed: Ignore any instance without `.name` set.
        Returns:
            LayoutToNetlist extracted from instance and cell port positions.
        """
        l2n = kdb.LayoutToNetlist(self.name, self.kcl.dbu)
        l2n.extract_netlist()
        il = l2n.internal_layout()
        il.assign(self.kcl.layout)

        called_kcells = [self.kcl[ci] for ci in self.called_cells()]
        called_kcells.sort(key=lambda c: c.hierarchy_levels())

        for c in called_kcells:
            c.circuit(
                l2n,
                port_types=port_types,
                exclude_purposes=exclude_purposes,
                ignore_unnamed=ignore_unnamed,
                allow_width_mismatch=allow_width_mismatch,
            )
        self.circuit(
            l2n,
            port_types=port_types,
            exclude_purposes=exclude_purposes,
            ignore_unnamed=ignore_unnamed,
            allow_width_mismatch=allow_width_mismatch,
        )
        return l2n

    def l2n_elec(
        self,
        mark_port_types: Iterable[str] = ("electrical", "RF", "DC"),
        connectivity: Sequence[
            tuple[kdb.LayerInfo]
            | tuple[kdb.LayerInfo, kdb.LayerInfo]
            | tuple[kdb.LayerInfo, kdb.LayerInfo, kdb.LayerInfo],
        ]
        | None = None,
        port_mapping: dict[str, dict[str, str]] | None = None,
    ) -> kdb.LayoutToNetlist:
        """Generate a LayoutToNetlist object from electrical connectivity.

        Args:
            mark_port_types: The port types to consider for the netlist extraction.
            connectivity: Define connectivity between layers. These can be single
                layers (just consider this layer as metal), two layers (two metals
                which touch each other), or three layers (two metals with a via)
            port_mapping: Remap ports of cells to others. This allows to define
                equivalent ports in the lvs.
        """
        from kfnetlist.extract import l2n_elec as _kfnetlist_l2n_elec

        return _kfnetlist_l2n_elec(
            self,
            mark_port_types=mark_port_types,
            connectivity=connectivity,
            port_mapping=port_mapping,
        )

    def netlist(
        self,
        port_types: Sequence[str] = ("optical",),
        mark_port_types: Iterable[str] = ("electrical", "RF", "DC"),
        connectivity: Sequence[
            tuple[kdb.LayerInfo, kdb.LayerInfo]
            | tuple[kdb.LayerInfo, kdb.LayerInfo, kdb.LayerInfo]
        ]
        | None = None,
        *,
        equivalent_ports: dict[str, list[list[str]]] | None = None,
        ignore_unnamed: bool = False,
        exclude_purposes: list[str] | None = None,
        allow_width_mismatch: bool = False,
    ) -> dict[str, Netlist]:
        from kfnetlist.extract import extract as _kfnetlist_extract

        return _kfnetlist_extract(
            self,
            wrap_kdb_instance=lambda i: Instance(kcl=self.kcl, instance=i),
            port_types=port_types,
            mark_port_types=mark_port_types,
            connectivity=connectivity,
            equivalent_ports=equivalent_ports,
            ignore_unnamed=ignore_unnamed,
            exclude_purposes=exclude_purposes,
            allow_width_mismatch=allow_width_mismatch,
        )

    def get_optical_nets(
        self,
        port_types: Sequence[str] = ("optical",),
        allow_width_mismatch: bool = False,
    ) -> list[Net]:
        """Extract geometric port-adjacency nets for the given port types."""
        from kfnetlist.extract import get_optical_nets as _kfnetlist_get_optical_nets

        return _kfnetlist_get_optical_nets(
            self,
            port_types=port_types,
            allow_width_mismatch=allow_width_mismatch,
        )

    def circuit(
        self,
        l2n: kdb.LayoutToNetlist,
        port_types: Iterable[str] = ("optical",),
        ignore_unnamed: bool = False,
        exclude_purposes: list[str] | None = None,
        allow_width_mismatch: bool = False,
    ) -> None:
        """Create the (optical type) circuit of the KCell in the given netlist.

        This is NOT recommended though."""
        netlist = l2n.netlist()

        def port_filter(num_port: tuple[int, ProtoPort[Any]]) -> bool:
            return num_port[1].port_type in port_types

        circ = kdb.Circuit()
        circ.name = self.name
        circ.cell_index = self.cell_index()
        circ.boundary = self.boundary or kdb.DPolygon(self.dbbox())

        inst_ports: dict[
            str,
            dict[str, list[tuple[int, int, Instance, ProtoPort[Any], kdb.SubCircuit]]],
        ] = {}
        cell_ports: dict[str, dict[str, list[tuple[int, ProtoPort[Any]]]]] = {}

        # sort the cell's ports by position and layer

        portnames: set[str] = set()

        for i, port in filter(
            port_filter, enumerate(Ports(kcl=self.kcl, bases=self.ports.bases))
        ):
            trans = port.trans.dup()
            trans.angle %= 2
            trans.mirror = False
            layer_info = self.kcl.layout.get_info(port.layer)
            layer = f"{layer_info.layer}_{layer_info.datatype}"

            if port.name in portnames:
                raise ValueError(
                    "Netlist extraction is not possible with"
                    f" colliding port names. Duplicate name: {port.name}"
                )

            v = trans.disp
            h = f"{v.x}_{v.y}"
            if h not in cell_ports:
                cell_ports[h] = {}
            if layer not in cell_ports[h]:
                cell_ports[h][layer] = []
            cell_ports[h][layer].append((i, port))

            if port.name:
                portnames.add(port.name)

        # create nets and connect pins for each cell_port
        for layer_dict in cell_ports.values():
            for _ports in layer_dict.values():
                net = circ.create_net(
                    "-".join(_port[1].name or f"{_port[0]}" for _port in _ports)
                )
                for i, port in _ports:
                    pin = circ.create_pin(port.name or f"{i}")
                    circ.connect_pin(pin, net)

        # sort the ports of all instances by position and layer
        for i, inst in enumerate(self.insts):
            name = inst.name
            subc = circ.create_subcircuit(
                netlist.circuit_by_cell_index(inst.cell_index), name
            )
            subc.trans = inst.dcplx_trans

            for j, port in filter(
                port_filter,
                enumerate(Ports(kcl=self.kcl, bases=[p.base for p in inst.ports])),
            ):
                trans = port.trans.dup()
                trans.angle %= 2
                trans.mirror = False
                v = trans.disp
                h = f"{v.x}_{v.y}"
                layer_info = self.kcl.layout.get_info(port.layer)
                layer = f"{layer_info.layer}_{layer_info.datatype}"
                if h not in inst_ports:
                    inst_ports[h] = {}
                if layer not in inst_ports[h]:
                    inst_ports[h][layer] = []
                inst_ports[h][layer].append(
                    (
                        i,
                        j,
                        Instance(kcl=self.kcl, instance=inst.instance),
                        port,
                        subc,
                    )
                )

        # go through each position and layer and connect ports to their matching cell
        # port or connect the instance ports
        for h, inst_layer_dict in inst_ports.items():
            for layer, ports in inst_layer_dict.items():
                if h in cell_ports and layer in cell_ports[h]:
                    # connect a cell port to its matching instance port
                    cellports = cell_ports[h][layer]

                    assert len(cellports) == 1, (
                        "Netlists with directly connect cell ports"
                        " are currently not supported"
                    )
                    assert len(ports) == 1, (
                        "Multiple instance "
                        f"{[instance_port_name(p[2], p[3]) for p in ports]}"
                        f"ports connected to the cell port {cellports[0]}"
                        " this is currently not supported and most likely a bug"
                    )

                    inst_port = ports[0]
                    port = inst_port[3]
                    if allow_width_mismatch:
                        port_check(
                            cellports[0][1], port, PortCheck.port_type + PortCheck.layer
                        )
                    else:
                        port_check(cellports[0][1], port, PortCheck.all_overlap)
                    subc = inst_port[4]
                    pin = subc.circuit_ref().pin_by_name(port.name or str(inst_port[1]))
                    net = circ.net_by_name(cellports[0][1].name or f"{cellports[0][0]}")
                    assert pin is not None
                    assert net is not None
                    subc.connect_pin(pin, net)
                elif len(ports) >= 2:
                    # connect instance ports to each other
                    check = PortCheck.position + PortCheck.opposite + PortCheck.layer
                    for n, (i, j, inst, port, subc) in enumerate(ports):
                        net_ports = [(i, j, inst, port, subc)]
                        for i_, j_, inst_, port_, subc_ in ports[n:]:
                            if port.base.check_connection(port_.base) & check == check:
                                net_ports.append((i_, j_, inst_, port_, subc_))
                        if len(net_ports) >= 2:
                            net_name = "-".join(
                                [
                                    (inst.name or str(i)) + "_" + (port.name or str(j))
                                    for i, j, inst, port, _ in ports
                                ]
                            )
                            net = circ.create_net(net_name)
                            for _, j_, _, port_, subc_ in net_ports:
                                subc_.connect_pin(
                                    subc_.circuit_ref().pin_by_name(
                                        port_.name or str(j_)
                                    ),
                                    net,
                                )

        del_subcs: list[kdb.SubCircuit] = []
        if ignore_unnamed:
            del_subcs = [
                circ.subcircuit_by_name(inst.name)
                for inst in self.insts
                if not inst.is_named()
            ]
        if exclude_purposes:
            del_subcs.extend(
                circ.subcircuit_by_name(inst.name)
                for inst in self.insts
                if inst.purpose in exclude_purposes
            )

        for subc in del_subcs:
            nets: list[kdb.Net] = []
            for net in circ.each_net():
                for sc_pin in net.each_subcircuit_pin():
                    if sc_pin.subcircuit().id() == subc.id():
                        nets.append(net)
                        break

            if nets:
                target_net = nets[0]
                for net in nets[1:]:
                    spinrefs = [
                        (spin.pin(), spin.subcircuit())
                        for spin in net.each_subcircuit_pin()
                    ]
                    for pin, _subc in spinrefs:
                        _subc.disconnect_pin(pin)
                        if _subc not in del_subcs:
                            _subc.connect_pin(pin, target_net)
                    net_pins = [pinref.pin() for pinref in net.each_pin()]
                    for pin in net_pins:
                        circ.disconnect_pin(pin)
                        circ.connect_pin(pin, target_net)
                    circ.remove_net(net)
        for subc in del_subcs:
            circ.remove_subcircuit(subc)

        netlist.add(circ)

    def connectivity_check(
        self,
        port_types: list[str] | None = None,
        layers: list[int] | None = None,
        db: rdb.ReportDatabase | None = None,
        recursive: bool = True,
        add_cell_ports: bool = False,
        check_layer_connectivity: bool = True,
    ) -> rdb.ReportDatabase:
        """Create a ReportDatabase for port problems.

        Problems are overlapping ports that aren't aligned, more than two ports
        overlapping, width mismatch, port_type mismatch.

        Args:
            port_types: Filter for certain port typers
            layers: Only create the report for certain layers
            db: Use an existing ReportDatabase instead of creating a new one
            recursive: Create the report not only for this cell, but all child cells as
                well.
            add_cell_ports: Also add a category "CellPorts" which contains all the cells
                selected ports.
            check_layer_connectivity: Check whether the layer overlaps with instances.
        """
        if layers is None:
            layers = []
        if port_types is None:
            port_types = []
        db_: rdb.ReportDatabase = db or rdb.ReportDatabase(
            f"Connectivity Check {self.name}"
        )
        assert isinstance(db_, rdb.ReportDatabase)
        if recursive:
            cc = self.called_cells()
            for c in self.kcl.each_cell_bottom_up():
                if c in cc:
                    self.kcl[c].connectivity_check(
                        port_types=port_types,
                        db=db_,
                        recursive=False,
                        add_cell_ports=add_cell_ports,
                        layers=layers,
                    )
        db_cell = db_.create_cell(self.name)
        cell_ports: dict[int, dict[tuple[float, float], list[ProtoPort[Any]]]] = {}
        layer_cats: dict[int, rdb.RdbCategory] = {}

        def layer_cat(layer: int) -> rdb.RdbCategory:
            if layer not in layer_cats:
                if isinstance(layer, LayerEnum):
                    ln = str(layer.name)
                else:
                    li = self.kcl.get_info(layer)
                    ln = str(li).replace("/", "_")
                layer_cats[layer] = db_.category_by_path(ln) or db_.create_category(ln)
            return layer_cats[layer]

        for port in Ports(kcl=self.kcl, bases=self.ports.bases):
            if (not port_types or port.port_type in port_types) and (
                not layers or port.layer in layers
            ):
                if add_cell_ports:
                    c_cat = db_.category_by_path(
                        f"{layer_cat(port.layer).path()}.CellPorts"
                    ) or db_.create_category(layer_cat(port.layer), "CellPorts")
                    it = db_.create_item(db_cell, c_cat)
                    if port.name:
                        it.add_value(f"Port name: {port.name}")
                    if port.base.trans:
                        it.add_value(
                            self.kcl.to_um(
                                port_polygon(port.width).transformed(port.trans)
                            )
                        )
                    else:
                        it.add_value(
                            self.kcl.to_um(port_polygon(port.width)).transformed(
                                port.dcplx_trans
                            )
                        )
                xy = (port.x, port.y)
                if port.layer not in cell_ports:
                    cell_ports[port.layer] = {xy: [port]}
                elif xy not in cell_ports[port.layer]:
                    cell_ports[port.layer][xy] = [port]
                else:
                    cell_ports[port.layer][xy].append(port)
                rec_it = kdb.RecursiveShapeIterator(
                    self.kcl.layout,
                    self._base.kdb_cell,
                    port.layer,
                    kdb.Box(2, port.width).transformed(port.trans),
                )
                edges = kdb.Region(rec_it).merge().edges().merge()
                port_edge = kdb.Edge(0, port.width // 2, 0, -port.width // 2)
                if port.base.trans:
                    port_edge = port_edge.transformed(port.trans)
                else:
                    port_edge = port_edge.transformed(
                        kdb.ICplxTrans(port.dcplx_trans, self.kcl.dbu)
                    )
                p_edges = kdb.Edges([port_edge])
                phys_overlap = p_edges & edges
                if not phys_overlap.is_empty() and phys_overlap[0] != port_edge:
                    p_cat = db_.category_by_path(
                        layer_cat(port.layer).path() + ".PartialPhysicalShape"
                    ) or db_.create_category(
                        layer_cat(port.layer), "PartialPhysicalShape"
                    )
                    it = db_.create_item(db_cell, p_cat)
                    it.add_value(
                        "Insufficient overlap, partial overlap with polygon of"
                        f" {(phys_overlap[0].p1 - phys_overlap[0].p2).abs()}/"
                        f"{port.width}"
                    )
                    it.add_value(
                        self.kcl.to_um(port_polygon(port.width).transformed(port.trans))
                        if port.base.trans
                        else self.kcl.to_um(port_polygon(port.width)).transformed(
                            port.dcplx_trans
                        )
                    )
                elif phys_overlap.is_empty():
                    p_cat = db_.category_by_path(
                        layer_cat(port.layer).path() + ".MissingPhysicalShape"
                    ) or db_.create_category(
                        layer_cat(port.layer), "MissingPhysicalShape"
                    )
                    it = db_.create_item(db_cell, p_cat)
                    it.add_value(
                        f"Found no overlapping Edge with Port {port.name or str(port)}"
                    )
                    it.add_value(
                        self.kcl.to_um(port_polygon(port.width).transformed(port.trans))
                        if port.base.trans
                        else self.kcl.to_um(port_polygon(port.width)).transformed(
                            port.dcplx_trans
                        )
                    )

        inst_ports: dict[
            LayerEnum | int,
            dict[tuple[int, int], list[tuple[Port, KCell, str]]],
        ] = {}
        for inst in self.insts:
            inst_name = inst.name
            inst_cell = inst.cell.to_itype()
            for port in Ports(kcl=self.kcl, bases=[p.base for p in inst.ports]):
                if (not port_types or port.port_type in port_types) and (
                    not layers or port.layer in layers
                ):
                    xy = (port.x, port.y)
                    entry = (port, inst_cell, inst_name)
                    if port.layer not in inst_ports:
                        inst_ports[port.layer] = {xy: [entry]}
                    elif xy not in inst_ports[port.layer]:
                        inst_ports[port.layer][xy] = [entry]
                    else:
                        inst_ports[port.layer][xy].append(entry)

        for layer, port_coord_mapping in inst_ports.items():
            lc = layer_cat(layer)
            for coord, ports in port_coord_mapping.items():
                match len(ports):
                    case 1:
                        if layer in cell_ports and coord in cell_ports[layer]:
                            ccp = check_cell_ports(
                                cell_ports[layer][coord][0], ports[0][0]
                            )
                            if ccp & 1:
                                subc = db_.category_by_path(
                                    lc.path() + ".WidthMismatch"
                                ) or db_.create_category(lc, "WidthMismatch")
                                create_port_error(
                                    ports[0][0],
                                    cell_ports[layer][coord][0],
                                    ports[0][1],
                                    self,
                                    db_,
                                    db_cell,
                                    subc,
                                    self.kcl.dbu,
                                    inst_name1=ports[0][2],
                                )

                            if ccp & 2:
                                subc = db_.category_by_path(
                                    lc.path() + ".AngleMismatch"
                                ) or db_.create_category(lc, "AngleMismatch")
                                create_port_error(
                                    ports[0][0],
                                    cell_ports[layer][coord][0],
                                    ports[0][1],
                                    self,
                                    db_,
                                    db_cell,
                                    subc,
                                    self.kcl.dbu,
                                    inst_name1=ports[0][2],
                                )
                            if ccp & 4:
                                subc = db_.category_by_path(
                                    lc.path() + ".TypeMismatch"
                                ) or db_.create_category(lc, "TypeMismatch")
                                create_port_error(
                                    ports[0][0],
                                    cell_ports[layer][coord][0],
                                    ports[0][1],
                                    self,
                                    db_,
                                    db_cell,
                                    subc,
                                    self.kcl.dbu,
                                    inst_name1=ports[0][2],
                                )
                        else:
                            subc = db_.category_by_path(
                                lc.path() + ".OrphanPort"
                            ) or db_.create_category(lc, "OrphanPort")
                            it = db_.create_item(db_cell, subc)
                            port_name = ports[0][0].name or str(ports[0][0])
                            cell_name = ports[0][1].name
                            inst_name = ports[0][2]
                            if inst_name:
                                it.add_value(
                                    f"Port Name: {inst_name}.{port_name}"
                                    f" (cell: {cell_name})"
                                )
                            else:
                                it.add_value(f"Port Name: {cell_name}.{port_name}")
                            if ports[0][0]._base.trans:
                                it.add_value(
                                    self.kcl.to_um(
                                        port_polygon(ports[0][0].width).transformed(
                                            ports[0][0]._base.trans
                                        )
                                    )
                                )
                            else:
                                it.add_value(
                                    self.kcl.to_um(
                                        port_polygon(port.width)
                                    ).transformed(port.dcplx_trans)
                                )

                    case 2:
                        cip = check_inst_ports(ports[0][0], ports[1][0])
                        if cip & 1:
                            subc = db_.category_by_path(
                                lc.path() + ".WidthMismatch"
                            ) or db_.create_category(lc, "WidthMismatch")
                            create_port_error(
                                ports[0][0],
                                ports[1][0],
                                ports[0][1],
                                ports[1][1],
                                db_,
                                db_cell,
                                subc,
                                self.kcl.dbu,
                                inst_name1=ports[0][2],
                                inst_name2=ports[1][2],
                            )

                        if cip & 2:
                            subc = db_.category_by_path(
                                lc.path() + ".AngleMismatch"
                            ) or db_.create_category(lc, "AngleMismatch")
                            create_port_error(
                                ports[0][0],
                                ports[1][0],
                                ports[0][1],
                                ports[1][1],
                                db_,
                                db_cell,
                                subc,
                                self.kcl.dbu,
                                inst_name1=ports[0][2],
                                inst_name2=ports[1][2],
                            )
                        if cip & 4:
                            subc = db_.category_by_path(
                                lc.path() + ".TypeMismatch"
                            ) or db_.create_category(lc, "TypeMismatch")
                            create_port_error(
                                ports[0][0],
                                ports[1][0],
                                ports[0][1],
                                ports[1][1],
                                db_,
                                db_cell,
                                subc,
                                self.kcl.dbu,
                                inst_name1=ports[0][2],
                                inst_name2=ports[1][2],
                            )
                        if layer in cell_ports and coord in cell_ports[layer]:
                            subc = db_.category_by_path(
                                lc.path() + ".portoverlap"
                            ) or db_.create_category(lc, "portoverlap")
                            it = db_.create_item(db_cell, subc)
                            text = "Port Names: "
                            values: list[rdb.RdbItemValue] = []
                            cell_port = cell_ports[layer][coord][0]
                            text += (
                                f"{self.name}."
                                f"{cell_port.name or cell_port.trans.to_s()}/"
                            )
                            if cell_port.base.trans:
                                values.append(
                                    rdb.RdbItemValue(
                                        self.kcl.to_um(
                                            port_polygon(cell_port.width).transformed(
                                                cell_port.base.trans
                                            )
                                        )
                                    )
                                )
                            else:
                                values.append(
                                    rdb.RdbItemValue(
                                        self.kcl.to_um(
                                            port_polygon(cell_port.width)
                                        ).transformed(cell_port.dcplx_trans)
                                    )
                                )
                            for _port in ports:
                                _label = (
                                    f"{_port[2]}." if _port[2] else f"{_port[1].name}."
                                )
                                text += (
                                    f"{_label}{_port[0].name or _port[0].trans.to_s()}/"
                                )

                                values.append(
                                    rdb.RdbItemValue(
                                        self.kcl.to_um(
                                            port_polygon(_port[0].width).transformed(
                                                _port[0].trans
                                            )
                                        )
                                    )
                                )
                            it.add_value(text[:-1])
                            for value in values:
                                it.add_value(value)

                    case x if x > 2:
                        subc = db_.category_by_path(
                            lc.path() + ".portoverlap"
                        ) or db_.create_category(lc, "portoverlap")
                        it = db_.create_item(db_cell, subc)
                        text = "Port Names: "
                        values = []
                        for _port in ports:
                            _label = f"{_port[2]}." if _port[2] else f"{_port[1].name}."
                            text += f"{_label}{_port[0].name or _port[0].trans.to_s()}/"

                            values.append(
                                rdb.RdbItemValue(
                                    self.kcl.to_um(
                                        port_polygon(_port[0].width).transformed(
                                            _port[0].trans
                                        )
                                    )
                                )
                            )
                        it.add_value(text[:-1])
                        for value in values:
                            it.add_value(value)
                    case _:
                        raise ValueError(f"Unexpected number of ports: {len(ports)}")
            if check_layer_connectivity:
                error_region_shapes = kdb.Region()
                error_region_instances = kdb.Region()
                reg = kdb.Region(self.shapes(layer))
                inst_regions: dict[int, kdb.Region] = {}
                inst_region = kdb.Region()
                for i, inst in enumerate(self.insts):
                    inst_region_ = kdb.Region(inst.ibbox(layer))
                    inst_shapes: kdb.Region | None = None
                    if not (inst_region & inst_region_).is_empty():
                        if inst_shapes is None:
                            inst_shapes = kdb.Region()
                            shape_it = self.begin_shapes_rec_overlapping(
                                layer, inst.bbox(layer)
                            )
                            shape_it.select_cells([inst.cell.cell_index()])
                            shape_it.min_depth = 1
                            shape_it.shape_flags = kdb.Shapes.SRegions
                            for _it in shape_it.each():
                                if _it.path()[0].inst() == inst.instance:
                                    inst_shapes.insert(
                                        _it.shape().polygon.transformed(_it.trans())
                                    )

                        for j, _reg in inst_regions.items():
                            if _reg & inst_region_:
                                reg_ = kdb.Region()
                                shape_it = self.begin_shapes_rec_touching(
                                    layer, (_reg & inst_region_).bbox()
                                )
                                shape_it.select_cells([self.insts[j].cell.cell_index()])
                                shape_it.min_depth = 1
                                shape_it.shape_flags = kdb.Shapes.SRegions
                                for _it in shape_it.each():
                                    if _it.path()[0].inst() == self.insts[j].instance:
                                        reg_.insert(
                                            _it.shape().polygon.transformed(_it.trans())
                                        )

                                error_region_instances.insert(reg_ & inst_shapes)

                    if not (inst_region_ & reg).is_empty():
                        rec_it = self.begin_shapes_rec_touching(
                            layer, (inst_region_ & reg).bbox()
                        )
                        rec_it.min_depth = 1
                        error_region_shapes += kdb.Region(rec_it) & reg
                    inst_region += inst_region_
                    inst_regions[i] = inst_region_
                if not error_region_shapes.is_empty():
                    sc = db_.category_by_path(
                        layer_cat(layer).path() + ".ShapeInstanceshapeOverlap"
                    ) or db_.create_category(
                        layer_cat(layer), "ShapeInstanceshapeOverlap"
                    )
                    for poly in error_region_shapes.merge().each():
                        it = db_.create_item(db_cell, sc)
                        it.add_value("Shapes overlapping with shapes of instances")
                        it.add_value(self.kcl.to_um(poly.downcast()))
                if not error_region_instances.is_empty():
                    sc = db_.category_by_path(
                        layer_cat(layer).path() + ".InstanceshapeOverlap"
                    ) or db_.create_category(layer_cat(layer), "InstanceshapeOverlap")
                    for poly in error_region_instances.merge().each():
                        it = db_.create_item(db_cell, sc)
                        it.add_value(
                            "Instance shapes overlapping with shapes of other instances"
                        )
                        it.add_value(self.kcl.to_um(poly.downcast()))

        return db_

    def insert_vinsts(self, recursive: bool = True) -> None:
        """Insert all virtual instances and create Instances of real KCells."""
        if not self._base.kdb_cell._destroyed():
            for vi in self._base.vinsts:
                vi.insert_into(self)
            self._base.vinsts.clear()

            if recursive:
                called_cell_indexes = set(self._base.kdb_cell.called_cells())
                for c in sorted(
                    (
                        self.kcl[ci]
                        for ci in called_cell_indexes & self.kcl.tkcells.keys()
                        if not self.kcl[ci].kdb_cell._destroyed()
                    ),
                    key=lambda c: c.hierarchy_levels(),
                ):
                    for vi in c._base.vinsts:
                        vi.insert_into(c)
                    c._base.vinsts.clear()

    @abstractmethod
    def get_cross_section(
        self,
        cross_section: str
        | dict[str, Any]
        | Callable[..., CrossSection | DCrossSection]
        | SymmetricalCrossSection,
        **cross_section_kwargs: Any,
    ) -> TCrossSection[T]: ...

    @property
    def lvs_equivalent_ports(self) -> list[list[str]] | None:
        return self._base.lvs_equivalent_ports

    def __reduce__(
        self,
    ) -> tuple[Callable[..., ProtoTKCell[Any]], tuple[str, str, dict[str, Any]]]:
        if self.has_factory_name():
            return (
                _reconstruct,
                (self.kcl.name, self.factory_name, self.settings.model_dump()),
            )
        raise NotImplementedError

ghost_cell property writable

ghost_cell: bool

Returns a value indicating whether the cell is a "ghost cell".

prop_id property writable

prop_id: int

Gets the properties ID associated with the cell.

__copy__

__copy__() -> Self

Enables use of copy.copy and copy.deep_copy.

Source code in kfactory/kcell.py
771
772
773
def __copy__(self) -> Self:
    """Enables use of `copy.copy` and `copy.deep_copy`."""
    return self.dup()

__getattr__

__getattr__(name: str) -> Any

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

Source code in kfactory/kcell.py
745
746
747
748
749
750
def __getattr__(self, name: str) -> Any:
    """If KCell doesn't have an attribute, look in the KLayout Cell."""
    try:
        return ProtoKCell.__getattribute__(self, name)
    except Exception:
        return getattr(self._base, name)

__getitem__ abstractmethod

__getitem__(key: int | str | None) -> ProtoPort[T]

Returns port from instance.

Source code in kfactory/kcell.py
687
688
689
690
@abstractmethod
def __getitem__(self, key: int | str | None) -> ProtoPort[T]:
    """Returns port from instance."""
    ...

__hash__

__hash__() -> int

Hash the KCell.

Source code in kfactory/kcell.py
714
715
716
def __hash__(self) -> int:
    """Hash the KCell."""
    return hash((self._base.kcl.library.name(), self._base.kdb_cell.cell_index()))

add_port abstractmethod

add_port(
    *,
    port: ProtoPort[Any],
    name: str | None = None,
    keep_mirror: bool = False,
) -> ProtoPort[Any]

Add an existing port. E.g. from an instance to propagate the port.

Parameters:

Name Type Description Default
port ProtoPort[Any]

The port to add.

required
name str | None

Overwrite the name of the port

None
keep_mirror bool

Keep the mirror part of the transformation of a port if True, else set the mirror flag to False.

False
Source code in kfactory/kcell.py
923
924
925
926
927
928
929
930
@abstractmethod
def add_port(
    self,
    *,
    port: ProtoPort[Any],
    name: str | None = None,
    keep_mirror: bool = False,
) -> ProtoPort[Any]: ...

auto_rename_ports

auto_rename_ports(
    rename_func: Callable[..., None] | None = None,
) -> None

Rename the ports with the schema angle -> "NSWE" and sort by x and y.

Parameters:

Name Type Description Default
rename_func Callable[..., None] | None

Function that takes Iterable[Port] and renames them. This can of course contain a filter and only rename some of the ports

None
Source code in kfactory/kcell.py
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
def auto_rename_ports(self, rename_func: Callable[..., None] | None = None) -> None:
    """Rename the ports with the schema angle -> "NSWE" and sort by x and y.

    Args:
        rename_func: Function that takes Iterable[Port] and renames them.
            This can of course contain a filter and only rename some of the ports
    """
    if self.locked:
        raise LockedError(self)
    if rename_func is None:
        self.kcl.rename_function(self.ports)
    else:
        rename_func(self.ports)

called_cells

called_cells() -> list[int]

Cell indices for every cell transitively instantiated inside this cell.

Source code in kfactory/kcell.py
756
757
758
def called_cells(self) -> list[int]:
    """Cell indices for every cell transitively instantiated inside this cell."""
    return self._base.kdb_cell.called_cells()

cell_index

cell_index() -> int

Gets the cell index.

Source code in kfactory/kcell.py
752
753
754
def cell_index(self) -> int:
    """Gets the cell index."""
    return self._base.kdb_cell.cell_index()

circuit

circuit(
    l2n: LayoutToNetlist,
    port_types: Iterable[str] = ("optical",),
    ignore_unnamed: bool = False,
    exclude_purposes: list[str] | None = None,
    allow_width_mismatch: bool = False,
) -> None

Create the (optical type) circuit of the KCell in the given netlist.

This is NOT recommended though.

Source code in kfactory/kcell.py
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
def circuit(
    self,
    l2n: kdb.LayoutToNetlist,
    port_types: Iterable[str] = ("optical",),
    ignore_unnamed: bool = False,
    exclude_purposes: list[str] | None = None,
    allow_width_mismatch: bool = False,
) -> None:
    """Create the (optical type) circuit of the KCell in the given netlist.

    This is NOT recommended though."""
    netlist = l2n.netlist()

    def port_filter(num_port: tuple[int, ProtoPort[Any]]) -> bool:
        return num_port[1].port_type in port_types

    circ = kdb.Circuit()
    circ.name = self.name
    circ.cell_index = self.cell_index()
    circ.boundary = self.boundary or kdb.DPolygon(self.dbbox())

    inst_ports: dict[
        str,
        dict[str, list[tuple[int, int, Instance, ProtoPort[Any], kdb.SubCircuit]]],
    ] = {}
    cell_ports: dict[str, dict[str, list[tuple[int, ProtoPort[Any]]]]] = {}

    # sort the cell's ports by position and layer

    portnames: set[str] = set()

    for i, port in filter(
        port_filter, enumerate(Ports(kcl=self.kcl, bases=self.ports.bases))
    ):
        trans = port.trans.dup()
        trans.angle %= 2
        trans.mirror = False
        layer_info = self.kcl.layout.get_info(port.layer)
        layer = f"{layer_info.layer}_{layer_info.datatype}"

        if port.name in portnames:
            raise ValueError(
                "Netlist extraction is not possible with"
                f" colliding port names. Duplicate name: {port.name}"
            )

        v = trans.disp
        h = f"{v.x}_{v.y}"
        if h not in cell_ports:
            cell_ports[h] = {}
        if layer not in cell_ports[h]:
            cell_ports[h][layer] = []
        cell_ports[h][layer].append((i, port))

        if port.name:
            portnames.add(port.name)

    # create nets and connect pins for each cell_port
    for layer_dict in cell_ports.values():
        for _ports in layer_dict.values():
            net = circ.create_net(
                "-".join(_port[1].name or f"{_port[0]}" for _port in _ports)
            )
            for i, port in _ports:
                pin = circ.create_pin(port.name or f"{i}")
                circ.connect_pin(pin, net)

    # sort the ports of all instances by position and layer
    for i, inst in enumerate(self.insts):
        name = inst.name
        subc = circ.create_subcircuit(
            netlist.circuit_by_cell_index(inst.cell_index), name
        )
        subc.trans = inst.dcplx_trans

        for j, port in filter(
            port_filter,
            enumerate(Ports(kcl=self.kcl, bases=[p.base for p in inst.ports])),
        ):
            trans = port.trans.dup()
            trans.angle %= 2
            trans.mirror = False
            v = trans.disp
            h = f"{v.x}_{v.y}"
            layer_info = self.kcl.layout.get_info(port.layer)
            layer = f"{layer_info.layer}_{layer_info.datatype}"
            if h not in inst_ports:
                inst_ports[h] = {}
            if layer not in inst_ports[h]:
                inst_ports[h][layer] = []
            inst_ports[h][layer].append(
                (
                    i,
                    j,
                    Instance(kcl=self.kcl, instance=inst.instance),
                    port,
                    subc,
                )
            )

    # go through each position and layer and connect ports to their matching cell
    # port or connect the instance ports
    for h, inst_layer_dict in inst_ports.items():
        for layer, ports in inst_layer_dict.items():
            if h in cell_ports and layer in cell_ports[h]:
                # connect a cell port to its matching instance port
                cellports = cell_ports[h][layer]

                assert len(cellports) == 1, (
                    "Netlists with directly connect cell ports"
                    " are currently not supported"
                )
                assert len(ports) == 1, (
                    "Multiple instance "
                    f"{[instance_port_name(p[2], p[3]) for p in ports]}"
                    f"ports connected to the cell port {cellports[0]}"
                    " this is currently not supported and most likely a bug"
                )

                inst_port = ports[0]
                port = inst_port[3]
                if allow_width_mismatch:
                    port_check(
                        cellports[0][1], port, PortCheck.port_type + PortCheck.layer
                    )
                else:
                    port_check(cellports[0][1], port, PortCheck.all_overlap)
                subc = inst_port[4]
                pin = subc.circuit_ref().pin_by_name(port.name or str(inst_port[1]))
                net = circ.net_by_name(cellports[0][1].name or f"{cellports[0][0]}")
                assert pin is not None
                assert net is not None
                subc.connect_pin(pin, net)
            elif len(ports) >= 2:
                # connect instance ports to each other
                check = PortCheck.position + PortCheck.opposite + PortCheck.layer
                for n, (i, j, inst, port, subc) in enumerate(ports):
                    net_ports = [(i, j, inst, port, subc)]
                    for i_, j_, inst_, port_, subc_ in ports[n:]:
                        if port.base.check_connection(port_.base) & check == check:
                            net_ports.append((i_, j_, inst_, port_, subc_))
                    if len(net_ports) >= 2:
                        net_name = "-".join(
                            [
                                (inst.name or str(i)) + "_" + (port.name or str(j))
                                for i, j, inst, port, _ in ports
                            ]
                        )
                        net = circ.create_net(net_name)
                        for _, j_, _, port_, subc_ in net_ports:
                            subc_.connect_pin(
                                subc_.circuit_ref().pin_by_name(
                                    port_.name or str(j_)
                                ),
                                net,
                            )

    del_subcs: list[kdb.SubCircuit] = []
    if ignore_unnamed:
        del_subcs = [
            circ.subcircuit_by_name(inst.name)
            for inst in self.insts
            if not inst.is_named()
        ]
    if exclude_purposes:
        del_subcs.extend(
            circ.subcircuit_by_name(inst.name)
            for inst in self.insts
            if inst.purpose in exclude_purposes
        )

    for subc in del_subcs:
        nets: list[kdb.Net] = []
        for net in circ.each_net():
            for sc_pin in net.each_subcircuit_pin():
                if sc_pin.subcircuit().id() == subc.id():
                    nets.append(net)
                    break

        if nets:
            target_net = nets[0]
            for net in nets[1:]:
                spinrefs = [
                    (spin.pin(), spin.subcircuit())
                    for spin in net.each_subcircuit_pin()
                ]
                for pin, _subc in spinrefs:
                    _subc.disconnect_pin(pin)
                    if _subc not in del_subcs:
                        _subc.connect_pin(pin, target_net)
                net_pins = [pinref.pin() for pinref in net.each_pin()]
                for pin in net_pins:
                    circ.disconnect_pin(pin)
                    circ.connect_pin(pin, target_net)
                circ.remove_net(net)
    for subc in del_subcs:
        circ.remove_subcircuit(subc)

    netlist.add(circ)

connectivity_check

connectivity_check(
    port_types: list[str] | None = None,
    layers: list[int] | None = None,
    db: ReportDatabase | None = None,
    recursive: bool = True,
    add_cell_ports: bool = False,
    check_layer_connectivity: bool = True,
) -> rdb.ReportDatabase

Create a ReportDatabase for port problems.

Problems are overlapping ports that aren't aligned, more than two ports overlapping, width mismatch, port_type mismatch.

Parameters:

Name Type Description Default
port_types list[str] | None

Filter for certain port typers

None
layers list[int] | None

Only create the report for certain layers

None
db ReportDatabase | None

Use an existing ReportDatabase instead of creating a new one

None
recursive bool

Create the report not only for this cell, but all child cells as well.

True
add_cell_ports bool

Also add a category "CellPorts" which contains all the cells selected ports.

False
check_layer_connectivity bool

Check whether the layer overlaps with instances.

True
Source code in kfactory/kcell.py
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
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
def connectivity_check(
    self,
    port_types: list[str] | None = None,
    layers: list[int] | None = None,
    db: rdb.ReportDatabase | None = None,
    recursive: bool = True,
    add_cell_ports: bool = False,
    check_layer_connectivity: bool = True,
) -> rdb.ReportDatabase:
    """Create a ReportDatabase for port problems.

    Problems are overlapping ports that aren't aligned, more than two ports
    overlapping, width mismatch, port_type mismatch.

    Args:
        port_types: Filter for certain port typers
        layers: Only create the report for certain layers
        db: Use an existing ReportDatabase instead of creating a new one
        recursive: Create the report not only for this cell, but all child cells as
            well.
        add_cell_ports: Also add a category "CellPorts" which contains all the cells
            selected ports.
        check_layer_connectivity: Check whether the layer overlaps with instances.
    """
    if layers is None:
        layers = []
    if port_types is None:
        port_types = []
    db_: rdb.ReportDatabase = db or rdb.ReportDatabase(
        f"Connectivity Check {self.name}"
    )
    assert isinstance(db_, rdb.ReportDatabase)
    if recursive:
        cc = self.called_cells()
        for c in self.kcl.each_cell_bottom_up():
            if c in cc:
                self.kcl[c].connectivity_check(
                    port_types=port_types,
                    db=db_,
                    recursive=False,
                    add_cell_ports=add_cell_ports,
                    layers=layers,
                )
    db_cell = db_.create_cell(self.name)
    cell_ports: dict[int, dict[tuple[float, float], list[ProtoPort[Any]]]] = {}
    layer_cats: dict[int, rdb.RdbCategory] = {}

    def layer_cat(layer: int) -> rdb.RdbCategory:
        if layer not in layer_cats:
            if isinstance(layer, LayerEnum):
                ln = str(layer.name)
            else:
                li = self.kcl.get_info(layer)
                ln = str(li).replace("/", "_")
            layer_cats[layer] = db_.category_by_path(ln) or db_.create_category(ln)
        return layer_cats[layer]

    for port in Ports(kcl=self.kcl, bases=self.ports.bases):
        if (not port_types or port.port_type in port_types) and (
            not layers or port.layer in layers
        ):
            if add_cell_ports:
                c_cat = db_.category_by_path(
                    f"{layer_cat(port.layer).path()}.CellPorts"
                ) or db_.create_category(layer_cat(port.layer), "CellPorts")
                it = db_.create_item(db_cell, c_cat)
                if port.name:
                    it.add_value(f"Port name: {port.name}")
                if port.base.trans:
                    it.add_value(
                        self.kcl.to_um(
                            port_polygon(port.width).transformed(port.trans)
                        )
                    )
                else:
                    it.add_value(
                        self.kcl.to_um(port_polygon(port.width)).transformed(
                            port.dcplx_trans
                        )
                    )
            xy = (port.x, port.y)
            if port.layer not in cell_ports:
                cell_ports[port.layer] = {xy: [port]}
            elif xy not in cell_ports[port.layer]:
                cell_ports[port.layer][xy] = [port]
            else:
                cell_ports[port.layer][xy].append(port)
            rec_it = kdb.RecursiveShapeIterator(
                self.kcl.layout,
                self._base.kdb_cell,
                port.layer,
                kdb.Box(2, port.width).transformed(port.trans),
            )
            edges = kdb.Region(rec_it).merge().edges().merge()
            port_edge = kdb.Edge(0, port.width // 2, 0, -port.width // 2)
            if port.base.trans:
                port_edge = port_edge.transformed(port.trans)
            else:
                port_edge = port_edge.transformed(
                    kdb.ICplxTrans(port.dcplx_trans, self.kcl.dbu)
                )
            p_edges = kdb.Edges([port_edge])
            phys_overlap = p_edges & edges
            if not phys_overlap.is_empty() and phys_overlap[0] != port_edge:
                p_cat = db_.category_by_path(
                    layer_cat(port.layer).path() + ".PartialPhysicalShape"
                ) or db_.create_category(
                    layer_cat(port.layer), "PartialPhysicalShape"
                )
                it = db_.create_item(db_cell, p_cat)
                it.add_value(
                    "Insufficient overlap, partial overlap with polygon of"
                    f" {(phys_overlap[0].p1 - phys_overlap[0].p2).abs()}/"
                    f"{port.width}"
                )
                it.add_value(
                    self.kcl.to_um(port_polygon(port.width).transformed(port.trans))
                    if port.base.trans
                    else self.kcl.to_um(port_polygon(port.width)).transformed(
                        port.dcplx_trans
                    )
                )
            elif phys_overlap.is_empty():
                p_cat = db_.category_by_path(
                    layer_cat(port.layer).path() + ".MissingPhysicalShape"
                ) or db_.create_category(
                    layer_cat(port.layer), "MissingPhysicalShape"
                )
                it = db_.create_item(db_cell, p_cat)
                it.add_value(
                    f"Found no overlapping Edge with Port {port.name or str(port)}"
                )
                it.add_value(
                    self.kcl.to_um(port_polygon(port.width).transformed(port.trans))
                    if port.base.trans
                    else self.kcl.to_um(port_polygon(port.width)).transformed(
                        port.dcplx_trans
                    )
                )

    inst_ports: dict[
        LayerEnum | int,
        dict[tuple[int, int], list[tuple[Port, KCell, str]]],
    ] = {}
    for inst in self.insts:
        inst_name = inst.name
        inst_cell = inst.cell.to_itype()
        for port in Ports(kcl=self.kcl, bases=[p.base for p in inst.ports]):
            if (not port_types or port.port_type in port_types) and (
                not layers or port.layer in layers
            ):
                xy = (port.x, port.y)
                entry = (port, inst_cell, inst_name)
                if port.layer not in inst_ports:
                    inst_ports[port.layer] = {xy: [entry]}
                elif xy not in inst_ports[port.layer]:
                    inst_ports[port.layer][xy] = [entry]
                else:
                    inst_ports[port.layer][xy].append(entry)

    for layer, port_coord_mapping in inst_ports.items():
        lc = layer_cat(layer)
        for coord, ports in port_coord_mapping.items():
            match len(ports):
                case 1:
                    if layer in cell_ports and coord in cell_ports[layer]:
                        ccp = check_cell_ports(
                            cell_ports[layer][coord][0], ports[0][0]
                        )
                        if ccp & 1:
                            subc = db_.category_by_path(
                                lc.path() + ".WidthMismatch"
                            ) or db_.create_category(lc, "WidthMismatch")
                            create_port_error(
                                ports[0][0],
                                cell_ports[layer][coord][0],
                                ports[0][1],
                                self,
                                db_,
                                db_cell,
                                subc,
                                self.kcl.dbu,
                                inst_name1=ports[0][2],
                            )

                        if ccp & 2:
                            subc = db_.category_by_path(
                                lc.path() + ".AngleMismatch"
                            ) or db_.create_category(lc, "AngleMismatch")
                            create_port_error(
                                ports[0][0],
                                cell_ports[layer][coord][0],
                                ports[0][1],
                                self,
                                db_,
                                db_cell,
                                subc,
                                self.kcl.dbu,
                                inst_name1=ports[0][2],
                            )
                        if ccp & 4:
                            subc = db_.category_by_path(
                                lc.path() + ".TypeMismatch"
                            ) or db_.create_category(lc, "TypeMismatch")
                            create_port_error(
                                ports[0][0],
                                cell_ports[layer][coord][0],
                                ports[0][1],
                                self,
                                db_,
                                db_cell,
                                subc,
                                self.kcl.dbu,
                                inst_name1=ports[0][2],
                            )
                    else:
                        subc = db_.category_by_path(
                            lc.path() + ".OrphanPort"
                        ) or db_.create_category(lc, "OrphanPort")
                        it = db_.create_item(db_cell, subc)
                        port_name = ports[0][0].name or str(ports[0][0])
                        cell_name = ports[0][1].name
                        inst_name = ports[0][2]
                        if inst_name:
                            it.add_value(
                                f"Port Name: {inst_name}.{port_name}"
                                f" (cell: {cell_name})"
                            )
                        else:
                            it.add_value(f"Port Name: {cell_name}.{port_name}")
                        if ports[0][0]._base.trans:
                            it.add_value(
                                self.kcl.to_um(
                                    port_polygon(ports[0][0].width).transformed(
                                        ports[0][0]._base.trans
                                    )
                                )
                            )
                        else:
                            it.add_value(
                                self.kcl.to_um(
                                    port_polygon(port.width)
                                ).transformed(port.dcplx_trans)
                            )

                case 2:
                    cip = check_inst_ports(ports[0][0], ports[1][0])
                    if cip & 1:
                        subc = db_.category_by_path(
                            lc.path() + ".WidthMismatch"
                        ) or db_.create_category(lc, "WidthMismatch")
                        create_port_error(
                            ports[0][0],
                            ports[1][0],
                            ports[0][1],
                            ports[1][1],
                            db_,
                            db_cell,
                            subc,
                            self.kcl.dbu,
                            inst_name1=ports[0][2],
                            inst_name2=ports[1][2],
                        )

                    if cip & 2:
                        subc = db_.category_by_path(
                            lc.path() + ".AngleMismatch"
                        ) or db_.create_category(lc, "AngleMismatch")
                        create_port_error(
                            ports[0][0],
                            ports[1][0],
                            ports[0][1],
                            ports[1][1],
                            db_,
                            db_cell,
                            subc,
                            self.kcl.dbu,
                            inst_name1=ports[0][2],
                            inst_name2=ports[1][2],
                        )
                    if cip & 4:
                        subc = db_.category_by_path(
                            lc.path() + ".TypeMismatch"
                        ) or db_.create_category(lc, "TypeMismatch")
                        create_port_error(
                            ports[0][0],
                            ports[1][0],
                            ports[0][1],
                            ports[1][1],
                            db_,
                            db_cell,
                            subc,
                            self.kcl.dbu,
                            inst_name1=ports[0][2],
                            inst_name2=ports[1][2],
                        )
                    if layer in cell_ports and coord in cell_ports[layer]:
                        subc = db_.category_by_path(
                            lc.path() + ".portoverlap"
                        ) or db_.create_category(lc, "portoverlap")
                        it = db_.create_item(db_cell, subc)
                        text = "Port Names: "
                        values: list[rdb.RdbItemValue] = []
                        cell_port = cell_ports[layer][coord][0]
                        text += (
                            f"{self.name}."
                            f"{cell_port.name or cell_port.trans.to_s()}/"
                        )
                        if cell_port.base.trans:
                            values.append(
                                rdb.RdbItemValue(
                                    self.kcl.to_um(
                                        port_polygon(cell_port.width).transformed(
                                            cell_port.base.trans
                                        )
                                    )
                                )
                            )
                        else:
                            values.append(
                                rdb.RdbItemValue(
                                    self.kcl.to_um(
                                        port_polygon(cell_port.width)
                                    ).transformed(cell_port.dcplx_trans)
                                )
                            )
                        for _port in ports:
                            _label = (
                                f"{_port[2]}." if _port[2] else f"{_port[1].name}."
                            )
                            text += (
                                f"{_label}{_port[0].name or _port[0].trans.to_s()}/"
                            )

                            values.append(
                                rdb.RdbItemValue(
                                    self.kcl.to_um(
                                        port_polygon(_port[0].width).transformed(
                                            _port[0].trans
                                        )
                                    )
                                )
                            )
                        it.add_value(text[:-1])
                        for value in values:
                            it.add_value(value)

                case x if x > 2:
                    subc = db_.category_by_path(
                        lc.path() + ".portoverlap"
                    ) or db_.create_category(lc, "portoverlap")
                    it = db_.create_item(db_cell, subc)
                    text = "Port Names: "
                    values = []
                    for _port in ports:
                        _label = f"{_port[2]}." if _port[2] else f"{_port[1].name}."
                        text += f"{_label}{_port[0].name or _port[0].trans.to_s()}/"

                        values.append(
                            rdb.RdbItemValue(
                                self.kcl.to_um(
                                    port_polygon(_port[0].width).transformed(
                                        _port[0].trans
                                    )
                                )
                            )
                        )
                    it.add_value(text[:-1])
                    for value in values:
                        it.add_value(value)
                case _:
                    raise ValueError(f"Unexpected number of ports: {len(ports)}")
        if check_layer_connectivity:
            error_region_shapes = kdb.Region()
            error_region_instances = kdb.Region()
            reg = kdb.Region(self.shapes(layer))
            inst_regions: dict[int, kdb.Region] = {}
            inst_region = kdb.Region()
            for i, inst in enumerate(self.insts):
                inst_region_ = kdb.Region(inst.ibbox(layer))
                inst_shapes: kdb.Region | None = None
                if not (inst_region & inst_region_).is_empty():
                    if inst_shapes is None:
                        inst_shapes = kdb.Region()
                        shape_it = self.begin_shapes_rec_overlapping(
                            layer, inst.bbox(layer)
                        )
                        shape_it.select_cells([inst.cell.cell_index()])
                        shape_it.min_depth = 1
                        shape_it.shape_flags = kdb.Shapes.SRegions
                        for _it in shape_it.each():
                            if _it.path()[0].inst() == inst.instance:
                                inst_shapes.insert(
                                    _it.shape().polygon.transformed(_it.trans())
                                )

                    for j, _reg in inst_regions.items():
                        if _reg & inst_region_:
                            reg_ = kdb.Region()
                            shape_it = self.begin_shapes_rec_touching(
                                layer, (_reg & inst_region_).bbox()
                            )
                            shape_it.select_cells([self.insts[j].cell.cell_index()])
                            shape_it.min_depth = 1
                            shape_it.shape_flags = kdb.Shapes.SRegions
                            for _it in shape_it.each():
                                if _it.path()[0].inst() == self.insts[j].instance:
                                    reg_.insert(
                                        _it.shape().polygon.transformed(_it.trans())
                                    )

                            error_region_instances.insert(reg_ & inst_shapes)

                if not (inst_region_ & reg).is_empty():
                    rec_it = self.begin_shapes_rec_touching(
                        layer, (inst_region_ & reg).bbox()
                    )
                    rec_it.min_depth = 1
                    error_region_shapes += kdb.Region(rec_it) & reg
                inst_region += inst_region_
                inst_regions[i] = inst_region_
            if not error_region_shapes.is_empty():
                sc = db_.category_by_path(
                    layer_cat(layer).path() + ".ShapeInstanceshapeOverlap"
                ) or db_.create_category(
                    layer_cat(layer), "ShapeInstanceshapeOverlap"
                )
                for poly in error_region_shapes.merge().each():
                    it = db_.create_item(db_cell, sc)
                    it.add_value("Shapes overlapping with shapes of instances")
                    it.add_value(self.kcl.to_um(poly.downcast()))
            if not error_region_instances.is_empty():
                sc = db_.category_by_path(
                    layer_cat(layer).path() + ".InstanceshapeOverlap"
                ) or db_.create_category(layer_cat(layer), "InstanceshapeOverlap")
                for poly in error_region_instances.merge().each():
                    it = db_.create_item(db_cell, sc)
                    it.add_value(
                        "Instance shapes overlapping with shapes of other instances"
                    )
                    it.add_value(self.kcl.to_um(poly.downcast()))

    return db_

convert_to_static

convert_to_static(recursive: bool = True) -> None

Convert the KCell to a static cell if it is pdk KCell.

Source code in kfactory/kcell.py
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
def convert_to_static(self, recursive: bool = True) -> None:
    """Convert the KCell to a static cell if it is pdk KCell."""
    if self.library().name() == self.kcl.name:
        raise ValueError(f"KCell {self.qname()} is already a static KCell.")
    from .layout import kcls

    lib_cell = kcls[self.library().name()][self.library_cell_index()]
    lib_cell.set_meta_data()
    kdb_cell = self.kcl.layout_cell(
        self.kcl.convert_cell_to_static(self.cell_index())
    )
    assert kdb_cell is not None
    kdb_cell.name = self.qname()
    ci_ = kdb_cell.cell_index()
    old_kdb_cell = self._base.kdb_cell
    kdb_cell.copy_meta_info(lib_cell.kdb_cell)
    self.get_meta_data()

    if recursive:
        for ci in self.called_cells():
            kc = self.kcl[ci]
            if kc.is_library_cell():
                kc.convert_to_static(recursive=recursive)

    self._base.kdb_cell = kdb_cell
    for ci in old_kdb_cell.caller_cells():
        c = self.kcl.layout_cell(ci)
        assert c is not None
        it = kdb.RecursiveInstanceIterator(self.kcl.layout, c)
        it.targets = [old_kdb_cell.cell_index()]
        it.max_depth = 0
        insts = [instit.current_inst_element().inst() for instit in it.each()]
        locked = c.locked
        c.locked = False
        for inst in insts:
            ca = inst.cell_inst
            ca.cell_index = ci_
            c.replace(inst, ca)
        c.locked = locked

    self.kcl.layout.delete_cell(old_kdb_cell.cell_index())

dcreate_inst

dcreate_inst(
    cell: ProtoTKCell[Any] | int,
    trans: DTrans | DVector | DCplxTrans | None = None,
    *,
    a: DVector | None = None,
    b: DVector | None = None,
    na: int = 1,
    nb: int = 1,
    libcell_as_static: bool = False,
    static_name_separator: str = "__",
) -> DInstance

Add an instance of another KCell.

Parameters:

Name Type Description Default
cell ProtoTKCell[Any] | int

The cell to be added

required
trans DTrans | DVector | DCplxTrans | None

The integer transformation applied to the reference

None
a DVector | None

Vector for the array. Needs to be in positive X-direction. Usually this is only a Vector in x-direction. Some foundries won't allow other Vectors.

None
b DVector | None

Vector for the array. Needs to be in positive Y-direction. Usually this is only a Vector in x-direction. Some foundries won't allow other Vectors.

None
na int

Number of elements in direction of a

1
nb int

Number of elements in direction of b

1
libcell_as_static bool

If the cell is a Library cell (different KCLayout object), convert it to a static cell. This can cause name collisions that are automatically resolved by appending $1[..n] on the newly created cell.

False
static_name_separator str

Stringt to separate the KCLayout name from the cell name when converting library cells (other KCLayout object than the one of this KCell) to static cells (copy them into this KCell's KCLayout).

'__'

Returns:

Type Description
DInstance

The created instance

Source code in kfactory/kcell.py
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
def dcreate_inst(
    self,
    cell: ProtoTKCell[Any] | int,
    trans: kdb.DTrans | kdb.DVector | kdb.DCplxTrans | None = None,
    *,
    a: kdb.DVector | None = None,
    b: kdb.DVector | None = None,
    na: int = 1,
    nb: int = 1,
    libcell_as_static: bool = False,
    static_name_separator: str = "__",
) -> DInstance:
    """Add an instance of another KCell.

    Args:
        cell: The cell to be added
        trans: The integer transformation applied to the reference
        a: Vector for the array.
            Needs to be in positive X-direction. Usually this is only a
            Vector in x-direction. Some foundries won't allow other Vectors.
        b: Vector for the array.
            Needs to be in positive Y-direction. Usually this is only a
            Vector in x-direction. Some foundries won't allow other Vectors.
        na: Number of elements in direction of `a`
        nb: Number of elements in direction of `b`
        libcell_as_static: If the cell is a Library cell
            (different KCLayout object), convert it to a static cell. This can cause
            name collisions that are automatically resolved by appending $1[..n] on
            the newly created cell.
        static_name_separator: Stringt to separate the KCLayout name from the cell
            name when converting library cells (other KCLayout object than the one
            of this KCell) to static cells (copy them into this KCell's KCLayout).

    Returns:
        The created instance
    """
    if trans is None:
        trans = kdb.DTrans()
    if isinstance(cell, int):
        ci = cell
    else:
        ci = self._get_ci(cell, libcell_as_static, static_name_separator)

    if a is None:
        inst = self._base.kdb_cell.insert(kdb.DCellInstArray(ci, trans))
    else:
        if b is None:
            b = kdb.DVector()
        inst = self._base.kdb_cell.insert(
            kdb.DCellInstArray(ci, trans, a, b, na, nb)
        )
    return DInstance(kcl=self.kcl, instance=inst)

delete

delete() -> None

Delete the cell.

Source code in kfactory/kcell.py
917
918
919
920
921
def delete(self) -> None:
    """Delete the cell."""
    ci = self.cell_index()
    self._base.kdb_cell.locked = False
    self.kcl.delete_cell(ci)

draw_ports

draw_ports() -> None

Draw all the ports on their respective layer.

Source code in kfactory/kcell.py
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
def draw_ports(self) -> None:
    """Draw all the ports on their respective layer."""
    locked = self._base.kdb_cell.locked
    self._base.kdb_cell.locked = False
    polys: dict[int, kdb.Region] = {}

    for port in Ports(kcl=self.kcl, bases=self.ports.bases):
        w = port.width

        if w in polys:
            poly = polys[w]
        else:
            poly = kdb.Region()
            poly.insert(
                kdb.Polygon(
                    [
                        kdb.Point(0, int(-w // 2)),
                        kdb.Point(0, int(w // 2)),
                        kdb.Point(int(w // 2), 0),
                    ]
                )
            )
            if w > 20:
                poly -= kdb.Region(
                    kdb.Polygon(
                        [
                            kdb.Point(int(w // 20), 0),
                            kdb.Point(
                                int(w // 20), int(-w // 2 + int(w * 2.5 // 20))
                            ),
                            kdb.Point(int(w // 2 - int(w * 1.41 / 20)), 0),
                        ]
                    )
                )
        polys[w] = poly
        if port.base.trans:
            self.shapes(port.layer).insert(poly.transformed(port.trans))
            self.shapes(port.layer).insert(kdb.Text(port.name or "", port.trans))
        else:
            self.shapes(port.layer).insert(poly, port.dcplx_trans)
            self.shapes(port.layer).insert(kdb.Text(port.name or "", port.trans))
    self._base.kdb_cell.locked = locked

dup

dup(new_name: str | None = None) -> Self

Copy the full cell.

Sets _locked to False

Returns:

Name Type Description
cell Self

Exact copy of the current cell. The name will have $1 as duplicate names are not allowed

Source code in kfactory/kcell.py
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
def dup(self, new_name: str | None = None) -> Self:
    """Copy the full cell.

    Sets `_locked` to `False`

    Returns:
        cell: Exact copy of the current cell.
            The name will have `$1` as duplicate names are not allowed
    """
    kdb_copy = self._kdb_copy()
    if new_name:
        if new_name == self.name:
            if config.debug_names:
                raise ValueError(
                    "When duplicating a Cell, avoid giving the duplicate the same "
                    "name, as this can cause naming conflicts and may render the "
                    "GDS/OASIS file unwritable. If you're using a @cell function, "
                    "ensure that the function has a different name than the one "
                    "being called."
                )
            logger.error(
                "When duplicating a Cell, avoid giving the duplicate the same "
                "name, as this can cause naming conflicts and may render the "
                "GDS/OASIS file unwritable. If you're using a @cell function, "
                "ensure that the function has a different name than the one being "
                "called."
            )
        kdb_copy.name = new_name

    c = self.__class__(kcl=self.kcl, kdb_cell=kdb_copy)
    c.ports = self.ports.copy()

    if self.pins:
        port_mapping = {id(p): i for i, p in enumerate(c.ports)}
        c._base.pins = [
            BasePin(
                name=p.name,
                kcl=self.kcl,
                ports=[c.base.ports[port_mapping[id(port)]] for port in p.ports],
                pin_type=p.pin_type,
                info=p.info,
            )
            for p in self._base.pins
        ]

    c._base.settings = self.settings.model_copy()
    c._base.settings_units = self.settings_units.model_copy()
    c._base.info = self.info.model_copy()
    c._base.vinsts = self._base.vinsts.dup()

    return c

each_inst

each_inst() -> Iterator[Instance]

Iterates over all child instances (which may actually be instance arrays).

Source code in kfactory/kcell.py
1485
1486
1487
1488
1489
def each_inst(self) -> Iterator[Instance]:
    """Iterates over all child instances (which may actually be instance arrays)."""
    yield from (
        Instance(self.kcl, inst) for inst in self._base.kdb_cell.each_inst()
    )

each_overlapping_inst

each_overlapping_inst(b: Box | DBox) -> Iterator[Instance]

Gets the instances overlapping the given rectangle.

Source code in kfactory/kcell.py
1491
1492
1493
1494
1495
1496
def each_overlapping_inst(self, b: kdb.Box | kdb.DBox) -> Iterator[Instance]:
    """Gets the instances overlapping the given rectangle."""
    yield from (
        Instance(self.kcl, inst)
        for inst in self._base.kdb_cell.each_overlapping_inst(b)
    )

each_touching_inst

each_touching_inst(b: Box | DBox) -> Iterator[Instance]

Gets the instances overlapping the given rectangle.

Source code in kfactory/kcell.py
1498
1499
1500
1501
1502
1503
def each_touching_inst(self, b: kdb.Box | kdb.DBox) -> Iterator[Instance]:
    """Gets the instances overlapping the given rectangle."""
    yield from (
        Instance(self.kcl, inst)
        for inst in self._base.kdb_cell.each_touching_inst(b)
    )

flatten

flatten(merge: bool = True) -> None

Flatten the cell.

Parameters:

Name Type Description Default
merge bool

Merge the shapes on all layers.

True
Source code in kfactory/kcell.py
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
def flatten(self, merge: bool = True) -> None:
    """Flatten the cell.

    Args:
        merge: Merge the shapes on all layers.
    """
    if self.locked:
        raise LockedError(self)
    for vinst in self._base.vinsts:
        vinst.insert_into_flat(self)
    self._base.vinsts = VInstances()
    self._base.kdb_cell.flatten(False)

    if merge:
        for layer in self.kcl.layout.layer_indexes():
            reg = kdb.Region(self.shapes(layer))
            reg = reg.merge()
            texts = kdb.Texts(self.shapes(layer))
            self.kdb_cell.clear(layer)
            self.shapes(layer).insert(reg)
            self.shapes(layer).insert(texts)

get_meta_data

get_meta_data(
    meta_format: Literal["v1", "v2", "v3"] | None = None,
) -> None

Read metadata from the KLayout Layout object.

Source code in kfactory/kcell.py
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
def get_meta_data(
    self,
    meta_format: Literal["v1", "v2", "v3"] | None = None,
) -> None:
    """Read metadata from the KLayout Layout object."""
    if meta_format is None:
        meta_format = config.meta_format
    port_dict: dict[str, Any] = {}
    pin_dict: dict[str, Any] = {}
    ports: dict[str, Port] = {}
    settings: dict[str, MetaData] = {}
    settings_units: dict[str, str] = {}
    from .layout import kcls

    match meta_format:
        case "v3":
            self.ports.clear()
            meta_iter = (
                kcls[self.library().name()][
                    self.library_cell_index()
                ].each_meta_info()
                if self.is_library_cell()
                else self.each_meta_info()
            )
            for meta in meta_iter:
                if meta.name.startswith("kfactory:ports"):
                    i = meta.name.removeprefix("kfactory:ports:")
                    port_dict[i] = meta.value
                elif meta.name.startswith("kfactory:pins"):
                    i = meta.name.removeprefix("kfactory:pins:")
                    pin_dict[i] = meta.value
                elif meta.name.startswith("kfactory:info"):
                    self._base.info = Info(**meta.value)
                elif meta.name.startswith("kfactory:settings_units"):
                    self._base.settings_units = KCellSettingsUnits(**meta.value)
                elif meta.name.startswith("kfactory:settings"):
                    self._base.settings = KCellSettings(**meta.value)
                elif meta.name == "kfactory:function_name":
                    self._base.function_name = meta.value
                elif meta.name == "kfactory:basename":
                    self._base.basename = meta.value

            if not self.is_library_cell():
                for index in sorted(port_dict.keys()):
                    v = port_dict[index]
                    trans_: kdb.Trans | None = v.get("trans")
                    if trans_ is not None:
                        ports[index] = self.create_port(
                            name=v.get("name"),
                            trans=trans_,
                            cross_section=self.kcl.get_symmetrical_cross_section(
                                v["cross_section"]
                            ),
                            port_type=v["port_type"],
                            info=v["info"],
                        )
                    else:
                        ports[index] = self.create_port(
                            name=v.get("name"),
                            dcplx_trans=v["dcplx_trans"],
                            cross_section=self.kcl.get_symmetrical_cross_section(
                                v["cross_section"]
                            ),
                            port_type=v["port_type"],
                            info=v["info"],
                        )
                for index in sorted(pin_dict.keys()):
                    v = pin_dict[index]
                    self.create_pin(
                        name=v.get("name"),
                        ports=[
                            Port(base=ports[str(port_index)].base)
                            for port_index in v["ports"]
                        ],
                        pin_type=v["pin_type"],
                        info=v["info"],
                    )
            else:
                lib_name = self.library().name()
                for index in sorted(port_dict.keys()):
                    v = port_dict[index]
                    trans_ = v.get("trans")
                    lib_kcl = kcls[lib_name]
                    cs = self.kcl.get_symmetrical_cross_section(
                        lib_kcl.get_symmetrical_cross_section(
                            v["cross_section"]
                        ).to_dtype(lib_kcl)
                    )

                    if trans_ is not None:
                        ports[index] = self.create_port(
                            name=v.get("name"),
                            trans=trans_.to_dtype(lib_kcl.dbu).to_itype(
                                self.kcl.dbu
                            ),
                            cross_section=cs,
                            port_type=v["port_type"],
                        )
                    else:
                        ports[index] = self.create_port(
                            name=v.get("name"),
                            dcplx_trans=v["dcplx_trans"],
                            cross_section=cs,
                            port_type=v["port_type"],
                        )
                for index in sorted(pin_dict):
                    v = pin_dict[index]
                    self.create_pin(
                        name=v.get("name"),
                        ports=[
                            Port(base=ports[str(port_index)].base)
                            for port_index in v["ports"]
                        ],
                        pin_type=v["pin_type"],
                        info=v["info"],
                    )

        case "v2":
            for meta in self.each_meta_info():
                if meta.name.startswith("kfactory:ports"):
                    i, type_ = meta.name.removeprefix("kfactory:ports:").split(
                        ":", 1
                    )
                    if i not in port_dict:
                        port_dict[i] = {}
                    if not type_.startswith("info"):
                        port_dict[i][type_] = meta.value
                    else:
                        if "info" not in port_dict[i]:
                            port_dict[i]["info"] = {}
                        port_dict[i]["info"][type_.removeprefix("info:")] = (
                            meta.value
                        )
                elif meta.name.startswith("kfactory:info"):
                    setattr(
                        self.info,
                        meta.name.removeprefix("kfactory:info:"),
                        meta.value,
                    )
                elif meta.name.startswith("kfactory:settings_units"):
                    settings_units[
                        meta.name.removeprefix("kfactory:settings_units:")
                    ] = meta.value
                elif meta.name.startswith("kfactory:settings"):
                    settings[meta.name.removeprefix("kfactory:settings:")] = (
                        meta.value
                    )

                elif meta.name == "kfactory:function_name":
                    self.function_name = meta.value

                elif meta.name == "kfactory:basename":
                    self.basename = meta.value

            self.settings = KCellSettings(**settings)
            self.settings_units = KCellSettingsUnits(**settings_units)

            self.ports.clear()
            for index in sorted(port_dict.keys()):
                d = port_dict[index]
                name = d.get("name", None)
                port_type = d["port_type"]
                layer_info = d["layer"]
                width = d["width"]
                trans = d.get("trans", None)
                dcplx_trans = d.get("dcplx_trans", None)
                port = Port(
                    name=name,
                    width=width,
                    layer_info=layer_info,
                    trans=kdb.Trans.R0,
                    kcl=self.kcl,
                    port_type=port_type,
                    info=d.get("info", {}),
                )
                if trans:
                    port.trans = trans
                elif dcplx_trans:
                    port.dcplx_trans = dcplx_trans

                self.add_port(port=port, keep_mirror=True)
        case "v1":
            for meta in self.each_meta_info():
                if meta.name.startswith("kfactory:ports"):
                    i, type_ = meta.name.removeprefix("kfactory:ports:").split(
                        ":", 1
                    )
                    if i not in port_dict:
                        port_dict[i] = {}
                    if not type_.startswith("info"):
                        port_dict[i][type_] = meta.value
                    else:
                        if "info" not in port_dict[i]:
                            port_dict[i]["info"] = {}
                        port_dict[i]["info"][type_.removeprefix("info:")] = (
                            meta.value
                        )
                elif meta.name.startswith("kfactory:info"):
                    setattr(
                        self.info,
                        meta.name.removeprefix("kfactory:info:"),
                        meta.value,
                    )
                elif meta.name.startswith("kfactory:settings_units"):
                    settings_units[
                        meta.name.removeprefix("kfactory:settings_units:")
                    ] = meta.value
                elif meta.name.startswith("kfactory:settings"):
                    settings[meta.name.removeprefix("kfactory:settings:")] = (
                        meta.value
                    )

                elif meta.name == "kfactory:function_name":
                    self.function_name = meta.value

                elif meta.name == "kfactory:basename":
                    self.basename = meta.value

            self.settings = KCellSettings(**settings)
            self.settings_units = KCellSettingsUnits(**settings_units)

            self.ports.clear()
            for index in sorted(port_dict.keys()):
                d = port_dict[index]
                name = d.get("name", None)
                port_type = d["port_type"]
                layer = d["layer"]
                width = d["width"]
                trans = d.get("trans", None)
                dcplx_trans = d.get("dcplx_trans", None)
                port = Port(
                    name=name,
                    width=width,
                    layer_info=layer,
                    trans=kdb.Trans.R0,
                    kcl=self.kcl,
                    port_type=port_type,
                    info=d.get("info", {}),
                )
                if trans:
                    port.trans = kdb.Trans.from_s(trans)
                elif dcplx_trans:
                    port.dcplx_trans = kdb.DCplxTrans.from_s(dcplx_trans)

                self.add_port(port=port, keep_mirror=True)

get_optical_nets

get_optical_nets(
    port_types: Sequence[str] = ("optical",),
    allow_width_mismatch: bool = False,
) -> list[Net]

Extract geometric port-adjacency nets for the given port types.

Source code in kfactory/kcell.py
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
def get_optical_nets(
    self,
    port_types: Sequence[str] = ("optical",),
    allow_width_mismatch: bool = False,
) -> list[Net]:
    """Extract geometric port-adjacency nets for the given port types."""
    from kfnetlist.extract import get_optical_nets as _kfnetlist_get_optical_nets

    return _kfnetlist_get_optical_nets(
        self,
        port_types=port_types,
        allow_width_mismatch=allow_width_mismatch,
    )

icreate_inst

icreate_inst(
    cell: ProtoTKCell[Any] | int,
    trans: Trans | Vector | ICplxTrans | None = None,
    *,
    a: Vector | None = None,
    b: Vector | None = None,
    na: int = 1,
    nb: int = 1,
    libcell_as_static: bool = False,
    static_name_separator: str = "__",
) -> Instance

Add an instance of another KCell.

Parameters:

Name Type Description Default
cell ProtoTKCell[Any] | int

The cell to be added

required
trans Trans | Vector | ICplxTrans | None

The integer transformation applied to the reference

None
a Vector | None

Vector for the array. Needs to be in positive X-direction. Usually this is only a Vector in x-direction. Some foundries won't allow other Vectors.

None
b Vector | None

Vector for the array. Needs to be in positive Y-direction. Usually this is only a Vector in x-direction. Some foundries won't allow other Vectors.

None
na int

Number of elements in direction of a

1
nb int

Number of elements in direction of b

1
libcell_as_static bool

If the cell is a Library cell (different KCLayout object), convert it to a static cell. This can cause name collisions that are automatically resolved by appending $1[..n] on the newly created cell.

False
static_name_separator str

Stringt to separate the KCLayout name from the cell name when converting library cells (other KCLayout object than the one of this KCell) to static cells (copy them into this KCell's KCLayout).

'__'

Returns:

Type Description
Instance

The created instance

Source code in kfactory/kcell.py
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
def icreate_inst(
    self,
    cell: ProtoTKCell[Any] | int,
    trans: kdb.Trans | kdb.Vector | kdb.ICplxTrans | None = None,
    *,
    a: kdb.Vector | None = None,
    b: kdb.Vector | None = None,
    na: int = 1,
    nb: int = 1,
    libcell_as_static: bool = False,
    static_name_separator: str = "__",
) -> Instance:
    """Add an instance of another KCell.

    Args:
        cell: The cell to be added
        trans: The integer transformation applied to the reference
        a: Vector for the array.
            Needs to be in positive X-direction. Usually this is only a
            Vector in x-direction. Some foundries won't allow other Vectors.
        b: Vector for the array.
            Needs to be in positive Y-direction. Usually this is only a
            Vector in x-direction. Some foundries won't allow other Vectors.
        na: Number of elements in direction of `a`
        nb: Number of elements in direction of `b`
        libcell_as_static: If the cell is a Library cell
            (different KCLayout object), convert it to a static cell. This can cause
            name collisions that are automatically resolved by appending $1[..n] on
            the newly created cell.
        static_name_separator: Stringt to separate the KCLayout name from the cell
            name when converting library cells (other KCLayout object than the one
            of this KCell) to static cells (copy them into this KCell's KCLayout).

    Returns:
        The created instance
    """
    if trans is None:
        trans = kdb.Trans()
    if isinstance(cell, int):
        ci = cell
    else:
        ci = self._get_ci(cell, libcell_as_static, static_name_separator)

    if a is None:
        inst = self._base.kdb_cell.insert(kdb.CellInstArray(ci, trans))
    else:
        if b is None:
            b = kdb.Vector()
        inst = self._base.kdb_cell.insert(
            kdb.CellInstArray(ci, trans, a, b, na, nb)
        )
    return Instance(kcl=self.kcl, instance=inst)

insert

insert(
    inst: Instance | CellInstArray | DCellInstArray,
) -> Instance
insert(
    inst: CellInstArray | DCellInstArray, property_id: int
) -> Instance
insert(
    inst: Instance | CellInstArray | DCellInstArray,
    property_id: int | None = None,
) -> Instance

Inserts a cell instance given by another reference.

Source code in kfactory/kcell.py
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
def insert(
    self,
    inst: Instance | kdb.CellInstArray | kdb.DCellInstArray,
    property_id: int | None = None,
) -> Instance:
    """Inserts a cell instance given by another reference."""
    if self.locked:
        raise LockedError(self)
    if isinstance(inst, Instance):
        return Instance(self.kcl, self._base.kdb_cell.insert(inst.instance))
    if not property_id:
        return Instance(self.kcl, self._base.kdb_cell.insert(inst))
    assert isinstance(inst, kdb.CellInstArray | kdb.DCellInstArray)
    return Instance(self.kcl, self._base.kdb_cell.insert(inst, property_id))

insert_vinsts

insert_vinsts(recursive: bool = True) -> None

Insert all virtual instances and create Instances of real KCells.

Source code in kfactory/kcell.py
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
def insert_vinsts(self, recursive: bool = True) -> None:
    """Insert all virtual instances and create Instances of real KCells."""
    if not self._base.kdb_cell._destroyed():
        for vi in self._base.vinsts:
            vi.insert_into(self)
        self._base.vinsts.clear()

        if recursive:
            called_cell_indexes = set(self._base.kdb_cell.called_cells())
            for c in sorted(
                (
                    self.kcl[ci]
                    for ci in called_cell_indexes & self.kcl.tkcells.keys()
                    if not self.kcl[ci].kdb_cell._destroyed()
                ),
                key=lambda c: c.hierarchy_levels(),
            ):
                for vi in c._base.vinsts:
                    vi.insert_into(c)
                c._base.vinsts.clear()

is_library_cell

is_library_cell() -> bool

True if this cell is imported from a klayout library.

Source code in kfactory/kcell.py
760
761
762
def is_library_cell(self) -> bool:
    """True if this cell is imported from a klayout library."""
    return self._base.kdb_cell.is_library_cell()

l2n_elec

l2n_elec(
    mark_port_types: Iterable[str] = (
        "electrical",
        "RF",
        "DC",
    ),
    connectivity: Sequence[
        tuple[LayerInfo]
        | tuple[LayerInfo, LayerInfo]
        | tuple[LayerInfo, LayerInfo, LayerInfo],
    ]
    | None = None,
    port_mapping: dict[str, dict[str, str]] | None = None,
) -> kdb.LayoutToNetlist

Generate a LayoutToNetlist object from electrical connectivity.

Parameters:

Name Type Description Default
mark_port_types Iterable[str]

The port types to consider for the netlist extraction.

('electrical', 'RF', 'DC')
connectivity Sequence[tuple[LayerInfo] | tuple[LayerInfo, LayerInfo] | tuple[LayerInfo, LayerInfo, LayerInfo],] | None

Define connectivity between layers. These can be single layers (just consider this layer as metal), two layers (two metals which touch each other), or three layers (two metals with a via)

None
port_mapping dict[str, dict[str, str]] | None

Remap ports of cells to others. This allows to define equivalent ports in the lvs.

None
Source code in kfactory/kcell.py
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
def l2n_elec(
    self,
    mark_port_types: Iterable[str] = ("electrical", "RF", "DC"),
    connectivity: Sequence[
        tuple[kdb.LayerInfo]
        | tuple[kdb.LayerInfo, kdb.LayerInfo]
        | tuple[kdb.LayerInfo, kdb.LayerInfo, kdb.LayerInfo],
    ]
    | None = None,
    port_mapping: dict[str, dict[str, str]] | None = None,
) -> kdb.LayoutToNetlist:
    """Generate a LayoutToNetlist object from electrical connectivity.

    Args:
        mark_port_types: The port types to consider for the netlist extraction.
        connectivity: Define connectivity between layers. These can be single
            layers (just consider this layer as metal), two layers (two metals
            which touch each other), or three layers (two metals with a via)
        port_mapping: Remap ports of cells to others. This allows to define
            equivalent ports in the lvs.
    """
    from kfnetlist.extract import l2n_elec as _kfnetlist_l2n_elec

    return _kfnetlist_l2n_elec(
        self,
        mark_port_types=mark_port_types,
        connectivity=connectivity,
        port_mapping=port_mapping,
    )

l2n_ports

l2n_ports(
    port_types: Iterable[str] = ("optical",),
    exclude_purposes: list[str] | None = None,
    ignore_unnamed: bool = False,
    allow_width_mismatch: bool = False,
) -> kdb.LayoutToNetlist

Generate a LayoutToNetlist object from the port types.

Uses kfactory ports as a basis for extraction.

Parameters:

Name Type Description Default
port_types Iterable[str]

The port types to consider for the netlist extraction.

('optical',)
exclude_purposes list[str] | None

List of purposes, if an instance has that purpose, it will be ignored.

None
ignore_unnamed bool

Ignore any instance without .name set.

False

Returns: LayoutToNetlist extracted from instance and cell port positions.

Source code in kfactory/kcell.py
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
def l2n_ports(
    self,
    port_types: Iterable[str] = ("optical",),
    exclude_purposes: list[str] | None = None,
    ignore_unnamed: bool = False,
    allow_width_mismatch: bool = False,
) -> kdb.LayoutToNetlist:
    """Generate a LayoutToNetlist object from the port types.

    Uses kfactory ports as a basis for extraction.

    Args:
        port_types: The port types to consider for the netlist extraction.
        exclude_purposes: List of purposes, if an instance has that purpose, it will
            be ignored.
        ignore_unnamed: Ignore any instance without `.name` set.
    Returns:
        LayoutToNetlist extracted from instance and cell port positions.
    """
    l2n = kdb.LayoutToNetlist(self.name, self.kcl.dbu)
    l2n.extract_netlist()
    il = l2n.internal_layout()
    il.assign(self.kcl.layout)

    called_kcells = [self.kcl[ci] for ci in self.called_cells()]
    called_kcells.sort(key=lambda c: c.hierarchy_levels())

    for c in called_kcells:
        c.circuit(
            l2n,
            port_types=port_types,
            exclude_purposes=exclude_purposes,
            ignore_unnamed=ignore_unnamed,
            allow_width_mismatch=allow_width_mismatch,
        )
    self.circuit(
        l2n,
        port_types=port_types,
        exclude_purposes=exclude_purposes,
        ignore_unnamed=ignore_unnamed,
        allow_width_mismatch=allow_width_mismatch,
    )
    return l2n

plot

plot(
    lyrdb: Path | str | None = None,
    display_type: Literal["image", "widget"] | None = None,
) -> None

Display cell.

Parameters:

Name Type Description Default
lyrdb Path | str | None

Path to the lyrdb file.

None
display_type Literal['image', 'widget'] | None

Type of display. Options are "widget" or "image".

None
Source code in kfactory/kcell.py
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
def plot(
    self,
    lyrdb: Path | str | None = None,
    display_type: Literal["image", "widget"] | None = None,
) -> None:
    """Display cell.

    Args:
        lyrdb: Path to the lyrdb file.
        display_type: Type of display. Options are "widget" or "image".

    """
    from .widgets.interactive import display_kcell

    display_kcell(self, lyrdb=lyrdb, display_type=display_type)

read

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

Read a GDS file into the existing KCell.

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

Layout meta infos are ignored from the loaded layout.

Parameters:

Name Type Description Default
filename str | Path

Path of the GDS file.

required
options LoadLayoutOptions | None

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

None
register_cells bool

If True create KCells for all cells in the GDS.

False
test_merge bool

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

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

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

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

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

None
Source code in kfactory/kcell.py
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
def read(
    self,
    filename: str | Path,
    options: kdb.LoadLayoutOptions | None = None,
    register_cells: bool = False,
    test_merge: bool = True,
    update_kcl_meta_data: Literal["overwrite", "skip", "drop"] = "drop",
    meta_format: Literal["v1", "v2", "v3"] | None = None,
) -> list[int]:
    """Read a GDS file into the existing KCell.

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

    Layout meta infos are ignored from the loaded layout.

    Args:
        filename: Path of the GDS file.
        options: KLayout options to load from the GDS. Can determine how merge
            conflicts are handled for example. See
            https://www.klayout.de/doc-qt5/code/class_LoadLayoutOptions.html
        register_cells: If `True` create KCells for all cells in the GDS.
        test_merge: Check the layouts first whether they are compatible
            (no differences).
        update_kcl_meta_data: How to treat loaded KCLayout info.
            overwrite: overwrite existing info entries
            skip: keep existing info values
            drop: don't add any new info
        meta_format: How to read KCell metainfo from the gds. `v1` had stored port
            transformations as strings, never versions have them stored and loaded
            in their native KLayout formats.
    """
    # see: wait for KLayout update https://github.com/KLayout/klayout/issues/1609
    logger.critical(
        "KLayout <=0.28.15 (last update 2024-02-02) cannot read LayoutMetaInfo on"
        " 'Cell.read'. kfactory uses these extensively for ports, info, and "
        "settings. Therefore proceed at your own risk."
    )
    if meta_format is None:
        meta_format = config.meta_format
    if options is None:
        options = load_layout_options()
    fn = str(Path(filename).expanduser().resolve())
    if test_merge and (
        options.cell_conflict_resolution
        != kdb.LoadLayoutOptions.CellConflictResolution.RenameCell
    ):
        self.kcl.set_meta_data()
        for kcell in self.kcl.kcells.values():
            kcell.set_meta_data()
        layout_b = kdb.Layout()
        layout_b.read(fn, options)
        layout_a = self.kcl.layout.dup()
        layout_a.delete_cell(layout_a.cell(self.name).cell_index())
        diff = MergeDiff(
            layout_a=layout_a,
            layout_b=layout_b,
            name_a=self.name,
            name_b=Path(filename).stem,
        )
        diff.compare()
        if diff.dbu_differs:
            raise MergeError("Layouts' DBU differ. Check the log for more info.")
        if diff.diff_xor.cells() > 0 or diff.layout_meta_diff:
            diff_kcl = KCLayout(self.name + "_XOR")
            diff_kcl.layout.assign(diff.diff_xor)
            show(diff_kcl)

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

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

            raise MergeError(err_msg)

    cell_ids = self._base.kdb_cell.read(fn, options)
    info, settings = self.kcl.get_meta_data()

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

            info.update(info_)
            self.kcl.info = Info(**info)
        case "drop":
            ...
    meta_format = settings.get("meta_format") or meta_format

    if register_cells:
        new_cis = set(cell_ids)

        for c in new_cis:
            kc = self.kcl[c]
            kc.get_meta_data(meta_format=meta_format)
    else:
        cis = self.kcl.tkcells.keys()
        new_cis = set(cell_ids)

        for c in new_cis & cis:
            kc = self.kcl[c]
            kc.get_meta_data(meta_format=meta_format)

    self.get_meta_data(meta_format=meta_format)

    return cell_ids

set_meta_data

set_meta_data() -> None

Set metadata of the Cell.

Currently, ports, settings and info will be set.

Source code in kfactory/kcell.py
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
def set_meta_data(self) -> None:
    """Set metadata of the Cell.

    Currently, ports, settings and info will be set.
    """
    self.clear_meta_info()
    if not self.is_library_cell():
        for i, port in enumerate(self.ports):
            if port.base.trans is not None:
                meta_info: dict[str, MetaData] = {
                    "name": port.name,
                    "cross_section": port.cross_section.name,
                    "trans": port.base.trans,
                    "port_type": port.port_type,
                    "info": port.info.model_dump(),
                }

                self.add_meta_info(
                    kdb.LayoutMetaInfo(f"kfactory:ports:{i}", meta_info, None, True)
                )
            else:
                meta_info = {
                    "name": port.name,
                    "cross_section": port.cross_section.name,
                    "dcplx_trans": port.dcplx_trans,
                    "port_type": port.port_type,
                    "info": port.info.model_dump(),
                }

                self.add_meta_info(
                    kdb.LayoutMetaInfo(f"kfactory:ports:{i}", meta_info, None, True)
                )
        for i, pin in enumerate(self.pins):
            meta_info = {
                "name": pin.name,
                "pin_type": pin.pin_type,
                "info": pin.info.model_dump(),
                "ports": [self.base.ports.index(port.base) for port in pin.ports],
            }
            self.add_meta_info(
                kdb.LayoutMetaInfo(f"kfactory:pins:{i}", meta_info, None, True)
            )
        settings = self.settings.model_dump()
        if settings:
            self.add_meta_info(
                kdb.LayoutMetaInfo("kfactory:settings", settings, None, True)
            )
        info = self.info.model_dump()
        if info:
            self.add_meta_info(
                kdb.LayoutMetaInfo("kfactory:info", info, None, True)
            )
        settings_units = self.settings_units.model_dump()
        if settings_units:
            self.add_meta_info(
                kdb.LayoutMetaInfo(
                    "kfactory:settings_units",
                    settings_units,
                    None,
                    True,
                )
            )

        if self.function_name is not None:
            self.add_meta_info(
                kdb.LayoutMetaInfo(
                    "kfactory:function_name", self.function_name, None, True
                )
            )

        if self.basename is not None:
            self.add_meta_info(
                kdb.LayoutMetaInfo("kfactory:basename", self.basename, None, True)
            )

show

show(
    lyrdb: ReportDatabase | Path | str | None = None,
    l2n: LayoutToNetlist | Path | str | None = None,
    keep_position: bool = True,
    save_options: SaveLayoutOptions | None = None,
    use_libraries: bool = True,
    library_save_options: SaveLayoutOptions | None = None,
    technology: str | None = None,
    markers: list[tuple[DShapeLike, MarkerConfig]]
    | None = None,
) -> None

Stream the gds to klive.

Will create a temporary file of the gds and load it in KLayout via klive

Source code in kfactory/kcell.py
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
def show(
    self,
    lyrdb: rdb.ReportDatabase | Path | str | None = None,
    l2n: kdb.LayoutToNetlist | Path | str | None = None,
    keep_position: bool = True,
    save_options: kdb.SaveLayoutOptions | None = None,
    use_libraries: bool = True,
    library_save_options: kdb.SaveLayoutOptions | None = None,
    technology: str | None = None,
    markers: list[tuple[DShapeLike, MarkerConfig]] | None = None,
) -> None:
    """Stream the gds to klive.

    Will create a temporary file of the gds and load it in KLayout via klive
    """
    if save_options is None:
        save_options = save_layout_options()
    if library_save_options is None:
        library_save_options = save_layout_options()
    show_f: ShowFunction = config.show_function or show

    kwargs: dict[str, Any] = {}
    if technology is not None:
        kwargs["technology"] = technology
    if l2n is not None:
        kwargs["l2n"] = l2n
    if lyrdb is not None:
        kwargs["lyrdb"] = lyrdb

    show_f(
        self,
        keep_position=keep_position,
        save_options=save_options,
        use_libraries=use_libraries,
        library_save_options=library_save_options,
        markers=markers,
        **kwargs,
    )

to_dtype

to_dtype() -> DKCell

Convert the kcell to a um kcell.

Source code in kfactory/kcell.py
851
852
853
def to_dtype(self) -> DKCell:
    """Convert the kcell to a um kcell."""
    return DKCell(base=self._base)

to_itype

to_itype() -> KCell

Convert the kcell to a dbu kcell.

Source code in kfactory/kcell.py
847
848
849
def to_itype(self) -> KCell:
    """Convert the kcell to a dbu kcell."""
    return KCell(base=self._base)

transform

transform(
    inst: Instance,
    trans: Trans | DTrans | ICplxTrans | DCplxTrans,
    /,
    *,
    transform_ports: bool = True,
) -> Instance
transform(
    trans: Trans | DTrans | ICplxTrans | DCplxTrans,
    /,
    *,
    transform_ports: bool = True,
) -> None
transform(
    inst_or_trans: Instance
    | Trans
    | DTrans
    | ICplxTrans
    | DCplxTrans,
    trans: Trans
    | DTrans
    | ICplxTrans
    | DCplxTrans
    | None = None,
    /,
    *,
    transform_ports: bool = True,
) -> Instance | None

Transforms the instance or cell with the transformation given.

Source code in kfactory/kcell.py
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
def transform(
    self,
    inst_or_trans: kdb.Instance
    | kdb.Trans
    | kdb.DTrans
    | kdb.ICplxTrans
    | kdb.DCplxTrans,
    trans: kdb.Trans | kdb.DTrans | kdb.ICplxTrans | kdb.DCplxTrans | None = None,
    /,
    *,
    transform_ports: bool = True,
) -> Instance | None:
    """Transforms the instance or cell with the transformation given."""
    if trans is not None:
        return Instance(
            self.kcl,
            self._base.kdb_cell.transform(
                cast("kdb.Instance", inst_or_trans),
                trans,
            ),
        )
    self._base.kdb_cell.transform(
        cast(
            "kdb.Trans | kdb.DTrans | kdb.ICplxTrans | kdb.DCplxTrans",
            inst_or_trans,
        )
    )
    if transform_ports:
        if isinstance(inst_or_trans, kdb.DTrans):
            inst_or_trans = kdb.DCplxTrans(inst_or_trans)
        elif isinstance(inst_or_trans, kdb.ICplxTrans):
            inst_or_trans = kdb.DCplxTrans(inst_or_trans, self.kcl.dbu)

        if isinstance(inst_or_trans, kdb.Trans):
            for port in self.ports:
                port.trans = inst_or_trans * port.trans
        else:
            for port in self.ports:
                port.dcplx_trans = inst_or_trans * port.dcplx_trans  # ty:ignore[unsupported-operator]
    return None

write

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

Write a KCell to a GDS.

See KCLayout.write for more info.

Source code in kfactory/kcell.py
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
def write(
    self,
    filename: str | Path,
    save_options: kdb.SaveLayoutOptions | None = None,
    convert_external_cells: bool = False,
    set_meta_data: bool = True,
    autoformat_from_file_extension: bool = True,
) -> None:
    """Write a KCell to a GDS.

    See [KCLayout.write][kfactory.layout.KCLayout.write] for more info.
    """
    if save_options is None:
        save_options = save_layout_options()
    self.insert_vinsts()
    match set_meta_data, convert_external_cells:
        case True, True:
            self.kcl.set_meta_data()
            for kcell in (self.kcl[ci] for ci in self.called_cells()):
                if not kcell._destroyed():
                    if kcell.is_library_cell():
                        kcell.convert_to_static(recursive=True)
                    kcell.set_meta_data()
            if self.is_library_cell():
                self.convert_to_static(recursive=True)
            self.set_meta_data()
        case True, False:
            self.kcl.set_meta_data()
            for kcell in (self.kcl[ci] for ci in self.called_cells()):
                if not kcell._destroyed():
                    kcell.set_meta_data()
            self.set_meta_data()
        case False, True:
            for kcell in (self.kcl[ci] for ci in self.called_cells()):
                if kcell.is_library_cell() and not kcell._destroyed():
                    kcell.convert_to_static(recursive=True)
            if self.is_library_cell():
                self.convert_to_static(recursive=True)
        case _:
            ...

    filename = str(filename)
    if autoformat_from_file_extension:
        save_options.set_format_from_filename(filename)
    self._base.kdb_cell.write(filename, save_options)

write_bytes

write_bytes(
    save_options: SaveLayoutOptions | None = None,
    convert_external_cells: bool = False,
    set_meta_data: bool = True,
) -> bytes

Write a KCell to a binary format as oasis.

See KCLayout.write for more info.

Source code in kfactory/kcell.py
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
def write_bytes(
    self,
    save_options: kdb.SaveLayoutOptions | None = None,
    convert_external_cells: bool = False,
    set_meta_data: bool = True,
) -> bytes:
    """Write a KCell to a binary format as oasis.

    See [KCLayout.write][kfactory.layout.KCLayout.write] for more info.
    """
    if save_options is None:
        save_options = save_layout_options()
    self.insert_vinsts()
    match set_meta_data, convert_external_cells:
        case True, True:
            self.kcl.set_meta_data()
            for kcell in (self.kcl[ci] for ci in self.called_cells()):
                if not kcell._destroyed():
                    if kcell.is_library_cell():
                        kcell.convert_to_static(recursive=True)
                    kcell.set_meta_data()
            if self.is_library_cell():
                self.convert_to_static(recursive=True)
            self.set_meta_data()
        case True, False:
            self.kcl.set_meta_data()
            for kcell in (self.kcl[ci] for ci in self.called_cells()):
                if not kcell._destroyed():
                    kcell.set_meta_data()
            self.set_meta_data()
        case False, True:
            for kcell in (self.kcl[ci] for ci in self.called_cells()):
                if kcell.is_library_cell() and not kcell._destroyed():
                    kcell.convert_to_static(recursive=True)
            if self.is_library_cell():
                self.convert_to_static(recursive=True)
        case _:
            ...

    save_options.format = save_options.format or "OASIS"
    save_options.clear_cells()
    save_options.select_cell(self.cell_index())
    return self.kcl.layout.write_bytes(save_options)

TKCell pydantic-model

Bases: BaseKCell

KLayout cell and change its class to KCell.

A KCell is a dynamic proxy for kdb.Cell. It has all the attributes of the official KLayout class. Some attributes have been adjusted to return KCell specific sub classes. If the function is listed here in the docs, they have been adjusted for KFactory specifically. This object will transparently proxy to kdb.Cell. Meaning any attribute not directly defined in this class that are available from the KLayout counter part can still be accessed. The pure KLayout object can be accessed with kdb_cell.

Attributes:

Name Type Description
kdb_cell Cell

Pure KLayout cell object.

locked bool

If set the cell shouldn't be modified anymore.

function_name str | None

Name of the function that created the cell.

virtual bool

If true, the Cell came from a VKCell.

vtrans DCplxTrans | None

If not None, the cell came from an instance which cannot be snapped lossless to the grid. This happens if a was used and the VInstance cannot be mapped to the grid without information loss.

Fields:

  • ports (list[BasePort])
  • pins (list[BasePin])
  • settings (KCellSettings)
  • settings_units (KCellSettingsUnits)
  • vinsts (VInstances)
  • info (Info)
  • kcl (KCLayout)
  • function_name (str | None)
  • basename (str | None)
  • kdb_cell (Cell)
  • boundary (DPolygon | None)
  • lvs_equivalent_ports (list[list[str]] | None)
  • virtual (bool)
  • vtrans (DCplxTrans | None)
Source code in kfactory/kcell.py
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
class TKCell(BaseKCell):
    """KLayout cell and change its class to KCell.

    A KCell is a dynamic proxy for kdb.Cell. It has all the
    attributes of the official KLayout class. Some attributes have been adjusted
    to return KCell specific sub classes. If the function is listed here in the
    docs, they have been adjusted for KFactory specifically. This object will
    transparently proxy to kdb.Cell. Meaning any attribute not directly
    defined in this class that are available from the KLayout counter part can
    still be accessed. The pure KLayout object can be accessed with
    `kdb_cell`.

    Attributes:
        kdb_cell: Pure KLayout cell object.
        locked: If set the cell shouldn't be modified anymore.
        function_name: Name of the function that created the cell.
        virtual: If true, the Cell came from a VKCell.
        vtrans: If not None, the cell came from an instance which cannot be snapped
            lossless to the grid. This happens if a was used and the VInstance cannot
            be mapped to the grid without information loss.
    """

    kdb_cell: kdb.Cell
    boundary: kdb.DPolygon | None = None
    lvs_equivalent_ports: list[list[str]] | None = None
    virtual: bool = False
    vtrans: kdb.DCplxTrans | None = None
    _schematic: TSchematic[Any] | None = PrivateAttr(default=None)
    _library_cell: KCell | None = PrivateAttr(default=None)

    def __getattr__(self, name: str) -> Any:
        """If KCell doesn't have an attribute, look in the KLayout Cell."""
        try:
            return super().__getattr__(name)  # ty:ignore[unresolved-attribute]
        except Exception:
            return getattr(self.kdb_cell, name)

    @property
    def schematic(self) -> TSchematic[Any] | None:
        return self._schematic

    @schematic.setter
    def schematic(self, value: TSchematic[Any] | None) -> None:
        self._schematic = value

    @property
    def locked(self) -> bool:
        return self.kdb_cell.is_locked()

    @locked.setter
    def locked(self, value: bool) -> None:
        self.kdb_cell.locked = value

    def __repr__(self) -> str:
        return f"{self.__class__.__name__}(name={self.kdb_cell.name})"

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

    @name.setter
    def name(self, value: str) -> None:
        if self.locked:
            raise LockedError(self)
        if (
            value != self.kdb_cell.name
            and value != self.kcl.layout.unique_cell_name(value)
            and not self.kcl.layout.cell(value).is_library_cell()
            and not self.is_library_cell()
        ):
            stack = inspect.stack()
            module = inspect.getmodule(stack[3].frame)
            tkcells = [
                self.kcl.tkcells[cell.cell_index()]
                for cell in self.kcl.layout.cells(value)
                if not cell.is_library_cell()
            ]

            if module is not None and module.__name__ == "kfactory.layout":
                frame_info = stack[5]
                logger.opt(depth=2).error(
                    "Name conflict in "
                    f"{frame_info.frame.f_locals['f'].__code__.co_filename}::"
                    f"{frame_info.frame.f_locals['f'].__name__} at line "
                    f"{frame_info.frame.f_locals['f'].__code__.co_firstlineno}\n"
                    f"Renaming {self.name} (cell_index={self.kdb_cell.cell_index()}) to"
                    f" {value} would cause it to be named the same as:\n"
                    + "\n".join(
                        f" - {tkcell.name} (cell_index={tkcell.kdb_cell.cell_index()}),"
                        f" function_name={tkcell.function_name},"
                        f" basename={tkcell.basename}"
                        for tkcell in tkcells
                    )
                )
                if config.debug_names:
                    raise ValueError(
                        "Name conflict in "
                        f"{frame_info.frame.f_locals['f'].__code__.co_filename}::"
                        f"{frame_info.frame.f_locals['f'].__name__} at line "
                        f"{frame_info.frame.f_locals['f'].__code__.co_firstlineno}\n"
                        f"Renaming {self.name} (cell_index={self.kdb_cell.cell_index()}"
                        f") to {value} would cause it to be named the same as:\n"
                        + "\n".join(
                            f" - {tkcell.name} "
                            f"(cell_index={tkcell.kdb_cell.cell_index()}),"
                            f" function_name={tkcell.function_name},"
                            f" basename={tkcell.basename}"
                            for tkcell in tkcells
                        )
                    )
            else:
                frame_info = stack[3]
                if module is not None:
                    module_name = module.__name__
                    if module_name == "__main__":
                        module_name = frame_info.filename
                    function_name = (
                        "::" + frame_info.function
                        if frame_info.function != "<module>"
                        else ""
                    )
                    logger.opt(depth=3).error(
                        "Name conflict in "
                        f"{module_name}{function_name} at line "
                        f"{frame_info.lineno}\n"
                        f"Renaming {self.name} (cell_index="
                        f"{self.kdb_cell.cell_index()}) to"
                        f" {value} would cause it to be named the same as:\n"
                        + "\n".join(
                            f" - {tkcell.name} "
                            f"(cell_index={tkcell.kdb_cell.cell_index()}),"
                            f" function_name={tkcell.function_name},"
                            f" basename={tkcell.basename}"
                            for tkcell in tkcells
                        )
                    )
                    if config.debug_names:
                        raise ValueError(
                            "Name conflict in "
                            f"{module_name}{function_name} at line "
                            f"{frame_info.lineno}\n"
                            f"Renaming {self.name} (cell_index="
                            f"{self.kdb_cell.cell_index()}) to"
                            f" {value} would cause it to be named the same as:\n"
                            + "\n".join(
                                f" - {tkcell.name} "
                                f"(cell_index={tkcell.kdb_cell.cell_index()}),"
                                f" function_name={tkcell.function_name},"
                                f" basename={tkcell.basename}"
                                for tkcell in tkcells
                            )
                        )
                else:
                    function_name = (
                        "::" + frame_info.function
                        if frame_info.function != "<module>"
                        else ""
                    )
                    logger.opt(depth=3).error(
                        "Name conflict in "
                        f"{frame_info.filename}"
                        f"{function_name} at line {frame_info.lineno}\n"
                        f"Renaming {self.name} (cell_index="
                        f"{self.kdb_cell.cell_index()}) to"
                        f" {value} would cause it to be named the same as:\n"
                        + "\n".join(
                            f" - {tkcell.name} "
                            f"(cell_index={tkcell.kdb_cell.cell_index()}),"
                            f" function_name={tkcell.function_name},"
                            f" basename={tkcell.basename}"
                            for tkcell in tkcells
                        )
                    )
                    if config.debug_names:
                        raise ValueError(
                            "Name conflict in "
                            f"{frame_info.filename}"
                            f"{function_name} at line {frame_info.lineno}\n"
                            f"Renaming {self.name} (cell_index="
                            f"{self.kdb_cell.cell_index()}) to"
                            f" {value} would cause it to be named the same as:\n"
                            + "\n".join(
                                f" - {tkcell.name} "
                                f"(cell_index={tkcell.kdb_cell.cell_index()}),"
                                f" function_name={tkcell.function_name},"
                                f" basename={tkcell.basename}"
                                for tkcell in tkcells
                            )
                        )

        self.kdb_cell.name = value

locked property writable

locked: bool

If set the cell shouldn't be modified anymore.

__getattr__

__getattr__(name: str) -> Any

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

Source code in kfactory/kcell.py
438
439
440
441
442
443
def __getattr__(self, name: str) -> Any:
    """If KCell doesn't have an attribute, look in the KLayout Cell."""
    try:
        return super().__getattr__(name)  # ty:ignore[unresolved-attribute]
    except Exception:
        return getattr(self.kdb_cell, name)

TVCell pydantic-model

Bases: BaseKCell

Fields:

Source code in kfactory/kcell.py
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
class TVCell(BaseKCell):
    _locked: bool = PrivateAttr(default=False)
    shapes: dict[int, VShapes] = Field(default_factory=dict)
    _name: str | None = PrivateAttr(default=None)

    @property
    def locked(self) -> bool:
        return self._locked

    @locked.setter
    def locked(self, value: bool) -> None:
        self._locked = value

    @property
    def name(self) -> str | None:
        return self._name

    @name.setter
    def name(self, value: str) -> None:
        self._name = value

locked property writable

locked: bool

If set the cell shouldn't be modified anymore.

VKCell

Bases: ProtoKCell[float, TVCell], UMGeometricObject, DCreatePort

Emulate [klayout.db.Cell][klayout.db.Cell].

Source code in kfactory/kcell.py
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
class VKCell(ProtoKCell[float, TVCell], UMGeometricObject, DCreatePort):
    """Emulate `[klayout.db.Cell][klayout.db.Cell]`."""

    @overload
    def __init__(self, *, base: TVCell) -> None: ...

    @overload
    def __init__(
        self,
        *,
        name: str | None = None,
        kcl: KCLayout | None = None,
        info: dict[str, Any] | None = None,
        settings: dict[str, Any] | None = None,
    ) -> None: ...

    def __init__(
        self,
        *,
        base: TVCell | None = None,
        name: str | None = None,
        kcl: KCLayout | None = None,
        info: dict[str, Any] | None = None,
        settings: dict[str, Any] | None = None,
    ) -> None:
        from .layout import get_default_kcl

        if base is not None:
            self._base = base
        else:
            kcl_ = kcl or get_default_kcl()
            self._base = TVCell(
                kcl=kcl_,
                info=Info(**(info or {})),
                settings=KCellSettings(**(settings or {})),
                vinsts=VInstances(),
            )
            if name:
                self._base.name = name

    def ibbox(self, layer: int | None = None) -> kdb.Box:
        return self.dbbox(layer).to_itype(self.kcl.dbu)

    def transform(
        self,
        trans: kdb.Trans | kdb.DTrans | kdb.ICplxTrans | kdb.DCplxTrans,
        /,
    ) -> None:
        shapes = self.base.shapes
        for key, vshape in shapes.items():
            shapes[key] = vshape.transform(trans)

    @property
    def ports(self) -> DPorts:
        """Ports associated with the cell."""
        return DPorts(kcl=self.kcl, bases=self._base.ports)

    @ports.setter
    def ports(self, new_ports: Iterable[ProtoPort[Any]]) -> None:
        if self.locked:
            raise LockedError(self)
        self._base.ports = [port.base for port in new_ports]

    @property
    def pins(self) -> DPins:
        """Ports associated with the cell."""
        return DPins(kcl=self.kcl, bases=self._base.pins)

    @pins.setter
    def pins(self, new_pins: Iterable[ProtoPin[Any]]) -> None:
        if self.locked:
            raise LockedError(self)
        self._base.pins = [pin.base for pin in new_pins]

    def dbbox(self, layer: int | LayerEnum | None = None) -> kdb.DBox:
        layers_ = set(self.shapes().keys())

        layers = layers_ if layer is None else {layer} & layers_
        box = kdb.DBox()
        for layer_ in layers:
            layer__ = layer_
            if isinstance(layer__, LayerEnum):
                layer__ = layer__.layout.layer(layer__.layer, layer__.datatype)
            box += self.shapes(layer__).bbox()

        for vinst in self.insts:
            box += vinst.dbbox()

        return box

    def __getitem__(self, key: int | str | None) -> DPort:
        """Returns port from instance."""
        return self.ports[key]

    @property
    def insts(self) -> VInstances:
        return self._base.vinsts

    def dup(self, new_name: str | None = None) -> Self:
        """Copy the full cell.

        Removes lock if the original cell was locked.

        Returns:
            cell: Exact copy of the current cell.
                The name will have `$1` as duplicate names are not allowed
        """
        c = self.__class__(
            kcl=self.kcl, name=new_name or self.name + "$1" if self.name else None
        )
        c.ports = DPorts(kcl=self.kcl, ports=self.ports.copy())

        c.settings = self.settings.model_copy()
        c.settings_units = self.settings_units.model_copy()
        c.info = self._base.info.model_copy()
        for layer, shapes in self.shapes().items():
            for shape in shapes:
                c.shapes(layer).insert(shape)
        c._base.vinsts = self._base.vinsts.dup()

        return c

    def show(
        self,
        lyrdb: rdb.ReportDatabase | Path | str | None = None,
        l2n: kdb.LayoutToNetlist | Path | str | None = None,
        keep_position: bool = True,
        save_options: kdb.SaveLayoutOptions | None = None,
        use_libraries: bool = True,
        library_save_options: kdb.SaveLayoutOptions | None = None,
        technology: str | None = None,
    ) -> None:
        """Stream the gds to klive.

        Will create a temporary file of the gds and load it in KLayout via klive
        """
        if save_options is None:
            save_options = save_layout_options()
        if library_save_options is None:
            library_save_options = save_layout_options()
        c = self.kcl.kcell()
        if self.name is not None:
            c.name = self.name
        VInstance(self).insert_into_flat(c, levels=0)
        c.add_ports(self.ports)
        c.info = self.info.model_copy()
        c.base.settings = self.settings.model_copy()

        kwargs: dict[str, Any] = {}
        if technology is not None:
            kwargs["technology"] = technology
        if l2n is not None:
            kwargs["l2n"] = l2n
        if lyrdb is not None:
            kwargs["lyrdb"] = lyrdb

        c.show(keep_position=keep_position, **kwargs)

    def plot(self) -> None:
        """Display cell.

        Usage: Pass the vkcell variable as an argument in the cell at the end
        """
        from .widgets.interactive import display_kcell

        c = self.kcl.kcell()
        if self.name is not None:
            c.name = self.name
        VInstance(self).insert_into_flat(c, levels=0)

        display_kcell(c)
        c.delete()

    def _ipython_display_(self) -> None:
        """Display a cell in a Jupyter Cell.

        Usage: Pass the kcell variable as an argument in the cell at the end
        """
        self.plot()

    def __repr__(self) -> str:
        """Return a string representation of the Cell."""
        port_names = [p.name for p in self.ports]
        pin_names = [pin.name for pin in self.pins]
        return (
            f"{self.name}: ports {port_names}, pins {pin_names}, {len(self.insts)} "
            "instances"
        )

    def add_port(
        self,
        *,
        port: ProtoPort[Any],
        name: str | None = None,
        keep_mirror: bool = False,
    ) -> DPort:
        """Proxy for [Ports.create_port][kfactory.ports.Ports.create_port]."""
        if self.locked:
            raise LockedError(self)
        return self.ports.add_port(
            port=port,
            name=name,
            keep_mirror=keep_mirror,
        )

    def create_inst(
        self, cell: AnyKCell, trans: kdb.DCplxTrans | None = None
    ) -> VInstance:
        if self.locked:
            raise LockedError(self)
        inst = VInstance(cell=cell, trans=trans or kdb.DCplxTrans())
        self.insts.append(inst)
        return inst

    def auto_rename_ports(self, rename_func: Callable[..., None] | None = None) -> None:
        """Rename the ports with the schema angle -> "NSWE" and sort by x and y.

        Args:
            rename_func: Function that takes Iterable[Port] and renames them.
                This can of course contain a filter and only rename some of the ports
        """
        if self.locked:
            raise LockedError(self)
        if rename_func is None:
            self.kcl.rename_function(self.ports)
        else:
            rename_func(self.ports)

    def __lshift__(self, cell: AnyKCell) -> VInstance:
        return self.create_inst(cell=cell)

    @overload
    def shapes(self, layer: None = ...) -> dict[int, VShapes]: ...

    @overload
    def shapes(self, layer: int | kdb.LayerInfo) -> VShapes: ...

    def shapes(
        self, layer: int | kdb.LayerInfo | None = None
    ) -> VShapes | dict[int, VShapes]:
        if layer is None:
            return self._base.shapes
        if isinstance(layer, kdb.LayerInfo):
            layer = self.kcl.layout.layer(layer)
        if layer not in self._base.shapes:
            self._base.shapes[layer] = VShapes(cell=self)
        return self._base.shapes[layer]

    def flatten(self) -> None:
        if self.locked:
            raise LockedError(self)
        for inst in self.insts:
            inst.insert_into_flat(self, inst.trans)

    def draw_ports(self) -> None:
        """Draw all the ports on their respective layer."""
        polys: dict[float, kdb.DPolygon] = {}

        for port in self.ports:
            w = port.width

            if w in polys:
                poly = polys[w]
            else:
                if w < 2:
                    poly = kdb.DPolygon(
                        [
                            kdb.DPoint(0, -w / 2),
                            kdb.DPoint(0, w / 2),
                            kdb.DPoint(w / 2, 0),
                        ]
                    )
                else:
                    poly = kdb.DPolygon(
                        [
                            kdb.DPoint(0, -w / 2),
                            kdb.DPoint(0, w / 2),
                            kdb.DPoint(w / 2, 0),
                            kdb.DPoint(w * 19 / 20, 0),
                            kdb.DPoint(w / 20, w * 9 / 20),
                            kdb.DPoint(w / 20, -w * 9 / 20),
                            kdb.DPoint(w * 19 / 20, 0),
                            kdb.DPoint(w / 2, 0),
                        ]
                    )
                polys[w] = poly
            self.shapes(port.layer).insert(poly.transformed(port.dcplx_trans))
            self.shapes(port.layer).insert(kdb.Text(port.name or "", port.trans))

    def write(
        self,
        filename: str | Path,
        save_options: kdb.SaveLayoutOptions | None = None,
        convert_external_cells: bool = False,
        set_meta_data: bool = True,
        autoformat_from_file_extension: bool = True,
    ) -> None:
        """Write a KCell to a GDS.

        See [KCLayout.write][kfactory.layout.KCLayout.write] for more info.
        """
        if save_options is None:
            save_options = save_layout_options()
        c = self.kcl.kcell()
        if self.name is not None:
            c.name = self.name
        c.settings = self.settings
        c.settings_units = self.settings_units
        c.info = self.info
        VInstance(self).insert_into_flat(c, levels=1)

        c.write(
            filename=filename,
            save_options=save_options,
            convert_external_cells=convert_external_cells,
            set_meta_data=set_meta_data,
            autoformat_from_file_extension=autoformat_from_file_extension,
        )

    def l2n(
        self, port_types: Iterable[str] = ("optical",)
    ) -> tuple[KCell, kdb.LayoutToNetlist]:
        """Generate a LayoutToNetlist object from the port types.

        Args:
            port_types: The port types to consider for the netlist extraction.
        """
        c = self.kcl.kcell()
        if self.name is not None:
            c.name = self.name
        c.settings = self.settings
        c.settings_units = self.settings_units
        c.info = self.info
        VInstance(self).insert_into(c)
        return c, c.l2n()

    def connectivity_check(
        self,
        port_types: list[str] | None = None,
        layers: list[int] | None = None,
        db: rdb.ReportDatabase | None = None,
        recursive: bool = True,
        add_cell_ports: bool = False,
        check_layer_connectivity: bool = True,
    ) -> tuple[KCell, rdb.ReportDatabase]:
        if layers is None:
            layers = []
        if port_types is None:
            port_types = []
        c = self.kcl.kcell()
        if self.name is not None:
            c.name = self.name
        c.settings = self.settings
        c.settings_units = self.settings_units
        c.info = self.info
        VInstance(self).insert_into_flat(c, levels=0)
        return c, c.connectivity_check(
            port_types=port_types,
            layers=layers,
            db=db,
            recursive=recursive,
            add_cell_ports=add_cell_ports,
            check_layer_connectivity=check_layer_connectivity,
        )

pins property writable

pins: DPins

Ports associated with the cell.

ports property writable

ports: DPorts

Ports associated with the cell.

__getitem__

__getitem__(key: int | str | None) -> DPort

Returns port from instance.

Source code in kfactory/kcell.py
3486
3487
3488
def __getitem__(self, key: int | str | None) -> DPort:
    """Returns port from instance."""
    return self.ports[key]

__repr__

__repr__() -> str

Return a string representation of the Cell.

Source code in kfactory/kcell.py
3576
3577
3578
3579
3580
3581
3582
3583
def __repr__(self) -> str:
    """Return a string representation of the Cell."""
    port_names = [p.name for p in self.ports]
    pin_names = [pin.name for pin in self.pins]
    return (
        f"{self.name}: ports {port_names}, pins {pin_names}, {len(self.insts)} "
        "instances"
    )

add_port

add_port(
    *,
    port: ProtoPort[Any],
    name: str | None = None,
    keep_mirror: bool = False,
) -> DPort

Proxy for Ports.create_port.

Source code in kfactory/kcell.py
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
def add_port(
    self,
    *,
    port: ProtoPort[Any],
    name: str | None = None,
    keep_mirror: bool = False,
) -> DPort:
    """Proxy for [Ports.create_port][kfactory.ports.Ports.create_port]."""
    if self.locked:
        raise LockedError(self)
    return self.ports.add_port(
        port=port,
        name=name,
        keep_mirror=keep_mirror,
    )

auto_rename_ports

auto_rename_ports(
    rename_func: Callable[..., None] | None = None,
) -> None

Rename the ports with the schema angle -> "NSWE" and sort by x and y.

Parameters:

Name Type Description Default
rename_func Callable[..., None] | None

Function that takes Iterable[Port] and renames them. This can of course contain a filter and only rename some of the ports

None
Source code in kfactory/kcell.py
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
def auto_rename_ports(self, rename_func: Callable[..., None] | None = None) -> None:
    """Rename the ports with the schema angle -> "NSWE" and sort by x and y.

    Args:
        rename_func: Function that takes Iterable[Port] and renames them.
            This can of course contain a filter and only rename some of the ports
    """
    if self.locked:
        raise LockedError(self)
    if rename_func is None:
        self.kcl.rename_function(self.ports)
    else:
        rename_func(self.ports)

draw_ports

draw_ports() -> None

Draw all the ports on their respective layer.

Source code in kfactory/kcell.py
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
def draw_ports(self) -> None:
    """Draw all the ports on their respective layer."""
    polys: dict[float, kdb.DPolygon] = {}

    for port in self.ports:
        w = port.width

        if w in polys:
            poly = polys[w]
        else:
            if w < 2:
                poly = kdb.DPolygon(
                    [
                        kdb.DPoint(0, -w / 2),
                        kdb.DPoint(0, w / 2),
                        kdb.DPoint(w / 2, 0),
                    ]
                )
            else:
                poly = kdb.DPolygon(
                    [
                        kdb.DPoint(0, -w / 2),
                        kdb.DPoint(0, w / 2),
                        kdb.DPoint(w / 2, 0),
                        kdb.DPoint(w * 19 / 20, 0),
                        kdb.DPoint(w / 20, w * 9 / 20),
                        kdb.DPoint(w / 20, -w * 9 / 20),
                        kdb.DPoint(w * 19 / 20, 0),
                        kdb.DPoint(w / 2, 0),
                    ]
                )
            polys[w] = poly
        self.shapes(port.layer).insert(poly.transformed(port.dcplx_trans))
        self.shapes(port.layer).insert(kdb.Text(port.name or "", port.trans))

dup

dup(new_name: str | None = None) -> Self

Copy the full cell.

Removes lock if the original cell was locked.

Returns:

Name Type Description
cell Self

Exact copy of the current cell. The name will have $1 as duplicate names are not allowed

Source code in kfactory/kcell.py
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
def dup(self, new_name: str | None = None) -> Self:
    """Copy the full cell.

    Removes lock if the original cell was locked.

    Returns:
        cell: Exact copy of the current cell.
            The name will have `$1` as duplicate names are not allowed
    """
    c = self.__class__(
        kcl=self.kcl, name=new_name or self.name + "$1" if self.name else None
    )
    c.ports = DPorts(kcl=self.kcl, ports=self.ports.copy())

    c.settings = self.settings.model_copy()
    c.settings_units = self.settings_units.model_copy()
    c.info = self._base.info.model_copy()
    for layer, shapes in self.shapes().items():
        for shape in shapes:
            c.shapes(layer).insert(shape)
    c._base.vinsts = self._base.vinsts.dup()

    return c

l2n

l2n(
    port_types: Iterable[str] = ("optical",),
) -> tuple[KCell, kdb.LayoutToNetlist]

Generate a LayoutToNetlist object from the port types.

Parameters:

Name Type Description Default
port_types Iterable[str]

The port types to consider for the netlist extraction.

('optical',)
Source code in kfactory/kcell.py
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
def l2n(
    self, port_types: Iterable[str] = ("optical",)
) -> tuple[KCell, kdb.LayoutToNetlist]:
    """Generate a LayoutToNetlist object from the port types.

    Args:
        port_types: The port types to consider for the netlist extraction.
    """
    c = self.kcl.kcell()
    if self.name is not None:
        c.name = self.name
    c.settings = self.settings
    c.settings_units = self.settings_units
    c.info = self.info
    VInstance(self).insert_into(c)
    return c, c.l2n()

plot

plot() -> None

Display cell.

Usage: Pass the vkcell variable as an argument in the cell at the end

Source code in kfactory/kcell.py
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
def plot(self) -> None:
    """Display cell.

    Usage: Pass the vkcell variable as an argument in the cell at the end
    """
    from .widgets.interactive import display_kcell

    c = self.kcl.kcell()
    if self.name is not None:
        c.name = self.name
    VInstance(self).insert_into_flat(c, levels=0)

    display_kcell(c)
    c.delete()

show

show(
    lyrdb: ReportDatabase | Path | str | None = None,
    l2n: LayoutToNetlist | Path | str | None = None,
    keep_position: bool = True,
    save_options: SaveLayoutOptions | None = None,
    use_libraries: bool = True,
    library_save_options: SaveLayoutOptions | None = None,
    technology: str | None = None,
) -> None

Stream the gds to klive.

Will create a temporary file of the gds and load it in KLayout via klive

Source code in kfactory/kcell.py
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
def show(
    self,
    lyrdb: rdb.ReportDatabase | Path | str | None = None,
    l2n: kdb.LayoutToNetlist | Path | str | None = None,
    keep_position: bool = True,
    save_options: kdb.SaveLayoutOptions | None = None,
    use_libraries: bool = True,
    library_save_options: kdb.SaveLayoutOptions | None = None,
    technology: str | None = None,
) -> None:
    """Stream the gds to klive.

    Will create a temporary file of the gds and load it in KLayout via klive
    """
    if save_options is None:
        save_options = save_layout_options()
    if library_save_options is None:
        library_save_options = save_layout_options()
    c = self.kcl.kcell()
    if self.name is not None:
        c.name = self.name
    VInstance(self).insert_into_flat(c, levels=0)
    c.add_ports(self.ports)
    c.info = self.info.model_copy()
    c.base.settings = self.settings.model_copy()

    kwargs: dict[str, Any] = {}
    if technology is not None:
        kwargs["technology"] = technology
    if l2n is not None:
        kwargs["l2n"] = l2n
    if lyrdb is not None:
        kwargs["lyrdb"] = lyrdb

    c.show(keep_position=keep_position, **kwargs)

write

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

Write a KCell to a GDS.

See KCLayout.write for more info.

Source code in kfactory/kcell.py
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
def write(
    self,
    filename: str | Path,
    save_options: kdb.SaveLayoutOptions | None = None,
    convert_external_cells: bool = False,
    set_meta_data: bool = True,
    autoformat_from_file_extension: bool = True,
) -> None:
    """Write a KCell to a GDS.

    See [KCLayout.write][kfactory.layout.KCLayout.write] for more info.
    """
    if save_options is None:
        save_options = save_layout_options()
    c = self.kcl.kcell()
    if self.name is not None:
        c.name = self.name
    c.settings = self.settings
    c.settings_units = self.settings_units
    c.info = self.info
    VInstance(self).insert_into_flat(c, levels=1)

    c.write(
        filename=filename,
        save_options=save_options,
        convert_external_cells=convert_external_cells,
        set_meta_data=set_meta_data,
        autoformat_from_file_extension=autoformat_from_file_extension,
    )

get_cells

get_cells(
    modules: Iterable[ModuleType], verbose: bool = False
) -> dict[str, Callable[..., KCell]]

Returns KCells (KCell functions) from a module or list of modules.

Parameters:

Name Type Description Default
modules Iterable[ModuleType]

module or iterable of modules.

required
verbose bool

prints in case any errors occur.

False
Source code in kfactory/kcell.py
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
def get_cells(
    modules: Iterable[ModuleType], verbose: bool = False
) -> dict[str, Callable[..., KCell]]:
    """Returns KCells (KCell functions) from a module or list of modules.

    Args:
        modules: module or iterable of modules.
        verbose: prints in case any errors occur.
    """
    cells: dict[str, Callable[..., KCell]] = {}
    for module in modules:
        for t in inspect.getmembers(module):
            if callable(t[1]) and t[0] != "partial":
                try:
                    r = inspect.signature(t[1]).return_annotation
                    if r == KCell or (isinstance(r, str) and r.endswith("KCell")):
                        cells[t[0]] = t[1]
                except ValueError:
                    if verbose:
                        logger.error(f"error in {t[0]}")
    return cells

show

show(
    layout: KCLayout | AnyKCell | Path | str,
    lyrdb: ReportDatabase | Path | str | None = None,
    l2n: LayoutToNetlist | Path | str | None = None,
    technology: str | None = None,
    keep_position: bool = True,
    save_options: SaveLayoutOptions | None = None,
    use_libraries: bool = True,
    library_save_options: SaveLayoutOptions | None = None,
    set_technology: bool = True,
    file_format: Literal["oas", "gds"] = "oas",
    markers: list[tuple[DShapeLike, MarkerConfig]]
    | None = None,
) -> None

Show GDS in klayout.

Parameters:

Name Type Description Default
layout KCLayout | AnyKCell | Path | str

The object to show. This can be a KCell, KCLayout, Path, or string.

required
lyrdb ReportDatabase | Path | str | None

A KLayout report database (.lyrdb/.rdb) file or object to show with the layout.

None
l2n LayoutToNetlist | Path | str | None

A KLayout LayoutToNetlist object or file (.l2n) to show with the layout.

None
keep_position bool

Keep the current KLayout position if a view is already open.

True
save_options SaveLayoutOptions | None

Custom options for saving the gds/oas.

None
use_libraries bool

Save other KCLayouts as libraries on write.

True
library_save_options SaveLayoutOptions | None

Specific saving options for Cells which are in a library and not the main KCLayout.

None
markers list[tuple[DShapeLike, MarkerConfig]] | None

lay.Marker list

None
Source code in kfactory/kcell.py
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
def show(
    layout: KCLayout | AnyKCell | Path | str,
    lyrdb: rdb.ReportDatabase | Path | str | None = None,
    l2n: kdb.LayoutToNetlist | Path | str | None = None,
    technology: str | None = None,
    keep_position: bool = True,
    save_options: kdb.SaveLayoutOptions | None = None,
    use_libraries: bool = True,
    library_save_options: kdb.SaveLayoutOptions | None = None,
    set_technology: bool = True,
    file_format: Literal["oas", "gds"] = "oas",
    markers: list[tuple[DShapeLike, MarkerConfig]] | None = None,
) -> None:
    """Show GDS in klayout.

    Args:
        layout: The object to show. This can be a KCell, KCLayout, Path, or string.
        lyrdb: A KLayout report database (.lyrdb/.rdb) file or object to show with the
            layout.
        l2n: A KLayout LayoutToNetlist object or file (.l2n) to show with the layout.
        keep_position: Keep the current KLayout position if a view is already open.
        save_options: Custom options for saving the gds/oas.
        use_libraries: Save other KCLayouts as libraries on write.
        library_save_options: Specific saving options for Cells which are in a library
            and not the main KCLayout.
        markers: lay.Marker list
    """
    from .layout import KCLayout, kcls

    delete = False
    delete_lyrdb = False
    delete_l2n = False

    if save_options is None:
        save_options = save_layout_options()
    if library_save_options is None:
        library_save_options = save_layout_options()

    # Find the file that calls stack
    try:
        stk = inspect.getouterframes(inspect.currentframe())
        frame = stk[2]
        frame_filename_stem = Path(frame.filename).stem
        if frame_filename_stem.startswith("<ipython-input"):  # IPython Case
            name = "ipython"
        elif frame.function != "<module>":
            name = clean_name(frame_filename_stem + "_" + frame.function)
        else:
            name = clean_name(frame_filename_stem)
    except Exception:
        try:
            from __main__ import __file__ as mf

            name = clean_name(mf)
        except ImportError:
            name = "shell"

    # Append name (and hash) for unique file paths
    if isinstance(layout, KCLayout) and layout.name:
        name += f"_{clean_name(layout.name)}"
    elif isinstance(layout, ProtoKCell) and layout.name:
        if basename := layout.basename or layout.function_name:
            name += f"_{clean_name(basename)}"
        name += f"_{cell_name_hash(layout.name)}"

    kcl_paths: list[dict[str, str]] = []

    if isinstance(layout, KCLayout):
        tf, delete = get_build_path(name, "mask", file_format)
        layout.write(str(tf), save_options)
        file = tf
        if use_libraries:
            dir_ = tf.parent
            kcls_ = list(kcls.values())
            kcls_.remove(layout)
            for _kcl in kcls_:
                if save_options.gds2_max_cellname_length:
                    p = (
                        (dir_ / _kcl.name[: save_options.gds2_max_cellname_length])
                        .with_suffix(f".{file_format}")
                        .resolve()
                    )
                else:
                    p = (dir_ / _kcl.name).with_suffix(f".{file_format}").resolve()
                _kcl.write(p, library_save_options)
                kcl_paths.append({"name": _kcl.name, "file": _klive_path(p)})
        if technology is None and layout.technology_file is not None:
            technology = layout.technology.name

    elif isinstance(layout, ProtoKCell):
        tf, delete = get_build_path(name, file_format, file_format)
        layout.write(str(tf), save_options)
        file = tf
        if use_libraries:
            dir_ = tf.parent
            kcls_ = list(kcls.values())
            kcls_.remove(layout.kcl)
            for _kcl in kcls_:
                p = (dir_ / _kcl.name).with_suffix(f".{file_format}").resolve()
                _kcl.write(p, library_save_options)
                kcl_paths.append({"name": _kcl.name, "file": _klive_path(p)})
        if technology is None and layout.kcl.technology_file is not None:
            technology = layout.kcl.technology.name

    elif isinstance(layout, str | Path):
        file = Path(layout).expanduser().resolve()
    else:
        raise NotImplementedError(
            f"Unknown type {type(layout)} for streaming to KLayout"
        )
    if not file.is_file():
        raise ValueError(f"{file} is not a File")
    logger.debug("klive file: {}", file)
    data_dict: JSONSerializable = {
        "gds": _klive_path(file),
        "keep_position": keep_position,
        "libraries": kcl_paths,
    }

    if lyrdb is not None:
        if isinstance(lyrdb, rdb.ReportDatabase):
            tf, delete_lyrdb = get_build_path(name, "mask", "lyrdb")
            lyrdb.save(str(tf))
            lyrdbfile = tf
        elif isinstance(lyrdb, str | Path):
            lyrdbfile = Path(lyrdb).expanduser().resolve()
        else:
            raise NotImplementedError(
                f"Unknown type {type(lyrdb)} for streaming to KLayout"
            )
        if not lyrdbfile.is_file():
            raise ValueError(f"{lyrdbfile} is not a File")
        data_dict["lyrdb"] = _klive_path(lyrdbfile)

    if l2n is not None:
        if isinstance(l2n, kdb.LayoutToNetlist):
            tf, delete_l2n = get_build_path(name, "mask", "l2n")
            l2n.write(str(tf))
            l2nfile = tf
        elif isinstance(l2n, str | Path):
            l2nfile = Path(l2n).expanduser().resolve()
        else:
            raise NotImplementedError(
                f"Unknown type {type(l2n)} for streaming to KLayout"
            )
        if not l2nfile.is_file():
            raise ValueError(f"{lyrdbfile} is not a File")
        data_dict["l2n"] = _klive_path(l2nfile)

    if set_technology and technology is not None:
        data_dict["technology"] = technology

    if markers:
        json_markers: list[tuple[str, str, MarkerConfig]] = []
        for marker_shape, marker_config in markers:
            json_markers.append(
                (marker_shape.__class__.__name__, marker_shape.to_s(), marker_config)
            )
        data_dict["markers"] = json_markers  # ty:ignore[invalid-assignment]

    data = json.dumps(data_dict)
    try:
        conn = socket.create_connection(("127.0.0.1", 8082), timeout=0.5)
        data += "\n"
        enc_data = data.encode()
        conn.sendall(enc_data)
        conn.settimeout(5)
    except OSError:
        logger.warning("Could not connect to klive server")
    else:
        msg = ""
        try:
            msg = conn.recv(1024).decode("utf-8")
            try:
                jmsg = json.loads(msg)
                match jmsg["type"]:
                    case "open":
                        info = jmsg.get("info")
                        if info:
                            (
                                logger.info(
                                    "klive v{version}: Opened file '{file}'"
                                    ", Messages: {info}",
                                    version=jmsg["version"],
                                    file=jmsg["file"],
                                    info=info,
                                ),
                            )
                        else:
                            logger.info(
                                "klive v{version}: Opened file '{file}'",
                                version=jmsg["version"],
                                file=jmsg["file"],
                            )
                    case "reload":
                        info = jmsg.get("info")
                        if info:
                            logger.info(
                                "klive v{version}: Reloaded file '{file}'"
                                ", Messages: {info}",
                                version=jmsg["version"],
                                file=jmsg["file"],
                                info=info,
                            )
                        else:
                            logger.info(
                                "klive v{version}: Reloaded file '{file}'",
                                version=jmsg["version"],
                                file=jmsg["file"],
                            )
                # check klive version
                klive_version = Version.parse(jmsg["version"])
                rec_klive_version = Version(major=0, minor=4, patch=1)
                klive_ok = rec_klive_version.compare(klive_version) >= 0

                if not klive_ok:
                    logger.warning(
                        f"klive is out of date. Installed:{jmsg['version']}/"
                        "Recommended:"
                        f"{rec_klive_version}. Please "
                        "update it in KLayout"
                    )
                else:
                    klayout_version = Version.parse(jmsg["klayout_version"])
                    kfactory_version = Version.parse(_klayout_version)

                    min_rec_klayout = Version(major=0, minor=28, patch=13)

                    if kfactory_version.compare(min_rec_klayout) < 0:
                        logger.error(
                            f"KLayout GUI version ({jmsg['klayout_version']}) "
                            "is older than the Python version "
                            f"({_klayout_version}). This may cause issues. Please "
                            "update the GUI to match or exceed the Python version."
                        )
                    elif kfactory_version.compare(klayout_version) < 0:
                        logger.debug(
                            f"KLayout GUI version ({jmsg['klayout_version']}) "
                            "is older than the Python version "
                            f"({_klayout_version}). This may cause issues. Please "
                            "update the GUI to match or exceed the Python version."
                        )

            except json.JSONDecodeError:
                logger.info(f"Message from klive: {msg}")
        except OSError:
            logger.warning("klive didn't send data, closing")
        finally:
            conn.close()

    if delete:
        Path(file).unlink()
    if delete_lyrdb and lyrdb is not None:
        Path(lyrdbfile).unlink()
    if delete_l2n and l2n is not None:
        Path(l2nfile).unlink()