Skip to content

Cross section

cross_section

CrossSections for KFactory.

AsymmetricCrossSection

Bases: TAsymmetricCrossSection[int]

dbu-flavored wrapper around an AsymmetricalCrossSection.

Source code in kfactory/cross_section.py
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
class AsymmetricCrossSection(TAsymmetricCrossSection[int]):
    """dbu-flavored wrapper around an `AsymmetricalCrossSection`."""

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

    @overload
    def __init__(
        self,
        kcl: KCLayout,
        section_min: int,
        section_max: int,
        layer: kdb.LayerInfo,
        sections: Sequence[CrossSectionLayer] = (),
        name: str | None = None,
        radius: int | None = None,
        radius_min: int | None = None,
        bbox_sections: dict[kdb.LayerInfo, int] | None = None,
    ) -> None: ...

    def __init__(
        self,
        kcl: KCLayout,
        section_min: int | None = None,
        section_max: int | None = None,
        layer: kdb.LayerInfo | None = None,
        sections: Sequence[CrossSectionLayer] = (),
        name: str | None = None,
        radius: int | None = None,
        radius_min: int | None = None,
        bbox_sections: dict[kdb.LayerInfo, int] | None = None,
        base: AsymmetricalCrossSection | None = None,
    ) -> None:
        if base is None:
            if section_min is None or section_max is None or layer is None:
                raise ValueError(
                    "If no base is given, section_min, section_max, and layer"
                    " must be defined"
                )
            base = kcl.get_asymmetrical_cross_section(
                AsymmetricalCrossSection(
                    layer=layer,
                    section_min=section_min,
                    section_max=section_max,
                    sections=tuple(sections),
                    name=name or "",
                    radius=radius,
                    radius_min=radius_min,
                    bbox_sections=bbox_sections or {},
                )
            )
        self.kcl = kcl
        self._base = base

    @property
    def width(self) -> int:
        return self._base.width

    @property
    def section_min(self) -> int:
        return self._base.section_min

    @property
    def section_max(self) -> int:
        return self._base.section_max

    @property
    def sections(self) -> tuple[CrossSectionLayer, ...]:
        return self._base.sections

    @property
    def radius(self) -> int | None:
        return self._base.radius

    @property
    def radius_min(self) -> int | None:
        return self._base.radius_min

    @property
    def bbox_sections(self) -> dict[kdb.LayerInfo, int]:
        return self._base.bbox_sections.copy()

    def get_xmin_xmax(self) -> tuple[int, int]:
        return (self._base.get_xmin(), self._base.get_xmax())

AsymmetricalCrossSection pydantic-model

Bases: BaseModel

Cross section composed of independent layer strips at signed bounds.

The main strip (layer, section_min, section_max) is the port reference; sections holds any additional strips. All bounds are signed integer dbu relative to the port centerline (x = 0). Strip edges are always grid-aligned regardless of width parity.

Fields:

  • layer (LayerInfo)
  • section_min (dbu)
  • section_max (dbu)
  • sections (tuple[CrossSectionLayer, ...])
  • name (str)
  • radius (dbu | None)
  • radius_min (dbu | None)
  • bbox_sections (dict[LayerInfo, dbu])

Validators:

  • _normalize
  • _validate
