File size: 15,722 Bytes
4df086e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
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
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
"""Generate Chinese, self-contained Dijkstra questions with independently checked labels."""

from collections import Counter
from heapq import heappop, heappush
import json
from random import Random


FAMILIES = (
    "sparse_cycle", "dense_network", "layered_dag", "equal_cost_diamond",
    "disconnected", "zero_weight_cycle",
)
TASKS = ("target_path", "round_state", "relaxation_log")


def _graph(rng, family):
    """Return nodes in tie-breaking order, directed edges and a useful starting node."""
    size = rng.randint(6, 12)
    nodes = [chr(65 + i) for i in range(size)]
    roles = rng.sample(nodes, size)
    weights = {}

    def add(u, v, weight):
        weights.setdefault((u, v), weight)

    def cycle(vertices):
        for u, v in zip(vertices, vertices[1:] + vertices[:1]):
            add(u, v, rng.randint(1, 10))

    def extras(vertices, probability, minimum):
        for u in vertices:
            for v in vertices:
                if u != v and (u, v) not in weights and rng.random() < probability:
                    add(u, v, rng.randint(minimum, 12))

    if family in ("sparse_cycle", "dense_network"):
        cycle(roles)
        probability = rng.uniform(.04, .13) if family == "sparse_cycle" else rng.uniform(.4, .7)
        extras(roles, probability, 1)
    elif family == "layered_dag":
        layer_count = rng.randint(3, min(5, size - 1))
        cuts = sorted(rng.sample(range(1, size), layer_count - 1))
        boundaries = [0] + cuts + [size]
        layers = [roles[a:b] for a, b in zip(boundaries, boundaries[1:])]
        for left, right in zip(layers, layers[1:]):
            for u in left:
                add(u, rng.choice(right), rng.randint(0, 9))
            for v in right:
                add(rng.choice(left), v, rng.randint(0, 9))
            for u in left:
                for v in right:
                    if rng.random() < .3:
                        add(u, v, rng.randint(0, 9))
    elif family == "equal_cost_diamond":
        root, left, right, join = roles[:4]
        front, back = rng.randint(0, 8), rng.randint(0, 8)
        for middle in (left, right):
            add(root, middle, front)
            add(middle, join, back)
        cycle(roles[3:])
        extras(roles[3:], .24, 0)
        add(roles[-1], root, rng.randint(1, 7))
    elif family == "disconnected":
        cut = rng.randint(2, size - 2)
        for component in (roles[:cut], roles[cut:]):
            cycle(component)
            extras(component, .26, 0)
    elif family == "zero_weight_cycle":
        width = rng.randint(2, min(5, size - 2))
        zero = roles[:width]
        for u, v in zip(zero, zero[1:] + zero[:1]):
            add(u, v, 0)
        cycle(roles)
        extras(roles, .15, 1)
    edges = [[u, v, w] for (u, v), w in sorted(weights.items())]
    return nodes, edges, roles[0]


def _group_key(nodes, edges):
    """Isomorphism-invariant WL fingerprint. Collisions discard extra candidates."""
    incoming = {v: [] for v in nodes}
    outgoing = {v: [] for v in nodes}
    for u, v, w in edges:
        outgoing[u].append((v, w))
        incoming[v].append((u, w))
    colors = dict.fromkeys(nodes, 0)
    for _ in nodes:
        signatures = {
            v: (colors[v],
                tuple(sorted((w, colors[u]) for u, w in incoming[v])),
                tuple(sorted((w, colors[u]) for u, w in outgoing[v])))
            for v in nodes
        }
        ranks = {signature: i for i, signature in enumerate(sorted(set(signatures.values())))}
        new_colors = {v: ranks[signature] for v, signature in signatures.items()}
        if new_colors == colors:
            break
        colors = new_colors
    colored_edges = sorted((colors[u], colors[v], w) for u, v, w in edges)
    return json.dumps([sorted(colors.values()), colored_edges], separators=(",", ":"))


def _run(instance):
    nodes, source = instance["nodes"], instance["source"]
    order = {v: i for i, v in enumerate(nodes)}
    adjacent = {v: [] for v in nodes}
    for u, v, w in instance["edges"]:
        adjacent[u].append((order[v], v, w))
    distance, previous = dict.fromkeys(nodes), dict.fromkeys(nodes)
    distance[source] = 0
    queue = [(0, order[source], source)]
    seen, trace = set(), []
    while queue:
        d, _, u = heappop(queue)
        if u in seen:
            continue
        seen.add(u)
        updates = []
        for i, v, w in sorted(adjacent[u]):
            old, new = distance[v], d + w
            if v not in seen and (old is None or new < old):
                updates.append({"to": v, "old": old, "new": new})
                distance[v], previous[v] = new, u
                heappush(queue, (new, i, v))
        trace.append({
            "round": len(trace) + 1, "settled": u, "settled_distance": d,
            "updates": updates, "distances": [distance[v] for v in nodes],
            "predecessors": [previous[v] for v in nodes],
        })
    return trace


