Skip to content

Instance

instance

DInstance

Bases: ProtoTInstance[float], UMGeometricObject

An Instance of a KCell.

An Instance is a reference to a KCell with a transformation.

Attributes:

Name Type Description
_instance

The internal kdb.Instance reference

ports DInstancePorts

Transformed ports of the KCell

kcl

Pointer to the layout object holding the instance

d

Helper that allows retrieval of instance information in um

Source code in kfactory/instance.py
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
class DInstance(ProtoTInstance[float], UMGeometricObject):
    """An Instance of a KCell.

    An Instance is a reference to a KCell with a transformation.

    Attributes:
        _instance: The internal `kdb.Instance` reference
        ports: Transformed ports of the KCell
        kcl: Pointer to the layout object holding the instance
        d: Helper that allows retrieval of instance information in um
    """

    yaml_tag: ClassVar[str] = "!Instance"

    def __init__(self, kcl: KCLayout, instance: kdb.Instance) -> None:
        """Create an instance from a KLayout Instance."""
        self.kcl = kcl
        self._instance = instance

    @functools.cached_property
    def ports(self) -> DInstancePorts:
        """Gets the transformed ports of the KCell."""
        from .instance_ports import DInstancePorts

        return DInstancePorts(self)

    @functools.cached_property
    def pins(self) -> DInstancePins:
        """Gets the transformed ports of the KCell."""
        from .instance_pins import DInstancePins

        return DInstancePins(self)

    @property
    def cell(self) -> DKCell:
        """Parent KCell  of the Instance."""
        return self.kcl.dkcells[self.cell_index]

    @cell.setter
    def cell(self, value: ProtoTKCell[Any]) -> None:
        self.cell_index = value.cell_index()

    @property
    def parent_cell(self) -> DKCell:
        """Gets the cell this instance is contained in."""
        return self.kcl.dkcells[self._instance.parent_cell.cell_index()]

    @parent_cell.setter
    def parent_cell(self, cell: KCell | DKCell | kdb.Cell) -> None:
        if isinstance(cell, KCell | DKCell):
            self.parent_cell.insts.remove(
                Instance(kcl=self.kcl, instance=self._instance)
            )
            self._instance.parent_cell = cell.kdb_cell
        else:
            self.parent_cell.insts.remove(
                Instance(kcl=self.kcl, instance=self._instance)
            )
            self._instance.parent_cell = cell

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

        The key can either be an integer, in which case the nth port is
        returned, or a string in which case the first port with a matching
        name is returned.

        If the instance is an array, the key can also be a tuple in the
        form of `c.ports[key_name, i_a, i_b]`, where `i_a` is the index in
        the `instance.a` direction and `i_b` the `instance.b` direction.

        E.g. `c.ports["a", 3, 5]`, accesses the ports of the instance which is
        3 times in `a` direction (4th index in the array), and 5 times in `b` direction
        (5th index in the array).
        """
        return DPort(base=self.ports[key].base)

cell property writable

cell: DKCell

Parent KCell of the Instance.

kcl instance-attribute

kcl = kcl

KCLayout object.

parent_cell property writable

parent_cell: DKCell

Gets the cell this instance is contained in.

pins cached property

pins: DInstancePins

Gets the transformed ports of the KCell.

ports cached property

ports: DInstancePorts

Gets the transformed ports of the KCell.

__getitem__

__getitem__(
    key: int
    | str
    | tuple[int | str | None, int, int]
    | None,
) -> DPort

Returns port from instance.

The key can either be an integer, in which case the nth port is returned, or a string in which case the first port with a matching name is returned.

If the instance is an array, the key can also be a tuple in the form of c.ports[key_name, i_a, i_b], where i_a is the index in the instance.a direction and i_b the instance.b direction.

E.g. c.ports["a", 3, 5], accesses the ports of the instance which is 3 times in a direction (4th index in the array), and 5 times in b direction (5th index in the array).

Source code in kfactory/instance.py
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
def __getitem__(
    self, key: int | str | tuple[int | str | None, int, int] | None
) -> DPort:
    """Returns port from instance.

    The key can either be an integer, in which case the nth port is
    returned, or a string in which case the first port with a matching
    name is returned.

    If the instance is an array, the key can also be a tuple in the
    form of `c.ports[key_name, i_a, i_b]`, where `i_a` is the index in
    the `instance.a` direction and `i_b` the `instance.b` direction.

    E.g. `c.ports["a", 3, 5]`, accesses the ports of the instance which is
    3 times in `a` direction (4th index in the array), and 5 times in `b` direction
    (5th index in the array).
    """
    return DPort(base=self.ports[key].base)

__init__

__init__(kcl: KCLayout, instance: Instance) -> None

Create an instance from a KLayout Instance.

Source code in kfactory/instance.py
595
596
597
598
def __init__(self, kcl: KCLayout, instance: kdb.Instance) -> None:
    """Create an instance from a KLayout Instance."""
    self.kcl = kcl
    self._instance = instance

Instance

Bases: ProtoTInstance[int], DBUGeometricObject

An Instance of a KCell.

An Instance is a reference to a KCell with a transformation.

Attributes:

Name Type Description
_instance

The internal kdb.Instance reference

ports InstancePorts

Transformed ports of the KCell

kcl

Pointer to the layout object holding the instance

d

Helper that allows retrieval of instance information in um

Source code in kfactory/instance.py
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
class Instance(ProtoTInstance[int], DBUGeometricObject):
    """An Instance of a KCell.

    An Instance is a reference to a KCell with a transformation.

    Attributes:
        _instance: The internal `kdb.Instance` reference
        ports: Transformed ports of the KCell
        kcl: Pointer to the layout object holding the instance
        d: Helper that allows retrieval of instance information in um
    """

    yaml_tag: ClassVar[str] = "!Instance"

    def __init__(self, kcl: KCLayout, instance: kdb.Instance) -> None:
        """Create an instance from a KLayout Instance."""
        self.kcl = kcl
        self._instance = instance

    @functools.cached_property
    def ports(self) -> InstancePorts:
        """Gets the transformed ports of the KCell."""
        from .instance_ports import InstancePorts

        return InstancePorts(self)

    @functools.cached_property
    def pins(self) -> InstancePins:
        """Gets the transformed pins of the KCell."""
        from .instance_pins import InstancePins

        return InstancePins(self)

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

        The key can either be an integer, in which case the nth port is
        returned, or a string in which case the first port with a matching
        name is returned.

        If the instance is an array, the key can also be a tuple in the
        form of `c.ports[key_name, i_a, i_b]`, where `i_a` is the index in
        the `instance.a` direction and `i_b` the `instance.b` direction.

        E.g. `c.ports["a", 3, 5]`, accesses the ports of the instance which is
        3 times in `a` direction (4th index in the array), and 5 times in `b` direction
        (5th index in the array).
        """
        return Port(base=self.ports[key].base)

    @property
    def parent_cell(self) -> KCell:
        """Gets the cell this instance is contained in."""
        return self.kcl[self._instance.parent_cell.cell_index()]

    @parent_cell.setter
    def parent_cell(self, cell: KCell | DKCell | kdb.Cell) -> None:
        if isinstance(cell, KCell | DKCell):
            self.parent_cell.insts.remove(self)
            self._instance.parent_cell = cell.kdb_cell
        else:
            self._instance.parent_cell = cell

    @property
    def cell(self) -> KCell:
        """Parent KCell of the Instance."""
        return self.kcl.kcells[self.cell_index]

    @cell.setter
    def cell(self, value: ProtoTKCell[Any]) -> None:
        self.cell_index = value.cell_index()

    @classmethod
    def to_yaml(cls, representer: BaseRepresenter, node: Self) -> MappingNode:
        """Convert the instance to a yaml representation."""
        d = {
            "cellname": node.cell.name,
            "trans": node._base.trans,
            "dcplx_trans": node._base.dcplx_trans,
        }
        return representer.represent_mapping(cls.yaml_tag, d)