Source code in kfactory/cross_section.py
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
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
class AsymmetricalCrossSection(BaseModel, frozen=True, arbitrary_types_allowed=True):
    """Cross section composed of independent layer strips at signed bounds.

    The main strip (`layer`, `section_min`, `section_max`) is the port
    reference; `sections` holds any additional strips. All bounds are signed
    integer dbu relative to the port centerline (`x = 0`). Strip edges are
    always grid-aligned regardless of width parity.
    """

    layer: kdb.LayerInfo
    section_min: dbu
    section_max: dbu
    sections: tuple[CrossSectionLayer, ...] = ()
    name: str = ""
    radius: dbu | None = None
    radius_min: dbu | None = None
    bbox_sections: dict[kdb.LayerInfo, dbu] = Field(default_factory=dict)

    @model_validator(mode="before")
    @classmethod
    def _normalize(cls, data: Any) -> Any:
        if not isinstance(data, dict):
            return data
        sections = data.get("sections", ())
        coerced: list[CrossSectionLayer] = []
        for s in sections:
            if isinstance(s, CrossSectionLayer):
                coerced.append(s)
            else:
                coerced.append(CrossSectionLayer.model_validate(s))
        data["sections"] = _normalize_sections(coerced)
        if not data.get("name"):
            data["name"] = _asym_auto_name(
                data["layer"],
                data["section_min"],
                data["section_max"],
                data["sections"],
                data.get("bbox_sections") or {},
            )
        return data

    def auto_name(self) -> str:
        """Deterministic structural name (hash of geometry, excluding radius)."""
        return _asym_auto_name(
            self.layer,
            self.section_min,
            self.section_max,
            self.sections,
            self.bbox_sections,
        )

    @property
    def is_named(self) -> bool:
        """Whether an explicit name was given (vs. the derived structural name)."""
        return self.name != self.auto_name()

    @model_validator(mode="after")
    def _validate(self) -> Self:
        if self.section_min >= self.section_max:
            raise ValueError(
                "section_min must be strictly less than section_max"
                f" (got section_min={self.section_min},"
                f" section_max={self.section_max})."
            )
        return self

    @property
    def width(self) -> int:
        """Main strip width in dbu (`section_max - section_min`)."""
        return self.section_max - self.section_min

    @property
    def main_layer(self) -> kdb.LayerInfo:
        """Main layer of the cross section (parity with SymmetricalCrossSection)."""
        return self.layer

    def to_dtype(self, kcl: KCLayout) -> DAsymmetricalCrossSection:
        return DAsymmetricalCrossSection(
            layer=self.layer,
            section_min=kcl.to_um(self.section_min),
            section_max=kcl.to_um(self.section_max),
            sections=tuple(
                DCrossSectionLayer(
                    layer=s.layer,
                    section_min=kcl.to_um(s.section_min),
                    section_max=kcl.to_um(s.section_max),
                )
                for s in self.sections
            ),
            name=self.name,
            radius=kcl.to_um(self.radius) if self.radius is not None else None,
            radius_min=kcl.to_um(self.radius_min)
            if self.radius_min is not None
            else None,
            bbox_sections={k: kcl.to_um(v) for k, v in self.bbox_sections.items()},
        )

    def is_symmetric(self) -> bool:
        """Whether this cross section is symmetric."""
        return False

    def _all_strips(self) -> tuple[tuple[int, int], ...]:
        """Return (section_min, section_max) for main + every aux section."""
        return (
            (self.section_min, self.section_max),
            *((s.section_min, s.section_max) for s in self.sections),
        )

    def get_xmin(self) -> int:
        return min(lo for lo, _ in self._all_strips())

    def get_xmax(self) -> int:
        return max(hi for _, hi in self._all_strips())

    def model_copy(
        self, *, update: Mapping[str, Any] | None = {"name": None}, deep: bool = False
    ) -> AsymmetricalCrossSection:
        return super().model_copy(update=update, deep=deep)

    def __eq__(self, o: object) -> bool:
        if isinstance(o, (SymmetricalCrossSection, TCrossSection)):
            return False
        if isinstance(o, TAsymmetricCrossSection):
            return self == o.base
        if isinstance(o, AsymmetricalCrossSection):
            # radius/radius_min are non-identifying metadata.
            return (
                self.layer == o.layer
                and self.section_min == o.section_min
                and self.section_max == o.section_max
                and self.sections == o.sections
                and self.name == o.name
                and self.bbox_sections == o.bbox_sections
            )
        return NotImplemented

    def __hash__(self) -> int:
        return hash(
            (
                self.layer,
                self.section_min,
                self.section_max,
                self.sections,
                self.name,
                tuple(sorted(self.bbox_sections.items(), key=lambda kv: kv[0].name)),
            )
        )

    def _sort_key(
        self,
    ) -> tuple[
        str, int, int, int, int, tuple[tuple[str, int, int, int, int], ...], str
    ]:
        return (
            self.layer.name,
            self.layer.layer,
            self.layer.datatype,
            self.section_min,
            self.section_max,
            tuple(s._sort_key() for s in self.sections),
            self.name,
        )

    def __lt__(self, other: object) -> bool:
        if not isinstance(other, AsymmetricalCrossSection):
            return NotImplemented
        return self._sort_key() < other._sort_key()

    def __le__(self, other: object) -> bool:
        if not isinstance(other, AsymmetricalCrossSection):
            return NotImplemented
        return self._sort_key() <= other._sort_key()

    def __gt__(self, other: object) -> bool:
        if not isinstance(other, AsymmetricalCrossSection):
            return NotImplemented
        return self._sort_key() > other._sort_key()

    def __ge__(self, other: object) -> bool:
        if not isinstance(other, AsymmetricalCrossSection):
            return NotImplemented
        return self._sort_key() >= other._sort_key()

is_named property

is_named: bool

Whether an explicit name was given (vs. the derived structural name).

main_layer property

main_layer: LayerInfo

Main layer of the cross section (parity with SymmetricalCrossSection).

width property

width: int

Main strip width in dbu (section_max - section_min).

auto_name

auto_name() -> str

Deterministic structural name (hash of geometry, excluding radius).

