Skip to content

Ports

ports

DCreatePort

Bases: ABC

Protocol for a create_port functionality

Source code in kfactory/ports.py
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
class DCreatePort(ABC):
    """Protocol for a create_port functionality"""

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

    @overload
    def create_port(
        self,
        *,
        trans: kdb.Trans,
        width: float,
        layer: int,
        name: str,
        port_type: str = "optical",
        info: dict[str, MetaData] | None = None,
    ) -> DPort: ...

    @overload
    def create_port(
        self,
        *,
        dcplx_trans: kdb.DCplxTrans,
        width: float,
        layer: LayerEnum | int,
        name: str,
        port_type: str = "optical",
        info: dict[str, MetaData] | None = None,
    ) -> DPort: ...

    @overload
    def create_port(
        self,
        *,
        width: float,
        layer: LayerEnum | int,
        center: tuple[float, float],
        orientation: float,
        name: str,
        port_type: str = "optical",
        info: dict[str, MetaData] | None = None,
    ) -> DPort: ...

    @overload
    def create_port(
        self,
        *,
        trans: kdb.Trans,
        width: float,
        layer_info: kdb.LayerInfo,
        name: str,
        port_type: str = "optical",
        info: dict[str, MetaData] | None = None,
    ) -> DPort: ...

    @overload
    def create_port(
        self,
        *,
        dcplx_trans: kdb.DCplxTrans,
        width: float,
        layer_info: kdb.LayerInfo,
        name: str,
        port_type: str = "optical",
        info: dict[str, MetaData] | None = None,
    ) -> DPort: ...

    @overload
    def create_port(
        self,
        *,
        width: float,
        layer_info: kdb.LayerInfo,
        center: tuple[float, float],
        orientation: float,
        name: str,
        port_type: str = "optical",
        info: dict[str, MetaData] | None = None,
    ) -> DPort: ...

    @overload
    def create_port(
        self,
        *,
        trans: kdb.Trans,
        cross_section: CrossSectionSpec
        | DCrossSectionSpec
        | CrossSection
        | DCrossSection
        | SymmetricalCrossSection,
        name: str,
        port_type: str = "optical",
        info: dict[str, MetaData] | None = None,
    ) -> DPort: ...
    @overload
    def create_port(
        self,
        *,
        dcplx_trans: kdb.DCplxTrans,
        cross_section: CrossSectionSpec
        | DCrossSectionSpec
        | CrossSection
        | DCrossSection
        | SymmetricalCrossSection,
        name: str,
        port_type: str = "optical",
        info: dict[str, MetaData] | None = None,
    ) -> DPort: ...

    def create_port(
        self,
        *,
        name: str,
        width: float | None = None,
        layer: LayerEnum | int | None = None,
        layer_info: kdb.LayerInfo | None = None,
        port_type: str = "optical",
        trans: kdb.Trans | None = None,
        dcplx_trans: kdb.DCplxTrans | None = None,
        center: tuple[float, float] | None = None,
        orientation: float | None = None,
        mirror_x: bool = False,
        cross_section: CrossSectionSpec
        | DCrossSectionSpec
        | CrossSection
        | DCrossSection
        | SymmetricalCrossSection
        | None = None,
        info: dict[str, MetaData] | None = None,
    ) -> DPort:
        """Create a port."""
        if cross_section is None:
            if width is None:
                raise ValueError(
                    "Either width must be set. It can be set through"
                    " a cross section as well."
                )
            if layer_info is None:
                if layer is None:
                    raise ValueError(
                        "layer or layer_info must be defined to create a port."
                    )
                layer_info = self.kcl.layout.get_info(layer)
            assert layer_info is not None
            try:
                xs = self.kcl.get_dcross_section(
                    DCrossSectionSpec(layer=layer_info, width=width, unit="um")
                )
            except ValidationError as e:
                raise ValueError(
                    "Port width needs to be even to snap to grid properly "
                    "and greater than 0"
                    f". 1 DBU is {self.kcl.dbu} um. Port width must be a "
                    f"multiple of {2 * self.kcl.dbu} um."
                ) from e
        else:
            xs = self.kcl.get_dcross_section(cross_section)
        if trans is not None:
            port = DPort(
                name=name,
                trans=trans,
                cross_section=xs,
                port_type=port_type,
                kcl=self.kcl,
            )
        elif dcplx_trans is not None:
            port = DPort(
                name=name,
                dcplx_trans=dcplx_trans,
                port_type=port_type,
                cross_section=xs,
                kcl=self.kcl,
            )
        elif orientation is not None and center is not None:
            port = DPort(
                name=name,
                port_type=port_type,
                cross_section=xs,
                orientation=orientation,
                center=center,
                mirror_x=mirror_x,
                kcl=self.kcl,
            )
        else:
            raise ValueError(
                f"You need to define width {width} and trans {trans} or orientation"
                f" {orientation} and center {center} or dcplx_trans {dcplx_trans}"
            )
        if info:
            port.info.update(info)

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

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

create_port

