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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
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
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
from __future__ import annotations

import argparse
import json
import math
import random
from pathlib import Path
from typing import Dict, List, Tuple

import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import numpy as np


Cell = Tuple[int, int]


# ---------------------------------------------------------------------------
# Geometry helpers
# ---------------------------------------------------------------------------


def _cross(ox: float, oy: float, px: float, py: float, qx: float, qy: float) -> float:
    return (px - ox) * (qy - oy) - (py - oy) * (qx - ox)


def segments_intersect_properly(
    ax: float, ay: float, bx: float, by: float,
    cx: float, cy: float, dx: float, dy: float,
) -> bool:
    """True if segment AB *properly* crosses segment CD (shared endpoints don't count)."""
    d1 = _cross(cx, cy, dx, dy, ax, ay)
    d2 = _cross(cx, cy, dx, dy, bx, by)
    d3 = _cross(ax, ay, bx, by, cx, cy)
    d4 = _cross(ax, ay, bx, by, dx, dy)
    if ((d1 > 0 and d2 < 0) or (d1 < 0 and d2 > 0)) and \
       ((d3 > 0 and d4 < 0) or (d3 < 0 and d4 > 0)):
        return True
    return False


def point_seg_dist(px: float, py: float, ax: float, ay: float, bx: float, by: float) -> float:
    dx = bx - ax
    dy = by - ay
    len_sq = dx * dx + dy * dy
    if len_sq < 1e-12:
        return math.hypot(px - ax, py - ay)
    t = max(0.0, min(1.0, ((px - ax) * dx + (py - ay) * dy) / len_sq))
    return math.hypot(px - (ax + t * dx), py - (ay + t * dy))


# ---------------------------------------------------------------------------
# Union-Find
# ---------------------------------------------------------------------------


class UnionFind:
    def __init__(self, n: int) -> None:
        self.parent = list(range(n))
        self.rank = [0] * n
        self.num_sets = n

    def find(self, x: int) -> int:
        while self.parent[x] != x:
            self.parent[x] = self.parent[self.parent[x]]
            x = self.parent[x]
        return x

    def union(self, a: int, b: int) -> bool:
        ra, rb = self.find(a), self.find(b)
        if ra == rb:
            return False
        if self.rank[ra] < self.rank[rb]:
            ra, rb = rb, ra
        self.parent[rb] = ra
        if self.rank[ra] == self.rank[rb]:
            self.rank[ra] += 1
        self.num_sets -= 1
        return True


# ---------------------------------------------------------------------------
# Graph construction — planar, no-dot-crossing edge set
# ---------------------------------------------------------------------------


def place_dots(
    rng: random.Random,
    grid_rows: int,
    grid_cols: int,
    num_dots: int,
    min_gap: float,
    border_margin: int = 5,
    max_attempts: int = 8000,
) -> List[Cell]:
    cells: List[Cell] = []
    lo_r, hi_r = border_margin, grid_rows - border_margin
    lo_c, hi_c = border_margin, grid_cols - border_margin
    for _ in range(max_attempts):
        if len(cells) == num_dots:
            break
        r = rng.randint(lo_r, hi_r - 1)
        c = rng.randint(lo_c, hi_c - 1)
        if all(math.hypot(r - er, c - ec) >= min_gap for er, ec in cells):
            cells.append((r, c))
    return cells


