File size: 18,988 Bytes
f69e256
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
"""Generate 'Spot the Signal Diff' visual benchmark dataset.

Two 1D signals are shown side by side. Each signal's x-axis is divided
into 9 equal segments. Independently for each segment, the right signal
may or may not have a short smooth perturbation applied at the segment's
centre (raised-cosine blend, endpoints anchored so the splice is
seamless). Task: count how many of the 9 segments are identical between
left and right. Answer is an integer 0..9.
"""
from __future__ import annotations

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

import matplotlib

matplotlib.use("Agg")
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import numpy as np
from tqdm import tqdm


# ---------------------------------------------------------------------------
# Constants
# ---------------------------------------------------------------------------

N_SAMPLES = 2000
X_RANGE = (0.0, 2000.0)

GRID_N = 9                         # segments along x
assert N_SAMPLES % GRID_N == 0 or True  # integer cell boundaries handled numerically

# Each perturbation is a contiguous span of this many samples, centred in
# its segment. Must be well below the segment length so the transition
# band never straddles a segment boundary.
SEGMENT_WIDTH = N_SAMPLES // GRID_N          # ≈ 222 samples per segment
PERTURB_WIDTH = 110                          # ~half of one segment
assert PERTURB_WIDTH < SEGMENT_WIDTH - 2 * 15

# Raised-cosine splice blend at each edge of the perturbation.
TRANSITION_BAND = 15
RESYNTH_PAD = 40
MIN_DEVIATION_MULT = 0.4
INTRA_SEGMENT_NOISE_SIGMA = 0.04

PANEL_W = 1500
PANEL_H = 440

BG_COLOR = "#ffffff"
LINE_COLOR = "#1f4e79"
GRID_COLOR = "#c0c6d0"            # segment-boundary grid (visible)
GRID_WIDTH = 1.2
BORDER_COLOR = "#888888"
BORDER_WIDTH = 1.5
LABEL_COLOR = "#333333"
HIGHLIGHT_COLOR = "#dc1e1e"

MARGIN_PX = 70
GAP_PX = 110
LABEL_HEIGHT = 44

def _build_question() -> str:
    n = GRID_N
    return (
        f"Two 1D signals are shown side by side. Each signal's x-axis is "
        f"divided into {n} equal segments by thin vertical gridlines, and "
        f"each segment is numbered 1 through {n} above the gridlines (the "
        f"two signals share the same numbering). Compare the left (Signal A) "
        f"and right (Signal B) signals segment by segment. List the numbers "
        f"of all segments that DIFFER between Signal A and Signal B, in "
        f"ascending order, separated by commas (for example: \"2, 5, {n}\"). "
        f"If no segments differ, write \"none\". "
        f"Provide your final answer enclosed in <answer>...</answer> tags."
    )


QUESTION = (
    "Two 1D signals are shown side by side. Each signal's x-axis is "
    "divided into 9 equal segments by thin vertical gridlines. Compare "
    "the left and right signals segment by segment. Count how many of "
    "the 9 segments are DIFFERENT between the two signals. Report the "
    "count as an integer between 0 and 9. "
    "Provide your final answer enclosed in <answer>...</answer> tags."
)


# ---------------------------------------------------------------------------
# Signal generator
# ---------------------------------------------------------------------------


def _gaussian_kernel(sigma: float) -> np.ndarray:
    radius = max(1, int(sigma * 4))
    k = np.arange(-radius, radius + 1, dtype=np.float64)
    w = np.exp(-(k * k) / (2.0 * sigma * sigma))
    return w / w.sum()


def _smoothed_noise(rng: random.Random, sigma: float) -> np.ndarray:
    raw = np.array([rng.gauss(0.0, 1.0) for _ in range(N_SAMPLES)], dtype=np.float64)
    kernel = _gaussian_kernel(sigma)
    return np.convolve(raw, kernel, mode="same")