create_port(
    *,
    trans: Trans,
    width: float,
    layer: int,
    name: str,
    port_type: str = "optical",
    info: dict[str, MetaData] | None = None,
) -> DPort
create_port(
    *,
    dcplx_trans: DCplxTrans,
    width: float,
    layer: LayerEnum | int,
    name: str,
    port_type: str = "optical",
    info: dict[str, MetaData] | None = None,
) -> DPort
create_port(
    *,
    width: float,
    layer: LayerEnum | int,
    center: tuple[float, float],
    orientation: float,
    name: str,
    port_type: str = "optical",
    info: dict[str, MetaData] | None = None,
) -> DPort
create_port(
    *,
    trans: Trans,
    width: float,
    layer_info: LayerInfo,
    name: str,
    port_type: str = "optical",
    info: dict[str, MetaData] | None = None,
) -> DPort
create_port(
    *,
    dcplx_trans: DCplxTrans,
    width: float,
    layer_info: LayerInfo,
    name: str,
    port_type: str = "optical",
    info: dict[str, MetaData] | None = None,
) -> DPort
create_port(
    *,
    width: float,
    layer_info: LayerInfo,
    center: tuple[float, float],
    orientation: float,
    name: str,
    port_type: str = "optical",
    info: dict[str, MetaData] | None = None,
) -> DPort
create_port(
    *,
    trans: Trans,
    cross_section: CrossSectionSpec
    | DCrossSectionSpec
    | CrossSection
    | DCrossSection
    | SymmetricalCrossSection,
    name: str,
    port_type: str = "optical",
    info: dict[str, MetaData] | None = None,
) -> DPort
create_port(
    *,
    dcplx_trans: DCplxTrans,
    cross_section: CrossSectionSpec
    | DCrossSectionSpec
    | CrossSection
    | DCrossSection
    | SymmetricalCrossSection,
    name: str,
    port_type: str = "optical",
    info: dict[str, MetaData] | None = None,
) -> DPort
create_port(
    *,
    name: str,
    width: float | None = None,
    layer: LayerEnum | int | None = None,
    layer_info: LayerInfo | None = None,
    port_type: str = "optical",
    trans: Trans | None = None,
    dcplx_trans: DCplxTrans | None = None,
    center: tuple[float, float] | None = None,
    orientation: float | None = None,
    mirror_x: bool = False,
    cross_section: CrossSectionSpec
    | DCrossSectionSpec
    | CrossSection
    | DCrossSection
    | SymmetricalCrossSection
    | None = None,
    info: dict[str, MetaData] | None = None,
) -> DPort

Create a port.

Source code in kfactory/ports.py
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
def create_port(
    self,
    *,
    name: str,
    width: float | None = None,
    layer: LayerEnum | int | None = None,
    layer_info: kdb.LayerInfo | None = None,
    port_type: str = "optical",
    trans: kdb.Trans | None = None,
    dcplx_trans: kdb.DCplxTrans | None = None,
    center: tuple[float, float] | None = None,
    orientation: float | None = None,
    mirror_x: bool = False,
    cross_section: CrossSectionSpec
    | DCrossSectionSpec
    | CrossSection
    | DCrossSection
    | SymmetricalCrossSection
    | None = None,
    info: dict[str, MetaData] | None = None,
) -> DPort:
    """Create a port."""
    if cross_section is None:
        if width is None:
            raise ValueError(
                "Either width must be set. It can be set through"
                " a cross section as well."
            )
        if layer_info is None:
            if layer is None:
                raise ValueError(
                    "layer or layer_info must be defined to create a port."
                )
            layer_info = self.kcl.layout.get_info(layer)
        assert layer_info is not None
        try:
            xs = self.kcl.get_dcross_section(
                DCrossSectionSpec(layer=layer_info, width=width, unit="um")
            )
        except ValidationError as e:
            raise ValueError(
                "Port width needs to be even to snap to grid properly "
                "and greater than 0"
                f". 1 DBU is {self.kcl.dbu} um. Port width must be a "
                f"multiple of {2 * self.kcl.dbu} um."
            ) from e
    else:
        xs = self.kcl.get_dcross_section(cross_section)
    if trans is not None:
        port = DPort(
            name=name,
            trans=trans,
            cross_section=xs,
            port_type=port_type,
            kcl=self.kcl,
        )
    elif dcplx_trans is not None:
        port = DPort(
            name=name,
            dcplx_trans=dcplx_trans,
            port_type=port_type,
            cross_section=xs,
            kcl=self.kcl,
        )
    elif orientation is not None and center is not None:
        port = DPort(
            name=name,
            port_type=port_type,
            cross_section=xs,
            orientation=orientation,
            center=center,
            mirror_x=mirror_x,
            kcl=self.kcl,
        )
    else:
        raise ValueError(
            f"You need to define width {width} and trans {trans} or orientation"
            f" {orientation} and center {center} or dcplx_trans {dcplx_trans}"
        )
    if info:
        port.info.update(info)

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

DPorts

Bases: ProtoPorts[float], DCreatePort

A collection of um ports.

It is not a traditional dictionary. Elements can be retrieved as in a traditional dictionary. But to keep tabs on names etc, the ports are stored as a list