def _answer(task, instance, trace):
    nodes = instance["nodes"]
    if task == "round_state":
        r = instance["round"]
        state = trace[r - 1]
        return {
            "settled_order": [step["settled"] for step in trace[:r]],
            "distances": state["distances"], "predecessors": state["predecessors"],
        }
    if task == "relaxation_log":
        return {"rounds": [{"settled": s["settled"], "updates": s["updates"]} for s in trace]}
    target = instance["target"]
    distance = trace[-1]["distances"][nodes.index(target)]
    path = []
    if distance is not None:
        v = target
        while v is not None:
            path.append(v)
            v = trace[-1]["predecessors"][nodes.index(v)]
    return {"distance": distance, "path": path[::-1]}


def _question(task, instance, style):
    nodes, edges, source = instance["nodes"], instance["edges"], instance["source"]
    if style % 2:
        adjacency = {v: [] for v in nodes}
        for u, v, w in edges:
            adjacency[u].append(f"{v}({w})")
        display = "邻接表每行给出起点及其出边,括号中是权重,空集表示没有出边。\n" + "\n".join(
            f"{v} → " + ("、".join(adjacency[v]) or "∅") for v in nodes
        )
    else:
        display = "每个三元组依次表示起点、终点、权重。边集为 " + "、".join(
            f"({u},{v},{w})" for u, v, w in edges
        ) + "。"
    start = (
        f"在这个非负权有向图上,从 {source} 运行 Dijkstra 算法。",
        f"请从节点 {source} 开始,手工跟踪下列有向图的 Dijkstra 搜索。",
        f"给定以下有向边,以 {source} 为源点执行 Dijkstra 单源最短路。",
        f"用 Dijkstra 算法分析下面的有向网络,起点取 {source}。",
    )[style]
    rules = (
        "节点顺序为 " + "、".join(nodes) + "。源点初始距离为 0,其余初始距离为无穷大,所有前驱初始为空。"
        "每轮定型一个暂定距离最小的可达未定型节点,同距取节点顺序靠前者。"
        "随后按节点顺序检查该节点的出边,只在到达未定型节点的距离严格变小时更新距离和前驱。"
        "继续至所有可达节点定型。用 JSON 作答,无穷大和空前驱都写 null。"
    )
    if task == "target_path":
        target = instance["target"]
        request = (
            f"到 {target} 的最终距离和按上述前驱回溯得到的路径是什么?",
            f"请还原从 {source} 到 {target} 的最短路径,并计算其长度。",
        )[style // 2]
        request += "用 distance 给出距离,用 path 按起点到终点的顺序列出节点。不可达时 path 写 []。"
    elif task == "round_state":
        r = instance["round"]
        request = (
            f"在第 {r} 轮的出边检查结束时暂停。",
            f"记录完成第 {r} 次定型并处理完其出边后的状态。",
        )[style // 2]
        request += (
            "用 settled_order 列出截至此时的定型顺序,用 distances 和 predecessors"
            " 分别给出所有节点此时的距离与前驱。这两个数组须遵循题给节点顺序。"
        )
    else:
        request = (
            "请交出整次运行中每一轮的成功松弛记录。",
            "逐轮还原哪些暂定距离被严格缩短,并保留没有发生更新的轮次。",
        )[style // 2]
        request += (
            "用 rounds 数组按轮列出对象,每个对象的 settled 为本轮定型节点,updates "
            "按处理顺序列出本轮成功更新,每项含 to(终点)、old(原距离)、new(新距离)。没有成功更新时写 []。"
        )
    return "\n".join((start, rules, display, request))


def make_group(seed: int, split: str) -> tuple[str, list[dict]]:
    """Build two different tasks for a shared graph; split never affects sampling."""
    rng = Random(seed)
    family = rng.choice(FAMILIES)
    nodes, edges, preferred = _graph(rng, family)
    rows = []
    for task in rng.sample(TASKS, 2):
        source = preferred if rng.random() < .68 else rng.choice(nodes)
        instance = {"nodes": nodes, "edges": edges, "source": source}
        trace = _run(instance)
        if task == "target_path":
            unreached = [v for v, d in zip(nodes, trace[-1]["distances"]) if d is None]
            if unreached and rng.random() < .52:
                instance["target"] = rng.choice(unreached)
            else:
                instance["target"] = rng.choice(nodes)
        elif task == "round_state":
            instance["round"] = rng.randint(1, len(trace))
        rows.append({
            "task": task, "family": family, "variant": "dijkstra",
            "question": _question(task, instance, rng.randrange(4)),
            "instance": instance, "answer": _answer(task, instance, trace), "trace": trace,
        })
    return _group_key(nodes, edges), rows


def _require(condition, message):
    if not condition:
        raise ValueError(message)


def verify(row: dict) -> None:
    """Replay by minimum scan, check all states, and cross-check with Bellman–Ford."""
    task, instance = row["task"], row["instance"]
    nodes, edges, source = instance["nodes"], instance["edges"], instance["source"]
    _require(task in TASKS and row["family"] in FAMILIES and row["variant"] == "dijkstra",
             "unknown task, family or variant")
    _require(len(set(nodes)) == len(nodes) and source in nodes, "invalid nodes/source")
    _require(all(u in nodes and v in nodes and u != v and type(w) is int and w >= 0
                 for u, v, w in edges), "edge endpoint or weight mismatch")
    _require(len({(u, v) for u, v, _ in edges}) == len(edges), "parallel directed edges")
    if task == "target_path":
        _require(instance["target"] in nodes, "target outside node set")
    _require(any(row["question"] == _question(task, instance, i) for i in range(4)),
             "question/instance mismatch")

    # Use a dense arc map and scan vertices in node order (the generator uses a heap).
    arcs = {(u, v): w for u, v, w in edges}
    inf = float("inf")
    d = dict.fromkeys(nodes, inf)
    pred = dict.fromkeys(nodes)
    d[source] = 0
    fixed = []
    round_answer = None
    logs = []
    for r, step in enumerate(row["trace"], 1):
        remaining = [v for v in nodes if v not in fixed and d[v] < inf]
        _require(bool(remaining), "trace runs past the reachable frontier")
        u = min(remaining, key=d.__getitem__)
        fixed.append(u)
        updates = []
        for v in nodes:
            if v in fixed or (u, v) not in arcs or d[v] <= d[u] + arcs[u, v]:
                continue
            old = None if d[v] == inf else d[v]
            d[v], pred[v] = d[u] + arcs[u, v], u
            updates.append({"to": v, "old": old, "new": d[v]})
        distances = [None if d[v] == inf else d[v] for v in nodes]
        predecessors = [pred[v] for v in nodes]
        expected = {
            "round": r, "settled": u, "settled_distance": d[u], "updates": updates,
            "distances": distances, "predecessors": predecessors,
        }
        _require(step == expected, f"incorrect Dijkstra state in round {r}")
        logs.append({"settled": u, "updates": updates})
        if task == "round_state" and r == instance["round"]:
            round_answer = {"settled_order": fixed.copy(), "distances": distances,
                            "predecessors": predecessors}
    _require(all(v in fixed or d[v] == inf for v in nodes), "incomplete trace")

    optimal = dict.fromkeys(nodes, inf)
    optimal[source] = 0
    for _ in range(len(nodes) - 1):
        changed = False
        for u, v, w in edges:
            if optimal[u] + w < optimal[v]:
                optimal[v] = optimal[u] + w
                changed = True
        if not changed:
            break
    _require(d == optimal, "Bellman–Ford distances disagree")
    if task == "target_path":
        target = instance["target"]
        path = []
        if optimal[target] < inf:
            # Build all predecessor-tree paths forward in settlement order.
            paths = {source: [source]}
            for v in fixed[1:]:
                paths[v] = paths[pred[v]] + [v]
            path = paths[target]
        expected_answer = {"distance": None if optimal[target] == inf else optimal[target],
                           "path": path}
    elif task == "round_state":
        _require(round_answer is not None, "requested round missing")
        expected_answer = round_answer
    else:
        expected_answer = {"rounds": logs}
    _require(row["answer"] == expected_answer, "answer mismatch")


def self_test() -> None:
    nodes = list("ABCDEF")
    edges = [["A", "B", 1], ["A", "C", 1], ["A", "D", 5], ["B", "C", 0],
             ["B", "D", 2], ["C", "B", 0], ["C", "D", 2], ["D", "F", 0]]
    instance = {"nodes": nodes, "edges": edges, "source": "A"}
    trace = _run(instance)
    _require([s["settled"] for s in trace] == list("ABCDF"), "settlement tie fixture")
    _require(trace[1]["updates"] == [{"to": "D", "old": 5, "new": 3}], "decrease-key fixture")
    _require(trace[2]["updates"] == [], "equal-distance fixture")
    _require(trace[-1]["distances"] == [0, 1, 1, 3, None, 3], "unreachable fixture")
    cases = [
        ("target_path", {"target": "F"}, {"distance": 3, "path": list("ABDF")}),
        ("target_path", {"target": "E"}, {"distance": None, "path": []}),
        ("target_path", {"target": "A"}, {"distance": 0, "path": ["A"]}),
        ("round_state", {"round": 2}, {"settled_order": ["A", "B"],
                                       "distances": [0, 1, 1, 3, None, None],
                                       "predecessors": [None, "A", "A", "B", None, None]}),
    ]
    for task, query, answer in cases:
        item = instance | query
        _require(_answer(task, item, trace) == answer, "hand-labeled answer fixture")
        verify({"family": "zero_weight_cycle", "variant": "dijkstra", "task": task,
                "instance": item, "trace": trace, "answer": answer, "question": _question(task, item, 0)})
    rename = dict(zip(nodes, reversed(nodes)))
    swapped = [[rename[u], rename[v], w] for u, v, w in reversed(edges)]
    _require(_group_key(nodes, edges) == _group_key(nodes[::-1], swapped), "graph renaming fixture")
    families = Counter()
    for seed in range(36):
        key, rows = make_group(seed, "train")
        _require((key, rows) == make_group(seed, "test"), "split-dependent graph")
        for row in rows:
            verify(row)
            families[row["family"]] += 1
    _require(set(families) == set(FAMILIES), "family coverage fixture")