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
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
#!/usr/bin/env python3
"""
i-GSM-style generator (mod 7) with ASCII variables.

Two operator modes:
  ascii  (hard): glyphs @ & $ ~ with MEANING randomized per problem
                 (may include lin / prodplus / modular inverse).
  arith  (easy): fixed conventional operators + - * / with fixed meanings:
                 a + b = (a + b) mod 7
                 a - b = (a - b) mod 7
                 a * b = (a × b) mod 7
                 a / b = (a × b⁻¹) mod 7   [b≠0]

Expressions are evaluated STRICTLY LEFT TO RIGHT (no standard precedence);
this convention is stated in each problem's preamble.

Usage:
    python construct.py --ops ascii --outdir out          # hard version
    python construct.py --ops arith --outdir out_arith    # easy +-*/ version
    python construct.py --ops arith --n 250 --depths 2 3 4 --distractors 0
"""

import argparse
import json
import os
import random

MOD = 7
INV7 = {1: 1, 2: 4, 3: 5, 4: 2, 5: 3, 6: 6}   # inverses mod 7 (0 excluded)

LETTERS_1 = "EFGHIJKL"    # first symbol of a variable name  (X in X#Y)
LETTERS_2 = "IJKLMNOP"    # second symbol of a variable name (Y in X#Y)


# --------------------------------------------------------------------------- #
# Operators
# --------------------------------------------------------------------------- #
def make_op(kind, glyph, rng=None, params=None):
    if kind == "add":
        f = lambda a, b: (a + b) % MOD
        definition = f"a {glyph} b = (a + b) mod {MOD}"
        show = lambda a, b: f"({a} + {b}) mod {MOD}"
        params = {}
    elif kind == "mul":
        f = lambda a, b: (a * b) % MOD
        definition = f"a {glyph} b = (a × b) mod {MOD}"
        show = lambda a, b: f"({a} × {b}) mod {MOD}"
        params = {}
    elif kind == "sub":
        f = lambda a, b: (a - b) % MOD
        definition = f"a {glyph} b = (a - b) mod {MOD}"
        show = lambda a, b: f"({a} - {b}) mod {MOD}"
        params = {}
    elif kind == "prodplus":
        f = lambda a, b: (a * b + a + b) % MOD
        definition = f"a {glyph} b = (a×b + a + b) mod {MOD}"
        show = lambda a, b: f"({a}×{b} + {a} + {b}) mod {MOD}"
        params = {}
    elif kind == "lin":
        if params is None:
            assert rng is not None
            params = {"al": rng.choice([2, 3, 4, 5]), "be": rng.choice([2, 3, 4, 5])}
        al, be = params["al"], params["be"]
        f = lambda a, b, al=al, be=be: (al * a + be * b) % MOD
        definition = f"a {glyph} b = ({al}·a + {be}·b) mod {MOD}"
        show = lambda a, b, al=al, be=be: f"({al}×{a} + {be}×{b}) mod {MOD}"
    elif kind == "div":
        f = lambda a, b: (a * INV7[b % MOD]) % MOD
        definition = f"a {glyph} b = (a × b⁻¹) mod {MOD}   [b≠0]"
        show = lambda a, b: f"({a} × {b}⁻¹) mod {MOD}"
        params = {}
    else:
        raise ValueError(kind)
    return {"glyph": glyph, "kind": kind, "params": params,
            "definition": definition, "f": f, "show": show}


ASCII_GLYPHS = ["@", "&", "$", "~"]   # fixed glyphs; MEANING randomized per problem
# Conventional ops: fixed glyph <-> meaning (easier).
ARITH_OPS = [
    ("add", "+"),
    ("sub", "-"),
    ("mul", "*"),
    ("div", "/"),
]