Source code in kfactory/ports.py
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
class DPorts(ProtoPorts[float], DCreatePort):
    """A collection of um ports.

    It is not a traditional dictionary. Elements can be retrieved as in a traditional
    dictionary. But to keep tabs on names etc, the ports are stored as a list
    """

    yaml_tag: ClassVar[str] = "!DPorts"

    def __iter__(self) -> Iterator[DPort]:
        """Iterator, that allows for loops etc to directly access the object."""
        yield from (DPort(base=b) for b in self._bases)

    def add_port(
        self,
        *,
        port: ProtoPort[Any],
        name: str | None = None,
        keep_mirror: bool = False,
    ) -> DPort:
        """Add a port object.

        Args:
            port: The port to add
            name: Overwrite the name of the port
            keep_mirror: Keep the mirror flag from the original port if `True`,
                else set [Port.trans.mirror][kfactory.Port.trans] (or the complex
                equivalent) to `False`.
        """
        if port.kcl == self.kcl:
            base = port.base.model_copy()
            if not keep_mirror:
                if base.trans is not None:
                    base.trans.mirror = False
                elif base.dcplx_trans is not None:
                    base.dcplx_trans.mirror = False
            if name is not None:
                base.name = name
            self._bases.append(base)
            port_ = DPort(base=base)
        else:
            dcplx_trans = port.dcplx_trans.dup()
            if not keep_mirror:
                dcplx_trans.mirror = False
            base = port.base.model_copy()
            base.trans = kdb.Trans.R0
            base.dcplx_trans = None
            base.kcl = self.kcl
            base.cross_section = self.kcl.get_symmetrical_cross_section(
                port.cross_section.base.to_dtype(port.kcl)
            )
            port_ = DPort(base=base)
            port_.dcplx_trans = dcplx_trans
            self._bases.append(port_.base)
        return port_

    def get_all_named(self) -> Mapping[str, DPort]:
        """Get all ports in a dictionary with names as keys."""
        return {v.name: DPort(base=v) for v in self._bases if v.name is not None}

    @overload
    def __getitem__(self, key: int | str | None) -> DPort:
        """Get a port by index or name."""

    @overload
    def __getitem__(self, key: slice) -> Self:
        """Get ports by slice."""

    def __getitem__(self, key: slice | int | str | None) -> Self | DPort:
        if isinstance(key, int):
            return DPort(base=self._bases[key])
        if isinstance(key, slice):
            return self.__class__(bases=self._bases[key], kcl=self.kcl)
        try:
            return DPort(base=next(filter(lambda base: base.name == key, self._bases)))
        except StopIteration as e:
            raise KeyError(
                f"{key=} is not a valid port name or index. "
                f"Available ports: {[v.name for v in self._bases]}"
            ) from e

    def copy(
        self, rename_function: Callable[[Sequence[DPort]], None] | None = None
    ) -> Self:
        """Get a copy of each port."""
        bases = [b.__copy__() for b in self._bases]
        if rename_function is not None:
            rename_function([DPort(base=b) for b in bases])
        return self.__class__(bases=bases, kcl=self.kcl)

    def filter(
        self,
        angle: Angle | None = None,
        orientation: float | None = None,
        layer: LayerEnum | int | None = None,
        port_type: str | None = None,
        regex: str | None = None,
    ) -> list[DPort]:
        """Filter ports by name.

        Args:
            angle: Filter by angle. 0, 1, 2, 3.
            orientation: Alias for angle.
            layer: Filter by layer.
            port_type: Filter by port type.
            regex: Filter by regex of the name.
        """
        return _filter_ports(
            (DPort(base=b) for b in self._bases),
            angle,
            orientation,
            layer,
            port_type,
            regex,
        )

    def __repr__(self) -> str:
        """Representation of the Ports as strings."""
        return repr([repr(Port(base=b)) for b in self._bases])

__iter__

__iter__() -> Iterator[DPort]

Iterator, that allows for loops etc to directly access the object.

Source code in kfactory/ports.py
794
795
796
def __iter__(self) -> Iterator[DPort]:
    """Iterator, that allows for loops etc to directly access the object."""
    yield from (DPort(base=b) for b in self._bases)

__repr__

__repr__() -> str

Representation of the Ports as strings.

Source code in kfactory/ports.py
901
902
903
def __repr__(self) -> str:
    """Representation of the Ports as strings."""
    return repr([repr(Port(base=b)) for b in self._bases])

add_port

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

Add a port object.

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 flag from the original port if True, else set [Port.trans.mirror][kfactory.Port.trans] (or the complex equivalent) to False.

False
Source code in kfactory/ports.py
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
def add_port(
    self,
    *,
    port: ProtoPort[Any],
    name: str | None = None,
    keep_mirror: bool = False,
) -> DPort:
    """Add a port object.

    Args:
        port: The port to add
        name: Overwrite the name of the port
        keep_mirror: Keep the mirror flag from the original port if `True`,
            else set [Port.trans.mirror][kfactory.Port.trans] (or the complex
            equivalent) to `False`.
    """
    if port.kcl == self.kcl:
        base = port.base.model_copy()
        if not keep_mirror:
            if base.trans is not None:
                base.trans.mirror = False
            elif base.dcplx_trans is not None:
                base.dcplx_trans.mirror = False
        if name is not None:
            base.name = name
        self._bases.append(base)
        port_ = DPort(base=base)
    else:
        dcplx_trans = port.dcplx_trans.dup()
        if not keep_mirror:
            dcplx_trans.mirror = False
        base = port.base.model_copy()
        base.trans = kdb.Trans.R0
        base.dcplx_trans = None
        base.kcl = self.kcl
        base.cross_section = self.kcl.get_symmetrical_cross_section(
            port.cross_section.base.to_dtype(port.kcl)
        )
        port_ = DPort(base=base)
        port_.dcplx_trans = dcplx_trans
        self._bases.append(port_.base)
    return port_

copy

copy(
    rename_function: Callable[[Sequence[DPort]], None]
    | None = None,
) -> Self

Get a copy of each port.

Source code in kfactory/ports.py
866
867
868
869
870
871
872
873
def copy(
    self, rename_function: Callable[[Sequence[DPort]], None] | None = None
) -> Self:
    """Get a copy of each port."""
    bases = [b.__copy__() for b in self._bases]
    if rename_function is not None:
        rename_function([DPort(base=b) for b in bases])
    return self.__class__(bases=bases, kcl=self.kcl)

filter

filter(
    angle: Angle | None = None,
    orientation: float | None = None,
    layer: LayerEnum | int | None = None,
    port_type: str | None = None,
    regex: str | None = None,
) -> list[DPort]

Filter ports by name.

Parameters:

Name Type Description Default
angle Angle | None

Filter by angle. 0, 1, 2, 3.

None
orientation float | None

Alias for angle.

None
layer LayerEnum | int | None

Filter by layer.

None
port_type str | None

Filter by port type.

None
regex str | None

Filter by regex of the name.

None
Source code in kfactory/ports.py
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
def filter(
    self,
    angle: Angle | None = None,
    orientation: float | None = None,
    layer: LayerEnum | int | None = None,
    port_type: str | None = None,
    regex: str | None = None,
) -> list[DPort]:
    """Filter ports by name.

    Args:
        angle: Filter by angle. 0, 1, 2, 3.
        orientation: Alias for angle.
        layer: Filter by layer.
        port_type: Filter by port type.
        regex: Filter by regex of the name.
    """
    return _filter_ports(
        (DPort(base=b) for b in self._bases),
        angle,
        orientation,
        layer,
        port_type,
        regex,
    )

get_all_named

get_all_named() -> Mapping[str, DPort]

Get all ports in a dictionary with names as keys.

Source code in kfactory/ports.py
841
842
843
def get_all_named(self) -> Mapping[str, DPort]:
    """Get all ports in a dictionary with names as keys."""
    return {v.name: DPort(base=v) for v in self._bases if v.name is not None}

