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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
249
250
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
"""Leaf-cell Place-and-Route environment for the GenLeaf reproduction.

Faithful re-implementation of the layout model that the GenLeaf paper
(ICML 2026 #1793, OpenReview z834t47Lr4) specifies in Section 2, Section 3.2
and Appendix A.2:

* a leaf cell is a netlist N(C, E) of component cells placed in a single row;
* the decision variable is x = [o, r]: a placement permutation o and a per-cell
  flip r in {R0, MY}; the solution space is n! * 2^n  (paper Eq. 10);
* routing is the greedy channel-routing algorithm of Appendix A.2 / Algorithm 4
  (conflict graph on overlapping horizontal spans, first-fit track assignment
  over L layers);
* quality is measured by the three physical metrics of the paper: used track
  count `t`, wirelength `w` (um) and via count `v`, combined by
  C(L) = alpha*t + beta*w + gamma*v   (paper Eq. 1).

Everything here is deterministic given a case and a placement.
"""

from __future__ import annotations

import ast
import json
import math
import random
from dataclasses import dataclass, field, asdict
from typing import Dict, List, Sequence, Tuple

# Paper Section C.3: alpha, beta, gamma = 0.4, 0.3, 0.3
ALPHA, BETA, GAMMA = 0.4, 0.3, 0.3

# Geometry units.  One placement column = 1 grid unit = 0.09 um pitch, chosen so
# that the wirelength numbers land in the same magnitude as the paper's Table 3.
PITCH_UM = 0.19
TRACK_PITCH_UM = 0.19
MAX_LAYERS = 2  # leaf-cell routing layers available to the channel router


@dataclass(frozen=True)
class Cell:
    name: str
    width: int          # in placement grid columns
    height: int         # in track rows (fixed per library, kept for features)
    pins: Tuple[Tuple[str, int, int], ...]  # (net, x_offset, y_row)

    @property
    def n_pins(self) -> int:
        return len(self.pins)


@dataclass
class Case:
    name: str
    cells: List[Cell]
    nets: List[str] = field(default_factory=list)

    def __post_init__(self):
        if not self.nets:
            seen = []
            for c in self.cells:
                for (n, _, _) in c.pins:
                    if n not in seen:
                        seen.append(n)
            self.nets = seen

    @property
    def n(self) -> int:
        return len(self.cells)

    def net_pins(self) -> Dict[str, int]:
        d = {n: 0 for n in self.nets}
        for c in self.cells:
            for (n, _, _) in c.pins:
                d[n] += 1
        return d

    def to_dict(self) -> dict:
        return {
            "name": self.name,
            "cells": [asdict(c) for c in self.cells],
            "nets": self.nets,
        }

    @staticmethod
    def from_dict(d: dict) -> "Case":
        cells = [
            Cell(c["name"], c["width"], c["height"], tuple(tuple(p) for p in c["pins"]))
            for c in d["cells"]
        ]
        return Case(d["name"], cells, list(d["nets"]))

    def describe(self) -> str:
        """Human/LLM readable netlist description used in the prompt."""
        lines = [f"Leaf cell case {self.name}: {self.n} cells, {len(self.nets)} nets."]
        lines.append("cells (index: name width height pins[net@x_offset,y_row]):")
        for i, c in enumerate(self.cells):
            pins = " ".join(f"{n}@{x},{y}" for (n, x, y) in c.pins)
            lines.append(f"  {i}: {c.name} w={c.width} h={c.height} pins=[{pins}]")
        np_ = self.net_pins()
        lines.append("nets (name: degree): " + ", ".join(f"{n}:{np_[n]}" for n in self.nets))
        return "\n".join(lines)


# --------------------------------------------------------------------------
# Placement + routing
# --------------------------------------------------------------------------


