File size: 26,085 Bytes
d9c109c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
578
579
580
581
582
583
584
585
586
587
588
589
590
"""Alien arithmetic: decode glyph numerals, an unknown base and unknown operators.



An invented script writes numbers in a positional system.  Each glyph stands for

one digit; the glyph->digit correspondence is a secret bijection and the base b

itself may be unknown.  One or two operators are drawn from a small stated menu

of formulas over the ordinary integer values of the operands.  The model sees

true equations written in glyphs and must evaluate new expressions.



Hypothesis space (enumerated by the independent solver):

  * the base b (a stated fixed value at d1-d2 on a decimal pad, otherwise one of

    the stated options), 

  * a bijection from the listed glyphs to distinct digits of that base,

  * a formula from the menu for each operator symbol (distinct for two symbols).

The generator adds equations by counterexample search (CEGIS) until every

hypothesis consistent with the evidence gives the same answer on the query.



Generalisation axes exercised by the queries (SPEC rule 9):

  * a result longer (more glyph positions) than any result shown in the evidence,

    i.e. a carry/column that never occurred in the data;

  * an operand combination (and, at d5, an operator chain) never shown verbatim;

  * decimals at d1 are read with a positional weight, not as concatenated labels.



Anti-shortcut: copying the result of the most similar equation, concatenating the

operands, echoing the first operand, or the majority result are all wrong; the

decoded mapping and the operator formulas must actually be recovered.

"""
from __future__ import annotations

import itertools
from collections import Counter

from ..core import ANSWER_INSTRUCTION, Task, TaskFamily, pseudo_words, sub_rng

# ---------------------------------------------------------------------------
# operator menu: name -> (function over integer values, English description)
# ---------------------------------------------------------------------------
OPS = {
    "sum": (lambda a, b: a + b, "a + b (the sum)"),
    "prod": (lambda a, b: a * b, "a * b (the product)"),
    "twice": (lambda a, b: 2 * a + b, "2a + b (twice the left operand plus the right)"),
    "sum1": (lambda a, b: a + b + 1, "a + b + 1 (the sum plus one)"),
    "abs": (lambda a, b: abs(a - b), "|a - b| (the absolute difference)"),
    "prod1": (lambda a, b: a * b + 1, "a * b + 1 (the product plus one)"),
}
MENU = list(OPS)

# difficulty parameters
#   base   : fixed base or None (unknown, drawn from BASE_OPTIONS)
#   nops   : number of hidden operators
#   L      : operand length range in glyph positions
#   neq0   : number of seed equations
#   max_ex : cap on evidence equations
#   d1 special-cases a decimal pad with digit glyphs {1,2} so the enumeration of
#          the mapping stays tiny.
BASE_OPTIONS = [4, 5, 6]
PARAMS = {
    1: dict(base=10, nops=1, menu=("sum",), L=(2, 2), neq0=5, max_ex=12),
    2: dict(base=None, nops=1, menu=tuple(MENU), L=(1, 2), neq0=5, max_ex=14),
    3: dict(base=None, nops=1, menu=tuple(MENU), L=(2, 2), neq0=6, max_ex=16),
    4: dict(base=None, nops=1, menu=tuple(MENU), L=(2, 3), neq0=8, max_ex=18),
    5: dict(base=None, nops=2, menu=tuple(MENU), L=(1, 2), neq0=8, max_ex=20),
}


# ---------------------------------------------------------------------------
# numeral arithmetic
# ---------------------------------------------------------------------------
def _encode(v, b, digit2glyph):
    """Glyphs of the numeral for v (MSB first), or None if a digit has no glyph."""
    if v < 0:
        return None
    if v == 0:
        g = digit2glyph.get(0)
        return None if g is None else [g]
    out = []
    while v > 0:
        g = digit2glyph.get(v % b)
        if g is None:
            return None
        out.append(g)
        v //= b
    out.reverse()
    return out


def _decode(tokens, b, glyph2digit):
    v = 0
    for t in tokens:
        v = v * b + glyph2digit[t]
    return v