cell property writable

cell: KCell

Parent KCell of the Instance.

kcl instance-attribute

kcl = kcl

KCLayout object.

parent_cell property writable

parent_cell: KCell

Gets the cell this instance is contained in.

pins cached property

pins: InstancePins

Gets the transformed pins of the KCell.

ports cached property

ports: InstancePorts

Gets the transformed ports of the KCell.

__getitem__

__getitem__(
    key: int
    | str
    | tuple[int | str | None, int, int]
    | None,
) -> Port

Returns port from instance.

The key can either be an integer, in which case the nth port is returned, or a string in which case the first port with a matching name is returned.

If the instance is an array, the key can also be a tuple in the form of c.ports[key_name, i_a, i_b], where i_a is the index in the instance.a direction and i_b the instance.b direction.

E.g. c.ports["a", 3, 5], accesses the ports of the instance which is 3 times in a direction (4th index in the array), and 5 times in b direction (5th index in the array).

Source code in kfactory/instance.py
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
def __getitem__(
    self, key: int | str | tuple[int | str | None, int, int] | None
) -> Port:
    """Returns port from instance.

    The key can either be an integer, in which case the nth port is
    returned, or a string in which case the first port with a matching
    name is returned.

    If the instance is an array, the key can also be a tuple in the
    form of `c.ports[key_name, i_a, i_b]`, where `i_a` is the index in
    the `instance.a` direction and `i_b` the `instance.b` direction.

    E.g. `c.ports["a", 3, 5]`, accesses the ports of the instance which is
    3 times in `a` direction (4th index in the array), and 5 times in `b` direction
    (5th index in the array).
    """
    return Port(base=self.ports[key].base)

__init__

__init__(kcl: KCLayout, instance: Instance) -> None

Create an instance from a KLayout Instance.

Source code in kfactory/instance.py
510
511
512
513
def __init__(self, kcl: KCLayout, instance: kdb.Instance) -> None:
    """Create an instance from a KLayout Instance."""
    self.kcl = kcl
    self._instance = instance

to_yaml classmethod

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

Convert the instance to a yaml representation.

Source code in kfactory/instance.py
570
571
572
573
574
575
576
577
578
@classmethod
def to_yaml(cls, representer: BaseRepresenter, node: Self) -> MappingNode:
    """Convert the instance to a yaml representation."""
    d = {
        "cellname": node.cell.name,
        "trans": node._base.trans,
        "dcplx_trans": node._base.dcplx_trans,
    }
    return representer.represent_mapping(cls.yaml_tag, d)

ProtoInstance

Bases: GeometricObject[T]

Base class for instances.

Source code in kfactory/instance.py
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
class ProtoInstance[T: (int, float)](GeometricObject[T]):
    """Base class for instances."""

    _kcl: KCLayout
    na: int
    nb: int
    a: kdb.Vector | kdb.DVector
    b: kdb.Vector | kdb.DVector

    @property
    def kcl(self) -> KCLayout:
        """KCLayout object."""
        return self._kcl

    @kcl.setter
    def kcl(self, val: KCLayout) -> None:
        self._kcl = val

    @property
    @abstractmethod
    def name(self) -> str | None:
        """Name of the instance."""

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

    @property
    @abstractmethod
    def cell_name(self) -> str | None:
        """Name of the cell the instance refers to."""

    @abstractmethod
    def __getitem__(
        self, key: int | str | tuple[int | str | None, int, int] | None
    ) -> ProtoPort[T]: ...
    @property
    @abstractmethod
    def ports(self) -> ProtoInstancePorts[T, ProtoInstance[T]]: ...

cell_name abstractmethod property

cell_name: str | None

Name of the cell the instance refers to.

kcl property writable

kcl: KCLayout

KCLayout object.

name abstractmethod property writable

name: str | None

Name of the instance.

ProtoTInstance