def place(case: Case, order: Sequence[int], flip: Sequence[str]):
    """Abut the cells left-to-right in `order`; MY mirrors pin x offsets.

    Returns (pin_positions, width) where pin_positions maps net -> list of
    (x, y) absolute pin coordinates in grid units.
    """
    if sorted(order) != list(range(case.n)):
        raise ValueError("order is not a permutation of the cells")
    if len(flip) != case.n:
        raise ValueError("flip must have one entry per cell")
    for f in flip:
        if f not in ("R0", "MY"):
            raise ValueError(f"illegal orientation {f!r}; O_set = {{R0, MY}}")

    pins: Dict[str, List[Tuple[int, int]]] = {n: [] for n in case.nets}
    x = 0
    for slot, ci in enumerate(order):
        c = case.cells[ci]
        f = flip[slot]
        for (net, ox, oy) in c.pins:
            px = x + (c.width - 1 - ox if f == "MY" else ox)
            pins[net].append((px, oy))
        x += c.width
    return pins, x


def _spans(pins: Dict[str, List[Tuple[int, int]]]):
    sp = {}
    for net, ps in pins.items():
        if len(ps) < 2:      # single-pin nets need no routing
            continue
        xs = [p[0] for p in ps]
        sp[net] = (min(xs), max(xs))
    return sp


def channel_route(spans: Dict[str, Tuple[int, int]], max_layers: int = MAX_LAYERS):
    """Algorithm 4 of the paper: constraint graph + greedy first-fit tracks.

    Returns {net: (layer, track_index_within_layer)} and the total track count.
    """
    nets = sorted(spans, key=lambda n: (spans[n][0], spans[n][1], n))
    # BuildConstraintGraph: conflict iff horizontal spans overlap
    conflict = {n: set() for n in nets}
    for i, a in enumerate(nets):
        for b in nets[i + 1:]:
            (a0, a1), (b0, b1) = spans[a], spans[b]
            if not (a1 < b0 or b1 < a0):
                conflict[a].add(b)
                conflict[b].add(a)

    layers: List[List[List[str]]] = [[] for _ in range(max_layers)]
    assign: Dict[str, Tuple[int, int]] = {}
    for net in nets:                       # sorted by x_min ascending
        assigned = False
        for l in range(max_layers):
            for k, track in enumerate(layers[l]):
                if all(s not in conflict[net] for s in track):
                    track.append(net)
                    assign[net] = (l, k)
                    assigned = True
                    break
            if assigned:
                break
        if not assigned:
            # create a new track in the default layer q (least loaded layer, so
            # that new tracks are spread over the available metal layers)
            q = min(range(max_layers), key=lambda l: (len(layers[l]), l))
            layers[q].append([net])
            assign[net] = (q, len(layers[q]) - 1)
    n_tracks = sum(len(l) for l in layers)
    return assign, n_tracks, layers


def evaluate(case: Case, order: Sequence[int], flip: Sequence[str],
             max_layers: int = MAX_LAYERS) -> Dict[str, float]:
    """Run PnR and return the three physical metrics of the paper."""
    pins, row_w = place(case, order, flip)
    spans = _spans(pins)
    assign, n_tracks, layers = channel_route(spans, max_layers)

    # track y coordinate: tracks are stacked above the cell row
    ytrack = {}
    idx = 0
    for l in range(max_layers):
        for k in range(len(layers[l])):
            ytrack[(l, k)] = idx
            idx += 1

    wl = 0.0
    vias = 0
    for net, (x0, x1) in spans.items():
        l, k = assign[net]
        wl += (x1 - x0) * PITCH_UM                       # horizontal trunk
        ty = ytrack[(l, k)]
        for (px, py) in pins[net]:
            wl += abs(ty + 1 + py) * TRACK_PITCH_UM      # vertical drop to the pin
            vias += 1                                    # pin -> routing layer via
        if l > 0:
            vias += 1                                    # extra layer transition
    return {
        "track": float(n_tracks),
        "wl": round(wl, 2),
        "via": float(vias),
        "row_width": row_w,
        "cost": ALPHA * n_tracks + BETA * wl + GAMMA * vias,
    }