Source code in kfactory/cross_section.py
433
434
435
436
437
438
439
440
441
def auto_name(self) -> str:
    """Deterministic structural name (hash of geometry, excluding radius)."""
    return _asym_auto_name(
        self.layer,
        self.section_min,
        self.section_max,
        self.sections,
        self.bbox_sections,
    )

is_symmetric

is_symmetric() -> bool

Whether this cross section is symmetric.

Source code in kfactory/cross_section.py
489
490
491
def is_symmetric(self) -> bool:
    """Whether this cross section is symmetric."""
    return False

CrossSectionLayer pydantic-model

Bases: BaseModel

Single strip in an asymmetrical cross section.

A strip on layer spanning [section_min, section_max] in dbu relative to the port centerline (offset=0). Both bounds are signed integer dbu, so edges are always grid-aligned. The strip's width is the derived section_max - section_min.

Fields:

  • layer (LayerInfo)
  • section_min (dbu)
  • section_max (dbu)

Validators:

  • _validate_bounds
Source code in kfactory/cross_section.py
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
class CrossSectionLayer(BaseModel, frozen=True, arbitrary_types_allowed=True):
    """Single strip in an asymmetrical cross section.

    A strip on `layer` spanning `[section_min, section_max]` in dbu relative to
    the port centerline (`offset=0`). Both bounds are signed integer dbu, so
    edges are always grid-aligned. The strip's width is the derived
    `section_max - section_min`.
    """

    layer: kdb.LayerInfo
    section_min: dbu
    section_max: dbu

    @model_validator(mode="after")
    def _validate_bounds(self) -> Self:
        if self.section_min >= self.section_max:
            raise ValueError(
                "section_min must be strictly less than section_max (got"
                f" section_min={self.section_min},"
                f" section_max={self.section_max})."
            )
        return self

    @property
    def width(self) -> int:
        """Width of the strip in dbu (`section_max - section_min`)."""
        return self.section_max - self.section_min

    def _sort_key(self) -> tuple[str, int, int, int, int]:
        return (
            self.layer.name,
            self.layer.layer,
            self.layer.datatype,
            self.section_min,
            self.section_max,
        )

    def __lt__(self, other: object) -> bool:
        if not isinstance(other, CrossSectionLayer):
            return NotImplemented
        return self._sort_key() < other._sort_key()

    def __le__(self, other: object) -> bool:
        if not isinstance(other, CrossSectionLayer):
            return NotImplemented
        return self._sort_key() <= other._sort_key()

    def __gt__(self, other: object) -> bool:
        if not isinstance(other, CrossSectionLayer):
            return NotImplemented
        return self._sort_key() > other._sort_key()

    def __ge__(self, other: object) -> bool:
        if not isinstance(other, CrossSectionLayer):
            return NotImplemented
        return self._sort_key() >= other._sort_key()

width property

width: int

Width of the strip in dbu (section_max - section_min).

CrossSectionModel pydantic-model

Bases: BaseModel

Fields:

Source code in kfactory/cross_section.py
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
class CrossSectionModel(BaseModel):
    cross_sections: dict[str, SymmetricalCrossSection | AsymmetricalCrossSection] = (
        Field(default_factory=dict)
    )
    kcl: KCLayout

    def __getitem__(
        self, name: str
    ) -> SymmetricalCrossSection | AsymmetricalCrossSection:
        return self.cross_sections[name]

    def get_asymmetrical_cross_section(
        self,
        cross_section: str | AsymmetricalCrossSection | DAsymmetricalCrossSection,
    ) -> AsymmetricalCrossSection:
        if isinstance(cross_section, str):
            xs = self.cross_sections[cross_section]
            if not isinstance(xs, AsymmetricalCrossSection):
                raise TypeError(
                    f"Cross section {cross_section!r} is symmetric; use "
                    "get_(symmetrical_)cross_section."
                )
            return xs
        if isinstance(cross_section, DAsymmetricalCrossSection):
            cross_section = cross_section.to_itype(self.kcl)
        registered = self._register(cross_section)
        assert isinstance(registered, AsymmetricalCrossSection)
        return registered

    def _register(
        self, cross_section: SymmetricalCrossSection | AsymmetricalCrossSection
    ) -> SymmetricalCrossSection | AsymmetricalCrossSection:
        """Register/resolve a cross section by its canonical (structural) name.

        Entries are keyed by their `auto_name()` and, when named, additionally by
        the explicit name. Existence is a single `get(auto_name())`.
        """
        auto = cross_section.auto_name()
        canonical = self.cross_sections.get(auto)
        if canonical is None:
            if cross_section.is_named and cross_section.name in self.cross_sections:
                raise CrossSectionNamingConflictError(
                    f"Cross section name {cross_section.name!r} is already "
                    "registered for a different structural signature."
                )
            self.cross_sections[auto] = cross_section
            if cross_section.is_named:
                self.cross_sections[cross_section.name] = cross_section
            return cross_section
        if not cross_section.is_named:
            return _resolve_radius(canonical, cross_section)
        if canonical.is_named:
            if canonical.name == cross_section.name:
                return _resolve_radius(canonical, cross_section)
            raise CrossSectionNamingConflictError(
                f"Cannot register cross section {cross_section.name!r}: the same "
                f"structural signature is already registered as {canonical.name!r}."
                " A structure can have at most one name."
            )
        # Promote the unnamed canonical to the named one (radius must match).
        _resolve_radius(canonical, cross_section)
        self.cross_sections[auto] = cross_section
        self.cross_sections[cross_section.name] = cross_section
        return cross_section

    def get_cross_section(
        self,
        cross_section: str
        | SymmetricalCrossSection
        | DSymmetricalCrossSection
        | CrossSectionSpecDict
        | DCrossSectionSpecDict
        | CrossSection
        | DCrossSection,
    ) -> SymmetricalCrossSection:
        if isinstance(cross_section, str):
            xs = self.cross_sections[cross_section]
            if not isinstance(xs, SymmetricalCrossSection):
                raise TypeError(
                    f"Cross section {cross_section!r} is asymmetric; use "
                    "get_asymmetrical_cross_section."
                )
            return xs
        if isinstance(cross_section, TCrossSection):
            cross_section = cross_section.base
        if isinstance(cross_section, SymmetricalCrossSection):
            canonical_enc = self.kcl.get_enclosure(cross_section.enclosure)
            if cross_section.enclosure != canonical_enc:
                return self.get_cross_section(
                    SymmetricalCrossSection(
                        enclosure=canonical_enc,
                        # Preserve named/unnamed provenance: re-derive the auto
                        # name from the canonical enclosure when unnamed.
                        name=cross_section.name if cross_section.is_named else None,
                        width=cross_section.width,
                        radius=cross_section.radius,
                        radius_min=cross_section.radius_min,
                    )
                )
        elif isinstance(cross_section, DSymmetricalCrossSection):
            cross_section = cross_section.to_itype(self.kcl)

        elif cross_section.get("unit", "dbu") == "dbu":
            cross_section = SymmetricalCrossSection(
                width=cross_section["width"],  # ty:ignore[invalid-argument-type]
                enclosure=self.kcl.layer_enclosures.get_enclosure(
                    LayerEnclosureSpec(
                        sections=cross_section.get("sections", []),  # ty:ignore[invalid-argument-type]
                        main_layer=cross_section["layer"],
                        name=cross_section.get("enclosure", {}).get("name"),
                    ),
                    kcl=self.kcl,
                ),
                name=cross_section.get("name", None),
            )
        else:
            cross_section = SymmetricalCrossSection(
                width=self.kcl.to_dbu(cross_section["width"]),
                enclosure=self.kcl.layer_enclosures.get_enclosure(
                    LayerEnclosureSpec(
                        sections=[
                            (section[0], self.kcl.to_dbu(section[1]))
                            if len(section) == 2
                            else (
                                section[0],
                                self.kcl.to_dbu(section[1]),
                                self.kcl.to_dbu(section[2]),
                            )
                            for section in cross_section.get("sections", [])
                        ],
                        main_layer=cross_section["layer"],
                        name=cross_section.get("enclosure", {}).get("name"),
                    ),
                    kcl=self.kcl,
                ),
                name=cross_section.get("name", None),
            )
        registered = self._register(cross_section)
        assert isinstance(registered, SymmetricalCrossSection)
        return registered

    def __repr__(self) -> str:
        return repr(self.cross_sections)

DAsymmetricCrossSection

Bases: TAsymmetricCrossSection[float]

um-flavored wrapper around an AsymmetricalCrossSection.