Bases: ProtoInstance[T]

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

    @property
    def instance(self) -> kdb.Instance:
        return self._instance

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

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

    @property
    def cell_name(self) -> str:
        return self._instance.cell.name

    def to_itype(self) -> Instance:
        return Instance(kcl=self.kcl, instance=self._instance)

    def to_dtype(self) -> DInstance:
        return DInstance(kcl=self.kcl, instance=self._instance)

    def __getattr__(self, name: str) -> Any:
        """If we don't have an attribute, get it from the instance."""
        try:
            return super().__getattr__(name)  # ty:ignore[unresolved-attribute]
        except Exception:
            return getattr(self._instance, name)

    def is_named(self) -> bool:
        return self.instance.property(PROPID.NAME) is not None

    @property
    def name(self) -> str:
        """Name of instance in GDS."""
        prop = self.instance.property(PROPID.NAME)
        if prop is not None:
            return str(prop)
        name = f"{self.cell.name}_{self.trans.disp.x}_{self.trans.disp.y}"
        if self.cplx_trans.angle != 0:
            if self.cplx_trans.angle.is_integer():
                name += f"_A{int(self.cplx_trans.angle)}"
            else:
                name += f"_A{str(self.cplx_trans.angle).replace('.', 'p')}"
        if self.cplx_trans.is_mirror():
            name += "_M"
        return name

    @name.setter
    def name(self, value: str | None) -> None:
        self.instance.set_property(PROPID.NAME, value)

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

    @property
    def purpose(self) -> str | None:
        """Purpose value of instance in GDS."""
        return self._instance.property(PROPID.PURPOSE)

    @purpose.setter
    def purpose(self, value: str | None) -> None:
        self._instance.set_property(PROPID.PURPOSE, value)

    @property
    def cell_index(self) -> int:
        """Get the index of the cell this instance refers to."""
        return self._instance.cell_index

    @cell_index.setter
    def cell_index(self, value: int) -> None:
        self._instance.cell_index = value

    @property
    @abstractmethod
    def cell(self) -> ProtoTKCell[T]:
        """Parent KCell  of the Instance."""
        ...

    @cell.setter
    @abstractmethod
    def cell(self, value: ProtoTKCell[Any]) -> None: ...

    @property
    @abstractmethod
    def ports(self) -> ProtoTInstancePorts[T]:
        """Ports of the instance."""
        ...

    @property
    @abstractmethod
    def pins(self) -> ProtoTInstancePins[T]:
        """Ports of the instance."""
        ...

    @property
    def a(self) -> kdb.Vector:
        """Returns the displacement vector for the 'a' axis."""
        return self._instance.a

    @a.setter
    def a(self, vec: kdb.Vector | kdb.DVector) -> None:
        self._instance.a = vec  # ty:ignore[invalid-assignment]

    @property
    def b(self) -> kdb.Vector:
        """Returns the displacement vector for the 'b' axis."""
        return self._instance.b

    @b.setter
    def b(self, vec: kdb.Vector | kdb.DVector) -> None:
        self._instance.b = vec  # ty:ignore[invalid-assignment]

    @property
    def cell_inst(self) -> kdb.CellInstArray:
        """Gets the basic CellInstArray object associated with this instance."""
        return self._instance.cell_inst

    @cell_inst.setter
    def cell_inst(self, cell_inst: kdb.CellInstArray | kdb.DCellInstArray) -> None:
        self._instance.cell_inst = cell_inst  # ty:ignore[invalid-assignment]

    @property
    def cplx_trans(self) -> kdb.ICplxTrans:
        """Gets the complex transformation of the instance.

        Or the first instance in the array.
        """
        return self._instance.cplx_trans

    @cplx_trans.setter
    def cplx_trans(self, trans: kdb.ICplxTrans | kdb.DCplxTrans) -> None:
        self._instance.cplx_trans = trans  # ty:ignore[invalid-assignment]

    @property
    def dcplx_trans(self) -> kdb.DCplxTrans:
        """Gets the complex transformation of the instance.

        Or the first instance in the array.
        """
        return self._instance.dcplx_trans

    @dcplx_trans.setter
    def dcplx_trans(self, trans: kdb.DCplxTrans) -> None:
        self._instance.dcplx_trans = trans

    @property
    def dtrans(self) -> kdb.DTrans:
        """Gets the complex transformation of the instance.

        Or the first instance in the array.
        """
        return self._instance.dtrans

    @dtrans.setter
    def dtrans(self, trans: kdb.DTrans) -> None:
        self._instance.dtrans = trans

    @property
    def trans(self) -> kdb.Trans:
        """Gets the complex transformation of the instance.

        Or the first instance in the array.
        """
        return self._instance.trans

    @trans.setter
    def trans(self, trans: kdb.Trans | kdb.DTrans) -> None:
        self._instance.trans = trans  # ty:ignore[invalid-assignment]

    @property
    def na(self) -> int:
        """Returns the displacement vector for the 'a' axis."""
        return self._instance.na

    @na.setter
    def na(self, value: int) -> None:
        self._instance.na = value

    @property
    def nb(self) -> int:
        """Returns the number of instances in the 'b' axis."""
        return self._instance.nb

    @nb.setter
    def nb(self, value: int) -> None:
        self._instance.nb = value

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

    @prop_id.setter
    def prop_id(self, value: int) -> None:
        self._instance.prop_id = value

    @property
    def hash(self) -> bytes:
        """Hash the instance."""
        h = sha3_512()
        h.update(self.cell.hash())
        if not self.is_complex():
            h.update(self.trans.hash().to_bytes(8, "big"))
        else:
            h.update(self.dcplx_trans.hash().to_bytes(8, "big"))
        return h.digest()

    @overload
    def connect(
        self,
        port: str | ProtoPort[Any] | None,
        other: ProtoPort[Any],
        *,
        mirror: bool = False,
        allow_width_mismatch: bool | None = None,
        allow_layer_mismatch: bool | None = None,
        allow_type_mismatch: bool | None = None,
        use_mirror: bool | None = None,
        use_angle: bool | None = None,
    ) -> Self: ...

    @overload
    def connect(
        self,
        port: str | ProtoPort[Any] | None,
        other: ProtoTInstance[Any],
        other_port_name: str | int | tuple[int | str, int, int] | None,
        *,
        mirror: bool = False,
        allow_width_mismatch: bool | None = None,
        allow_layer_mismatch: bool | None = None,
        allow_type_mismatch: bool | None = None,
        use_mirror: bool | None = None,
        use_angle: bool | None = None,
    ) -> Self: ...

    @overload
    def connect(
        self,
        port: str | ProtoPort[Any] | None,
        other: VInstance,
        other_port_name: str | int | None,
        *,
        mirror: bool = False,
        allow_width_mismatch: bool | None = None,
        allow_layer_mismatch: bool | None = None,
        allow_type_mismatch: bool | None = None,
        use_mirror: bool | None = None,
        use_angle: bool | None = None,
    ) -> Self: ...

    def connect(
        self,
        port: str | ProtoPort[Any] | None,
        other: ProtoInstance[Any] | ProtoPort[Any],
        other_port_name: str | int | tuple[int | str, int, int] | None = None,
        *,
        mirror: bool = False,
        allow_width_mismatch: bool | None = None,
        allow_layer_mismatch: bool | None = None,
        allow_type_mismatch: bool | None = None,
        use_mirror: bool | None = None,
        use_angle: bool | None = None,
    ) -> Self:
        """Align port with name `portname` to a port.

        Function to allow to transform this instance so that a port of this instance is
        connected (same center with 180° turn) to another instance.

        Args:
            port: The name of the port of this instance to be connected, or directly an
                instance port. Can be `None` because port names can be `None`.
            other: The other instance or a port. Skip `other_port_name` if it's a port.
            other_port_name: The name of the other port. Ignored if
                `other` is a port.
            mirror: Instead of applying klayout.db.Trans.R180 as a connection
                transformation, use klayout.db.Trans.M90, which effectively means this
                instance will be mirrored and connected.
            allow_width_mismatch: Skip width check between the ports if set.
            allow_layer_mismatch: Skip layer check between the ports if set.
            allow_type_mismatch: Skip port_type check between the ports if set.
            use_mirror: If False mirror flag does not get applied from the connection.
            use_angle: If False the angle does not get applied from the connection.
        """
        if allow_width_mismatch is None:
            allow_width_mismatch = config.allow_width_mismatch
        if allow_layer_mismatch is None:
            allow_layer_mismatch = config.allow_layer_mismatch
        if allow_type_mismatch is None:
            allow_type_mismatch = config.allow_type_mismatch
        if use_mirror is None:
            use_mirror = config.connect_use_mirror
        if use_angle is None:
            use_angle = config.connect_use_angle

        if isinstance(other, ProtoPort):
            op = Port(base=other.base)
        else:
            if other_port_name is None:
                raise ValueError(
                    "portname cannot be None if an Instance Object is given. For"
                    "complex connections (non-90 degree and floating point ports) use"
                    "route_cplx instead"
                )
            op = Port(base=other.ports[other_port_name].base)  # ty:ignore[invalid-argument-type]
        if isinstance(port, ProtoPort):
            p = Port(base=port.base.transformed(self.dcplx_trans.inverted()))
        else:
            p = Port(base=self.cell.ports[port].base)

        assert isinstance(p, Port)
        assert isinstance(op, Port)

        if p.width != op.width and not allow_width_mismatch:
            raise PortWidthMismatchError(self, other, p, op)
        if p.layer != op.layer and not allow_layer_mismatch:
            raise PortLayerMismatchError(self.cell.kcl, self, other, p, op)
        if p.port_type != op.port_type and not allow_type_mismatch:
            raise PortTypeMismatchError(self, other, p, op)
        if p.base.dcplx_trans or op.base.dcplx_trans:
            dconn_trans = kdb.DCplxTrans.M90 if mirror else kdb.DCplxTrans.R180
            match (use_mirror, use_angle):
                case True, True:
                    dcplx_trans = (
                        op.dcplx_trans * dconn_trans * p.dcplx_trans.inverted()
                    )
                    self._instance.dcplx_trans = dcplx_trans
                case False, True:
                    dconn_trans = (
                        kdb.DCplxTrans.M90
                        if mirror ^ self.dcplx_trans.mirror
                        else kdb.DCplxTrans.R180
                    )
                    opt = op.dcplx_trans
                    opt.mirror = False
                    dcplx_trans = opt * dconn_trans * p.dcplx_trans.inverted()
                    self._instance.dcplx_trans = dcplx_trans
                case False, False:
                    self._instance.dcplx_trans = kdb.DCplxTrans(
                        op.dcplx_trans.disp - p.dcplx_trans.disp
                    )
                case True, False:
                    self._instance.dcplx_trans = kdb.DCplxTrans(
                        op.dcplx_trans.disp - p.dcplx_trans.disp
                    )
                    self.dmirror_y(op.dcplx_trans.disp.y)
                case _:
                    raise NotImplementedError("This shouldn't happen")

        else:
            conn_trans = kdb.Trans.M90 if mirror else kdb.Trans.R180
            match (use_mirror, use_angle):
                case True, True:
                    trans = op.trans * conn_trans * p.trans.inverted()
                    self._instance.trans = trans
                case False, True:
                    conn_trans = (
                        kdb.Trans.M90 if mirror ^ self.trans.mirror else kdb.Trans.R180
                    )
                    op = op.copy()
                    op.trans.mirror = False
                    trans = op.trans * conn_trans * p.trans.inverted()
                    self._instance.trans = trans
                case False, False:
                    self._instance.trans = kdb.Trans(op.trans.disp - p.trans.disp)
                case True, False:
                    self._instance.trans = kdb.Trans(op.trans.disp - p.trans.disp)
                    self.dmirror_y(op.dcplx_trans.disp.y)
                case _:
                    raise NotImplementedError("This shouldn't happen")

        return self

    def __repr__(self) -> str:
        """Return a string representation of the instance."""
        port_names = [p.name for p in self.ports]
        return (
            f"{self.parent_cell.name}: ports {port_names}, {self.kcl[self.cell_index]}"
        )

    def transform(
        self,
        trans: kdb.Trans | kdb.DTrans | kdb.ICplxTrans | kdb.DCplxTrans,
        /,
    ) -> None:
        self._instance.transform(trans)

    def flatten(self, levels: int | None = None) -> None:
        """Flatten all or just certain instances.

        Args:
            levels: If level < #hierarchy-levels -> pull the sub instances to self,
                else pull the polygons. None will always flatten all levels.
        """
        if levels:
            self._instance.flatten(levels)
        else:
            self._instance.flatten()

