Skip to content
Edit this page

ictdesigntools.cabling.channels

Cable channels: equipment port to equipment port through cable assemblies and the parts that join them (adapters, cassettes, splitters, splices), checked, budgeted and drawn.

A Channel is its items in order. Equipment is a port at an end (a transceiver, a switch port). An Assembly (cabling.assemblies) is a patch cord, trunk or breakout. Bulk is a length of cable with bare fiber at either end, or a factory plug (a pigtail), for splicing. Part places a join from parts.joins (count of them side by side), in a patch panel when panel names one (a TIA-606 identifier from identifiers).

problems() finds plugs that do not fit the next part, plugs meeting plugs or sockets meeting sockets, connector counts that differ, angled (APC) plugs meeting flat ones in an adapter, and splices not between bare fiber. loss() budgets the channel with the ANSI/TIA-568.3 maxima: fiber attenuation by length, 0.75 dB a mated pair inside the channel, 0.3 dB a splice, and each splitter's own loss.

channel_drawing() draws it from the side: parts and plugs at 1:1, cable lengths to scale (mm of drawing per metre), and any run longer than coil_over_m drawn that long with the rest wound into a coil marked with the true length. Each part can carry its own dimension line (dims), and the channel's total is dimensioned under them.

>>> from .assemblies import assembly
>>> ch = Channel((
...     Equipment("Switch", "lc", ports=2),
...     assembly("lc-lc-duplex-om4-2m"),
...     Part("lc-adapter", panel="AD02-35"),
...     assembly("lc-lc-duplex-om4-2m"),
...     Equipment("Server", "lc", ports=2),
... ))
>>> ch.problems(), ch.length_m
([], 4.022)
>>> [(r.what, round(r.db, 3)) for r in ch.loss(850)]
[('Fiber, 4 m', 0.014), ('Mated pairs, 2 × 0.75 dB', 1.5)]

Equipment dataclass

Equipment(
    name: str,
    connector: str,
    ports: int = 1,
    polish: str = "",
)

A port at a channel's end: ports of connector (a connectors.toml slug).

Bulk dataclass

Bulk(
    name: str,
    type: str,
    length_m: float,
    a: End | None = None,
    b: End | None = None,
    outside_plant: bool = False,
)

A length of cable of a NetBox cable type with bare fiber at an end for splicing, or a factory plug there (a, b) for a pigtail.

Part dataclass

Part(
    slug: str,
    count: int = 0,
    label: str = "",
    panel: str = "",
    flip: bool | None = None,
)