def _apply(vals, funcs):
    v = vals[0]
    for f, x in zip(funcs, vals[1:]):
        v = f(v, x)
    return v


def _op_assignments(symbols, menu):
    """Every way the operator symbols can be matched to distinct menu formulas."""
    if len(symbols) == 1:
        for k in menu:
            yield {symbols[0]: k}
    else:
        for p in itertools.permutations(menu, len(symbols)):
            yield dict(zip(symbols, p))


# ---------------------------------------------------------------------------
# independent solver
# ---------------------------------------------------------------------------
def _equation_holds(eq, b, g2d, inv, oa):
    vals = [_decode(x, b, g2d) for x in eq["lhs"]]
    funcs = [OPS[oa[s]][0] for s in eq["ops"]]
    enc = _encode(_apply(vals, funcs), b, inv)
    return enc is not None and list(enc) == list(eq["rhs"])


def _item_answer(item, b, g2d, inv, oa):
    vals = [_decode(x, b, g2d) for x in item["lhs"]]
    funcs = [OPS[oa[s]][0] for s in item["ops"]]
    enc = _encode(_apply(vals, funcs), b, inv)
    return None if enc is None else " ".join(enc)


def _hypotheses(ev, q, limit=None):
    """All (base, mapping, op-assignment, answer) consistent with the evidence.



    Stops early once `limit` distinct answers are known (keeps it fast)."""
    glyphs = ev["glyphs"]
    g = len(glyphs)
    base = ev["base"]
    bases = [base] if base is not None else [b for b in ev["base_options"] if b >= g]
    out = []
    seen = set()
    for b in bases:
        for perm in itertools.permutations(range(b), g):
            g2d = dict(zip(glyphs, perm))
            inv = {d: gl for gl, d in g2d.items()}
            for oa in _op_assignments(ev["op_symbols"], ev["op_menu"]):
                if not all(_equation_holds(eq, b, g2d, inv, oa) for eq in ev["equations"]):
                    continue
                ans = []
                ok = True
                for item in q["items"]:
                    a = _item_answer(item, b, g2d, inv, oa)
                    if a is None:
                        ok = False
                        break
                    ans.append(a)
                if not ok:
                    continue
                answer = " | ".join(ans)
                out.append((b, g2d, oa, answer))
                if limit is not None:
                    seen.add(answer)
                    if len(seen) >= limit:
                        return out
    return out


# ---------------------------------------------------------------------------
# sampling helpers (all take explicit RNG streams)
# ---------------------------------------------------------------------------
def _sample_system(rng, P):
    """Hidden (base, glyph lists, digit<->glyph maps, operator symbols, formulas)."""
    b = P["base"] if P["base"] is not None else rng.choice(BASE_OPTIONS)
    digits = list(range(b))
    order = digits[:]
    rng.shuffle(order)  # order[i] = digit value carried by the i-th glyph name
    words = pseudo_words(rng, b + 2, syllables=(1, 1))
    glyph_names = words[:b]
    digit2glyph = {order[i]: glyph_names[i] for i in range(b)}
    glyph2digit = {gl: d for d, gl in digit2glyph.items()}
    syms = words[b:b + P["nops"]]
    ops = list(rng.sample(P["menu"], P["nops"]))
    # At d1 the formula is public; keep the single symbol's formula fixed.
    if P["base"] == 10:
        ops = ["sum"]
    return {
        "b": b, "digit2glyph": digit2glyph, "glyph2digit": glyph2digit,
        "symbols": syms, "ops": ops,
        "omit": None if P["base"] == 10 else b - 1,
        "allowed": [1, 2] if P["base"] == 10 else list(range(0, b - 1)),
    }


def _sample_digits(rng, L, allowed):
    n = rng.randint(L[0], L[1])
    while True:
        ds = [rng.choice(allowed) for _ in range(n)]
        if ds[0] != 0:
            return ds