def sample_operator_table(rng, allow_div=True, ops_mode="ascii"):
    """Build the operator table for one problem."""
    if ops_mode == "arith":
        kinds_glyphs = list(ARITH_OPS)
        if not allow_div:
            kinds_glyphs = [(k, g) for k, g in kinds_glyphs if k != "div"]
        return [make_op(k, g, rng) for k, g in kinds_glyphs]

    # ascii: randomize glyph <-> meaning each problem.
    kinds = ["add", "mul"]                       # always present -> expressive
    pool = ["sub", "lin", "prodplus"] + (["div"] if allow_div else [])
    rng.shuffle(pool)
    while len(kinds) < 4 and pool:
        kinds.append(pool.pop())
    rng.shuffle(kinds)
    glyphs = list(ASCII_GLYPHS)
    rng.shuffle(glyphs)                          # randomize glyph <-> meaning
    return [make_op(k, g, rng) for k, g in zip(kinds, glyphs)]


# --------------------------------------------------------------------------- #
# Variable names
# --------------------------------------------------------------------------- #
def new_var(used, rng):
    while True:
        nm = rng.choice(LETTERS_1) + "#" + rng.choice(LETTERS_2)
        if nm not in used:
            used.add(nm)
            return nm


# --------------------------------------------------------------------------- #
# Expression building (left-to-right fold)
# --------------------------------------------------------------------------- #
def build_expr(rng, parents, mandatory, ops, value):
    n_terms = rng.choice([1, 2, 2, 3])
    term_vars = [mandatory]
    others = [p for p in parents if p != mandatory]
    rng.shuffle(others)
    while len(term_vars) < n_terms and (others or rng.random() < 0.4):
        if others and rng.random() < 0.7:
            term_vars.append(others.pop())
        else:
            term_vars.append(("const", rng.randint(2, 6)))
    rng.shuffle(term_vars)
    terms = [t if isinstance(t, tuple) else ("var", t) for t in term_vars]

    def tval(t):
        return value[t[1]] if t[0] == "var" else t[1] % MOD

    if len(terms) == 1:
        return terms, [], tval(terms[0])

    op_seq = []
    acc = tval(terms[0])
    for i in range(1, len(terms)):
        rv = tval(terms[i])
        choices = [o for o in ops if not (o["kind"] == "div" and rv % MOD == 0)]
        op = rng.choice(choices)
        op_seq.append(op)
        acc = op["f"](acc, rv)
    return terms, op_seq, acc


def term_str(t):
    return t[1] if t[0] == "var" else str(t[1])


def expr_str(terms, op_seq):
    if not op_seq:
        return term_str(terms[0])
    out = [term_str(terms[0])]
    for op, t in zip(op_seq, terms[1:]):
        out += [op["glyph"], term_str(t)]
    return " ".join(out)