Source code in kfactory/cross_section.py
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
class DAsymmetricCrossSection(TAsymmetricCrossSection[float]):
    """um-flavored wrapper around an `AsymmetricalCrossSection`."""

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

    @overload
    def __init__(
        self,
        kcl: KCLayout,
        section_min: float,
        section_max: float,
        layer: kdb.LayerInfo,
        sections: Sequence[DCrossSectionLayer] = (),
        name: str | None = None,
        radius: float | None = None,
        radius_min: float | None = None,
        bbox_sections: dict[kdb.LayerInfo, float] | None = None,
    ) -> None: ...

    def __init__(
        self,
        kcl: KCLayout,
        section_min: float | None = None,
        section_max: float | None = None,
        layer: kdb.LayerInfo | None = None,
        sections: Sequence[DCrossSectionLayer] = (),
        name: str | None = None,
        radius: float | None = None,
        radius_min: float | None = None,
        bbox_sections: dict[kdb.LayerInfo, float] | None = None,
        base: AsymmetricalCrossSection | None = None,
    ) -> None:
        if base is None:
            if section_min is None or section_max is None or layer is None:
                raise ValueError(
                    "If no base is given, section_min, section_max, and layer"
                    " must be defined"
                )
            base = kcl.get_asymmetrical_cross_section(
                DAsymmetricalCrossSection(
                    layer=layer,
                    section_min=section_min,
                    section_max=section_max,
                    sections=tuple(sections),
                    name=name,
                    radius=radius,
                    radius_min=radius_min,
                    bbox_sections=bbox_sections or {},
                ).to_itype(kcl)
            )
        self.kcl = kcl
        self._base = base

    @property
    def width(self) -> float:
        return self.kcl.to_um(self._base.width)

    @property
    def section_min(self) -> float:
        return self.kcl.to_um(self._base.section_min)

    @property
    def section_max(self) -> float:
        return self.kcl.to_um(self._base.section_max)

    @property
    def sections(self) -> tuple[DCrossSectionLayer, ...]:
        return tuple(
            DCrossSectionLayer(
                layer=s.layer,
                section_min=self.kcl.to_um(s.section_min),
                section_max=self.kcl.to_um(s.section_max),
            )
            for s in self._base.sections
        )

    @property
    def radius(self) -> float | None:
        r = self._base.radius
        return self.kcl.to_um(r) if r is not None else None

    @property
    def radius_min(self) -> float | None:
        r = self._base.radius_min
        return self.kcl.to_um(r) if r is not None else None

    @property
    def bbox_sections(self) -> dict[kdb.LayerInfo, float]:
        return {k: self.kcl.to_um(v) for k, v in self._base.bbox_sections.items()}

    def get_xmin_xmax(self) -> tuple[float, float]:
        return (
            self.kcl.to_um(self._base.get_xmin()),
            self.kcl.to_um(self._base.get_xmax()),
        )

DAsymmetricalCrossSection pydantic-model

Bases: BaseModel

um based AsymmetricalCrossSection.

Fields:

  • layer (LayerInfo)
  • section_min (float)
  • section_max (float)
  • sections (tuple[DCrossSectionLayer, ...])
  • name (str | None)
  • radius (float | None)
  • radius_min (float | None)
  • bbox_sections (dict[LayerInfo, float])

Validators:

  • _validate_bounds
Source code in kfactory/cross_section.py
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
class DAsymmetricalCrossSection(BaseModel, arbitrary_types_allowed=True):
    """um based AsymmetricalCrossSection."""

    layer: kdb.LayerInfo
    section_min: float
    section_max: float
    sections: tuple[DCrossSectionLayer, ...] = ()
    name: str | None = None
    radius: float | None = None
    radius_min: float | None = None
    bbox_sections: dict[kdb.LayerInfo, float] = Field(default_factory=dict)

    @model_validator(mode="after")
    def _validate_bounds(self) -> Self:
        if self.section_min >= self.section_max:
            raise ValueError(
                "section_min must be strictly less than section_max"
                f" (got section_min={self.section_min},"
                f" section_max={self.section_max})."
            )
        return self

    @property
    def width(self) -> float:
        """Main strip width in um (`section_max - section_min`)."""
        return self.section_max - self.section_min

    def is_symmetric(self) -> bool:
        """Whether this cross section is symmetric."""
        return False

    def to_itype(self, kcl: KCLayout) -> AsymmetricalCrossSection:
        return AsymmetricalCrossSection(
            layer=self.layer,
            section_min=kcl.to_dbu(self.section_min),
            section_max=kcl.to_dbu(self.section_max),
            sections=tuple(s.to_itype(kcl) for s in self.sections),
            name=self.name or "",
            radius=kcl.to_dbu(self.radius) if self.radius is not None else None,
            radius_min=kcl.to_dbu(self.radius_min)
            if self.radius_min is not None
            else None,
            bbox_sections={k: kcl.to_dbu(v) for k, v in self.bbox_sections.items()},
        )

width property

width: float

Main strip width in um (section_max - section_min).

is_symmetric

is_symmetric() -> bool

Whether this cross section is symmetric.

Source code in kfactory/cross_section.py
603
604
605
def is_symmetric(self) -> bool:
    """Whether this cross section is symmetric."""
    return False

DCrossSectionLayer pydantic-model

Bases: BaseModel

um based CrossSectionLayer.

Fields:

  • layer (LayerInfo)
  • section_min (float)
  • section_max (float)

Validators:

  • _validate_bounds