ICreatePort

Bases: ABC

Protocol for a create_port functionality

Source code in kfactory/ports.py
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
class ICreatePort(ABC):
    """Protocol for a create_port functionality"""

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

    @overload
    def create_port(
        self,
        *,
        name: str,
        trans: kdb.Trans,
        cross_section: CrossSectionSpec
        | DCrossSectionSpec
        | CrossSection
        | DCrossSection
        | SymmetricalCrossSection,
        port_type: str = "optical",
        info: dict[str, MetaData] | None = None,
    ) -> Port: ...

    @overload
    def create_port(
        self,
        *,
        name: str,
        trans: kdb.Trans,
        width: int,
        layer: int,
        port_type: str = "optical",
        info: dict[str, MetaData] | None = None,
    ) -> Port: ...

    @overload
    def create_port(
        self,
        *,
        name: str,
        dcplx_trans: kdb.DCplxTrans,
        width: int,
        layer: LayerEnum | int,
        port_type: str = "optical",
    ) -> Port: ...

    @overload
    def create_port(
        self,
        *,
        name: str,
        width: int,
        layer: LayerEnum | int,
        center: tuple[int, int],
        angle: Angle,
        port_type: str = "optical",
        info: dict[str, MetaData] | None = None,
    ) -> Port: ...

    @overload
    def create_port(
        self,
        *,
        name: str,
        trans: kdb.Trans,
        width: int,
        layer_info: kdb.LayerInfo,
        port_type: str = "optical",
        info: dict[str, MetaData] | None = None,
    ) -> Port: ...

    @overload
    def create_port(
        self,
        *,
        name: str,
        width: int,
        layer_info: kdb.LayerInfo,
        center: tuple[int, int],
        angle: Angle,
        port_type: str = "optical",
        info: dict[str, MetaData] | None = None,
    ) -> Port: ...

    @overload
    def create_port(
        self,
        *,
        name: str,
        layer_info: kdb.LayerInfo,
        trans: kdb.Trans,
        cross_section: CrossSectionSpec
        | DCrossSectionSpec
        | CrossSection
        | DCrossSection
        | SymmetricalCrossSection,
        port_type: str = "optical",
        info: dict[str, MetaData] | None = None,
    ) -> Port: ...
    @overload
    def create_port(
        self,
        *,
        name: str,
        dcplx_trans: kdb.DCplxTrans,
        cross_section: CrossSectionSpec
        | DCrossSectionSpec
        | CrossSection
        | DCrossSection
        | SymmetricalCrossSection,
        port_type: str = "optical",
        info: dict[str, MetaData] | None = None,
    ) -> Port: ...

    def create_port(
        self,
        *,
        name: str,
        width: int | None = None,
        layer: LayerEnum | int | None = None,
        layer_info: kdb.LayerInfo | None = None,
        port_type: str = "optical",
        trans: kdb.Trans | None = None,
        dcplx_trans: kdb.DCplxTrans | None = None,
        center: tuple[int, int] | None = None,
        angle: Angle | None = None,
        mirror_x: bool = False,
        cross_section: CrossSectionSpec
        | DCrossSectionSpec
        | CrossSection
        | DCrossSection
        | SymmetricalCrossSection
        | None = None,
        info: dict[str, MetaData] | None = None,
    ) -> Port:
        """Create a port."""

        if cross_section is None:
            if width is None:
                raise ValueError(
                    "Either width or dwidth must be set. It can be set through"
                    " a cross section as well."
                )
            if layer_info is None:
                if layer is None:
                    raise ValueError(
                        "layer or layer_info must be defined to create a port."
                    )
                layer_info = self.kcl.layout.get_info(layer)
            assert layer_info is not None
            try:
                xs = self.kcl.get_icross_section(
                    CrossSectionSpec(layer=layer_info, width=width, unit="dbu")
                )
            except ValidationError as e:
                raise ValueError(
                    "Port width needs to be even to snap to grid properly "
                    "and greater than 0"
                    f". 1 DBU is {self.kcl.dbu} um."
                ) from e
        else:
            xs = self.kcl.get_icross_section(cross_section)
        if trans is not None:
            port = Port(
                name=name,
                trans=trans,
                cross_section=xs,
                port_type=port_type,
                kcl=self.kcl,
            )
        elif dcplx_trans is not None:
            port = Port(
                name=name,
                dcplx_trans=dcplx_trans,
                port_type=port_type,
                cross_section=xs,
                kcl=self.kcl,
            )
        elif angle is not None and center is not None:
            port = Port(
                name=name,
                port_type=port_type,
                cross_section=xs,
                angle=angle,
                center=center,
                mirror_x=mirror_x,
                kcl=self.kcl,
            )
        else:
            raise ValueError(
                f"You need to define width {width} and trans {trans} or angle {angle}"
                f" and center {center} or dcplx_trans {dcplx_trans}"
            )
        if info:
            port.info.update(info)

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

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

create_port

