Skip to content
Edit this page

ictdesigntools.draw.route

Orthogonal connector routing: paths of horizontal and vertical runs that go around boxes, and nudging that spreads parallel runs sharing a channel so they do not lie on one another.

orthogonal searches a sparse grid made from the ends and the boxes' sides (pushed out by margin) with A*, counting length and a penalty per bend, so a route takes few turns and keeps clear of the boxes. nudge then finds runs of several routes on the same line that overlap and spaces them spacing apart about it, keeping each route's end points where they are. This is the usual approach to orthogonal connector routing (a visibility graph, a shortest path with bend costs, then a nudging pass), in pure Python.

>>> orthogonal((0, 3), (30, 3), [(10, 0, 10, 10)], margin=2)  # over the box: nearer
[(0, 3), (0, -2), (30, -2), (30, 3)]

simplify

simplify(points: list[Point]) -> list[Point]

Drop repeated points and points in the middle of a straight run.

Source code in src/ictdesigntools/draw/route.py
def simplify(points: list[Point]) -> list[Point]:
    """Drop repeated points and points in the middle of a straight run."""
    out: list[Point] = []
    for p in points:
        if out and math.isclose(out[-1][0], p[0]) and math.isclose(out[-1][1], p[1]):
            continue
        if len(out) >= 2:
            (ax, ay), (bx, by) = out[-2], out[-1]
            if (math.isclose(ax, bx) and math.isclose(bx, p[0])) or (
                math.isclose(ay, by) and math.isclose(by, p[1])
            ):
                out[-1] = p
                continue
        out.append(p)
    return out

orthogonal

orthogonal(
    start: Point,
    end: Point,
    boxes: list[Box],
    margin: float = 4.0,
    bend: float | None = None,
    lines: tuple[list[float], list[float]] = ([], []),
) -> list[Point]

The shortest route of horizontal and vertical runs from start to end that keeps out of boxes, with bend (default: twice the margin plus 10) added for each turn. lines adds x and y lines the route may run along, such as the middle of a channel. The ends must lie outside the boxes. Raises ValueError when no route exists.

Source code in src/ictdesigntools/draw/route.py
def orthogonal(start: Point, end: Point, boxes: list[Box], margin: float = 4.0,
               bend: float | None = None, lines: tuple[list[float], list[float]] = ([], []),
               ) -> list[Point]:  # fmt: skip
    """The shortest route of horizontal and vertical runs from ``start`` to ``end`` that keeps
    out of ``boxes``, with ``bend`` (default: twice the margin plus 10) added for each turn.
    ``lines`` adds x and y lines the route may run along, such as the middle of a channel.
    The ends must lie outside the boxes. Raises ValueError when no route exists."""
    for p in (start, end):
        if any(_inside(*p, b) for b in boxes):
            raise ValueError(f"{p} is inside a box: route from outside it.")
    bend = 2 * margin + 10 if bend is None else bend
    xs = {start[0], end[0], *lines[0]}
    ys = {start[1], end[1], *lines[1]}
    for bx, by, bw, bh in boxes:
        xs |= {bx - margin, bx + bw + margin}
        ys |= {by - margin, by + bh + margin}
    xs_, ys_ = sorted(xs), sorted(ys)

    def free(x: float, y: float) -> bool:
        return not any(_inside(x, y, b) for b in boxes)

    def step(p: Point, axis: int, sign: int) -> Point | None:
        """The next grid point from p along an axis, if the run there is clear."""
        coords = xs_ if axis == 0 else ys_
        v = p[axis]
        k = bisect_right(coords, v) if sign > 0 else bisect_left(coords, v) - 1
        if not 0 <= k < len(coords):
            return None
        q = (coords[k], p[1]) if axis == 0 else (p[0], coords[k])
        if not free(*q) or any(_crosses(p, q, b) for b in boxes):
            return None
        return q

    def h(p: Point) -> float:
        return abs(p[0] - end[0]) + abs(p[1] - end[1])

    # A* over (point, direction); direction is (axis, sign) or None at the start.
    start_state = (start, None)
    best = {start_state: 0.0}
    came: dict = {}
    heap = [(h(start), 0.0, 0, start, None)]
    tie = 1
    while heap:
        _, cost, _, p, d = heapq.heappop(heap)
        if p == end:
            path = [p]
            state = (p, d)
            while state in came:
                state = came[state]
                path.append(state[0])
            return simplify(path[::-1])
        if cost > best.get((p, d), math.inf):
            continue
        for axis in (0, 1):
            for sign in (1, -1):
                if d is not None and d == (axis, -sign):
                    continue  # no doubling back
                q = step(p, axis, sign)
                if q is None:
                    continue
                nd = (axis, sign)
                c = cost + abs(q[0] - p[0]) + abs(q[1] - p[1])
                if d is not None and d != nd:
                    c += bend
                if c < best.get((q, nd), math.inf):
                    best[(q, nd)] = c
                    came[(q, nd)] = (p, d)
                    heapq.heappush(heap, (c + h(q), c, tie, q, nd))
                    tie += 1
    raise ValueError(f"No route from {start} to {end} around the boxes.")