def _make_equation(rng, P, H, sym=None, force_digit=None):
    """A true equation under H (optionally containing one forced digit value)."""
    b, allowed, omit = H["b"], H["allowed"], H["omit"]
    d2g = H["digit2glyph"]
    sym = sym or rng.choice(H["symbols"])
    func = OPS[H["ops"][H["symbols"].index(sym)]][0]
    for _ in range(60):
        if force_digit is None:
            ds1 = _sample_digits(rng, P["L"], allowed)
        elif force_digit == 0:
            a = rng.choice([d for d in allowed if d != 0])
            ds1 = [a, 0]
        else:
            ds1 = [force_digit]
        n1 = [d2g[d] for d in ds1]
        n2 = [d2g[d] for d in _sample_digits(rng, P["L"], allowed)]
        v1 = _decode(n1, b, H["glyph2digit"])
        v2 = _decode(n2, b, H["glyph2digit"])
        val = _apply([v1, v2], [func])
        rhs = _encode(val, b, H["digit2glyph"])
        if rhs is None:
            continue
        if omit is not None and any(H["glyph2digit"][t] == omit for t in rhs):
            continue
        return {"lhs": [n1, n2], "ops": [sym], "rhs": rhs}
    return None


def _make_query_item(rng, P, H, force_len=None):
    b, allowed, omit = H["b"], H["allowed"], H["omit"]
    nops = len(H["symbols"])
    for _ in range(80):
        L = P["L"] if force_len is None else (force_len, force_len)
        lhs = [[H["digit2glyph"][d] for d in _sample_digits(rng, L, allowed)]
               for _ in range(nops + 1)]
        syms = H["symbols"][:] if nops == 1 else rng.sample(H["symbols"], nops)
        funcs = [OPS[H["ops"][H["symbols"].index(s)]][0] for s in syms]
        vals = [_decode(x, b, H["glyph2digit"]) for x in lhs]
        rhs = _encode(_apply(vals, funcs), b, H["digit2glyph"])
        if rhs is None:
            continue
        if omit is not None and any(H["glyph2digit"][t] == omit for t in rhs):
            continue
        return {"lhs": lhs, "ops": syms}, rhs
    return None, None


# ---------------------------------------------------------------------------
# public data assembly
# ---------------------------------------------------------------------------
def _revealed_glyphs(H, equations, query):
    used = set()
    for eq in equations:
        for x in eq["lhs"]:
            used.update(H["glyph2digit"][t] for t in x)
        used.update(H["glyph2digit"][t] for t in eq["rhs"])
    for item in query["items"]:
        for x in item["lhs"]:
            used.update(H["glyph2digit"][t] for t in x)
            # include the answer digits as well (computed below)
    ans_digits = set()
    for item in query["items"]:
        vals = [_decode(x, H["b"], H["glyph2digit"]) for x in item["lhs"]]
        funcs = [OPS[H["ops"][H["symbols"].index(s)]][0] for s in item["ops"]]
        enc = _encode(_apply(vals, funcs), H["b"], H["digit2glyph"])
        ans_digits.update(H["glyph2digit"][t] for t in enc)
    used |= ans_digits
    return sorted(used)


def _evidence_dict(H, P, equations, query, order, base_known):
    return {
        "base": H["b"] if base_known else None,
        "base_options": list(BASE_OPTIONS),
        "glyphs": [H["digit2glyph"][d] for d in order],
        "op_menu": list(P["menu"]) if not base_known else ["sum"],
        "op_symbols": list(H["symbols"]),
        "precedence": "left to right" if len(H["symbols"]) == 2 else None,
        "equations": equations,
    }


