Skip to content
Edit this page

ictdesigntools.spaces.racks

Racks and cabinets: what is mounted where, whether it fits, and the elevation drawing.

The model follows NetBox DCIM, so a design moves into NetBox and back without translation: RackType is a NetBox rack type, DeviceType a device type, Role a device role, and Device a device placed at a position (its lowest unit, counted on the rails from the rack's starting_unit) on a face. Units are whole or half (u_height 0.5, 1, 1.5 …).

check finds what does not fit: positions off the rails, overlaps on a face (a full-depth device takes both faces), weight over the rack's rating, power over a budget, and airflow that runs against the rest of the rack. elevation draws the front and rear with the library's drawing engine (ictdesigntools.draw), so it can be written out as SVG, PDF or DXF.

Generic racks and equipment come from data/racks.toml (rack_types(), device_types(), roles()); custom ones are made directly.

>>> rack = Rack(rack_type("generic-cabinet-42u-600x1070"), [
...     Device(device_type("patch-panel-24-1u"), 42, name="PP-A"),
...     Device(device_type("server-2u"), 20),
... ])
>>> report = check(rack)
>>> report.passes, report.u_used
(True, 3.0)

PortTemplate dataclass

PortTemplate(
    type: str,
    count: int = 1,
    name: str = "{n}",
    positions: int = 1,
    connector: str = "",
)

A NetBox front or rear port template: count ports of a NetBox port type (such as 8p8c, lc, sn, mpo or f), named by name with {n} for the number, each with positions fibers or circuits behind it (12 for an MPO-12 rear port). A port is one connector, as in NetBox: a duplex LC pair is two ports. connector names the footprint in data/connectors.toml for a type NetBox has no slug for, such as MMC (type="other", connector="mmc").

PortMapping dataclass

PortMapping(
    front_port: str,
    front_position: int,
    rear_port: str,
    rear_position: int,
)

One front port position passing through to one rear port position (NetBox 4.5's port mapping; before it, a front port's rear_port and rear_port_position).

DeviceType dataclass

DeviceType(
    model: str,
    u_height: float = 1.0,
    is_full_depth: bool = True,
    airflow: str | None = None,
    weight_kg: float | None = None,
    maximum_draw: float | None = None,
    allocated_draw: float | None = None,
    exclude_from_utilization: bool = False,
    role: Role | None = None,
    manufacturer: str = "Generic",
    part_number: str = "",
    slug: str = "",
    source: str = "",
    front_ports: tuple[PortTemplate, ...] = (),
    rear_ports: tuple[PortTemplate, ...] = (),
)

port_mappings property

port_mappings: list[PortMapping]

How the front ports pass through to the rear ports (none without both).

draw_w property

draw_w: float

Planned power: the allocated draw, else the maximum, else none.

Device dataclass

Device(
    device_type: DeviceType,
    position: float | None,
    face: str = "front",
    name: str = "",
)

A device in a rack. position None leaves it unracked (a 0U PDU, a device on a shelf): it still counts towards weight and power.

top property

top: float

The top of the device, in units (position 10 and 2U high: 12).

rack_airflow property

rack_airflow: str | None

The device's airflow as seen from the rack's front.

port_map

port_map(
    front: tuple[PortTemplate, ...],
    rear: tuple[PortTemplate, ...],
) -> list[PortMapping]

Front port positions mapped onto rear port positions in order, as NetBox assigns them when ports are made from a pattern: 48 LC front ports fill four MPO-12 rear ports, front port 13 landing on MPO 2 position 1. Raises ValueError when the positions differ.

Source code in src/ictdesigntools/spaces/racks.py
def port_map(front: tuple[PortTemplate, ...], rear: tuple[PortTemplate, ...]) -> list[PortMapping]:
    """Front port positions mapped onto rear port positions in order, as NetBox assigns them
    when ports are made from a pattern: 48 LC front ports fill four MPO-12 rear ports, front
    port 13 landing on MPO 2 position 1. Raises ValueError when the positions differ."""
    fronts = [(n, k) for t in front for n in t.names() for k in range(1, t.positions + 1)]
    rears = [(n, k) for t in rear for n in t.names() for k in range(1, t.positions + 1)]
    if len(fronts) != len(rears):
        raise ValueError(f"{len(fronts)} front port positions do not match {len(rears)} rear ones.")
    return [PortMapping(f, fk, r, rk) for (f, fk), (r, rk) in zip(fronts, rears, strict=True)]

check

check(rack: Rack) -> RackReport

Space, weight, power and airflow of a rack and its devices.

Source code in src/ictdesigntools/spaces/racks.py
def check(rack: Rack) -> RackReport:
    """Space, weight, power and airflow of a rack and its devices."""
    rt = rack.rack_type
    n_slots = rt.u_height * 2
    owner = {face: [None] * n_slots for face in FACES}
    used = [False] * n_slots
    problems: list[Problem] = []
    flows: dict[str, list[int]] = {}

    for i, d in enumerate(rack.devices):
        dt = d.device_type
        if d.position is None or dt.u_height == 0:
            continue
        if d.position < rt.starting_unit or d.top > rt.top_unit + 1:
            where = f"U{rt.starting_unit}–U{rt.top_unit}"
            problems.append(Problem("range", f"{d.label} at U{d.position:g} does not fit on the "
                                    f"rails ({where}).", (i,)))  # fmt: skip
            continue
        for s in _slots(d, rt.starting_unit):
            for face in d.faces:
                j = owner[face][s]
                if j is None:
                    owner[face][s] = i
                elif not any(p.kind in ("overlap", "depth") and p.devices == (j, i)
                             for p in problems):  # fmt: skip
                    other = rack.devices[j]
                    kind = "overlap" if d.face == other.face else "depth"
                    why = (f"{d.label} overlaps {other.label} on the {face}." if kind == "overlap"
                           else f"{d.label} and {other.label} both need the {face} at "
                           f"U{rt.starting_unit + s / 2:g}; a full-depth device takes both "
                           "faces.")  # fmt: skip
                    problems.append(Problem(kind, why, (j, i)))
            if not dt.exclude_from_utilization:
                used[s] = True
        if d.rack_airflow in _OPPOSITE:
            flows.setdefault(d.rack_airflow, []).append(i)

    if len(flows) > 1:
        minority = min(flows, key=lambda f: len(flows[f]))
        majority = next(f for f in flows if f != minority)
        names = ", ".join(rack.devices[i].label for i in flows[minority])
        problems.append(Problem("airflow", f"{names}: airflow runs {minority}, against the rest "
                                f"of the rack ({majority}); check its face or fan option.",
                                tuple(flows[minority])))  # fmt: skip

    weight = sum(d.device_type.weight_kg or 0.0 for d in rack.devices)
    if rt.max_weight_kg is not None and weight > rt.max_weight_kg:
        problems.append(Problem("weight", f"Equipment weighs {weight:.0f} kg, over the rack's "
                                f"rating of {rt.max_weight_kg:g} kg."))  # fmt: skip
    allocated = sum(d.device_type.draw_w for d in rack.devices)
    maximum = sum(d.device_type.maximum_draw or d.device_type.draw_w for d in rack.devices)
    if rack.power_budget_w is not None and allocated > rack.power_budget_w:
        problems.append(Problem("power", f"Planned draw {allocated:.0f} W is over the power "
                                f"budget of {rack.power_budget_w:g} W."))  # fmt: skip

    def longest_free(face: str) -> float:
        best = run = 0
        for slot in owner[face]:
            run = run + 1 if slot is None else 0
            best = max(best, run)
        return best / 2

    return RackReport(
        u_total=rt.u_height,
        u_used=sum(used) / 2,
        largest_free={face: longest_free(face) for face in FACES},
        weight_kg=weight,
        max_weight_kg=rt.max_weight_kg,
        allocated_w=allocated,
        maximum_w=maximum,
        power_budget_w=rack.power_budget_w,
        problems=tuple(problems),
    )

elevation

elevation(
    rack: Rack,
    faces: tuple[str, ...] = FACES,
    report: RackReport | None = None,
    ports: bool = False,
) -> Drawing

Front and rear elevations side by side, in mm, with unit numbers on the rails, each device labelled to fit, full-depth devices shown from behind on the other face, and devices with a problem outlined. Devices carry a Meta (id device-<index>, kind device) for to_svg(interactive=True). With ports, devices with port templates show their ports (front ports on the face they are mounted on, rear ports from behind when full depth), each a Meta of kind port with id device-<index>-<front|rear>-port-<name>, and the label moves to the left of the ports; shapes are styled by name (rail, unit, behind, problem, role-<slug>) for to_svg(classes=True).

Source code in src/ictdesigntools/spaces/racks.py
def elevation(rack: Rack, faces: tuple[str, ...] = FACES, report: RackReport | None = None,
              ports: bool = False) -> Drawing:  # fmt: skip
    """Front and rear elevations side by side, in mm, with unit numbers on the rails, each device
    labelled to fit, full-depth devices shown from behind on the other face, and devices with a
    problem outlined. Devices carry a ``Meta`` (id ``device-<index>``, kind ``device``) for
    ``to_svg(interactive=True)``. With ``ports``, devices with port templates show their ports
    (front ports on the face they are mounted on, rear ports from behind when full depth), each
    a ``Meta`` of kind ``port`` with id ``device-<index>-<front|rear>-port-<name>``, and the
    label moves to the left of the ports; shapes are styled by name (``rail``, ``unit``, ``behind``,
    ``problem``, ``role-<slug>``) for ``to_svg(classes=True)``."""
    rt = rack.rack_type
    report = report or check(rack)
    flagged = {i for p in report.problems if p.kind != "airflow" for i in p.devices}
    height = rt.u_height * RACK_UNIT_MM
    title_h = 24.0
    pitch = RACK_WIDTH_MM + GAP_MM
    left = 30.0  # unit numbers
    styles = {
        "rail": Style(fill="#d6d5cf", stroke=MUTED, width=0.5),
        "opening": Style(fill="#fbfbf9", stroke=MUTED, width=0.5),
        "unit": Style(stroke="#e3e3df", width=0.35),
        "unit-label": Style(color=MUTED),
        "face-title": Style(color=INK),
        "behind": Style(fill="#efeeea", stroke="#b5b4ad", width=0.35, dash=True),
        "behind-label": Style(color=MUTED),
        "problem": Style(stroke="#b42318", width=1.2),
        "device": Style(fill="#898781", stroke="#52514e", width=0.35),
        "device-label": Style(color="#ffffff"),
    }
    if ports:
        from ..cabling.connectors import PORT_STYLES

        styles.update(PORT_STYLES)
    for dev in rack.devices:
        role = dev.device_type.role
        if role:
            styles[f"role-{_key(role.slug)}"] = Style(fill=role.color, stroke="#52514e",
                                                      width=0.35)  # fmt: skip
            styles[f"role-{_key(role.slug)}-label"] = Style(color=_on(role.color))
    width = left + pitch * len(faces) - GAP_MM + 4
    d = Drawing(
        view=(-left, -title_h, width, height + title_h + 6), units="mm", stroke=0.35,
        font=UNIT_LABEL_MM, title=f"Elevation of {rack.label}",
        desc=f"{rt.u_height}U {rt.model}, {len(rack.devices)} devices, "
        f"{report.u_used:g}U used.", styles=styles,
    )  # fmt: skip

    def unit_top(u: float, h: float) -> float:
        """y of the top edge of something ``h`` units high whose lowest unit is ``u``."""
        k = (u - rt.starting_unit) if rt.desc_units else (rt.top_unit + 1 - (u + h))
        return k * RACK_UNIT_MM

    for n, face in enumerate(faces):
        x0 = n * pitch
        d.add(Text(x0 + RACK_WIDTH_MM / 2, -title_h / 2, face.capitalize(), 12, style="face-title"))
        d.add(Rect(x0, 0, RACK_WIDTH_MM, height, style="rail"))
        d.add(Rect(x0 + RAIL_MM, 0, RACK_WIDTH_MM - 2 * RAIL_MM, height, style="opening"))
        for k in range(rt.u_height):
            u = rt.starting_unit + k
            y = unit_top(u, 1)
            if k:
                edge = y + RACK_UNIT_MM if not rt.desc_units else y
                d.add(Line(x0 + RAIL_MM, edge, x0 + RACK_WIDTH_MM - RAIL_MM, edge, style="unit"))
            d.add(Text(x0 - 3, y + RACK_UNIT_MM / 2, str(u), UNIT_LABEL_MM * 0.8, anchor="end",
                       style="unit-label"))  # fmt: skip

        for i, dev in enumerate(rack.devices):
            dt = dev.device_type
            if dev.position is None or dt.u_height == 0 or face not in dev.faces:
                continue
            if dev.position < rt.starting_unit or dev.top > rt.top_unit + 1:
                continue
            y, h = unit_top(dev.position, dt.u_height), dt.u_height * RACK_UNIT_MM
            seen_from_behind = face != dev.face
            role = f"role-{_key(dt.role.slug)}" if dt.role else "device"
            style = "behind" if seen_from_behind else role
            label = f"Behind: {dev.label}" if seen_from_behind else dev.label
            meta = Meta.of(id=f"device-{i}", kind="device", name=dev.label,
                           position=f"{dev.position:g}", face=dev.face,
                           u_height=f"{dt.u_height:g}")  # fmt: skip
            title = f"{dev.label} · U{dev.position:g} · {dt.u_height:g}U · {dev.face}"
            d.add(Rect(x0 + 0.6, y + 0.4, RACK_WIDTH_MM - 1.2, h - 0.8, rx=1.0, style=style,
                       title=title, meta=meta))  # fmt: skip
            if i in flagged:
                d.add(Rect(x0 + 0.6, y + 0.4, RACK_WIDTH_MM - 1.2, h - 0.8, rx=1.0,
                           style="problem"))  # fmt: skip
            side = "rear" if seen_from_behind else "front"
            shown = []
            if ports and (not seen_from_behind or dt.is_full_depth):
                shown = _port_shapes(i, dev, face, x0, y, side)
            room = (PORT_LABEL_MM - 4) if shown else RACK_WIDTH_MM - 2 * RAIL_MM - 16
            size = fit_size(label, min(LABEL_MM, h * 0.5), room, smallest=4.0)
            if size is None:
                size = 4.0
                label = truncate(label, size, room)
            text_style = "behind-label" if seen_from_behind else f"{style}-label"
            if shown:
                d.add(Text(x0 + RAIL_MM + 2, y + h / 2, label, size, anchor="start",
                           style=text_style))  # fmt: skip
                d.add(*shown)
            else:
                d.add(Text(x0 + RACK_WIDTH_MM / 2, y + h / 2, label, size, style=text_style))
    return d