def build_planar_edge_set(
    dots: List[Cell],
    dot_radius: float,
    max_edge_len: float,
) -> List[Tuple[int, int, float]]:
    n = len(dots)
    candidates: List[Tuple[float, int, int]] = []
    for i in range(n):
        ri, ci = dots[i]
        for j in range(i + 1, n):
            rj, cj = dots[j]
            d = math.hypot(ri - rj, ci - cj)
            if d > max_edge_len:
                continue
            clear = True
            for k in range(n):
                if k == i or k == j:
                    continue
                if point_seg_dist(dots[k][0], dots[k][1], ri, ci, rj, cj) < dot_radius + 0.8:
                    clear = False
                    break
            if clear:
                candidates.append((d, i, j))
    candidates.sort()

    accepted: List[Tuple[int, int, float]] = []
    seg_coords: List[Tuple[float, float, float, float]] = []
    for dist, i, j in candidates:
        ri, ci = dots[i]
        rj, cj = dots[j]
        crosses = False
        for ax, ay, bx, by in seg_coords:
            if (ri == ax and ci == ay) or (ri == bx and ci == by) or \
               (rj == ax and cj == ay) or (rj == bx and cj == by):
                continue
            if segments_intersect_properly(ri, ci, rj, cj, ax, ay, bx, by):
                crosses = True
                break
        if not crosses:
            accepted.append((i, j, dist))
            seg_coords.append((float(ri), float(ci), float(rj), float(cj)))

    return accepted


# ---------------------------------------------------------------------------
# Graph construction for bounded faces
# ---------------------------------------------------------------------------


def build_graph_with_faces(
    rng: random.Random,
    n: int,
    planar_edges: List[Tuple[int, int, float]],
    target_faces: int,
) -> Tuple[List[Tuple[int, int]], int, int] | None:
    """Build a planar graph targeting a specific number of bounded faces.

    Strategy:
      1. Build a spanning forest from shuffled edges (connecting as many dots
         as possible into one component).
      2. Each additional intra-component edge beyond the spanning forest creates
         exactly one new bounded face (Euler: F_bounded = E - V + C).
      3. Add extra edges until we reach the target face count.

    Returns (edges, bounded_faces, num_components) or None if infeasible.
    """
    uf = UnionFind(n)

    # Shuffle edges, biased toward shorter ones
    mid = len(planar_edges) // 2
    short = list(planar_edges[:mid])
    long = list(planar_edges[mid:])
    rng.shuffle(short)
    rng.shuffle(long)
    shuffled = short + long

    # Phase 1: build spanning forest (connect everything into one component ideally)
    tree_edges: List[Tuple[int, int]] = []
    extra_edges: List[Tuple[int, int]] = []

    for i, j, d in shuffled:
        if uf.find(i) != uf.find(j):
            uf.union(i, j)
            tree_edges.append((i, j))
        else:
            extra_edges.append((i, j))

    num_components = uf.num_sets

    # Phase 2: add extra edges to create faces
    # bounded_faces = E - V + C = (tree + extra) - V + C
    # spanning forest has V - C edges, so faces = num_extra_added
    rng.shuffle(extra_edges)

    if len(extra_edges) < target_faces:
        return None

    selected_edges = tree_edges + extra_edges[:target_faces]
    bounded_faces = target_faces

    return selected_edges, bounded_faces, num_components


# ---------------------------------------------------------------------------
# Instance sampling
# ---------------------------------------------------------------------------

QUESTION = (
    "How many distinct enclosed regions (bounded faces) are visible in this image? "
    "An enclosed region is a maximal area that is fully surrounded by the drawn "
    "line segments on every side, with no opening to the outside background. The "
    "unbounded outside area does not count as an enclosed region. Each enclosed "
    "region should be counted exactly once, regardless of its shape. Count every "
    "enclosed region in the entire image and report the total as a positive integer. "
    "Provide your final answer enclosed in <answer>...</answer> tags."
)


def sample_instance(
    rng: random.Random,
    width: int,
    height: int,
    grid_rows: int,
    grid_cols: int,
    min_faces: int,
    max_faces: int,
    num_dots_min: int,
    num_dots_max: int,
    min_gap: float,
    dot_radius: float,
    max_edge_len: float,
) -> Dict[str, object] | None:
    target_faces = rng.randint(min_faces, max_faces)
    num_dots = rng.randint(num_dots_min, num_dots_max)

    dots = place_dots(rng, grid_rows, grid_cols, num_dots, min_gap)
    if len(dots) < 10:
        return None

    planar_edges = build_planar_edge_set(dots, dot_radius, max_edge_len)

    result = build_graph_with_faces(rng, len(dots), planar_edges, target_faces)
    if result is None:
        return None

    edges, bounded_faces, num_components = result

    if bounded_faces < min_faces:
        return None

    margin = int(min(width, height) * 0.10)
    square_size = min(width, height) - 2 * margin
    square_left = (width - square_size) / 2.0
    square_top = (height - square_size) / 2.0

    return {
        "width": width,
        "height": height,
        "grid_rows": grid_rows,
        "grid_cols": grid_cols,
        "square_left": round(square_left, 2),
        "square_top": round(square_top, 2),
        "square_size": round(square_size, 2),
        "num_dots": len(dots),
        "num_edges": len(edges),
        "num_components": num_components,
        "question": QUESTION,
        "answer": bounded_faces,
        "dots": [[r, c] for r, c in dots],
        "edges": [[i, j] for i, j in edges],
        "dot_radius": dot_radius,
    }