Source code in kfactory/cross_section.py
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
class DCrossSectionLayer(BaseModel, arbitrary_types_allowed=True):
    """um based CrossSectionLayer."""

    layer: kdb.LayerInfo
    section_min: float
    section_max: float

    @model_validator(mode="after")
    def _validate_bounds(self) -> Self:
        if self.section_min >= self.section_max:
            raise ValueError(
                "section_min must be strictly less than section_max (got"
                f" section_min={self.section_min},"
                f" section_max={self.section_max})."
            )
        return self

    @property
    def width(self) -> float:
        """Width of the strip in um (`section_max - section_min`)."""
        return self.section_max - self.section_min

    def to_itype(self, kcl: KCLayout) -> CrossSectionLayer:
        return CrossSectionLayer(
            layer=self.layer,
            section_min=kcl.to_dbu(self.section_min),
            section_max=kcl.to_dbu(self.section_max),
        )

width property

width: float

Width of the strip in um (section_max - section_min).

DSymmetricalCrossSection pydantic-model

Bases: BaseModel

um based CrossSection.

Fields:

  • width (float)
  • enclosure (DLayerEnclosure)
  • name (str | None)

Validators:

  • _validate_width
Source code in kfactory/cross_section.py
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
class DSymmetricalCrossSection(BaseModel):
    """um based CrossSection."""

    width: float
    enclosure: DLayerEnclosure
    name: str | None = None

    @model_validator(mode="after")
    def _validate_width(self) -> Self:
        if self.width <= 0:
            raise ValueError("Width must be greater than 0.")
        return self

    def is_symmetric(self) -> bool:
        """Whether this cross section is symmetric."""
        return True

    def to_itype(self, kcl: KCLayout) -> SymmetricalCrossSection:
        """Convert to a dbu based CrossSection."""
        return SymmetricalCrossSection(
            width=kcl.to_dbu(self.width),
            enclosure=kcl.get_enclosure(self.enclosure.to_itype(kcl)),
            name=self.name,
        )

is_symmetric

is_symmetric() -> bool

Whether this cross section is symmetric.

Source code in kfactory/cross_section.py
198
199
200
def is_symmetric(self) -> bool:
    """Whether this cross section is symmetric."""
    return True

to_itype

to_itype(kcl: KCLayout) -> SymmetricalCrossSection

Convert to a dbu based CrossSection.

Source code in kfactory/cross_section.py
202
203
204
205
206
207
208
def to_itype(self, kcl: KCLayout) -> SymmetricalCrossSection:
    """Convert to a dbu based CrossSection."""
    return SymmetricalCrossSection(
        width=kcl.to_dbu(self.width),
        enclosure=kcl.get_enclosure(self.enclosure.to_itype(kcl)),
        name=self.name,
    )

SymmetricalCrossSection pydantic-model

Bases: BaseModel

CrossSection which is symmetrical to its main_layer/width.

Fields:

Validators:

  • _set_name
  • _validate_enclosure_main_layer
  • _validate_width
Source code in kfactory/cross_section.py
 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
 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
class SymmetricalCrossSection(BaseModel, frozen=True, arbitrary_types_allowed=True):
    """CrossSection which is symmetrical to its main_layer/width."""

    width: dbu
    enclosure: LayerEnclosure
    name: str = ""
    radius: dbu | None = None
    radius_min: dbu | None = None

    def __init__(
        self,
        width: dbu,
        enclosure: LayerEnclosure,
        name: str | None = None,
        radius: dbu | None = None,
        radius_min: dbu | None = None,
    ) -> None:
        """Initialized the CrossSection.

        `bbox_sections` live on the `enclosure` — build the enclosure with them.
        """
        super().__init__(
            width=width,
            enclosure=enclosure,
            name=name or f"{enclosure.name}_{width}",
            radius=radius,
            radius_min=radius_min,
        )

    @property
    def bbox_sections(self) -> dict[kdb.LayerInfo, dbu]:
        """Bounding-box sections (owned by the enclosure)."""
        return self.enclosure.bbox_sections

    def auto_name(self) -> str:
        return f"{self.enclosure.name}_{self.width}"

    @property
    def is_named(self) -> bool:
        """Whether an explicit name was given (vs. the enclosure-derived name)."""
        return self.name != self.auto_name()

    @property
    def extent(self) -> dbu:
        return 0

    @model_validator(mode="before")
    @classmethod
    def _set_name(cls, data: Any) -> Any:
        if not isinstance(data, dict):
            return data
        data["name"] = data.get("name") or f"{data['enclosure'].name}_{data['width']}"
        return data

    @model_validator(mode="after")
    def _validate_enclosure_main_layer(self) -> Self:
        if self.enclosure.main_layer is None:
            raise ValueError("Enclosures of cross sections must have a main layer.")
        if self.width % 2:
            raise ValueError(
                "Width of symmetrical cross sections must have be a multiple of 2 dbu. "
                "This could cause cross sections and extrusions to become unsymmetrical"
                " otherwise."
            )
        if not self.width:
            raise ValueError("Cross section with width 0 is not allowed.")
        return self

    @model_validator(mode="after")
    def _validate_width(self) -> Self:
        if self.width <= 0:
            raise ValueError("Width must be greater than 0.")
        return self

    @property
    def main_layer(self) -> kdb.LayerInfo:
        """Main Layer of the enclosure and cross section."""
        assert self.enclosure.main_layer is not None
        return self.enclosure.main_layer

    def is_symmetric(self) -> bool:
        """Whether this cross section is symmetric."""
        return True

    def to_dtype(self, kcl: KCLayout) -> DSymmetricalCrossSection:
        """Convert to a um based CrossSection."""
        return DSymmetricalCrossSection(
            width=kcl.to_um(self.width),
            enclosure=self.enclosure.to_dtype(kcl),
            name=self.name,
        )

    def get_xmax(self) -> int:
        return self.width // 2 + max(
            s.d_max
            for sections in self.enclosure.layer_sections.values()
            for s in sections.sections
        )

    def get_xmin(self) -> int:
        # Symmetric by construction: the full extent is mirrored about the center line.
        return -self.get_xmax()

    def model_copy(
        self, *, update: Mapping[str, Any] | None = {"name": None}, deep: bool = False
    ) -> SymmetricalCrossSection:
        return super().model_copy(update=update, deep=deep)

    def __eq__(self, o: object) -> bool:
        if isinstance(o, (AsymmetricalCrossSection, TAsymmetricCrossSection)):
            return False
        if isinstance(o, TCrossSection):
            return self == o.base
        if isinstance(o, SymmetricalCrossSection):
            # radius/radius_min are non-identifying metadata.
            return (
                self.width == o.width
                and self.enclosure == o.enclosure
                and self.name == o.name
            )
        return NotImplemented

    def __hash__(self) -> int:
        return hash((self.width, self.enclosure, self.name))