# ---------------------------------------------------------------------------
# generator
# ---------------------------------------------------------------------------
class AlienArithmetic(TaskFamily):
    name = "alien_arithmetic"
    heldout = True
    skills = ("reading an invented numeral system", "cryptarithmetic", "operator induction",
              "hypothesis search", "compositional generalisation")

    # ---- CEGIS ------------------------------------------------------------
    def _counterexample(self, rng, P, H, wrong):
        """An equation true under H but false under the wrong hypothesis."""
        b, g2d, oa, _ = wrong
        inv = {d: gl for gl, d in g2d.items()}
        for _ in range(60):
            eq = _make_equation(rng, P, H)
            if eq is None:
                continue
            sym = eq["ops"][0]
            try:
                vals = [_decode(x, b, g2d) for x in eq["lhs"]]
                func = OPS[oa[sym]][0]
                enc = _encode(_apply(vals, [func]), b, inv)
            except (KeyError, ValueError):
                enc = None
            if enc is None or list(enc) != list(eq["rhs"]):
                return eq
        return None

    def _build(self, rng, P, H, query, truth):
        base_known = P["base"] == 10
        # seed equations: cover the query's digits and both operator symbols
        needed = set()
        for item in query["items"]:
            for x in item["lhs"]:
                needed.update(H["glyph2digit"][t] for t in x)
            vals = [_decode(x, H["b"], H["glyph2digit"]) for x in item["lhs"]]
            funcs = [OPS[H["ops"][H["symbols"].index(s)]][0] for s in item["ops"]]
            rhs = _encode(_apply(vals, funcs), H["b"], H["digit2glyph"])
            needed.update(H["glyph2digit"][t] for t in rhs)
        equations = []
        seen = set()

        def add(eq):
            if eq is None:
                return False
            key = (tuple(map(tuple, eq["lhs"])), eq["ops"][0], tuple(eq["rhs"]))
            if key in seen:
                return False
            seen.add(key)
            equations.append(eq)
            return True

        for sym in H["symbols"]:
            add(_make_equation(rng, P, H, sym=sym))
        for d in sorted(needed):
            if any(d == H["glyph2digit"][t] for eq in equations
                   for x in eq["lhs"] + [eq["rhs"]] for t in x):
                continue
            add(_make_equation(rng, P, H, force_digit=d))
        while len(equations) < P["neq0"]:
            if not add(_make_equation(rng, P, H)):
                break

        for _ in range(6 * P["max_ex"]):
            order = _revealed_glyphs(H, equations, query)
            ev = _evidence_dict(H, P, equations, query, order, base_known)
            hyps = _hypotheses(ev, query)
            answers = {h[3] for h in hyps}
            if answers == {truth}:
                return equations, order
            if len(equations) >= P["max_ex"]:
                return None
            wrong = [h for h in hyps if h[3] != truth]
            if not wrong or truth not in answers:
                return None
            rng.shuffle(wrong)
            ce = None
            for h in wrong[:25]:
                ce = self._counterexample(rng, P, H, h)
                if ce is not None and add(ce):
                    break
            else:
                return None
        return None

    def generate(self, seed: int, difficulty: int) -> Task:
        P = PARAMS[difficulty]
        base_known = P["base"] == 10
        srng = sub_rng(seed, difficulty, "surface")
        for attempt in range(500):
            rng = sub_rng(seed, difficulty, "sem", attempt)
            H = _sample_system(rng, P)
            # query: two expressions, operands at the long end of the range
            qitems = []
            truth_parts = []
            ok = True
            for _ in range(2):
                item, rhs = _make_query_item(rng, P, H, force_len=P["L"][1])
                if item is None:
                    ok = False
                    break
                qitems.append(item)
                truth_parts.append(" ".join(rhs))
            if not ok:
                continue
            query = {"items": qitems}
            truth = " | ".join(truth_parts)

            built = self._build(rng, P, H, query, truth)
            if built is None:
                continue
            equations, order = built

            # d2-d5: require a query result longer than any evidence result, so a
            # column/carry is exercised that never appeared in the evidence.  d1
            # exercises the positional reading of an unseen numeral instead.
            if not base_known:
                max_ev_len = max(len(eq["rhs"]) for eq in equations)
                if max(len(p.split()) for p in truth_parts) <= max_ev_len:
                    continue
            # require the query not to repeat an evidence left-hand side, and the
            # two query items to differ (otherwise one answer is wasted)
            ev_keys = {tuple(map(tuple, eq["lhs"])) for eq in equations}
            if any(tuple(map(tuple, it["lhs"])) in ev_keys for it in qitems):
                continue
            if tuple(map(tuple, qitems[0]["lhs"])) == tuple(map(tuple, qitems[1]["lhs"])):
                continue

            order = order[:]
            srng.shuffle(order)
            ev = _evidence_dict(H, P, equations, query, order, base_known)
            if truth in self.shortcuts(ev, query).values():
                continue
            break
        else:
            raise RuntimeError(
                f"alien_arithmetic: no identifiable task for seed={seed} d={difficulty}")

        srng.shuffle(ev["equations"])
        prompt = self._render(srng, ev, query, difficulty)
        hidden = {
            "base": H["b"],
            "digit_to_glyph": {str(k): v for k, v in H["digit2glyph"].items()},
            "glyph_to_digit": H["glyph2digit"],
            "operators": {s: k for s, k in zip(H["symbols"], H["ops"])},
            "precedence": ev["precedence"],
        }
        return Task(self.name, seed, difficulty, ev, query, prompt, truth, hidden)

    # ---- rendering --------------------------------------------------------
    def _num(self, tokens):
        return " ".join(tokens)

    def _render(self, rng, ev, q, difficulty) -> str:
        intro = rng.choice([
            "A folded slab of stone is covered in an unknown script and a few worked equations.",
            "An archivist found a tablet from a lost counting-house; only the examples were kept.",
            "You are handed a page of sums in a script nobody has read before.",
        ])
        lines = [intro, ""]
        if ev["base"] is not None:
            lines.append(rng.choice([
                f"Numerals are written in base {ev['base']}, most significant glyph first, "
                "with no leading zero.",
                f"The script uses ordinary base-{ev['base']} place values: leftmost glyph is the "
                "most significant, and none starts with zero.",
            ]))
        else:
            opts = ", ".join(str(b) for b in ev["base_options"])
            lines.append(rng.choice([
                "Numerals are written in an unknown positional base b (a single integer, "
                f"one of {opts}, the same everywhere). A glyph one place to the left counts "
                "b times as much. No numeral has a leading zero.",
                "The place value is a fixed but secret base b, known only to be "
                f"{opts}. Reading right to left, each position is worth b times the previous one; "
                "leading glyphs are never zero.",
            ]))
        lines.append("")
        lines.append(rng.choice([
            "The glyphs that occur are: ",
            "Only these glyphs appear: ",
            "The following glyphs show up: ",
        ]) + ", ".join(ev["glyphs"]) + ".")
        lines.append(rng.choice([
            "Each glyph is a different digit of the system; the glyph-to-digit correspondence is a "
            "secret bijection and the order of the list means nothing. The system may have further "
            "digits that never appear here. Glyph shapes carry no meaning by themselves.",
            "The glyphs are labels for distinct digits, but which digit each one denotes is hidden "
            "and unrelated to the order shown. More digits may exist than are listed. A glyph's "
            "shape tells you nothing.",
        ]))
        lines.append("Every numeral on the page, and every numeral you write as an answer, is "
                     "spelled with the glyphs listed above (and shows the same, single base).")
        lines.append("")
        nops = len(ev["op_symbols"])
        if nops == 1 and ev["op_menu"] == ["sum"]:
            lines.append(f"There is a single operator, written \"{ev['op_symbols'][0]}\". It is "
                         "ordinary addition: for usable numbers a and b, a "
                         f"{ev['op_symbols'][0]} b means a + b. Everything is written in the "
                         "alien numerals.")
        else:
            desc = "\n".join(f"   - {OPS[k][1]}" for k in ev["op_menu"])
            if nops == 1:
                lines.append(f"There is a single hidden operator, written \"{ev['op_symbols'][0]}\". "
                             "Over the ordinary integer values of its two operands it is exactly one "
                             "of the following formulas:")
            else:
                lines.append("There are two hidden operators, written "
                             + " and ".join(f"\"{s}\"" for s in ev["op_symbols"])
                             + ". Each takes two ordinary integer values and is exactly one of the "
                             "following formulas (they are different from each other):")
            lines.append(desc)
            if nops == 2:
                lines.append(rng.choice([
                    "In a chain of operators, apply them strictly from left to right.",
                    "When several operators are chained, evaluate strictly left to right.",
                ]))
        lines.append("")
        lines.append(rng.choice([
            "Worked equations in the alien script:",
            "Recorded true equations:",
            "Examples that are known to be true:",
        ]))
        style = rng.choice(["numbered", "arrow", "table"])
        if style == "table":
            lines.append("| equation |")
            lines.append("|---|")
            for eq in ev["equations"]:
                parts = [self._num(eq["lhs"][0])]
                for sym, nxt in zip(eq["ops"], eq["lhs"][1:]):
                    parts.append(sym)
                    parts.append(self._num(nxt))
                lines.append("| " + " ".join(parts) + " = " + self._num(eq["rhs"]) + " |")
        else:
            for i, eq in enumerate(ev["equations"], 1):
                parts = [self._num(eq["lhs"][0])]
                for sym, nxt in zip(eq["ops"], eq["lhs"][1:]):
                    parts.append(sym)
                    parts.append(self._num(nxt))
                body = " ".join(parts) + " = " + self._num(eq["rhs"])
                if style == "arrow":
                    lines.append(f"- {body}")
                else:
                    lines.append(f"{i}. {body}")
        lines.append("")
        lines.append(rng.choice([
            "Evaluate each expression below and write the result in the alien numerals "
            "(same base and same glyphs):",
            "For each expression, compute the value and write it back in the alien script:",
        ]))
        letters = "ABCDEFGH"
        for i, item in enumerate(q["items"]):
            parts = [self._num(item["lhs"][0])]
            for sym, nxt in zip(item["ops"], item["lhs"][1:]):
                parts.append(sym)
                parts.append(self._num(nxt))
            lines.append(f"{letters[i]}. " + " ".join(parts))
        lines.append("")
        lines.append('Give the two results in order A, B separated by " | ".')
        lines.append("")
        fmt = " | ".join(f"<result {letters[i]}>" for i in range(len(q["items"])))
        lines.append(ANSWER_INSTRUCTION.format(fmt=fmt))
        return "\n".join(lines)

    def render(self, evidence, query, seed, difficulty):
        return self._render(sub_rng(seed, difficulty, "surface-render"), evidence, query, difficulty)

    # ---- solver -----------------------------------------------------------
    def solve(self, evidence, query) -> set[str]:
        hyps = _hypotheses(evidence, query, limit=2)
        return {h[3] for h in hyps}

    # ---- lazy baselines ---------------------------------------------------
    def _shortcut_all(self, ev, q):
        eqs = ev["equations"]
        out = {}
        # majority result string
        if eqs:
            maj = Counter(self._num(e["rhs"]) for e in eqs).most_common(1)[0][0]
        else:
            maj = ""
        # concatenate operands / first operand / nearest result
        concat, first, nearest = [], [], []
        for item in q["items"]:
            toks = [t for x in item["lhs"] for t in x]
            concat.append(" ".join(toks))
            first.append(self._num(item["lhs"][0]))
            qset = set(toks)
            best, best_score = None, -1
            for e in eqs:
                eset = set(t for x in e["lhs"] for t in x)
                score = len(qset & eset) + (2 if e["ops"][0] in item["ops"] else 0)
                if score > best_score:
                    best, best_score = e, score
            nearest.append(self._num(best["rhs"]) if best else "")
        out["majority"] = " | ".join(maj for _ in q["items"])
        out["concatenate_operands"] = " | ".join(concat)
        out["identity_first_operand"] = " | ".join(first)
        out["copy_nearest_result"] = " | ".join(nearest)
        return out

    def shortcuts(self, evidence, query) -> dict[str, str]:
        return self._shortcut_all(evidence, query)

    # ---- scoring ----------------------------------------------------------
    def split_items(self, answer: str) -> list[str]:
        return [part.strip() for part in answer.split("|") if part.strip()]

    def normalize_item(self, item: str) -> str:
        return "".join(item.split()).strip("`*'\".?!;:").lower()