# ---------------------------------------------------------------------------
# Rendering (matplotlib — smooth anti-aliased output)
# ---------------------------------------------------------------------------

LINE_COLOR = "#2f2f2f"
DOT_COLOR = "#1d1916"


def render_instance(out_path: Path, record: Dict[str, object], noise_seed: int = 0) -> None:
    width = int(record["width"])
    height = int(record["height"])
    grid_rows = int(record["grid_rows"])
    grid_cols = int(record["grid_cols"])
    square_left = float(record["square_left"])
    square_top = float(record["square_top"])
    square_size = float(record["square_size"])
    dots: List[List[int]] = record["dots"]  # type: ignore[assignment]
    edges: List[List[int]] = record["edges"]  # type: ignore[assignment]
    dot_radius_grid = float(record["dot_radius"])

    cell_w = square_size / grid_cols
    cell_h = square_size / grid_rows

    def to_pixel(r: float, c: float) -> Tuple[float, float]:
        px = square_left + (c + 0.5) * cell_w
        py = square_top + (r + 0.5) * cell_h
        return px, py

    pixel_dot_radius = dot_radius_grid * min(cell_w, cell_h) * 0.5
    edge_thickness = max(1.5, pixel_dot_radius * 0.3)

    fig = plt.figure(figsize=(width / 100, height / 100), dpi=100)
    ax = fig.add_axes([0, 0, 1, 1])
    ax.set_xlim(0, width)
    ax.set_ylim(height, 0)
    ax.axis("off")
    ax.set_facecolor("#f8f6f0")

    # Subtle noise background
    nrng = np.random.default_rng(noise_seed)
    noise = nrng.normal(0.0, 1.0, size=(height, width))
    noise = (noise - noise.min()) / max(noise.max() - noise.min(), 1e-6)
    ax.imshow(noise, cmap="Greys", alpha=0.05, extent=(0, width, height, 0),
              interpolation="bilinear")

    # White square background
    ax.fill_between(
        [square_left, square_left + square_size],
        [square_top, square_top],
        [square_top + square_size, square_top + square_size],
        color="#fffdf8", zorder=0.5,
    )

    # Border
    bx = [square_left, square_left + square_size, square_left + square_size, square_left, square_left]
    by = [square_top, square_top, square_top + square_size, square_top + square_size, square_top]
    ax.plot(bx, by, color="#2d2720", linewidth=2.0, solid_capstyle="round", zorder=1.0)

    # Plain (v4_plain): solid edges. No dashed-line anti-shortcut.
    for i, j in edges:
        px1, py1 = to_pixel(dots[i][0], dots[i][1])
        px2, py2 = to_pixel(dots[j][0], dots[j][1])
        ax.plot([px1, px2], [py1, py2],
                color=LINE_COLOR, linewidth=edge_thickness,
                solid_capstyle="round", alpha=0.92, zorder=2.0)

    # Dots on top
    for r, c in dots:
        px, py = to_pixel(r, c)
        circle = plt.Circle((px, py), pixel_dot_radius, color=DOT_COLOR, zorder=3.0)
        ax.add_patch(circle)

    fig.savefig(out_path, dpi=100, bbox_inches="tight", pad_inches=0)
    plt.close(fig)