create_port(
    *,
    name: str,
    trans: Trans,
    cross_section: CrossSectionSpec
    | DCrossSectionSpec
    | CrossSection
    | DCrossSection
    | SymmetricalCrossSection,
    port_type: str = "optical",
    info: dict[str, MetaData] | None = None,
) -> Port
create_port(
    *,
    name: str,
    trans: Trans,
    width: int,
    layer: int,
    port_type: str = "optical",
    info: dict[str, MetaData] | None = None,
) -> Port
create_port(
    *,
    name: str,
    dcplx_trans: DCplxTrans,
    width: int,
    layer: LayerEnum | int,
    port_type: str = "optical",
) -> Port
create_port(
    *,
    name: str,
    width: int,
    layer: LayerEnum | int,
    center: tuple[int, int],
    angle: Angle,
    port_type: str = "optical",
    info: dict[str, MetaData] | None = None,
) -> Port
create_port(
    *,
    name: str,
    trans: Trans,
    width: int,
    layer_info: LayerInfo,
    port_type: str = "optical",
    info: dict[str, MetaData] | None = None,
) -> Port
create_port(
    *,
    name: str,
    width: int,
    layer_info: LayerInfo,
    center: tuple[int, int],
    angle: Angle,
    port_type: str = "optical",
    info: dict[str, MetaData] | None = None,
) -> Port
create_port(
    *,
    name: str,
    layer_info: LayerInfo,
    trans: Trans,
    cross_section: CrossSectionSpec
    | DCrossSectionSpec
    | CrossSection
    | DCrossSection
    | SymmetricalCrossSection,
    port_type: str = "optical",
    info: dict[str, MetaData] | None = None,
) -> Port
create_port(
    *,
    name: str,
    dcplx_trans: DCplxTrans,
    cross_section: CrossSectionSpec
    | DCrossSectionSpec
    | CrossSection
    | DCrossSection
    | SymmetricalCrossSection,
    port_type: str = "optical",
    info: dict[str, MetaData] | None = None,
) -> Port
create_port(
    *,
    name: str,
    width: int | None = None,
    layer: LayerEnum | int | None = None,
    layer_info: LayerInfo | None = None,
    port_type: str = "optical",
    trans: Trans | None = None,
    dcplx_trans: DCplxTrans | None = None,
    center: tuple[int, int] | None = None,
    angle: Angle | None = None,
    mirror_x: bool = False,
    cross_section: CrossSectionSpec
    | DCrossSectionSpec
    | CrossSection
    | DCrossSection
    | SymmetricalCrossSection
    | None = None,
    info: dict[str, MetaData] | None = None,
) -> Port

Create a port.

Source code in kfactory/ports.py
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
def create_port(
    self,
    *,
    name: str,
    width: int | None = None,
    layer: LayerEnum | int | None = None,
    layer_info: kdb.LayerInfo | None = None,
    port_type: str = "optical",
    trans: kdb.Trans | None = None,
    dcplx_trans: kdb.DCplxTrans | None = None,
    center: tuple[int, int] | None = None,
    angle: Angle | None = None,
    mirror_x: bool = False,
    cross_section: CrossSectionSpec
    | DCrossSectionSpec
    | CrossSection
    | DCrossSection
    | SymmetricalCrossSection
    | None = None,
    info: dict[str, MetaData] | None = None,
) -> Port:
    """Create a port."""

    if cross_section is None:
        if width is None:
            raise ValueError(
                "Either width or dwidth must be set. It can be set through"
                " a cross section as well."
            )
        if layer_info is None:
            if layer is None:
                raise ValueError(
                    "layer or layer_info must be defined to create a port."
                )
            layer_info = self.kcl.layout.get_info(layer)
        assert layer_info is not None
        try:
            xs = self.kcl.get_icross_section(
                CrossSectionSpec(layer=layer_info, width=width, unit="dbu")
            )
        except ValidationError as e:
            raise ValueError(
                "Port width needs to be even to snap to grid properly "
                "and greater than 0"
                f". 1 DBU is {self.kcl.dbu} um."
            ) from e
    else:
        xs = self.kcl.get_icross_section(cross_section)
    if trans is not None:
        port = Port(
            name=name,
            trans=trans,
            cross_section=xs,
            port_type=port_type,
            kcl=self.kcl,
        )
    elif dcplx_trans is not None:
        port = Port(
            name=name,
            dcplx_trans=dcplx_trans,
            port_type=port_type,
            cross_section=xs,
            kcl=self.kcl,
        )
    elif angle is not None and center is not None:
        port = Port(
            name=name,
            port_type=port_type,
            cross_section=xs,
            angle=angle,
            center=center,
            mirror_x=mirror_x,
            kcl=self.kcl,
        )
    else:
        raise ValueError(
            f"You need to define width {width} and trans {trans} or angle {angle}"
            f" and center {center} or dcplx_trans {dcplx_trans}"
        )
    if info:
        port.info.update(info)

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

Ports

Bases: ProtoPorts[int], ICreatePort

A collection of dbu ports.

It is not a traditional dictionary. Elements can be retrieved as in a traditional dictionary. But to keep tabs on names etc, the ports are stored as a list

Source code in kfactory/ports.py
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
class Ports(ProtoPorts[int], ICreatePort):
    """A collection of dbu ports.

    It is not a traditional dictionary. Elements can be retrieved as in a traditional
    dictionary. But to keep tabs on names etc, the ports are stored as a list
    """

    yaml_tag: ClassVar[str] = "!Ports"

    def __iter__(self) -> Iterator[Port]:
        """Iterator, that allows for loops etc to directly access the object."""
        yield from (Port(base=b) for b in self._bases)

    def add_port(
        self,
        *,
        port: ProtoPort[Any],
        name: str | None = None,
        keep_mirror: bool = False,
    ) -> Port:
        """Add a port object.

        Args:
            port: The port to add
            name: Overwrite the name of the port
            keep_mirror: Keep the mirror flag from the original port if `True`,
                else set [Port.trans.mirror][kfactory.Port.trans] (or the complex
                equivalent) to `False`.
        """
        if port.kcl == self.kcl:
            base = port.base.model_copy()
            if not keep_mirror:
                if base.trans is not None:
                    base.trans.mirror = False
                elif base.dcplx_trans is not None:
                    base.dcplx_trans.mirror = False
            if name is not None:
                base.name = name
            self._bases.append(base)
            port_ = Port(base=base)
        else:
            dcplx_trans = port.dcplx_trans.dup()
            if not keep_mirror:
                dcplx_trans.mirror = False
            base = port.base.model_copy()
            base.trans = kdb.Trans.R0
            base.dcplx_trans = None
            base.kcl = self.kcl
            base.cross_section = self.kcl.get_symmetrical_cross_section(
                port.cross_section.base.to_dtype(port.kcl)
            )
            if name is not None:
                base.name = name
            port_ = Port(base=base)
            port_.dcplx_trans = dcplx_trans
            self._bases.append(port_.base)
        return port_

    def get_all_named(self) -> Mapping[str, Port]:
        """Get all ports in a dictionary with names as keys."""
        return {v.name: Port(base=v) for v in self._bases if v.name is not None}

    @overload
    def __getitem__(self, key: int | str | None) -> Port:
        """Get a port by index or name."""

    @overload
    def __getitem__(self, key: slice) -> Self:
        """Get ports by slice."""

    def __getitem__(self, key: slice | int | str | None) -> Self | Port:
        if isinstance(key, int):
            return Port(base=self._bases[key])
        if isinstance(key, slice):
            return self.__class__(bases=self._bases[key], kcl=self.kcl)
        try:
            return Port(base=next(filter(lambda base: base.name == key, self._bases)))
        except StopIteration as e:
            raise KeyError(
                f"{key=} is not a valid port name or index. "
                f"Available ports: {[v.name for v in self._bases]}"
            ) from e

    def copy(
        self, rename_function: Callable[[Sequence[Port]], None] | None = None
    ) -> Self:
        """Get a copy of each port."""
        bases = [b.__copy__() for b in self._bases]
        if rename_function is not None:
            rename_function([Port(base=b) for b in bases])
        return self.__class__(bases=bases, kcl=self.kcl)

    def filter(
        self,
        angle: Angle | None = None,
        orientation: float | None = None,
        layer: LayerEnum | int | None = None,
        port_type: str | None = None,
        regex: str | None = None,
    ) -> list[Port]:
        """Filter ports.

        Args:
            angle: Filter by angle. 0, 1, 2, 3.
            orientation: Filter by orientation in degrees.
            layer: Filter by layer.
            port_type: Filter by port type.
            regex: Filter by regex of the name.
        """
        return _filter_ports(
            (Port(base=b) for b in self._bases),
            angle,
            orientation,
            layer,
            port_type,
            regex,
        )

    def __repr__(self) -> str:
        """Representation of the Ports as strings."""
        return repr([repr(DPort(base=b)) for b in self._bases])