a property writable

a: Vector

Returns the displacement vector for the 'a' axis.

b property writable

b: Vector

Returns the displacement vector for the 'b' axis.

cell abstractmethod property writable

cell: ProtoTKCell[T]

Parent KCell of the Instance.

cell_index property writable

cell_index: int

Get the index of the cell this instance refers to.

cell_inst property writable

cell_inst: CellInstArray

Gets the basic CellInstArray object associated with this instance.

cell_name property

cell_name: str

Name of the cell the instance refers to.

cplx_trans property writable

cplx_trans: ICplxTrans

Gets the complex transformation of the instance.

Or the first instance in the array.

dcplx_trans property writable

dcplx_trans: DCplxTrans

Gets the complex transformation of the instance.

Or the first instance in the array.

dtrans property writable

dtrans: DTrans

Gets the complex transformation of the instance.

Or the first instance in the array.

hash property

hash: bytes

Hash the instance.

na property writable

na: int

Returns the displacement vector for the 'a' axis.

name property writable

name: str

Name of instance in GDS.

nb property writable

nb: int

Returns the number of instances in the 'b' axis.

pins abstractmethod property

pins: ProtoTInstancePins[T]

Ports of the instance.

ports abstractmethod property

ports: ProtoTInstancePorts[T]

Ports of the instance.

prop_id property writable

prop_id: int

Gets the properties ID associated with the instance.

purpose property writable

purpose: str | None

Purpose value of instance in GDS.

trans property writable

trans: Trans

Gets the complex transformation of the instance.

Or the first instance in the array.

__getattr__

__getattr__(name: str) -> Any

If we don't have an attribute, get it from the instance.

Source code in kfactory/instance.py
116
117
118
119
120
121
def __getattr__(self, name: str) -> Any:
    """If we don't have an attribute, get it from the instance."""
    try:
        return super().__getattr__(name)  # ty:ignore[unresolved-attribute]
    except Exception:
        return getattr(self._instance, name)

__repr__

__repr__() -> str

Return a string representation of the instance.

Source code in kfactory/instance.py
469
470
471
472
473
474
def __repr__(self) -> str:
    """Return a string representation of the instance."""
    port_names = [p.name for p in self.ports]
    return (
        f"{self.parent_cell.name}: ports {port_names}, {self.kcl[self.cell_index]}"
    )

connect

connect(
    port: str | ProtoPort[Any] | None,
    other: ProtoPort[Any],
    *,
    mirror: bool = False,
    allow_width_mismatch: bool | None = None,
    allow_layer_mismatch: bool | None = None,
    allow_type_mismatch: bool | None = None,
    use_mirror: bool | None = None,
    use_angle: bool | None = None,
) -> Self
connect(
    port: str | ProtoPort[Any] | None,
    other: ProtoTInstance[Any],
    other_port_name: str
    | int
    | tuple[int | str, int, int]
    | None,
    *,
    mirror: bool = False,
    allow_width_mismatch: bool | None = None,
    allow_layer_mismatch: bool | None = None,
    allow_type_mismatch: bool | None = None,
    use_mirror: bool | None = None,
    use_angle: bool | None = None,
) -> Self
connect(
    port: str | ProtoPort[Any] | None,
    other: VInstance,
    other_port_name: str | int | None,
    *,
    mirror: bool = False,
    allow_width_mismatch: bool | None = None,
    allow_layer_mismatch: bool | None = None,
    allow_type_mismatch: bool | None = None,
    use_mirror: bool | None = None,
    use_angle: bool | None = None,
) -> Self
connect(
    port: str | ProtoPort[Any] | None,
    other: ProtoInstance[Any] | ProtoPort[Any],
    other_port_name: str
    | int
    | tuple[int | str, int, int]
    | None = None,
    *,
    mirror: bool = False,
    allow_width_mismatch: bool | None = None,
    allow_layer_mismatch: bool | None = None,
    allow_type_mismatch: bool | None = None,
    use_mirror: bool | None = None,
    use_angle: bool | None = None,
) -> Self

Align port with name portname to a port.

Function to allow to transform this instance so that a port of this instance is connected (same center with 180° turn) to another instance.

Parameters:

Name Type Description Default
port str | ProtoPort[Any] | None

The name of the port of this instance to be connected, or directly an instance port. Can be None because port names can be None.

required
other ProtoInstance[Any] | ProtoPort[Any]

The other instance or a port. Skip other_port_name if it's a port.

required
other_port_name str | int | tuple[int | str, int, int] | None

The name of the other port. Ignored if other is a port.

None
mirror bool

Instead of applying klayout.db.Trans.R180 as a connection transformation, use klayout.db.Trans.M90, which effectively means this instance will be mirrored and connected.

False
allow_width_mismatch bool | None

Skip width check between the ports if set.

None
allow_layer_mismatch bool | None

Skip layer check between the ports if set.

None
allow_type_mismatch bool | None

Skip port_type check between the ports if set.

None
use_mirror bool | None

If False mirror flag does not get applied from the connection.