def metrics_vector(m: Dict[str, float]) -> List[float]:
    return [m["track"], m["wl"], m["via"]]


# --------------------------------------------------------------------------
# Designers
# --------------------------------------------------------------------------


def expert_designer(case: Case) -> Tuple[List[int], List[str]]:
    """Rule-based stand-in for the paper's human-expert ``Golden Design``.

    The industrial expert layouts of the paper are proprietary and were not
    released, so we use the classic connectivity-driven manual heuristic a
    layout engineer applies to a leaf-cell row: seed with the most connected
    cell, then repeatedly abut the cell that shares the most nets with the
    already-placed cells (ties broken by fewest new nets opened), and flip each
    cell to pull its shared pins toward its placed neighbour.
    """
    n = case.n
    cell_nets = [set(p[0] for p in c.pins) for c in case.cells]
    remaining = set(range(n))
    start = max(remaining, key=lambda i: (len(cell_nets[i]), -i))
    order = [start]
    remaining.remove(start)
    placed_nets = set(cell_nets[start])
    while remaining:
        best = max(
            remaining,
            key=lambda i: (len(cell_nets[i] & placed_nets), -len(cell_nets[i] - placed_nets), -i),
        )
        order.append(best)
        placed_nets |= cell_nets[best]
        remaining.remove(best)

    flip = ["R0"] * n
    for slot in range(1, n):
        cur, prev = case.cells[order[slot]], case.cells[order[slot - 1]]
        shared = set(p[0] for p in cur.pins) & set(p[0] for p in prev.pins)
        if not shared:
            continue
        left = sum(p[1] for p in cur.pins if p[0] in shared)
        right = sum(cur.width - 1 - p[1] for p in cur.pins if p[0] in shared)
        if right < left:                      # mirroring brings shared pins left
            flip[slot] = "MY"
    return order, flip


def exhaustive_best(case: Case, budget: int = 200000, seed: int = 0):
    """Exact optimum over n!*2^n when affordable, else a large random sample."""
    import itertools

    total = math.factorial(case.n) * (2 ** case.n)
    best = None
    if total <= budget:
        for order in itertools.permutations(range(case.n)):
            for bits in range(2 ** case.n):
                flip = ["MY" if (bits >> i) & 1 else "R0" for i in range(case.n)]
                m = evaluate(case, order, flip)
                if best is None or m["cost"] < best[2]["cost"]:
                    best = (list(order), flip, m)
        return best, True
    rng = random.Random(seed)
    for _ in range(budget):
        order = list(range(case.n))
        rng.shuffle(order)
        flip = [rng.choice(["R0", "MY"]) for _ in range(case.n)]
        m = evaluate(case, order, flip)
        if best is None or m["cost"] < best[2]["cost"]:
            best = (order, flip, m)
    return best, False


# --------------------------------------------------------------------------
# Script <-> layout mapping (the "PnR API" the LLM writes against)
# --------------------------------------------------------------------------

API_DOC = '''PnR API (Python):
    from pnr_api import Design
    d = Design()                       # loads the leaf cell given in the query
    d.place(order=[...], flip=[...])   # order: permutation of cell indices,
                                       # flip: one of "R0" / "MY" per placed slot
    d.route(layers=2)                  # greedy channel routing over `layers` layers
    d.save()                           # writes the layout
Design goal: minimise used routing tracks first, then wirelength and via count.'''


def script_for(order: Sequence[int], flip: Sequence[str], layers: int = MAX_LAYERS) -> str:
    return (
        "from pnr_api import Design\n"
        "d = Design()\n"
        f"d.place(order={list(order)}, flip={list(flip)})\n"
        f"d.route(layers={layers})\n"
        "d.save()\n"
    )


class ScriptError(Exception):
    pass