# --------------------------------------------------------------------------- #
# Problem generation
# --------------------------------------------------------------------------- #
def generate_problem(rng, depth, n_distractors=2, allow_div=True, ops_mode="ascii"):
    ops = sample_operator_table(rng, allow_div=allow_div, ops_mode=ops_mode)
    used = set()
    layers, definitions, order, var_layer, value = {}, {}, [], {}, {}

    layers[1] = []
    for _ in range(rng.randint(2, 4)):
        v = new_var(used, rng)
        c = rng.randint(1, 6)
        definitions[v] = {"type": "const", "c": c}
        value[v] = c % MOD
        var_layer[v] = 1
        layers[1].append(v); order.append(v)

    for d in range(2, depth + 1):
        layers[d] = []
        n_nodes = rng.randint(2, 3) if d < depth else 1
        lower = [x for L in range(1, d) for x in layers[L]]
        for _ in range(n_nodes):
            v = new_var(used, rng)
            mandatory = rng.choice(layers[d - 1])
            terms, op_seq, val = build_expr(rng, lower, mandatory, ops, value)
            definitions[v] = {"type": "expr", "terms": terms, "ops": op_seq}
            value[v] = val
            var_layer[v] = d
            layers[d].append(v); order.append(v)

    query = layers[depth][-1]

    non_query = [x for x in order if x != query]
    for _ in range(n_distractors):
        v = new_var(used, rng)
        d = rng.randint(2, depth)
        eligible = [x for x in non_query if var_layer[x] < d]
        if not eligible:
            continue
        mandatory = rng.choice(eligible)
        terms, op_seq, val = build_expr(rng, eligible, mandatory, ops, value)
        definitions[v] = {"type": "expr", "terms": terms, "ops": op_seq}
        value[v] = val
        var_layer[v] = d
        order.append(v); non_query.append(v)

    answer = value[query]

    depth_of = {}
    for v in order:
        d = definitions[v]
        if d["type"] == "const":
            depth_of[v] = 1
        else:
            pv = [depth_of[t[1]] for t in d["terms"] if t[0] == "var"]
            depth_of[v] = 1 + (max(pv) if pv else 0)
    achieved_depth = depth_of[query]

    seen, stack = set(), [query]
    while stack:
        x = stack.pop()
        if x in seen:
            continue
        seen.add(x)
        d = definitions[x]
        if d["type"] == "expr":
            for t in d["terms"]:
                if t[0] == "var":
                    stack.append(t[1])
    necessary = seen

    op_lines = "  ".join(o["definition"] for o in ops)
    preamble = ("Operator definitions (evaluate strictly left to right, "
                f"all results mod {MOD}):  " + op_lines + ".")

    printed = list(order)
    rng.shuffle(printed)
    eq_lines = []
    for v in printed:
        d = definitions[v]
        rhs = str(d["c"]) if d["type"] == "const" else expr_str(d["terms"], d["ops"])
        eq_lines.append(f"{v} := {rhs}.")
    equations = " ".join(eq_lines)
    question = preamble + "\n\n" + equations + f" {query}?"

    cot = []
    for v in order:
        if v not in necessary:
            continue
        d = definitions[v]
        if d["type"] == "const":
            cot.append(f"{v} = {d['c']}  ->  {v} = {value[v]}")
            continue
        terms, op_seq = d["terms"], d["ops"]
        sym = expr_str(terms, op_seq)
        if not op_seq:
            cot.append(f"{v} = {sym} = {value[v]}")
            continue
        subbed = [str(value[t[1]]) if t[0] == "var" else str(t[1] % MOD) for t in terms]
        sub_line = subbed[0]
        for op, s in zip(op_seq, subbed[1:]):
            sub_line += f" {op['glyph']} {s}"
        block = [f"{v} = {sym}", f"    = {sub_line}"]
        acc = value[terms[0][1]] if terms[0][0] == "var" else terms[0][1] % MOD
        for op, t in zip(op_seq, terms[1:]):
            rv = value[t[1]] if t[0] == "var" else t[1] % MOD
            res = op["f"](acc, rv)
            block.append(f"    {acc} {op['glyph']} {rv} = {op['show'](acc, rv)} = {res}")
            acc = res
        block.append(f"    => {v} = {value[v]}")
        cot.append("\n".join(block))

    return {
        "mod": MOD,
        "ops_mode": ops_mode,
        "question": question,
        "preamble": preamble,
        "equations": equations,
        "query": query,
        "answer": answer,
        "cot": "\n".join(cot),
        "operator_table": [{"glyph": o["glyph"], "kind": o["kind"],
                            "params": o["params"], "definition": o["definition"]}
                           for o in ops],
        "target_depth": depth,
        "achieved_depth": achieved_depth,
        "num_vars": len(order),
        "num_necessary": len(necessary),
        "num_distractors": len(order) - sum(len(layers[d]) for d in layers),
        "var_layer": var_layer,
    }


# --------------------------------------------------------------------------- #
# Independent verifier
# --------------------------------------------------------------------------- #
def verify_record(rec):
    ops = {}
    for o in rec["operator_table"]:
        ops[o["glyph"]] = make_op(o["kind"], o["glyph"], params=o["params"] or None)["f"]

    defs = {}
    for chunk in rec["equations"].split("."):
        chunk = chunk.strip()
        if not chunk:
            continue
        name, rhs = chunk.split(" := ")
        defs[name.strip()] = rhs.strip().split()

    value = {}

    def resolve(v, stack=()):
        if v in value:
            return value[v]
        assert v not in stack, f"cycle at {v}"
        toks = defs[v]
        if len(toks) == 1:
            t = toks[0]
            value[v] = (int(t) % MOD) if t.isdigit() else resolve(t, stack + (v,))
            return value[v]

        def tv(t):
            return (int(t) % MOD) if t.isdigit() else resolve(t, stack + (v,))
        acc, i = tv(toks[0]), 1
        while i < len(toks):
            acc = ops[toks[i]](acc, tv(toks[i + 1]))
            i += 2
        value[v] = acc % MOD
        return value[v]

    got = resolve(rec["query"])
    assert got == rec["answer"], f"answer mismatch {got} != {rec['answer']}"
    assert rec["achieved_depth"] == rec["target_depth"], "depth mismatch"
    return True