nudge

nudge(
    routes: list[list[Point]], spacing: float
) -> list[list[Point]]

Routes with their overlapping parallel runs spread spacing apart about the line they shared, ordered so routes keep their order across the channel. A route's first and last points stay put, so the runs that end on them are not moved.

Source code in src/ictdesigntools/draw/route.py
def nudge(routes: list[list[Point]], spacing: float) -> list[list[Point]]:
    """Routes with their overlapping parallel runs spread ``spacing`` apart about the line they
    shared, ordered so routes keep their order across the channel. A route's first and last
    points stay put, so the runs that end on them are not moved."""
    out = [list(r) for r in routes]
    for axis in (0, 1):  # 0: vertical runs (x fixed), 1: horizontal runs (y fixed)
        runs: dict[float, list[tuple[int, int, float, float]]] = {}
        for i, r in enumerate(out):
            for k in range(1, len(r) - 2):  # not the first or last run
                p, q = r[k], r[k + 1]
                if math.isclose(p[axis], q[axis]):
                    lo, hi = sorted((p[1 - axis], q[1 - axis]))
                    runs.setdefault(round(p[axis], 6), []).append((i, k, lo, hi))
        for at, found in runs.items():
            for cluster in _clusters(found):
                if len({i for i, *_ in cluster}) < 2:
                    continue
                # Order across the channel by where each route starts, then where it ends.
                cluster.sort(key=lambda s: (out[s[0]][0][1 - axis], out[s[0]][-1][1 - axis]))
                n = len(cluster)
                for j, (i, k, _, _) in enumerate(cluster):
                    v = at + (j - (n - 1) / 2) * spacing
                    for m in (k, k + 1):
                        x, y = out[i][m]
                        out[i][m] = (v, y) if axis == 0 else (x, v)
    return out

s_curve

s_curve(
    start: Point, end: Point, steps: int = 24
) -> list[Point]

A smooth S from start to end, leaving and arriving level (a cubic Bézier with its control points half way across), as points for a polyline: how a cable fans out from a furcation to its legs, or gathers into a bundle.

>>> s_curve((0, 0), (10, 4), steps=2)
[(0.0, 0.0), (5.0, 2.0), (10.0, 4.0)]
Source code in src/ictdesigntools/draw/route.py
def s_curve(start: Point, end: Point, steps: int = 24) -> list[Point]:
    """A smooth S from ``start`` to ``end``, leaving and arriving level (a cubic Bézier with
    its control points half way across), as points for a polyline: how a cable fans out from a
    furcation to its legs, or gathers into a bundle.

    >>> s_curve((0, 0), (10, 4), steps=2)
    [(0.0, 0.0), (5.0, 2.0), (10.0, 4.0)]
    """
    (x0, y0), (x3, y3) = start, end
    xm = (x0 + x3) / 2
    out = []
    for i in range(steps + 1):
        t = i / steps
        u = 1 - t
        x = u**3 * x0 + 3 * u * u * t * xm + 3 * u * t * t * xm + t**3 * x3
        y = u**3 * y0 + 3 * u * u * t * y0 + 3 * u * t * t * y3 + t**3 * y3
        out.append((round(x, 4), round(y, 4)))
    return out