__iter__

__iter__() -> Iterator[Port]

Iterator, that allows for loops etc to directly access the object.

Source code in kfactory/ports.py
671
672
673
def __iter__(self) -> Iterator[Port]:
    """Iterator, that allows for loops etc to directly access the object."""
    yield from (Port(base=b) for b in self._bases)

__repr__

__repr__() -> str

Representation of the Ports as strings.

Source code in kfactory/ports.py
780
781
782
def __repr__(self) -> str:
    """Representation of the Ports as strings."""
    return repr([repr(DPort(base=b)) for b in self._bases])

add_port

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

Add a port object.

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 flag from the original port if True, else set [Port.trans.mirror][kfactory.Port.trans] (or the complex equivalent) to False.

False
Source code in kfactory/ports.py
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
def add_port(
    self,
    *,
    port: ProtoPort[Any],
    name: str | None = None,
    keep_mirror: bool = False,
) -> Port:
    """Add a port object.

    Args:
        port: The port to add
        name: Overwrite the name of the port
        keep_mirror: Keep the mirror flag from the original port if `True`,
            else set [Port.trans.mirror][kfactory.Port.trans] (or the complex
            equivalent) to `False`.
    """
    if port.kcl == self.kcl:
        base = port.base.model_copy()
        if not keep_mirror:
            if base.trans is not None:
                base.trans.mirror = False
            elif base.dcplx_trans is not None:
                base.dcplx_trans.mirror = False
        if name is not None:
            base.name = name
        self._bases.append(base)
        port_ = Port(base=base)
    else:
        dcplx_trans = port.dcplx_trans.dup()
        if not keep_mirror:
            dcplx_trans.mirror = False
        base = port.base.model_copy()
        base.trans = kdb.Trans.R0
        base.dcplx_trans = None
        base.kcl = self.kcl
        base.cross_section = self.kcl.get_symmetrical_cross_section(
            port.cross_section.base.to_dtype(port.kcl)
        )
        if name is not None:
            base.name = name
        port_ = Port(base=base)
        port_.dcplx_trans = dcplx_trans
        self._bases.append(port_.base)
    return port_

copy

copy(
    rename_function: Callable[[Sequence[Port]], None]
    | None = None,
) -> Self

Get a copy of each port.

Source code in kfactory/ports.py
745
746
747
748
749
750
751
752
def copy(
    self, rename_function: Callable[[Sequence[Port]], None] | None = None
) -> Self:
    """Get a copy of each port."""
    bases = [b.__copy__() for b in self._bases]
    if rename_function is not None:
        rename_function([Port(base=b) for b in bases])
    return self.__class__(bases=bases, kcl=self.kcl)

filter

filter(
    angle: Angle | None = None,
    orientation: float | None = None,
    layer: LayerEnum | int | None = None,
    port_type: str | None = None,
    regex: str | None = None,
) -> list[Port]

Filter ports.

Parameters:

Name Type Description Default
angle Angle | None

Filter by angle. 0, 1, 2, 3.

None
orientation float | None

Filter by orientation in degrees.

None
layer LayerEnum | int | None

Filter by layer.

None
port_type str | None

Filter by port type.

None
regex str | None

Filter by regex of the name.

None
Source code in kfactory/ports.py
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
def filter(
    self,
    angle: Angle | None = None,
    orientation: float | None = None,
    layer: LayerEnum | int | None = None,
    port_type: str | None = None,
    regex: str | None = None,
) -> list[Port]:
    """Filter ports.

    Args:
        angle: Filter by angle. 0, 1, 2, 3.
        orientation: Filter by orientation in degrees.
        layer: Filter by layer.
        port_type: Filter by port type.
        regex: Filter by regex of the name.
    """
    return _filter_ports(
        (Port(base=b) for b in self._bases),
        angle,
        orientation,
        layer,
        port_type,
        regex,
    )

get_all_named

get_all_named() -> Mapping[str, Port]

Get all ports in a dictionary with names as keys.

Source code in kfactory/ports.py
720
721
722
def get_all_named(self) -> Mapping[str, Port]:
    """Get all ports in a dictionary with names as keys."""
    return {v.name: Port(base=v) for v in self._bases if v.name is not None}