# ---------------------------------------------------------------------------
# Dataset generation
# ---------------------------------------------------------------------------


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("--output-root", type=Path, required=True)
    parser.add_argument("--count", type=int, default=30)
    parser.add_argument("--seed", type=int, default=42)
    parser.add_argument("--width", type=int, default=1024)
    parser.add_argument("--height", type=int, default=1024)
    parser.add_argument("--grid-rows", type=int, default=100)
    parser.add_argument("--grid-cols", type=int, default=100)
    parser.add_argument("--min-faces", type=int, default=4)
    parser.add_argument("--max-faces", type=int, default=15)
    parser.add_argument("--num-dots-min", type=int, default=60)
    parser.add_argument("--num-dots-max", type=int, default=120)
    parser.add_argument("--min-gap", type=float, default=5.0)
    parser.add_argument("--dot-radius", type=float, default=1.5)
    parser.add_argument("--max-edge-len", type=float, default=25.0)
    parser.add_argument("--difficulty", type=int, default=5,
                        help="Integer difficulty >=0; scales faces and dot count.")
    args = parser.parse_args()

    d = max(0, int(args.difficulty))
    # Difficulty scaling per spec
    args.min_faces = 5
    args.max_faces = 5 + 2 * d
    args.num_dots_min = 10 * d
    args.num_dots_max = 20 + 10 * d
    base_max_edge_len = args.max_edge_len
    args.max_edge_len = base_max_edge_len / (1.0 + 0.08 * d)

    # Canvas scaling based on num_dots_max growth
    N_d = 20 + 10 * d
    N_0 = 20
    s = math.sqrt(max(1.0, N_d / N_0))
    args.width = int(round(args.width * s))
    args.height = int(round(args.height * s))

    out_root: Path = args.output_root
    img_dir = out_root / "images"
    img_dir.mkdir(parents=True, exist_ok=True)
    ann_path = out_root / "annotations.jsonl"

    rng = random.Random(args.seed)
    records = []
    # Force evenly-spaced answers across [min_faces, max_faces].
    if args.count > 1:
        forced_targets = [
            int(round(args.min_faces + i * (args.max_faces - args.min_faces) / (args.count - 1)))
            for i in range(args.count)
        ]
    else:
        forced_targets = [args.min_faces]
    print(f"forced face counts: {forced_targets}")
    with ann_path.open("w") as f:
        for i in range(args.count):
            sub_seed = rng.randint(0, 2**31 - 1)
            tgt = forced_targets[i]
            for _ in range(2000):
                record = sample_instance(
                    rng=rng,
                    width=args.width,
                    height=args.height,
                    grid_rows=args.grid_rows,
                    grid_cols=args.grid_cols,
                    min_faces=tgt,
                    max_faces=tgt,
                    num_dots_min=args.num_dots_min,
                    num_dots_max=args.num_dots_max,
                    min_gap=args.min_gap,
                    dot_radius=args.dot_radius,
                    max_edge_len=args.max_edge_len,
                )
                if record is not None and record.get("answer") == tgt:
                    break
            else:
                print(f"  [{i+1}/{args.count}] SKIP (failed to generate)")
                continue

            name = f"bounded_faces_counting_{i:05d}.png"
            render_instance(img_dir / name, record, noise_seed=sub_seed)
            print(f"  [{i+1}/{args.count}] faces={record['answer']} dots={record['num_dots']} edges={record['num_edges']}")

            rec = {
                "image": f"images/{name}",
                "question": QUESTION,
                "answer": record["answer"],
                "metadata": {
                    "bounded_faces": record["answer"],
                    "num_dots": record["num_dots"],
                    "num_edges": record["num_edges"],
                    "num_components": record["num_components"],
                    "seed": sub_seed,
                },
            }
            f.write(json.dumps(rec) + "\n")
            records.append(rec)

    data_json = {
        "task": "bounded_faces_counting",
        "category": "distributed_scanning",
        "count": len(records),
        "items": records,
    }
    (out_root / "data.json").write_text(json.dumps(data_json, indent=2))
    print(f"Saved to {out_root}")


if __name__ == "__main__":
    main()