def generate_signal(rng: random.Random) -> np.ndarray:
    coarse = _smoothed_noise(rng, sigma=rng.uniform(60.0, 110.0))
    medium = _smoothed_noise(rng, sigma=rng.uniform(18.0, 35.0))
    fine = _smoothed_noise(rng, sigma=rng.uniform(4.0, 8.0))
    micro = _smoothed_noise(rng, sigma=rng.uniform(1.5, 2.5))

    def _norm(a: np.ndarray) -> np.ndarray:
        s = float(np.std(a)) or 1.0
        return a / s

    y = (
        1.8 * _norm(coarse)
        + 0.75 * _norm(medium)
        + 0.40 * _norm(fine)
        + 0.20 * _norm(micro)
    )
    y = y + np.random.normal(0.0, INTRA_SEGMENT_NOISE_SIGMA, size=y.shape)
    return y


# ---------------------------------------------------------------------------
# Segment geometry and perturbation selection
# ---------------------------------------------------------------------------


def _segment_bounds(idx: int) -> Tuple[int, int]:
    """Return (start, end) sample-index bounds of segment idx (end exclusive)."""
    start = round(idx * N_SAMPLES / GRID_N)
    end = round((idx + 1) * N_SAMPLES / GRID_N)
    return int(start), int(end)


def _perturb_window(segment_idx: int) -> Tuple[int, int]:
    """Return (start, end) sample indices of the perturbation window,
    centred within segment ``segment_idx``."""
    s, e = _segment_bounds(segment_idx)
    mid = (s + e) // 2
    half = PERTURB_WIDTH // 2
    p_start = mid - half
    p_end = p_start + PERTURB_WIDTH
    return p_start, p_end


MIN_PERTURBED = 0
MAX_PERTURBED = GRID_N


def _sample_perturbed_segments(rng: random.Random) -> List[int]:
    """Uniform num_perturbed ∈ {MIN_PERTURBED..MAX_PERTURBED}, then that many
    segments chosen at random."""
    num_perturbed = rng.randint(MIN_PERTURBED, MAX_PERTURBED)
    all_idx = list(range(GRID_N))
    rng.shuffle(all_idx)
    return sorted(all_idx[:num_perturbed])


# ---------------------------------------------------------------------------
# Perturbation (segment-resynthesis with edge-anchored raised-cosine splice)
# ---------------------------------------------------------------------------