ProtoPorts

Bases: Protocol

Base class for kf.Ports, kf.DPorts.

Source code in kfactory/ports.py
 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
 87
 88
 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
class ProtoPorts[T: (int, float)](Protocol):
    """Base class for kf.Ports, kf.DPorts."""

    _kcl: KCLayout
    _locked: bool
    _bases: list[BasePort]

    @overload
    def __init__(self, *, kcl: KCLayout) -> None: ...

    @overload
    def __init__(
        self,
        *,
        kcl: KCLayout,
        ports: Iterable[ProtoPort[Any]] | None = None,
    ) -> None: ...

    @overload
    def __init__(
        self,
        *,
        kcl: KCLayout,
        bases: list[BasePort] | None = None,
    ) -> None: ...

    def __init__(
        self,
        *,
        kcl: KCLayout,
        ports: Iterable[ProtoPort[Any]] | None = None,
        bases: list[BasePort] | None = None,
    ) -> None:
        """Initialize the Ports.

        Args:
            kcl: The KCLayout instance.
            ports: The ports to add.
            bases: The bases to add.
        """
        self.kcl = kcl
        if bases is not None:
            self._bases = bases
        elif ports is not None:
            self._bases = [p.base for p in ports]
        else:
            self._bases = []
        self._locked = False

    def __len__(self) -> int:
        """Return Port count."""
        return len(self._bases)

    @property
    def bases(self) -> list[BasePort]:
        """Get the bases."""
        return self._bases

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

    @kcl.setter
    def kcl(self, value: KCLayout) -> None:
        """Set the KCLayout."""
        self._kcl = value

    @abstractmethod
    def copy(
        self,
        rename_function: Callable[[Sequence[ProtoPort[T]]], None] | None = None,
    ) -> Self:
        """Get a copy of each port."""
        ...

    def to_itype(self) -> Ports:
        """Convert to a Ports."""
        return Ports(kcl=self.kcl, bases=self._bases)

    def to_dtype(self) -> DPorts:
        """Convert to a DPorts."""
        return DPorts(kcl=self.kcl, bases=self._bases)

    @abstractmethod
    def __iter__(self) -> Iterator[ProtoPort[T]]:
        """Iterator over the Ports."""
        ...

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

    @abstractmethod
    def get_all_named(self) -> Mapping[str, ProtoPort[T]]:
        """Get all ports in a dictionary with names as keys.

        This filters out Ports with `None` as name.
        """
        ...

    def add_ports(
        self,
        ports: Iterable[ProtoPort[Any]],
        prefix: str = "",
        keep_mirror: bool = False,
        suffix: str = "",
    ) -> None:
        """Append a list of ports."""
        for p in ports:
            name = p.name or ""
            self.add_port(port=p, name=prefix + name + suffix, keep_mirror=keep_mirror)

    @overload
    @abstractmethod
    def __getitem__(self, key: int | str | None) -> ProtoPort[T]:
        """Get a port by index or name."""
        ...

    @overload
    @abstractmethod
    def __getitem__(self, key: slice) -> Self:
        """Get ports by slice."""
        ...

    @abstractmethod
    def filter(
        self,
        angle: Angle | None = None,
        orientation: float | None = None,
        layer: LayerEnum | int | None = None,
        port_type: str | None = None,
        regex: str | None = None,
    ) -> Sequence[ProtoPort[T]]:
        """Filter ports.

        Args:
            angle: Filter by angle. 0, 1, 2, 3.
            orientation: Filter by orientation in degrees.
            layer: Filter by layer.
            port_type: Filter by port type.
            regex: Filter by regex of the name.
        """
        ...

    def __contains__(self, port: str | ProtoPort[Any] | BasePort) -> bool:
        """Check whether a port is in this port collection."""
        if isinstance(port, ProtoPort):
            return port.base in self._bases
        if isinstance(port, BasePort):
            return port in self._bases
        return any(_port.name == port for _port in self._bases)

    def clear(self) -> None:
        """Deletes all ports."""
        self._bases.clear()

    def __eq__(self, other: object) -> bool:
        """Support for `ports1 == ports2` comparisons."""
        if isinstance(other, Iterable):
            if len(self._bases) != len(list(other)):
                return False
            return all(b1 == b2 for b1, b2 in zip(iter(self), other, strict=False))
        return False

    def print(
        self,
        unit: Literal["dbu", "um"] | None = None,
    ) -> None:
        """Pretty print ports."""
        config.console.print(pprint_ports(self, unit=unit))

    def pformat(self, unit: Literal["dbu", "um"] | None = None) -> str:
        """Pretty print ports."""
        with config.console.capture() as capture:
            config.console.print(pprint_ports(self, unit=unit))
        return str(capture.get())

    def __hash__(self) -> int:
        """Hash the ports."""
        return hash(self._bases)

bases property

bases: list[BasePort]

Get the bases.

kcl property writable

kcl: KCLayout

Get the KCLayout.

__contains__

__contains__(port: str | ProtoPort[Any] | BasePort) -> bool

Check whether a port is in this port collection.

Source code in kfactory/ports.py
213
214
215
216
217
218
219
def __contains__(self, port: str | ProtoPort[Any] | BasePort) -> bool:
    """Check whether a port is in this port collection."""
    if isinstance(port, ProtoPort):
        return port.base in self._bases
    if isinstance(port, BasePort):
        return port in self._bases
    return any(_port.name == port for _port in self._bases)

__eq__

__eq__(other: object) -> bool

Support for ports1 == ports2 comparisons.

Source code in kfactory/ports.py
225
226
227
228
229
230
231
def __eq__(self, other: object) -> bool:
    """Support for `ports1 == ports2` comparisons."""
    if isinstance(other, Iterable):
        if len(self._bases) != len(list(other)):
            return False
        return all(b1 == b2 for b1, b2 in zip(iter(self), other, strict=False))
    return False

__hash__

__hash__() -> int

Hash the ports.

Source code in kfactory/ports.py
246
247
248
def __hash__(self) -> int:
    """Hash the ports."""
    return hash(self._bases)