# --------------------------------------------------------------------------- #
# Driver
# --------------------------------------------------------------------------- #
def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--n", type=int, default=100)
    ap.add_argument("--depths", type=int, nargs="+", default=[4, 5, 6])
    ap.add_argument("--distractors", type=int, default=2)
    ap.add_argument("--seed", type=int, default=0)
    ap.add_argument("--no-div", action="store_true")
    ap.add_argument("--ops", choices=["ascii", "arith"], default="ascii",
                    help="ascii: randomized @&$~ meanings; arith: fixed +-*/")
    ap.add_argument("--outdir", type=str, default=None,
                    help="default: out (ascii) or out_arith (arith)")
    args = ap.parse_args()

    if args.outdir is None:
        args.outdir = "out_arith" if args.ops == "arith" else "out"

    os.makedirs(args.outdir, exist_ok=True)
    rng = random.Random(args.seed)
    outfile = "igsm_mod7_arith.jsonl" if args.ops == "arith" else "igsm_mod7.jsonl"
    path = os.path.join(args.outdir, outfile)
    manifest = {
        "file": path, "ops": args.ops, "depths": {},
        "n_per_depth": args.n, "total_n": 0,
    }
    preview_recs = []
    id_prefix = "mod7_arith" if args.ops == "arith" else "mod7"

    with open(path, "w") as f:
        for depth in args.depths:
            answers, nec = [], []
            for i in range(args.n):
                rec = generate_problem(
                    rng, depth,
                    n_distractors=args.distractors,
                    allow_div=not args.no_div,
                    ops_mode=args.ops,
                )
                verify_record(rec)
                rec["id"] = f"{id_prefix}_d{depth}_{i:04d}"
                answers.append(rec["answer"]); nec.append(rec["num_necessary"])
                f.write(json.dumps(rec, ensure_ascii=False) + "\n")
                if i < 2:
                    preview_recs.append(rec)
            dist = {v: answers.count(v) for v in range(MOD)}
            manifest["depths"][f"d{depth}"] = {
                "n": args.n, "depth": depth,
                "random_baseline": round(1 / MOD, 4),
                "answer_hist": dist,
                "avg_necessary_nodes": round(sum(nec) / len(nec), 2),
            }
            manifest["total_n"] += args.n
            print(f"[d{depth}] wrote {args.n} verified examples -> {path}")
            print(f"        answers {dist}  | avg necessary nodes {manifest['depths'][f'd{depth}']['avg_necessary_nodes']}")

    with open(os.path.join(args.outdir, "manifest.json"), "w") as f:
        json.dump(manifest, f, indent=2, ensure_ascii=False)

    with open(os.path.join(args.outdir, "sample_preview.txt"), "w") as f:
        if args.ops == "arith":
            f.write("Operators + - * / have FIXED conventional meanings (mod 7). "
                    "Evaluate left-to-right.\n\n")
        else:
            f.write("Glyphs @ & $ ~ are fixed; their MEANING is randomized per "
                    "problem (see each problem's operator line). Left-to-right.\n\n")
        for r in preview_recs:
            f.write("=" * 74 + "\n")
            f.write(f"[{r['id']}]  depth={r['achieved_depth']}  vars={r['num_vars']} "
                    f"(necessary={r['num_necessary']}, distractors={r['num_distractors']})\n\n")
            f.write("Operators: " +
                    "  ".join(o["definition"] for o in r["operator_table"]) + "\n\n")
            f.write("Question. " + r["equations"] + f" {r['query']}?\n\n")
            f.write("Answer with CoT.\n" + r["cot"] + "\n")
            f.write(f"\n=> {r['query']} = {r['answer']}  (mod 7)\n\n")
    print(f"all depths -> {path}  (total {manifest['total_n']}, ops={args.ops})")
    print("preview ->", os.path.join(args.outdir, "sample_preview.txt"))


if __name__ == "__main__":
    main()