A join from parts.joins by slug, count side by side (0: as many as the plugs that enter it), with a label and the panel it is mounted in. flip turns it round (a cassette's LC side first); by default it is turned to suit the plugs on its left.

Channel dataclass

Channel(items: tuple[Item, ...], name: str = '')

length_m property

length_m: float

Cable lengths plus the lengths of the parts the light passes through (adapters, cassettes, splitters; a splice sleeve sits over the fiber and adds none).

count

count(i: int) -> int

How many of a part sit side by side (its own count, or the plugs entering it).

Source code in src/ictdesigntools/cabling/channels.py
def count(self, i: int) -> int:
    """How many of a part sit side by side (its own count, or the plugs entering it)."""
    p = self.items[i]
    if not isinstance(p, Part):
        return 1
    if p.count:
        return p.count
    if i and p.join.a_ports == 1 and p.join.kind in ("adapter", "fusion-splice",
                                                     "mechanical-splice"):  # fmt: skip
        return self._side(i - 1, "b").count
    return 1

flipped

flipped(i: int) -> bool

Whether part i is turned round, its B side facing left.

Source code in src/ictdesigntools/cabling/channels.py
def flipped(self, i: int) -> bool:
    """Whether part ``i`` is turned round, its B side facing left."""
    p = self.items[i]
    if not isinstance(p, Part):
        return False
    if p.flip is not None:
        return p.flip
    j = p.join
    if not i or j.a == j.b or isinstance(self.items[i - 1], Part):
        return False
    return self._side(i - 1, "b").connector == j.b

polarity

polarity() -> Channel | None

The channel as cabling.polarity parts, to trace lanes and check transmit meets receive, pins and polish end to end: array cables become trunks, two-cord duplex assemblies A-to-B (type B) or A-to-A cords, cassettes fiber transitions behind their rear adapters, and array adapters adapters. None when the channel carries no array (MPO or MMC) cable, or has parts this cannot follow (a breakout, a splitter, splices).

Source code in src/ictdesigntools/cabling/channels.py
def polarity(self) -> pol.Channel | None:
    """The channel as ``cabling.polarity`` parts, to trace lanes and check transmit meets
    receive, pins and polish end to end: array cables become trunks, two-cord duplex
    assemblies A-to-B (type B) or A-to-A cords, cassettes fiber transitions behind their
    rear adapters, and array adapters adapters. None when the channel carries no array
    (MPO or MMC) cable, or has parts this cannot follow (a breakout, a splitter, splices).
    """
    parts: list = []
    n = 0
    for i, it in enumerate(self.items):
        if isinstance(it, Equipment):
            continue
        if isinstance(it, Bulk):
            return None
        if isinstance(it, Assembly):
            p = it.profile
            if p.kind == "breakout":
                return None
            if it.a.connector in ("mpo", "mmc"):
                if p.a_connectors != 1 or p.b_connectors != 1:
                    return None
                n = n or p.a_positions
                parts.append(pol.Trunk(it.polarity, it.a, it.b))
            elif p.a_connectors == 2 and p.a_positions == 1:
                parts.append(pol.Cord("A-to-B" if it.polarity == "B" else "A-to-A"))
            else:
                return None
            continue
        j = it.join
        if j.kind == "adapter" and j.keying:
            parts.append(pol.Adapter(j.keying))
        elif j.kind == "cassette" and j.transition:
            n = n or j.a_positions
            left = self.flipped(i)  # the duplex side faces left: near end of the channel
            trunk_end = self._array_end(i, left)
            plug = End("mpo", trunk_end.polish if trunk_end else "", "unpinned")
            t = pol.Transition(j.transition, plug, far=not left)
            adapter = pol.Adapter(j.keying or "KU-KD")
            parts.extend((t, adapter) if left else (adapter, t))
        elif j.kind != "adapter":
            return None
    if not n or not any(isinstance(p, pol.Trunk) for p in parts):
        return None
    return pol.Channel(tuple(parts), n, _method(parts))

loss

loss(
    wavelength_nm: int = 1310, grade: str = ""
) -> list[LossRow]

The channel's loss, row by row: fiber by type and length, the mated pairs inside the channel (not the equipment's own ports), splices, and splitters. Mated pairs take the ANSI/TIA-568.3 maximum, or with grade an IEC 61753-1 attenuation grade's 97 % maximum (optical.components: B, C or D; Bm or Cm for multimode).

Source code in src/ictdesigntools/cabling/channels.py
def loss(self, wavelength_nm: int = 1310, grade: str = "") -> list[LossRow]:
    """The channel's loss, row by row: fiber by type and length, the mated pairs inside
    the channel (not the equipment's own ports), splices, and splitters. Mated pairs take
    the ANSI/TIA-568.3 maximum, or with ``grade`` an IEC 61753-1 attenuation grade's
    97 % maximum (``optical.components``: B, C or D; Bm or Cm for multimode)."""
    mated_db = components.grade(grade).max_db if grade else CONNECTION_LOSS_DB
    rows: dict[str, list] = {}
    fiber_km = 0.0
    fiber_db = 0.0
    cables = []
    for i, it in enumerate(self.items):
        t = it.type if isinstance(it, (Assembly, Bulk)) else ""
        if not t.startswith(("smf", "mmf")):
            continue
        family = "mmf" if t.startswith("mmf") else "smf"
        if family == "smf" and isinstance(it, Bulk) and it.outside_plant:
            family = "smf-osp"
        band = min((w for f, w in ATTENUATION_DB_PER_KM if f == family),
                   key=lambda w: abs(w - wavelength_nm))  # fmt: skip
        km = _length_m(it) / 1000
        fiber_km += km
        fiber_db += km * ATTENUATION_DB_PER_KM[(family, band)]
        cables.append(i)
    out = []
    if cables:
        out.append(LossRow(f"Fiber, {fiber_km * 1000:g} m", fiber_db, tuple(cables)))
    for i, it in enumerate(self.items):
        if not isinstance(it, Part):
            continue
        j, k = it.join, self.count(i)
        rows.setdefault("connections", []).extend([i] * (j.connections * k))
        rows.setdefault("splices", []).extend([i] * (j.splices * k))
        if j.loss_db:
            out.append(LossRow(j.name, j.loss_db * k, (i,)))
    # Count each part once per row, however many mated pairs it holds.
    if n := len(rows.get("connections", [])):
        items = tuple(sorted(set(rows["connections"])))
        label = f"grade {components.grade(grade).grade}, " if grade else ""
        out.append(LossRow(f"Mated pairs, {label}{n} × {mated_db:g} dB", n * mated_db,
                           items))  # fmt: skip
    if n := len(rows.get("splices", [])):
        items = tuple(sorted(set(rows["splices"])))
        out.append(LossRow(f"Splices, {n} × {SPLICE_LOSS_DB:g} dB", n * SPLICE_LOSS_DB,
                           items))  # fmt: skip
    # Put the fiber first, then parts in the order they add up.
    return out[:1] + sorted(out[1:], key=lambda r: r.what.startswith("PLC"))