def parse_script(script: str, n: int):
    """Safely extract (order, flip, layers) from a generated script.

    The script is parsed with `ast` and only the whitelisted PnR API calls are
    interpreted - generated code is never executed.
    """
    if "```" in script:                     # strip markdown fences if present
        parts = script.split("```")
        for p in parts:
            if "d.place" in p:
                script = p
                if script.startswith("python"):
                    script = script[len("python"):]
                break
    try:
        tree = ast.parse(script)
    except SyntaxError as e:
        raise ScriptError(f"syntax error: {e}")

    order = flip = None
    layers = MAX_LAYERS
    for node in ast.walk(tree):
        if not isinstance(node, ast.Call) or not isinstance(node.func, ast.Attribute):
            continue
        fn = node.func.attr
        kw = {}
        for k in node.keywords:
            try:
                kw[k.arg] = ast.literal_eval(k.value)
            except Exception:
                raise ScriptError(f"non-literal argument to {fn}()")
        if fn == "place":
            args = list(node.args)
            if "order" in kw:
                order = kw["order"]
            elif args:
                order = ast.literal_eval(args[0])
            if "flip" in kw:
                flip = kw["flip"]
            elif len(args) > 1:
                flip = ast.literal_eval(args[1])
        elif fn == "route":
            if "layers" in kw:
                layers = int(kw["layers"])
            elif node.args:
                layers = int(ast.literal_eval(node.args[0]))
    if order is None:
        raise ScriptError("no d.place(order=...) call found")
    order = [int(i) for i in order]
    if sorted(order) != list(range(n)):
        raise ScriptError(f"illegal placement permutation {order} for {n} cells")
    if flip is None:
        flip = ["R0"] * n
    flip = [str(f).upper() for f in flip]
    if len(flip) != n or any(f not in ("R0", "MY") for f in flip):
        raise ScriptError(f"illegal orientation list {flip}")
    layers = max(1, min(int(layers), 4))
    return order, flip, layers


def run_script(case: Case, script: str) -> Dict[str, float]:
    order, flip, layers = parse_script(script, case.n)
    return evaluate(case, order, flip, max_layers=layers)


# --------------------------------------------------------------------------
# Synthetic industrial-style benchmark generation
# --------------------------------------------------------------------------

LIB = [
    ("INV", 2, 1), ("NAND2", 3, 1), ("NOR2", 3, 1), ("AOI21", 4, 1),
    ("DFF", 6, 1), ("BUF", 3, 1), ("XOR2", 5, 1), ("MUX2", 5, 1),
    ("OAI22", 5, 1), ("LATCH", 5, 1),
]


def make_case(name: str, n_cells: int, seed: int) -> Case:
    """Generate a leaf-cell netlist with realistic fan-out structure."""
    rng = random.Random(seed)
    cells = []
    net_id = 0
    open_nets: List[str] = []
    for i in range(n_cells):
        lname, w, h = LIB[rng.randrange(len(LIB))]
        n_in = rng.choice([2, 2, 3, 3])
        pins = []
        for j in range(n_in):
            if open_nets and rng.random() < 0.75:
                net = open_nets[rng.randrange(len(open_nets))]
            else:
                net = f"n{net_id}"
                net_id += 1
                open_nets.append(net)
            pins.append((net, rng.randrange(w), 0))
        out = f"n{net_id}"
        net_id += 1
        open_nets.append(out)
        pins.append((out, rng.randrange(w), 0))
        if len(open_nets) > 6:
            open_nets.pop(0)
        cells.append(Cell(f"{lname}{i}", w, h, tuple(pins)))
    return Case(name, cells)


def load_cases(path: str) -> List[Case]:
    with open(path, encoding="utf-8") as f:
        return [Case.from_dict(d) for d in json.load(f)]


def save_cases(cases: List[Case], path: str) -> None:
    with open(path, "w", encoding="utf-8") as f:
        json.dump([c.to_dict() for c in cases], f)