def _resynthesise_segment(
    rng: random.Random,
    left: np.ndarray,
    start: int,
    end: int,
    sig_std: float,
    max_tries: int = 30,
) -> np.ndarray:
    n = end - start
    orig = left[start:end]
    a = float(left[start])
    b = float(left[end - 1])
    min_dev = MIN_DEVIATION_MULT * sig_std

    for _ in range(max_tries):
        cand_full = generate_signal(rng)
        if len(cand_full) <= n + 2 * RESYNTH_PAD:
            continue
        cs = rng.randint(RESYNTH_PAD, len(cand_full) - n - RESYNTH_PAD)
        cand = cand_full[cs:cs + n].copy()

        ca, cb = float(cand[0]), float(cand[-1])
        t = np.linspace(0.0, 1.0, n)
        cand = cand - ((1.0 - t) * (ca - a) + t * (cb - b))

        margin = min(TRANSITION_BAND, max(5, n // 10))
        interior_dev = float(np.max(np.abs(cand[margin:n - margin] - orig[margin:n - margin])))
        if interior_dev < min_dev:
            continue
        return cand

    raise RuntimeError("Could not synthesise a sufficiently different segment.")


def _splice_with_blend(
    signal: np.ndarray,
    start: int,
    end: int,
    replacement: np.ndarray,
) -> None:
    n = end - start
    band = min(TRANSITION_BAND, n // 2)

    w = np.ones(n)
    if band > 0:
        edge = 0.5 * (1.0 - np.cos(np.linspace(0.0, np.pi, band + 2)[1:-1]))
        w[:band] = edge
        w[-band:] = edge[::-1]

    signal[start:end] = (1.0 - w) * signal[start:end] + w * replacement


def build_sample(
    rng: random.Random,
) -> Tuple[np.ndarray, np.ndarray, np.ndarray, List[Dict[str, Any]]]:
    x = np.linspace(X_RANGE[0], X_RANGE[1], N_SAMPLES)
    left = generate_signal(rng)
    right = left.copy()

    sig_std = float(np.std(left)) or 1.0
    perturbed = set(_sample_perturbed_segments(rng))

    segment_records: List[Dict[str, Any]] = []
    for idx in range(GRID_N):
        seg_start, seg_end = _segment_bounds(idx)
        is_perturbed = idx in perturbed
        record: Dict[str, Any] = {
            "segment": idx,
            "seg_start_index": seg_start,
            "seg_end_index": seg_end,
            "seg_x_start": float(x[seg_start]),
            "seg_x_end": float(x[min(seg_end, N_SAMPLES) - 1]),
            "perturbed": is_perturbed,
        }
        if is_perturbed:
            p_start, p_end = _perturb_window(idx)
            replacement = _resynthesise_segment(rng, left, p_start, p_end, sig_std)
            _splice_with_blend(right, p_start, p_end, replacement)
            record.update({
                "perturb_start_index": int(p_start),
                "perturb_end_index": int(p_end),
                "perturb_x_start": float(x[p_start]),
                "perturb_x_end": float(x[p_end - 1]),
            })
        segment_records.append(record)

    return x, left, right, segment_records


# ---------------------------------------------------------------------------
# Rendering
# ---------------------------------------------------------------------------


LEGEND_W_SCALE = 0.40   # legend width = 40% of a signal panel
LEGEND_H = 80           # legend bar height (px) — independent of signal panel height


def _legend_dims() -> Tuple[int, int]:
    return int(round(PANEL_W * LEGEND_W_SCALE)), int(LEGEND_H)


def _panel_origins() -> Tuple[Tuple[float, float],
                              Tuple[float, float],
                              Tuple[float, float]]:
    """(ox, oy) for legend (small bar, vertically centered), Signal A,
    Signal B. Layout: [legend] [GAP] [Signal A] [GAP] [Signal B]."""
    oy_signal = MARGIN_PX + LABEL_HEIGHT
    leg_w, leg_h = _legend_dims()
    ox_legend = MARGIN_PX
    oy_legend = oy_signal + (PANEL_H - leg_h) / 2
    ox_left = ox_legend + leg_w + GAP_PX
    ox_right = ox_left + PANEL_W + GAP_PX
    return (ox_legend, oy_legend), (ox_left, oy_signal), (ox_right, oy_signal)


def _canvas_size() -> Tuple[int, int]:
    leg_w, _ = _legend_dims()
    w = MARGIN_PX + leg_w + GAP_PX + PANEL_W + GAP_PX + PANEL_W + MARGIN_PX
    h = MARGIN_PX + LABEL_HEIGHT + PANEL_H + MARGIN_PX
    return int(w), int(h)


def _draw_legend(ax: plt.Axes, ox: float, oy: float) -> None:
    """Small horizontal index bar: N cells partitioned by vertical
    gridlines, each labeled with its 1-based segment number."""
    leg_w, leg_h = _legend_dims()
    cell_w = leg_w / GRID_N
    legend_bg = mpatches.Rectangle(
        (ox, oy), leg_w, leg_h,
        facecolor="#e8e6e0", edgecolor=BORDER_COLOR,
        linewidth=BORDER_WIDTH, zorder=2,
    )
    ax.add_patch(legend_bg)
    for i in range(1, GRID_N):
        gx = ox + i * cell_w
        ax.plot([gx, gx], [oy, oy + leg_h],
                color="#888", linewidth=GRID_WIDTH, zorder=3)
    fontsize = max(10, int(min(cell_w, leg_h) * 0.40))
    for i in range(GRID_N):
        cx = ox + i * cell_w + cell_w / 2
        cy = oy + leg_h / 2
        ax.text(cx, cy, str(i + 1),
                ha="center", va="center",
                fontsize=fontsize, fontweight="bold",
                color="#222", zorder=4)


def _draw_panel(
    ax: plt.Axes,
    x: np.ndarray,
    y: np.ndarray,
    ox: float,
    oy: float,
    y_lo: float,
    y_hi: float,
) -> None:
    sx = PANEL_W / (X_RANGE[1] - X_RANGE[0])
    sy = PANEL_H / (y_hi - y_lo) if y_hi > y_lo else 1.0

    px = ox + (x - X_RANGE[0]) * sx
    py = oy + PANEL_H - (y - y_lo) * sy
    ax.plot(px, py, color=LINE_COLOR, linewidth=1.8, zorder=3, antialiased=True)


def _draw_segment_grid(ax: plt.Axes, ox: float, oy: float) -> None:
    """Draw GRID_N-1 internal vertical dividers, partitioning the panel
    x-axis into ``GRID_N`` equal segments."""
    for i in range(1, GRID_N):
        gx = ox + PANEL_W * i / GRID_N
        ax.plot(
            [gx, gx], [oy, oy + PANEL_H],
            color=GRID_COLOR, linewidth=GRID_WIDTH, zorder=1,
        )


def _render(
    out_path: Path,
    x: np.ndarray,
    left: np.ndarray,
    right: np.ndarray,
    segment_records: List[Dict[str, Any]] | None = None,
) -> None:
    w, h = _canvas_size()
    dpi = 100
    fig, ax = plt.subplots(1, 1, figsize=(w / dpi, h / dpi), dpi=dpi)
    ax.set_xlim(0, w)
    ax.set_ylim(h, 0)
    ax.set_aspect("auto")
    ax.axis("off")
    fig.patch.set_facecolor(BG_COLOR)
    ax.set_facecolor(BG_COLOR)

    (ox_legend, oy_legend), (ox_left, oy), (ox_right, _) = _panel_origins()
    _draw_legend(ax, ox_legend, oy_legend)
    leg_w, _ = _legend_dims()
    ax.text(
        ox_legend + leg_w / 2, oy_legend - 12,
        "Index", ha="center", va="bottom",
        fontsize=13, fontweight="bold", color=LABEL_COLOR,
    )

    y_all = np.concatenate([left, right])
    y_lo = float(y_all.min())
    y_hi = float(y_all.max())
    pad = (y_hi - y_lo) * 0.08 if y_hi > y_lo else 1.0
    y_lo -= pad
    y_hi += pad

    for ox in (ox_left, ox_right):
        border = mpatches.Rectangle(
            (ox, oy), PANEL_W, PANEL_H,
            facecolor="none", edgecolor=BORDER_COLOR,
            linewidth=BORDER_WIDTH, zorder=2,
        )
        ax.add_patch(border)
        _draw_segment_grid(ax, ox, oy)

    _draw_panel(ax, x, left, ox_left, oy, y_lo, y_hi)
    _draw_panel(ax, x, right, ox_right, oy, y_lo, y_hi)

    ax.text(
        ox_left + PANEL_W / 2, MARGIN_PX + LABEL_HEIGHT * 0.3,
        "Signal A", ha="center", va="center",
        fontsize=15, fontweight="bold", color=LABEL_COLOR,
    )
    ax.text(
        ox_right + PANEL_W / 2, MARGIN_PX + LABEL_HEIGHT * 0.3,
        "Signal B", ha="center", va="center",
        fontsize=15, fontweight="bold", color=LABEL_COLOR,
    )


    if segment_records:
        sx = PANEL_W / (X_RANGE[1] - X_RANGE[0])
        for rec in segment_records:
            if not rec.get("perturbed"):
                continue
            px_start = (rec["perturb_x_start"] - X_RANGE[0]) * sx
            px_end = (rec["perturb_x_end"] - X_RANGE[0]) * sx
            for ox in (ox_left, ox_right):
                ax.add_patch(mpatches.Rectangle(
                    (ox + px_start, oy),
                    px_end - px_start, PANEL_H,
                    facecolor=HIGHLIGHT_COLOR, edgecolor="none", alpha=0.18, zorder=4,
                ))

    fig.savefig(out_path, facecolor=BG_COLOR)
    plt.close(fig)


def render_pair(
    out_path: Path,
    x: np.ndarray,
    left: np.ndarray,
    right: np.ndarray,
) -> None:
    _render(out_path, x, left, right)


def render_answer(
    out_path: Path,
    x: np.ndarray,
    left: np.ndarray,
    right: np.ndarray,
    segment_records: List[Dict[str, Any]],
) -> None:
    _render(out_path, x, left, right, segment_records)


# ---------------------------------------------------------------------------
# Annotation
# ---------------------------------------------------------------------------


def build_annotation(
    image_name: str,
    segment_records: List[Dict[str, Any]],
) -> Dict[str, Any]:
    num_identical = sum(1 for r in segment_records if not r["perturbed"])
    num_different = GRID_N - num_identical
    diff_indices = sorted(
        r["segment"] + 1 for r in segment_records if r.get("perturbed")
    )
    answer = ", ".join(str(i) for i in diff_indices) if diff_indices else "none"
    return {
        "image": image_name,
        "num_segments": GRID_N,
        "num_identical": num_identical,
        "num_different": num_different,
        "diff_indices": diff_indices,
        "segments": segment_records,
        "question": _build_question(),
        "answer": answer,
    }


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


def generate_dataset(
    rng: random.Random,
    count: int,
    output_dir: Path,
) -> None:
    images_dir = output_dir / "images"
    answers_dir = output_dir / "answers"
    images_dir.mkdir(parents=True, exist_ok=True)
    answers_dir.mkdir(parents=True, exist_ok=True)

    annotations: List[Dict[str, Any]] = []
    data_items: List[Dict[str, Any]] = []

    np.random.seed(rng.randint(0, 2**31 - 1))

    for idx in tqdm(range(count), desc="Generating signal diff pairs"):
        for _ in range(20):
            try:
                x, left, right, segment_records = build_sample(rng)
                break
            except RuntimeError:
                continue
        else:
            raise RuntimeError(f"Failed to build sample {idx}")

        image_name = f"signal_diff_{idx:05d}.png"
        img_path = images_dir / image_name
        ans_path = answers_dir / image_name

        render_pair(img_path, x, left, right)
        render_answer(ans_path, x, left, right, segment_records)

        rel_image = f"images/{image_name}"
        diff_indices = sorted(
            r["segment"] + 1 for r in segment_records if r.get("perturbed")
        )
        answer = ", ".join(str(i) for i in diff_indices) if diff_indices else "none"
        annotations.append(build_annotation(rel_image, segment_records))
        data_items.append({
            "image": rel_image,
            "question": _build_question(),
            "answer": answer,
        })

    with (output_dir / "annotations.jsonl").open("w", encoding="utf-8") as fh:
        for rec in annotations:
            fh.write(json.dumps(rec) + "\n")

    data_json = {
        "task": "spot_the_signal_diff",
        "category": "visual_attribute_transfer",
        "count": len(data_items),
        "items": data_items,
    }
    with (output_dir / "data.json").open("w", encoding="utf-8") as fh:
        json.dump(data_json, fh, indent=2)
        fh.write("\n")


# ---------------------------------------------------------------------------
# CLI
# ---------------------------------------------------------------------------


def parse_args() -> argparse.Namespace:
    p = argparse.ArgumentParser(
        description="Generate 'Spot the Signal Diff' visual benchmark dataset."
    )
    p.add_argument("--output-root", type=Path, default=".")
    p.add_argument("--count", type=int, default=20)
    p.add_argument("--seed", type=int, default=42)
    p.add_argument("--difficulty", type=int, default=5,
                   help="Integer difficulty >=0; scales perturbed segments and perturbation amplitude.")
    return p.parse_args()


def main() -> None:
    import math
    args = parse_args()
    rng = random.Random(args.seed)
    d = max(0, int(args.difficulty))

    global GRID_N, SEGMENT_WIDTH, PERTURB_WIDTH
    global MIN_PERTURBED, MAX_PERTURBED, MIN_DEVIATION_MULT
    global INTRA_SEGMENT_NOISE_SIGMA, PANEL_W

    GRID_N = 5 + d
    SEGMENT_WIDTH = N_SAMPLES // GRID_N
    PERTURB_WIDTH = min(110, max(30, SEGMENT_WIDTH - 2 * TRANSITION_BAND - 10))
    MIN_PERTURBED = 1
    MAX_PERTURBED = GRID_N
    scale = 0.5 / (1.0 + 0.1 * d)
    MIN_DEVIATION_MULT = MIN_DEVIATION_MULT * scale
    INTRA_SEGMENT_NOISE_SIGMA = 0.03 + 0.01 * d

    # Canvas scaling (X-axis only): panel width scales with sqrt((5+d)/5).
    s = math.sqrt(max(1.0, (5 + d) / 5))
    PANEL_W = int(round(PANEL_W * s))

    generate_dataset(rng, args.count, args.output_root)
    print(f"Saved {args.count} signal diff pairs to {args.output_root}")


if __name__ == "__main__":
    main()