__init__

__init__(*, kcl: KCLayout) -> None
__init__(
    *,
    kcl: KCLayout,
    ports: Iterable[ProtoPort[Any]] | None = None,
) -> None
__init__(
    *, kcl: KCLayout, bases: list[BasePort] | None = None
) -> None
__init__(
    *,
    kcl: KCLayout,
    ports: Iterable[ProtoPort[Any]] | None = None,
    bases: list[BasePort] | None = None,
) -> None

Initialize the Ports.

Parameters:

Name Type Description Default
kcl KCLayout

The KCLayout instance.

required
ports Iterable[ProtoPort[Any]] | None

The ports to add.

None
bases list[BasePort] | None

The bases to add.

None
Source code in kfactory/ports.py
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
def __init__(
    self,
    *,
    kcl: KCLayout,
    ports: Iterable[ProtoPort[Any]] | None = None,
    bases: list[BasePort] | None = None,
) -> None:
    """Initialize the Ports.

    Args:
        kcl: The KCLayout instance.
        ports: The ports to add.
        bases: The bases to add.
    """
    self.kcl = kcl
    if bases is not None:
        self._bases = bases
    elif ports is not None:
        self._bases = [p.base for p in ports]
    else:
        self._bases = []
    self._locked = False

__iter__ abstractmethod

__iter__() -> Iterator[ProtoPort[T]]

Iterator over the Ports.

Source code in kfactory/ports.py
145
146
147
148
@abstractmethod
def __iter__(self) -> Iterator[ProtoPort[T]]:
    """Iterator over the Ports."""
    ...

__len__

__len__() -> int

Return Port count.

Source code in kfactory/ports.py
110
111
112
def __len__(self) -> int:
    """Return Port count."""
    return len(self._bases)

add_port abstractmethod

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

Add a port.

Source code in kfactory/ports.py
150
151
152
153
154
155
156
157
158
159
@abstractmethod
def add_port(
    self,
    *,
    port: ProtoPort[Any],
    name: str | None = None,
    keep_mirror: bool = False,
) -> ProtoPort[T]:
    """Add a port."""
    ...

add_ports

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

Append a list of ports.

Source code in kfactory/ports.py
169
170
171
172
173
174
175
176
177
178
179
def add_ports(
    self,
    ports: Iterable[ProtoPort[Any]],
    prefix: str = "",
    keep_mirror: bool = False,
    suffix: str = "",
) -> None:
    """Append a list of ports."""
    for p in ports:
        name = p.name or ""
        self.add_port(port=p, name=prefix + name + suffix, keep_mirror=keep_mirror)

clear

clear() -> None

Deletes all ports.

Source code in kfactory/ports.py
221
222
223
def clear(self) -> None:
    """Deletes all ports."""
    self._bases.clear()

copy abstractmethod

copy(
    rename_function: Callable[
        [Sequence[ProtoPort[T]]], None
    ]
    | None = None,
) -> Self

Get a copy of each port.

Source code in kfactory/ports.py
129
130
131
132
133
134
135
@abstractmethod
def copy(
    self,
    rename_function: Callable[[Sequence[ProtoPort[T]]], None] | None = None,
) -> Self:
    """Get a copy of each port."""
    ...

filter abstractmethod

filter(
    angle: Angle | None = None,
    orientation: float | None = None,
    layer: LayerEnum | int | None = None,
    port_type: str | None = None,
    regex: str | None = None,
) -> Sequence[ProtoPort[T]]

Filter ports.

Parameters:

Name Type Description Default
angle Angle | None

Filter by angle. 0, 1, 2, 3.

None
orientation float | None

Filter by orientation in degrees.

None
layer LayerEnum | int | None

Filter by layer.

None
port_type str | None

Filter by port type.

None
regex str | None

Filter by regex of the name.

None
Source code in kfactory/ports.py
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
@abstractmethod
def filter(
    self,
    angle: Angle | None = None,
    orientation: float | None = None,
    layer: LayerEnum | int | None = None,
    port_type: str | None = None,
    regex: str | None = None,
) -> Sequence[ProtoPort[T]]:
    """Filter ports.

    Args:
        angle: Filter by angle. 0, 1, 2, 3.
        orientation: Filter by orientation in degrees.
        layer: Filter by layer.
        port_type: Filter by port type.
        regex: Filter by regex of the name.
    """
    ...

get_all_named abstractmethod

get_all_named() -> Mapping[str, ProtoPort[T]]

Get all ports in a dictionary with names as keys.

This filters out Ports with None as name.

Source code in kfactory/ports.py
161
162
163
164
165
166
167
@abstractmethod
def get_all_named(self) -> Mapping[str, ProtoPort[T]]:
    """Get all ports in a dictionary with names as keys.

    This filters out Ports with `None` as name.
    """
    ...

pformat

pformat(unit: Literal['dbu', 'um'] | None = None) -> str

Pretty print ports.

Source code in kfactory/ports.py
240
241
242
243
244
def pformat(self, unit: Literal["dbu", "um"] | None = None) -> str:
    """Pretty print ports."""
    with config.console.capture() as capture:
        config.console.print(pprint_ports(self, unit=unit))
    return str(capture.get())

print

print(unit: Literal['dbu', 'um'] | None = None) -> None

Pretty print ports.

Source code in kfactory/ports.py
233
234
235
236
237
238
def print(
    self,
    unit: Literal["dbu", "um"] | None = None,
) -> None:
    """Pretty print ports."""
    config.console.print(pprint_ports(self, unit=unit))

to_dtype

to_dtype() -> DPorts

Convert to a DPorts.

Source code in kfactory/ports.py
141
142
143
def to_dtype(self) -> DPorts:
    """Convert to a DPorts."""
    return DPorts(kcl=self.kcl, bases=self._bases)

to_itype

to_itype() -> Ports

Convert to a Ports.

Source code in kfactory/ports.py
137
138
139
def to_itype(self) -> Ports:
    """Convert to a Ports."""
    return Ports(kcl=self.kcl, bases=self._bases)