bbox_sections property

bbox_sections: dict[LayerInfo, dbu]

Bounding-box sections (owned by the enclosure).

is_named property

is_named: bool

Whether an explicit name was given (vs. the enclosure-derived name).

main_layer property

main_layer: LayerInfo

Main Layer of the enclosure and cross section.

__init__

__init__(
    width: dbu,
    enclosure: LayerEnclosure,
    name: str | None = None,
    radius: dbu | None = None,
    radius_min: dbu | None = None,
) -> None

Initialized the CrossSection.

bbox_sections live on the enclosure — build the enclosure with them.

Source code in kfactory/cross_section.py
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
def __init__(
    self,
    width: dbu,
    enclosure: LayerEnclosure,
    name: str | None = None,
    radius: dbu | None = None,
    radius_min: dbu | None = None,
) -> None:
    """Initialized the CrossSection.

    `bbox_sections` live on the `enclosure` — build the enclosure with them.
    """
    super().__init__(
        width=width,
        enclosure=enclosure,
        name=name or f"{enclosure.name}_{width}",
        radius=radius,
        radius_min=radius_min,
    )

is_symmetric

is_symmetric() -> bool

Whether this cross section is symmetric.

Source code in kfactory/cross_section.py
139
140
141
def is_symmetric(self) -> bool:
    """Whether this cross section is symmetric."""
    return True

to_dtype

to_dtype(kcl: KCLayout) -> DSymmetricalCrossSection

Convert to a um based CrossSection.

Source code in kfactory/cross_section.py
143
144
145
146
147
148
149
def to_dtype(self, kcl: KCLayout) -> DSymmetricalCrossSection:
    """Convert to a um based CrossSection."""
    return DSymmetricalCrossSection(
        width=kcl.to_um(self.width),
        enclosure=self.enclosure.to_dtype(kcl),
        name=self.name,
    )

TAsymmetricCrossSection

Bases: ABC

Unit-flavored wrapper around an AsymmetricalCrossSection base.

Mirrors TCrossSection for the symmetric case: both the dbu wrapper (AsymmetricCrossSection) and the um wrapper (DAsymmetricCrossSection) hold the same AsymmetricalCrossSection as _base, so they compare equal across units via .base.