None
use_angle bool | None

If False the angle does not get applied from the connection.

None
Source code in kfactory/instance.py
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
def connect(
    self,
    port: str | ProtoPort[Any] | None,
    other: ProtoInstance[Any] | ProtoPort[Any],
    other_port_name: str | int | tuple[int | str, int, int] | None = None,
    *,
    mirror: bool = False,
    allow_width_mismatch: bool | None = None,
    allow_layer_mismatch: bool | None = None,
    allow_type_mismatch: bool | None = None,
    use_mirror: bool | None = None,
    use_angle: bool | None = None,
) -> Self:
    """Align port with name `portname` to a port.

    Function to allow to transform this instance so that a port of this instance is
    connected (same center with 180° turn) to another instance.

    Args:
        port: The name of the port of this instance to be connected, or directly an
            instance port. Can be `None` because port names can be `None`.
        other: The other instance or a port. Skip `other_port_name` if it's a port.
        other_port_name: The name of the other port. Ignored if
            `other` is a port.
        mirror: Instead of applying klayout.db.Trans.R180 as a connection
            transformation, use klayout.db.Trans.M90, which effectively means this
            instance will be mirrored and connected.
        allow_width_mismatch: Skip width check between the ports if set.
        allow_layer_mismatch: Skip layer check between the ports if set.
        allow_type_mismatch: Skip port_type check between the ports if set.
        use_mirror: If False mirror flag does not get applied from the connection.
        use_angle: If False the angle does not get applied from the connection.
    """
    if allow_width_mismatch is None:
        allow_width_mismatch = config.allow_width_mismatch
    if allow_layer_mismatch is None:
        allow_layer_mismatch = config.allow_layer_mismatch
    if allow_type_mismatch is None:
        allow_type_mismatch = config.allow_type_mismatch
    if use_mirror is None:
        use_mirror = config.connect_use_mirror
    if use_angle is None:
        use_angle = config.connect_use_angle

    if isinstance(other, ProtoPort):
        op = Port(base=other.base)
    else:
        if other_port_name is None:
            raise ValueError(
                "portname cannot be None if an Instance Object is given. For"
                "complex connections (non-90 degree and floating point ports) use"
                "route_cplx instead"
            )
        op = Port(base=other.ports[other_port_name].base)  # ty:ignore[invalid-argument-type]
    if isinstance(port, ProtoPort):
        p = Port(base=port.base.transformed(self.dcplx_trans.inverted()))
    else:
        p = Port(base=self.cell.ports[port].base)

    assert isinstance(p, Port)
    assert isinstance(op, Port)

    if p.width != op.width and not allow_width_mismatch:
        raise PortWidthMismatchError(self, other, p, op)
    if p.layer != op.layer and not allow_layer_mismatch:
        raise PortLayerMismatchError(self.cell.kcl, self, other, p, op)
    if p.port_type != op.port_type and not allow_type_mismatch:
        raise PortTypeMismatchError(self, other, p, op)
    if p.base.dcplx_trans or op.base.dcplx_trans:
        dconn_trans = kdb.DCplxTrans.M90 if mirror else kdb.DCplxTrans.R180
        match (use_mirror, use_angle):
            case True, True:
                dcplx_trans = (
                    op.dcplx_trans * dconn_trans * p.dcplx_trans.inverted()
                )
                self._instance.dcplx_trans = dcplx_trans
            case False, True:
                dconn_trans = (
                    kdb.DCplxTrans.M90
                    if mirror ^ self.dcplx_trans.mirror
                    else kdb.DCplxTrans.R180
                )
                opt = op.dcplx_trans
                opt.mirror = False
                dcplx_trans = opt * dconn_trans * p.dcplx_trans.inverted()
                self._instance.dcplx_trans = dcplx_trans
            case False, False:
                self._instance.dcplx_trans = kdb.DCplxTrans(
                    op.dcplx_trans.disp - p.dcplx_trans.disp
                )
            case True, False:
                self._instance.dcplx_trans = kdb.DCplxTrans(
                    op.dcplx_trans.disp - p.dcplx_trans.disp
                )
                self.dmirror_y(op.dcplx_trans.disp.y)
            case _:
                raise NotImplementedError("This shouldn't happen")

    else:
        conn_trans = kdb.Trans.M90 if mirror else kdb.Trans.R180
        match (use_mirror, use_angle):
            case True, True:
                trans = op.trans * conn_trans * p.trans.inverted()
                self._instance.trans = trans
            case False, True:
                conn_trans = (
                    kdb.Trans.M90 if mirror ^ self.trans.mirror else kdb.Trans.R180
                )
                op = op.copy()
                op.trans.mirror = False
                trans = op.trans * conn_trans * p.trans.inverted()
                self._instance.trans = trans
            case False, False:
                self._instance.trans = kdb.Trans(op.trans.disp - p.trans.disp)
            case True, False:
                self._instance.trans = kdb.Trans(op.trans.disp - p.trans.disp)
                self.dmirror_y(op.dcplx_trans.disp.y)
            case _:
                raise NotImplementedError("This shouldn't happen")

    return self

flatten

flatten(levels: int | None = None) -> None

Flatten all or just certain instances.

Parameters:

Name Type Description Default
levels int | None

If level < #hierarchy-levels -> pull the sub instances to self, else pull the polygons. None will always flatten all levels.

None
Source code in kfactory/instance.py
483
484
485
486
487
488
489
490
491
492
493
def flatten(self, levels: int | None = None) -> None:
    """Flatten all or just certain instances.

    Args:
        levels: If level < #hierarchy-levels -> pull the sub instances to self,
            else pull the polygons. None will always flatten all levels.
    """
    if levels:
        self._instance.flatten(levels)
    else:
        self._instance.flatten()

VInstance

Bases: ProtoInstance[float], UMGeometricObject

Source code in kfactory/instance.py
 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