channel_drawing

channel_drawing(
    ch: Channel,
    scale: float = 20.0,
    coil_over_m: float = 5.0,
    dims: str | set[int] = "cables",
    wavelength_nm: int | None = None,
    title: str = "",
) -> Drawing

The channel from the side, left to right.

scale is millimetres of drawing per metre of cable (20: 1:50). A run longer than coil_over_m is drawn that long and the rest wound into a coil, marked with the true length and "not to scale". Plugs and parts are drawn at 1:1. dims says which items get a dimension line of their own: "cables" (assemblies and bulk cable), "all", "none", or a set of item indexes; the channel's total length is always dimensioned. wavelength_nm adds the loss budget under the drawing.

Source code in src/ictdesigntools/cabling/channels.py
def channel_drawing(ch: Channel, scale: float = 20.0, coil_over_m: float = 5.0,
                    dims: str | set[int] = "cables", wavelength_nm: int | None = None,
                    title: str = "") -> Drawing:  # fmt: skip
    """The channel from the side, left to right.

    ``scale`` is millimetres of drawing per metre of cable (20: 1:50). A run longer than
    ``coil_over_m`` is drawn that long and the rest wound into a coil, marked with the true
    length and "not to scale". Plugs and parts are drawn at 1:1. ``dims`` says which items get
    a dimension line of their own: ``"cables"`` (assemblies and bulk cable), ``"all"``,
    ``"none"``, or a set of item indexes; the channel's total length is always dimensioned.
    ``wavelength_nm`` adds the loss budget under the drawing."""
    items = ch.items
    used = {e.connector for it in items if isinstance(it, Assembly) for e in (it.a, it.b)}
    used |= {e.connector for it in items if isinstance(it, Bulk) for e in (it.a, it.b) if e}
    known = [plug(c) for c in used if c in plugs()]
    pitch = max([p.housing_h_mm for p in known] + [6.0]) + 7.0

    def rows(n: int) -> tuple[float, ...]:
        return tuple(round((k - (n - 1) / 2) * pitch, 3) for k in range(n))

    def depth(i: int) -> float:
        if not 0 <= i < len(items):
            return 0.0
        it = items[i]
        if isinstance(it, Equipment):
            return EQUIPMENT_DEPTH_MM
        if isinstance(it, Part):
            return it.join.depth_mm
        return 0.0

    def cable_type(it) -> str:
        return it.type if isinstance(it, (Assembly, Bulk)) else ""

    styles = {
        **PART_STYLES,
        **JOIN_STYLES,
        "cable": Style(stroke="#5f5e58", width=2.0),
        "leg": Style(stroke="#5f5e58", width=1.6),
        "equipment": Style(fill="#d6d5cf", stroke=INK, width=0.3),
        "port": Style(fill="#1d1c1a", stroke="#55534d", width=0.2),
        "panel": Style(fill="#8f8e84", stroke=INK, width=0.2),
        "furcation": Style(fill="#3c3b37", stroke=INK, width=0.3),
        "label": Style(color=INK),
        "quiet": Style(color=MUTED),
    }
    back: list = []  # cables and plugs, under the parts they enter
    front: list = []  # parts and equipment
    notes: list = []  # labels over the drawing
    spans: list[tuple[int, float, float, str]] = []  # item, x from, x to, dimension text
    coiled = False
    chain = ch.polarity()
    x = 0.0
    ys_all = [0.0]

    def plugs_at(face: float, ys, end: End, ctype: str, left: bool) -> float:
        """Plugs with their faces at ``face``, pointing left (end A) or right; returns where
        their boots end."""
        if end.connector not in plugs():
            return face
        p = plug(end.connector)
        side = plug_side(end.connector, tone_for(ctype, end.polish))
        for y in ys:
            t = translate(face, y) if left else translate(face, y) @ Transform.mirror_x()
            back.append(Use(side, t))
        return face + (p.body_mm + p.boot_mm) * (1 if left else -1)

    def coil(cx: float, y: float, length_m: float) -> None:
        r = COIL_R_MM
        for k in (-1, 0, 1):
            c = cx + k * r * 0.22
            pts = tuple((c + r * _cos(a), y - r + r * _sin(a)) for a in range(0, 361, 10))
            back.append(Polyline(pts, style="cable"))
        notes.append(Text(cx, y - 2 * r - 3, f"{_fmt_m(length_m)} coiled", 2.6,
                          style="quiet"))  # fmt: skip

    for i, it in enumerate(items):
        if isinstance(it, Equipment):
            ys = rows(it.ports)
            ys_all += ys
            top, bottom = min(ys) - pitch / 2, max(ys) + pitch / 2
            first = i == 0
            x0 = x  # at the start, the block's left edge; at the end, its face
            front.append(Rect(x0, top, EQUIPMENT_MM, bottom - top, rx=1.5, style="equipment"))
            face = x0 + EQUIPMENT_MM if first else x0
            for y in ys:
                px = face - 6 if first else face
                front.append(Rect(px, y - 2.5, 6, 5, rx=0.5, style="port"))
            notes.append(Text(x0 + EQUIPMENT_MM / 2, top - 3, it.name, 3.0, style="label"))
            spans.append((i, face, face, ""))
            x = x0 + EQUIPMENT_MM
            continue
        if isinstance(it, Part):
            j = it.join
            # Draw the ports in use: as many as the plugs either side (all, when none).
            sa, sb = ch._side(i, "a"), ch._side(i, "b")
            na = ch._side(i - 1, "b").count if i and ch._side(i - 1, "b").role == "plug" else 0
            nb = (ch._side(i + 1, "a").count if i + 1 < len(items)
                  and ch._side(i + 1, "a").role == "plug" else 0)  # fmt: skip
            a_ys, b_ys = rows(min(na, sa.count) or sa.count), rows(min(nb, sb.count) or sb.count)
            turned = ch.flipped(i)
            comp_a, comp_b = (b_ys, a_ys) if turned else (a_ys, b_ys)
            ys_all += a_ys + b_ys
            tone = ""
            for nb in (i - 1, i + 1):
                if 0 <= nb < len(items) and cable_type(items[nb]):
                    end = items[nb].b if nb < i else items[nb].a
                    tone = tone_for(cable_type(items[nb]), end.polish if end else "")
                    break
            if j.splice:  # the fiber runs through the sleeve
                for y in a_ys:
                    back.append(Line(x, y, x + j.length_mm, y, style="leg"))
            t = (translate(x + j.length_mm, 0) @ Transform.mirror_x() if turned
                 else translate(x, 0))  # fmt: skip
            front.append(Use(join_side(it.slug, comp_a, comp_b, tone), t))
            top = min(a_ys + b_ys) - j.height_mm / 2
            if it.panel:
                # An adapter mounts at its flange; a cassette or splitter at its front (B) face.
                if j.kind == "adapter":
                    px = x + j.length_mm / 2
                else:
                    px = x + (9.0 if turned else j.length_mm - 9.0)
                bottom = max(a_ys + b_ys) + j.height_mm / 2
                front.append(Rect(px - 0.8, top - 8, 1.6, bottom - top + 16, style="panel"))
                notes.append(Text(px, top - 11, it.panel, 2.4, style="quiet"))
                top -= 8
            label = it.label or j.name
            boxed = 3.0 if j.kind in ("cassette", "splitter") else 0.0
            notes.append(Text(x + j.length_mm / 2, top - boxed - (7 if it.panel else 3), label,
                              2.6, style="label"))  # fmt: skip
            spans.append((i, x, x + j.length_mm, _fmt_m(j.length_mm / 1000)))
            x += j.length_mm
            continue
        # A cable: an assembly or bulk cable, plug faces inside the parts either side.
        ctype = cable_type(it)
        if isinstance(it, Assembly):
            na, nb = it.profile.a_connectors, it.profile.b_connectors
            end_a, end_b, legs = it.a, it.b, it.legs
        else:
            na = nb = 1
            end_a, end_b, legs = it.a, it.b, None
        ys_a, ys_b = rows(na), rows(nb)
        ys_all += ys_a + ys_b
        fa = x - depth(i - 1)
        ea = plugs_at(fa, ys_a, end_a, ctype, True) if end_a else fa
        length = _length_m(it)
        leg_m = legs.leg_length_m if legs else 0.0
        trunk_m = max(length - leg_m, 0.0)
        drawn = min(trunk_m, coil_over_m) * scale
        coil_w = 2.6 * COIL_R_MM if trunk_m > coil_over_m else 0.0
        leg_w = max(leg_m * scale, 30.0) if legs else 0.0
        split = 0.0 if legs else min(30.0, drawn * 0.3)
        eb = ea + drawn + coil_w + leg_w  # cords part within the drawn length
        pb = plug(end_b.connector) if end_b and end_b.connector in plugs() else None
        fb = eb + (pb.body_mm + pb.boot_mm if pb else 0.0)
        if end_b:
            plugs_at(fb, ys_b, end_b, ctype, False)
        # The cable between the boots: cords run apart then join, legs fan from a furcation.
        ja = ea + (split if na > 1 else 0)
        jb = eb - (leg_w if legs else (split if nb > 1 else 0))
        bend = 10.0
        for y in ys_a if na > 1 else ():
            back.append(Polyline(((ea, y),) + tuple(s_curve((ja - bend, y), (ja, 0))),
                                 style="leg"))  # fmt: skip
        back.append(Line(ja, 0, jb, 0, style="cable"))
        for y in ys_b if nb > 1 else ():
            if legs:
                back.append(Polyline(tuple(s_curve((jb, 0), (eb, y))), style="leg"))
            else:
                back.append(Polyline(tuple(s_curve((jb, 0), (jb + bend, y))) + ((eb, y),),
                                     style="leg"))  # fmt: skip
        if legs:
            front.append(Rect(jb - 6, -2.4, 12, 4.8, rx=2.4, style="furcation"))
        if coil_w:
            coiled = True
            coil((ja + jb) / 2, 0, trunk_m - coil_over_m)
        name = it.name
        if chain and isinstance(it, Assembly) and it.a.connector in ("mpo", "mmc"):
            name += f" · {chain.descriptor()}"
        notes.append(Text((ja + jb) / 2, min(ys_a + ys_b) - pitch / 2 - 2
                          - (2 * COIL_R_MM + 4 if coil_w else 0), name, 2.6,
                          style="label"))  # fmt: skip
        text = _fmt_m(length) + (" (not to scale)" if coil_w else "")
        spans.append((i, fa if end_a else ea, fb if end_b else eb, text))
        x = fb - depth(i + 1) if end_b else eb

    top = min(ys_all) - pitch / 2 - (2 * COIL_R_MM + 8 if coiled else 0) - 16
    bottom = max(ys_all) + pitch / 2 + 6
    want = (
        set(range(len(items))) if dims == "all"
        else set() if dims == "none"
        else {i for i, it in enumerate(items) if isinstance(it, (Assembly, Bulk))}
        if dims == "cables" else set(dims)
    )  # fmt: skip
    d = Drawing(units="mm", stroke=0.3, font=2.6, styles=styles,
                title=title or ch.name or "Cable channel",
                desc=f"Parts and plugs 1:1; cable lengths 1:{1000 / scale:g}"
                f"{f', runs over {coil_over_m:g} m coiled and not to scale' if coiled else ''}."
                )  # fmt: skip
    for it in back + front + notes:
        d.add(it)
    y = bottom
    row = 0
    for i, x1, x2, text in spans:
        if i in want and x2 > x1:
            d.add(Dim(x1, y + 6 + 9 * (row % 2), x2, y + 6 + 9 * (row % 2), text, -3))
            row += 1
    y += 6 + (18 if row > 1 else 9 if row else 0)
    # The channel runs from the first plug to the last (equipment ports are its ends).
    inner = [sp for sp in spans if not isinstance(items[sp[0]], Equipment)] or spans
    x_first, x_last = inner[0][1], inner[-1][2]
    d.add(Dim(x_first, y + 6, x_last, y + 6, f"Channel {_fmt_m(ch.length_m)}", -3))
    y += 16
    if wavelength_nm:
        d.add(Text(x_first, y, f"Loss at {wavelength_nm} nm (TIA-568.3 maxima)", 3.0,
                   anchor="start", style="label"))  # fmt: skip
        for r in ch.loss(wavelength_nm):
            y += 5
            d.add(Text(x_first, y, r.what, 2.6, anchor="start", style="quiet"))
            d.add(Text(x_first + 90, y, f"{r.db:.2f} dB", 2.6, anchor="end", style="quiet"))
        y += 5
        d.add(Text(x_first, y, "Total", 2.6, anchor="start", style="label"))
        d.add(Text(x_first + 90, y, f"{ch.total_loss(wavelength_nm):.2f} dB", 2.6,
                   anchor="end", style="label"))  # fmt: skip
        y += 6
    if title or ch.name:
        d.add(Text(min(0.0, x_first), top, title or ch.name, 4.0, anchor="start",
                   style="label"))  # fmt: skip
    return d.fit(8)