Source code in kfactory/cross_section.py
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
class TAsymmetricCrossSection[T: (int, float)](ABC):
    """Unit-flavored wrapper around an `AsymmetricalCrossSection` base.

    Mirrors `TCrossSection` for the symmetric case: both the dbu wrapper
    (`AsymmetricCrossSection`) and the um wrapper (`DAsymmetricCrossSection`)
    hold the same `AsymmetricalCrossSection` as `_base`, so they compare equal
    across units via `.base`.
    """

    _base: AsymmetricalCrossSection = PrivateAttr()
    kcl: KCLayout

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

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

    @property
    def layer(self) -> kdb.LayerInfo:
        return self._base.layer

    @property
    def main_layer(self) -> kdb.LayerInfo:
        return self._base.layer

    def is_symmetric(self) -> bool:
        """Whether this cross section is symmetric."""
        return False

    @property
    @abstractmethod
    def width(self) -> T: ...

    @property
    @abstractmethod
    def section_min(self) -> T: ...

    @property
    @abstractmethod
    def section_max(self) -> T: ...

    @property
    @abstractmethod
    def sections(
        self,
    ) -> tuple[CrossSectionLayer, ...] | tuple[DCrossSectionLayer, ...]: ...

    @property
    @abstractmethod
    def radius(self) -> T | None: ...

    @property
    @abstractmethod
    def radius_min(self) -> T | None: ...

    @property
    @abstractmethod
    def bbox_sections(self) -> dict[kdb.LayerInfo, T]: ...

    @abstractmethod
    def get_xmin_xmax(self) -> tuple[T, T]: ...

    def to_itype(self) -> AsymmetricCrossSection:
        return AsymmetricCrossSection(kcl=self.kcl, base=self._base)

    def to_dtype(self) -> DAsymmetricCrossSection:
        return DAsymmetricCrossSection(kcl=self.kcl, base=self._base)

    def __eq__(self, o: object) -> bool:
        if isinstance(o, TAsymmetricCrossSection):
            return self.base == o.base
        if isinstance(o, AsymmetricalCrossSection):
            return self.base == o
        return False

    def __hash__(self) -> int:
        return hash(self._base)

is_symmetric

is_symmetric() -> bool

Whether this cross section is symmetric.

Source code in kfactory/cross_section.py
659
660
661
def is_symmetric(self) -> bool:
    """Whether this cross section is symmetric."""
    return False

TCrossSection

Bases: ABC

Source code in kfactory/cross_section.py
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
class TCrossSection[T: (int, float)](ABC):
    _base: SymmetricalCrossSection = PrivateAttr()
    kcl: KCLayout

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

    @overload
    @abstractmethod
    def __init__(
        self,
        kcl: KCLayout,
        width: T,
        layer: kdb.LayerInfo,
        sections: Sequence[tuple[T, T] | tuple[T]],
        radius: T | None = None,
        radius_min: T | None = None,
        bbox_layers: Sequence[kdb.LayerInfo] | None = None,
        bbox_offsets: Sequence[T] | None = None,
    ) -> None: ...

    @abstractmethod
    def __init__(
        self,
        kcl: KCLayout,
        width: T | None = None,
        layer: kdb.LayerInfo | None = None,
        sections: Sequence[tuple[T, T] | tuple[T]] | None = None,
        radius: T | None = None,
        radius_min: T | None = None,
        bbox_layers: Sequence[kdb.LayerInfo] | None = None,
        bbox_offsets: Sequence[T] | None = None,
        base: SymmetricalCrossSection | None = None,
    ) -> None: ...

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

    @property
    @abstractmethod
    def width(self) -> T: ...

    @property
    def layer(self) -> kdb.LayerInfo:
        return self._base.main_layer

    @property
    def enclosure(self) -> LayerEnclosure:
        return self._base.enclosure

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

    def to_itype(self) -> CrossSection:
        return CrossSection(kcl=self.kcl, base=self._base)

    def to_dtype(self) -> DCrossSection:
        return DCrossSection(kcl=self.kcl, base=self._base)

    @property
    @abstractmethod
    def sections(self) -> dict[kdb.LayerInfo, list[tuple[T | None, T]]]: ...

    @property
    @abstractmethod
    def radius(self) -> T | None: ...

    @property
    @abstractmethod
    def radius_min(self) -> T | None: ...

    @property
    @abstractmethod
    def bbox_sections(
        self,
    ) -> dict[kdb.LayerInfo, T]: ...

    @abstractmethod
    def get_xmin_xmax(self) -> tuple[T, T]: ...

    @abstractmethod
    def model_copy(
        self, *, update: Mapping[str, Any] = {"name": None}, deep: bool
    ) -> Self: ...

    def __eq__(self, o: object) -> bool:
        if isinstance(o, TCrossSection):
            return self.base == o.base
        if isinstance(o, SymmetricalCrossSection):
            return self.base == o
        return False

    @property
    def main_layer(self) -> kdb.LayerInfo:
        """Main Layer of the enclosure and cross section."""
        return self.base.main_layer

    def is_symmetric(self) -> bool:
        """Whether this cross section is symmetric."""
        return True

main_layer property

main_layer: LayerInfo

Main Layer of the enclosure and cross section.

is_symmetric

is_symmetric() -> bool

Whether this cross section is symmetric.

Source code in kfactory/cross_section.py
997
998
999
def is_symmetric(self) -> bool:
    """Whether this cross section is symmetric."""
    return True