class VInstance(ProtoInstance[float], UMGeometricObject):
    _name: str | None
    cell: AnyKCell
    trans: kdb.DCplxTrans
    a: kdb.DVector
    b: kdb.DVector
    na: int = 1
    nb: int = 1

    def __init__(
        self,
        cell: AnyKCell,
        trans: kdb.DCplxTrans | None = None,
        name: str | None = None,
        *,
        a: kdb.DVector = kdb.DVector(0, 0),  # noqa: B008
        b: kdb.DVector = kdb.DVector(0, 0),  # noqa: B008
        na: int = 1,
        nb: int = 1,
    ) -> None:
        self.kcl = cell.kcl
        self._name = name
        self.cell = cell
        self.trans = trans or kdb.DCplxTrans()
        self.a = a
        self.b = b
        self.na = na
        self.nb = nb

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

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

    @property
    def dcplx_trans(self) -> kdb.DCplxTrans:
        return self.trans

    @dcplx_trans.setter
    def dcplx_trans(self, val: kdb.DCplxTrans) -> None:
        self.trans = val

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

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

    def dbbox(self, layer: int | LayerEnum | None = None) -> kdb.DBox:
        cell_bb = self.cell.dbbox(layer)
        na_ = self.na - 1
        nb_ = self.nb - 1
        if na_ or nb_:
            return cell_bb.transformed(self.trans) + cell_bb.transformed(
                self.trans * kdb.DCplxTrans(na_ * self.a + nb_ * self.b)
            )
        return cell_bb.transformed(self.trans)

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

        The key can either be an integer, in which case the nth port is
        returned, or a string in which case the first port with a matching
        name is returned.

        If the instance is an array, the key can also be a tuple in the
        form of `c.ports[key_name, i_a, i_b]`, where `i_a` is the index in
        the `instance.a` direction and `i_b` the `instance.b` direction.

        E.g. `c.ports["a", 3, 5]`, accesses the ports of the instance which is
        3 times in `a` direction (4th index in the array), and 5 times in `b` direction
        (5th index in the array).
        """
        return self.ports[key]

    @functools.cached_property
    def ports(self) -> VInstancePorts:
        from .instance_ports import VInstancePorts

        return VInstancePorts(self)

    @functools.cached_property
    def pins(self) -> VInstancePins:
        from .instance_pins import VInstancePins

        return VInstancePins(self)

    def __repr__(self) -> str:
        """Return a string representation of the instance."""
        port_names = [p.name for p in self.ports]
        return f"{self.cell.name}: ports {port_names}, transformation {self.trans}"

    def insert_into(
        self,
        cell: AnyTKCell,
        trans: kdb.DCplxTrans | None = None,
    ) -> Instance:
        from .kcell import KCell, ProtoTKCell, VKCell

        if trans is None:
            trans = kdb.DCplxTrans()

        if isinstance(self.cell, VKCell):
            trans_ = trans * self.trans
            base_trans = kdb.DCplxTrans(
                kdb.DCplxTrans(
                    kdb.ICplxTrans(trans_, cell.kcl.dbu)
                    .s_trans()
                    .to_dtype(cell.kcl.dbu)
                )
            )
            trans_ = base_trans.inverted() * trans_
            cell_name = self.cell.name
            if cell_name is None:
                raise ValueError(
                    "Cannot insert a non-flattened VInstance into a VKCell when the"
                    f" name is 'None'. VKCell at {self.trans}"
                )
            if trans_ != kdb.DCplxTrans():
                cell_name += f"_{trans_.hash():x}"
            if cell.kcl.layout_cell(cell_name) is None:
                cell_ = KCell(kcl=self.cell.kcl, name=cell_name)  # self.cell.dup()
                for layer, shapes in self.cell.shapes().items():
                    for shape in shapes.transform(trans_):
                        if isinstance(shape, kdb.DPolygon | kdb.DSimplePolygon):
                            cell_.shapes(layer).insert(shape.to_itype(cell.kcl.dbu))
                        else:
                            cell_.shapes(layer).insert(shape)
                for inst in self.cell.insts:
                    inst.insert_into(cell=cell_, trans=trans_)
                cell_.name = cell_name
                for port in self.cell.ports:
                    cell_.add_port(port=port.copy(trans_))
                for c_shapes in (
                    cell_.shapes(layer) for layer in cell_.kcl.layer_indexes()
                ):
                    if not c_shapes.is_empty():
                        r = kdb.Region(c_shapes)
                        r.merge()
                        c_shapes.clear()
                        c_shapes.insert(r)
                settings = self.cell.settings.model_copy()
                settings_units = self.cell.settings_units.model_copy()
                cell_.settings = settings
                cell_.info = self.cell.info.model_copy(deep=True)
                cell_.settings_units = settings_units
                cell_.function_name = self.cell.function_name
                cell_.basename = self.cell.basename
                cell_._base.virtual = True
                if trans_ != kdb.DCplxTrans.R0:
                    cell_._base.vtrans = trans_
            else:
                cell_ = cell.kcl[cell_name]
            inst_ = cell.create_inst(
                cell=cell_, na=self.na, nb=self.nb, a=self.a, b=self.b
            )
            inst_.transform(base_trans)
            if self._name:
                inst_.name = self._name
            return Instance(kcl=self.cell.kcl, instance=inst_.instance)

        assert isinstance(self.cell, ProtoTKCell)
        trans_ = trans * self.trans
        base_trans = kdb.DCplxTrans(
            kdb.ICplxTrans(trans_, cell.kcl.dbu).s_trans().to_dtype(cell.kcl.dbu)
        )
        trans_ = base_trans.inverted() * trans_
        cell_name = self.cell.name
        if trans_ != kdb.DCplxTrans():
            cell_name += f"_{trans_.hash():x}"
        else:
            inst_ = cell.create_inst(
                cell=self.cell, na=self.na, nb=self.nb, a=self.a, b=self.b
            )
            if self._name:
                inst_.name = self._name
            inst_.transform(base_trans)
            return Instance(kcl=self.cell.kcl, instance=inst_.instance)
        if cell.kcl.layout_cell(cell_name) is None:
            tkcell = self.cell.dup()
            tkcell.name = cell_name
            tkcell.flatten(True)
            for layer in tkcell.kcl.layer_indexes():
                tkcell.shapes(layer).transform(trans_)
            for _port in tkcell.ports:
                _port.dcplx_trans = trans_ * _port.dcplx_trans
            if trans_ != kdb.DCplxTrans.R0:
                tkcell._base.vtrans = trans_
            settings = self.cell.settings.model_copy()
            settings_units = self.cell.settings_units.model_copy()
            tkcell.settings = settings
            tkcell.info = self.cell.info.model_copy(deep=True)
            tkcell.settings_units = settings_units
            tkcell.function_name = self.cell.function_name
            tkcell.basename = self.cell.basename
            tkcell._base.vtrans = trans_
        else:
            tkcell = cell.kcl[cell_name]
        inst_ = cell.create_inst(
            cell=tkcell, na=self.na, nb=self.nb, a=self.a, b=self.b
        )
        inst_.transform(base_trans)
        if self._name:
            inst_.name = self._name
        return Instance(kcl=self.cell.kcl, instance=inst_.instance)

    @overload
    def insert_into_flat(
        self,
        cell: AnyKCell,
        trans: kdb.DCplxTrans | None = None,
        *,
        levels: None = None,
    ) -> None: ...

    @overload
    def insert_into_flat(
        self,
        cell: AnyKCell,
        *,
        trans: kdb.DCplxTrans | None = None,
        levels: int,
    ) -> None: ...

    def insert_into_flat(
        self,
        cell: AnyKCell,
        trans: kdb.DCplxTrans | None = None,
        *,
        levels: int | None = None,
    ) -> None:
        from .kcell import ProtoTKCell, VKCell

        if trans is None:
            trans = kdb.DCplxTrans()

        if isinstance(self.cell, VKCell):
            for layer, shapes in self.cell.shapes().items():
                for shape in shapes.transform(trans * self.trans):
                    if isinstance(cell, ProtoTKCell) and isinstance(
                        shape, kdb.DPolygon | kdb.DSimplePolygon
                    ):
                        cell.shapes(layer).insert(shape.to_itype(cell.kcl.dbu))
                    else:
                        cell.shapes(layer).insert(shape)  # ty:ignore[no-matching-overload]
            for inst in self.cell.insts:
                if levels is not None:
                    if levels > 0:
                        inst.insert_into_flat(
                            cell, trans=trans * self.trans, levels=levels - 1
                        )
                    else:
                        assert isinstance(cell, ProtoTKCell)
                        inst.insert_into(cell, trans=trans * self.trans)
                else:
                    inst.insert_into_flat(cell, trans=trans * self.trans)

        else:
            assert isinstance(self.cell, ProtoTKCell)
            if levels:
                logger.warning(
                    "Levels are not supported if the inserted Instance is a KCell."
                )
            if isinstance(self.cell, ProtoTKCell):
                for layer in self.cell.kcl.layer_indexes():
                    reg = kdb.Region(self.cell.kdb_cell.begin_shapes_rec(layer))
                    reg.transform(kdb.ICplxTrans((trans * self.trans), cell.kcl.dbu))
                    cell.shapes(layer).insert(reg)
            else:
                for layer, shapes in self.cell.shapes.items():
                    for shape in shapes.transform(trans * self.trans):
                        cell.shapes(layer).insert(shape)
                for vinst in self.cell.vinsts:
                    vinst.insert_into_flat(cell, trans=trans * self.trans)

    @overload
    def connect(
        self,
        port: str | ProtoPort[Any] | None,
        other: ProtoPort[Any],
        *,
        mirror: bool = False,
        allow_width_mismatch: bool | None = None,
        allow_layer_mismatch: bool | None = None,
        allow_type_mismatch: bool | None = None,
        use_mirror: bool | None = None,
        use_angle: bool | None = None,
    ) -> Self: ...

    @overload
    def connect(
        self,
        port: str | ProtoPort[Any] | None,
        other: ProtoTInstance[Any],
        other_port_name: str | int | tuple[int | str, int, int] | None,
        *,
        mirror: bool = False,
        allow_width_mismatch: bool | None = None,
        allow_layer_mismatch: bool | None = None,
        allow_type_mismatch: bool | None = None,
        use_mirror: bool | None = None,
        use_angle: bool | None = None,
    ) -> Self: ...

    @overload
    def connect(
        self,
        port: str | ProtoPort[Any] | None,
        other: VInstance,
        other_port_name: str | int | None,
        *,
        mirror: bool = False,
        allow_width_mismatch: bool | None = None,
        allow_layer_mismatch: bool | None = None,
        allow_type_mismatch: bool | None = None,
        use_mirror: bool | None = None,
        use_angle: bool | None = None,
    ) -> Self: ...

    def connect(
        self,
        port: str | ProtoPort[Any] | None,
        other: ProtoInstance[Any] | ProtoPort[Any],
        other_port_name: str | int | tuple[int | str, int, int] | None = None,
        *,
        mirror: bool = False,
        allow_width_mismatch: bool | None = None,
        allow_layer_mismatch: bool | None = None,
        allow_type_mismatch: bool | None = None,
        use_mirror: bool | None = None,
        use_angle: bool | None = None,
    ) -> Self:
        """Align port with name `portname` to a port.

        Function to allow to transform this instance so that a port of this instance is
        connected (same center with 180° turn) to another instance.

        Args:
            port: The name of the port of this instance to be connected, or directly an
                instance port. Can be `None` because port names can be `None`.
            other: The other instance or a port. Skip `other_port_name` if it's a port.
            other_port_name: The name of the other port. Ignored if
                `other` is a port.
            mirror: Instead of applying klayout.db.Trans.R180 as a connection
                transformation, use klayout.db.Trans.M90, which effectively means this
                instance will be mirrored and connected.
            allow_width_mismatch: Skip width check between the ports if set.
            allow_layer_mismatch: Skip layer check between the ports if set.
            allow_type_mismatch: Skip port_type check between the ports if set.
            use_mirror: If False mirror flag does not get applied from the connection.
            use_angle: If False the angle does not get applied from the connection.
        """
        if allow_layer_mismatch is None:
            allow_layer_mismatch = config.allow_layer_mismatch
        if allow_width_mismatch is None:
            allow_width_mismatch = config.allow_width_mismatch
        if allow_type_mismatch is None:
            allow_type_mismatch = config.allow_type_mismatch
        if use_mirror is None:
            use_mirror = config.connect_use_mirror
        if use_angle is None:
            use_angle = config.connect_use_angle
        if isinstance(other, ProtoInstance):
            if other_port_name is None:
                raise ValueError(
                    "portname cannot be None if an Instance Object is given. For"
                    "complex connections (non-90 degree and floating point ports) use"
                    "route_cplx instead"
                )
            op = Port(base=other.ports[other_port_name].base)  # ty:ignore[invalid-argument-type]
        else:
            op = Port(base=other.base)
        if isinstance(port, ProtoPort):
            p = port.copy(self.trans.inverted()).to_itype()
        else:
            p = self.cell.ports[port].to_itype()

        assert isinstance(p, Port)
        assert isinstance(op, Port)

        if p.width != op.width and not allow_width_mismatch:
            raise PortWidthMismatchError(self, other, p, op)
        if p.layer != op.layer and not allow_layer_mismatch:
            raise PortLayerMismatchError(self.cell.kcl, self, other, p, op)
        if p.port_type != op.port_type and not allow_type_mismatch:
            raise PortTypeMismatchError(self, other, p, op)
        dconn_trans = kdb.DCplxTrans.M90 if mirror else kdb.DCplxTrans.R180
        match (use_mirror, use_angle):
            case True, True:
                trans = op.dcplx_trans * dconn_trans * p.dcplx_trans.inverted()
                self.trans = trans
            case False, True:
                dconn_trans = (
                    kdb.DCplxTrans.M90
                    if mirror ^ self.dcplx_trans.mirror
                    else kdb.DCplxTrans.R180
                )
                opt = op.dcplx_trans
                opt.mirror = False
                dcplx_trans = opt * dconn_trans * p.dcplx_trans.inverted()
                self.trans = dcplx_trans
            case False, False:
                self.trans = kdb.DCplxTrans(op.dcplx_trans.disp - p.dcplx_trans.disp)
            case True, False:
                self.trans = kdb.DCplxTrans(op.dcplx_trans.disp - p.dcplx_trans.disp)
                self.mirror_y(op.dcplx_trans.disp.y)
            case _:
                ...

        return self

    def transform(
        self,
        trans: kdb.Trans | kdb.DTrans | kdb.ICplxTrans | kdb.DCplxTrans,
        /,
    ) -> None:
        if isinstance(trans, kdb.Trans):
            trans = trans.to_dtype(self.kcl.dbu)
        self.trans = kdb.DCplxTrans(trans) * self.trans

    def dup(self) -> VInstance:
        return VInstance(
            cell=self.cell,
            trans=self.trans,
            name=self.name,
            a=self.a,
            b=self.b,
            na=self.na,
            nb=self.nb,
        )

    def copy(self) -> VInstance:
        return self.dup()

cell_name property

cell_name: str | None

Name of the cell the instance refers to.

kcl instance-attribute

kcl = kcl

KCLayout object.

name property writable

name: str | None

Name of the instance.

__getitem__

__getitem__(
    key: int
    | str
    | tuple[int | str | None, int, int]
    | None,
) -> DPort

Returns port from instance.

The key can either be an integer, in which case the nth port is returned, or a string in which case the first port with a matching name is returned.

If the instance is an array, the key can also be a tuple in the form of c.ports[key_name, i_a, i_b], where i_a is the index in the instance.a direction and i_b the instance.b direction.

E.g. c.ports["a", 3, 5], accesses the ports of the instance which is 3 times in a direction (4th index in the array), and 5 times in b direction (5th index in the array).

Source code in kfactory/instance.py
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
def __getitem__(
    self, key: int | str | tuple[int | str | None, int, int] | None
) -> DPort:
    """Returns port from instance.

    The key can either be an integer, in which case the nth port is
    returned, or a string in which case the first port with a matching
    name is returned.

    If the instance is an array, the key can also be a tuple in the
    form of `c.ports[key_name, i_a, i_b]`, where `i_a` is the index in
    the `instance.a` direction and `i_b` the `instance.b` direction.

    E.g. `c.ports["a", 3, 5]`, accesses the ports of the instance which is
    3 times in `a` direction (4th index in the array), and 5 times in `b` direction
    (5th index in the array).
    """
    return self.ports[key]

__repr__

__repr__() -> str

Return a string representation of the instance.

Source code in kfactory/instance.py
754
755
756
757
def __repr__(self) -> str:
    """Return a string representation of the instance."""
    port_names = [p.name for p in self.ports]
    return f"{self.cell.name}: ports {port_names}, transformation {self.trans}"

connect

connect(
    port: str | ProtoPort[Any] | None,
    other: ProtoPort[Any],
    *,
    mirror: bool = False,
    allow_width_mismatch: bool | None = None,
    allow_layer_mismatch: bool | None = None,
    allow_type_mismatch: bool | None = None,
    use_mirror: bool | None = None,
    use_angle: bool | None = None,
) -> Self
connect(
    port: str | ProtoPort[Any] | None,
    other: ProtoTInstance[Any],
    other_port_name: str
    | int
    | tuple[int | str, int, int]
    | None,
    *,
    mirror: bool = False,
    allow_width_mismatch: bool | None = None,
    allow_layer_mismatch: bool | None = None,
    allow_type_mismatch: bool | None = None,
    use_mirror: bool | None = None,
    use_angle: bool | None = None,
) -> Self
connect(
    port: str | ProtoPort[Any] | None,
    other: VInstance,
    other_port_name: str | int | None,
    *,
    mirror: bool = False,
    allow_width_mismatch: bool | None = None,
    allow_layer_mismatch: bool | None = None,
    allow_type_mismatch: bool | None = None,
    use_mirror: bool | None = None,
    use_angle: bool | None = None,
) -> Self
connect(
    port: str | ProtoPort[Any] | None,
    other: ProtoInstance[Any] | ProtoPort[Any],
    other_port_name: str
    | int
    | tuple[int | str, int, int]
    | None = None,
    *,
    mirror: bool = False,
    allow_width_mismatch: bool | None = None,
    allow_layer_mismatch: bool | None = None,
    allow_type_mismatch: bool | None = None,
    use_mirror: bool | None = None,
    use_angle: bool | None = None,
) -> Self

Align port with name portname to a port.

Function to allow to transform this instance so that a port of this instance is connected (same center with 180° turn) to another instance.

Parameters:

Name Type Description Default
port str | ProtoPort[Any] | None

The name of the port of this instance to be connected, or directly an instance port. Can be None because port names can be None.

required
other ProtoInstance[Any] | ProtoPort[Any]

The other instance or a port. Skip other_port_name if it's a port.

required
other_port_name str | int | tuple[int | str, int, int] | None

The name of the other port. Ignored if other is a port.

None
mirror bool

Instead of applying klayout.db.Trans.R180 as a connection transformation, use klayout.db.Trans.M90, which effectively means this instance will be mirrored and connected.

False
allow_width_mismatch bool | None

Skip width check between the ports if set.

None
allow_layer_mismatch bool | None

Skip layer check between the ports if set.

None
allow_type_mismatch bool | None

Skip port_type check between the ports if set.

None
use_mirror bool | None

If False mirror flag does not get applied from the connection.

None
use_angle bool | None

If False the angle does not get applied from the connection.

None
Source code in kfactory/instance.py
 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
def connect(
    self,
    port: str | ProtoPort[Any] | None,
    other: ProtoInstance[Any] | ProtoPort[Any],
    other_port_name: str | int | tuple[int | str, int, int] | None = None,
    *,
    mirror: bool = False,
    allow_width_mismatch: bool | None = None,
    allow_layer_mismatch: bool | None = None,
    allow_type_mismatch: bool | None = None,
    use_mirror: bool | None = None,
    use_angle: bool | None = None,
) -> Self:
    """Align port with name `portname` to a port.

    Function to allow to transform this instance so that a port of this instance is
    connected (same center with 180° turn) to another instance.

    Args:
        port: The name of the port of this instance to be connected, or directly an
            instance port. Can be `None` because port names can be `None`.
        other: The other instance or a port. Skip `other_port_name` if it's a port.
        other_port_name: The name of the other port. Ignored if
            `other` is a port.
        mirror: Instead of applying klayout.db.Trans.R180 as a connection
            transformation, use klayout.db.Trans.M90, which effectively means this
            instance will be mirrored and connected.
        allow_width_mismatch: Skip width check between the ports if set.
        allow_layer_mismatch: Skip layer check between the ports if set.
        allow_type_mismatch: Skip port_type check between the ports if set.
        use_mirror: If False mirror flag does not get applied from the connection.
        use_angle: If False the angle does not get applied from the connection.
    """
    if allow_layer_mismatch is None:
        allow_layer_mismatch = config.allow_layer_mismatch
    if allow_width_mismatch is None:
        allow_width_mismatch = config.allow_width_mismatch
    if allow_type_mismatch is None:
        allow_type_mismatch = config.allow_type_mismatch
    if use_mirror is None:
        use_mirror = config.connect_use_mirror
    if use_angle is None:
        use_angle = config.connect_use_angle
    if isinstance(other, ProtoInstance):
        if other_port_name is None:
            raise ValueError(
                "portname cannot be None if an Instance Object is given. For"
                "complex connections (non-90 degree and floating point ports) use"
                "route_cplx instead"
            )
        op = Port(base=other.ports[other_port_name].base)  # ty:ignore[invalid-argument-type]
    else:
        op = Port(base=other.base)
    if isinstance(port, ProtoPort):
        p = port.copy(self.trans.inverted()).to_itype()
    else:
        p = self.cell.ports[port].to_itype()

    assert isinstance(p, Port)
    assert isinstance(op, Port)

    if p.width != op.width and not allow_width_mismatch:
        raise PortWidthMismatchError(self, other, p, op)
    if p.layer != op.layer and not allow_layer_mismatch:
        raise PortLayerMismatchError(self.cell.kcl, self, other, p, op)
    if p.port_type != op.port_type and not allow_type_mismatch:
        raise PortTypeMismatchError(self, other, p, op)
    dconn_trans = kdb.DCplxTrans.M90 if mirror else kdb.DCplxTrans.R180
    match (use_mirror, use_angle):
        case True, True:
            trans = op.dcplx_trans * dconn_trans * p.dcplx_trans.inverted()
            self.trans = trans
        case False, True:
            dconn_trans = (
                kdb.DCplxTrans.M90
                if mirror ^ self.dcplx_trans.mirror
                else kdb.DCplxTrans.R180
            )
            opt = op.dcplx_trans
            opt.mirror = False
            dcplx_trans = opt * dconn_trans * p.dcplx_trans.inverted()
            self.trans = dcplx_trans
        case False, False:
            self.trans = kdb.DCplxTrans(op.dcplx_trans.disp - p.dcplx_trans.disp)
        case True, False:
            self.trans = kdb.DCplxTrans(op.dcplx_trans.disp - p.dcplx_trans.disp)
            self.mirror_y(op.dcplx_trans.disp.y)
        case _:
            ...

    return self