File size: 7,932 Bytes
5cb070c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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

import json
import random
import numpy
import pickle

n = 17  # 长度改为 13
k_offset = 5  # 步长 (与 13 互质)
num_train = 5000000
num_test = 1000

# 一个固定的、按位置变化的常量,扩展到 13 位
# (来自圆周率,只是为了固定且看起来随机)
pos_const = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 8, 9, 7, 9, 3, 2] # 扩展了一位



import random
from typing import List, Tuple, Set, Optional

Latin = List[List[int]]

def cyclic_latin_square(n: int = 10) -> Latin:
    return [[(i + j) % n for j in range(n)] for i in range(n)]

def is_latin_square(L: Latin) -> bool:
    n = len(L)
    target = set(range(n))
    for i in range(n):
        if set(L[i]) != target:
            return False
    for j in range(n):
        col = {L[i][j] for i in range(n)}
        if col != target:
            return False
    return True

def _try_random_intercalate_move(L: Latin, rng: random.Random) -> bool:
    """
    Try one random 2x2 intercalate flip. Return True if moved, else False.
    """
    n = len(L)
    r1, r2 = rng.sample(range(n), 2)
    c1, c2 = rng.sample(range(n), 2)

    a = L[r1][c1]
    b = L[r1][c2]
    if a == b:
        return False

    # Need the 2x2 pattern:
    # L[r1,c1]=a, L[r1,c2]=b
    # L[r2,c1]=b, L[r2,c2]=a
    if L[r2][c1] != b or L[r2][c2] != a:
        return False

    # Flip to:
    # b a
    # a b
    L[r1][c1], L[r1][c2] = b, a
    L[r2][c1], L[r2][c2] = a, b
    return True

def mcmc_step(L: Latin, rng: random.Random, lazy_p: float = 0.1, max_trials: int = 200) -> None:
    """
    One Markov step:
      - with probability lazy_p: do nothing (aperiodicity)
      - else: attempt up to max_trials random intercalate moves; if none found, do nothing
    """
    if rng.random() < lazy_p:
        return
    for _ in range(max_trials):
        if _try_random_intercalate_move(L, rng):
            return
    # No valid move found in trials -> stay

def sample_latin_square_10(
    rng: random.Random,
    burn_in: int = 50_000,
    steps_after: int = 20_000,
    lazy_p: float = 0.1,
    max_trials_per_step: int = 200
) -> Latin:
    """
    Start from cyclic Latin square and run MCMC.
    Return one approximately-uniform sample.
    """
    L = cyclic_latin_square(10)

    # Burn-in
    for _ in range(burn_in):
        mcmc_step(L, rng, lazy_p=lazy_p, max_trials=max_trials_per_step)

    # Extra steps (thinning / further mixing)
    for _ in range(steps_after):
        mcmc_step(L, rng, lazy_p=lazy_p, max_trials=max_trials_per_step)

    return [row[:] for row in L]

def make_functions(
    n: int,
    seed: Optional[int] = None,
    burn_in: int = 500000,
    steps_between_samples: int = 500000,
    lazy_p: float = 0.1,
    max_trials_per_step: int = 200
) -> List[Latin]:
    """
    Generate n distinct 10x10 Latin squares via MCMC (approx uniform).
    Distinctness is enforced by hashing full matrices.
    """
    rng = random.Random(seed)
    out: List[Latin] = []
    seen: Set[Tuple[Tuple[int, ...], ...]] = set()

    # We keep one chain running and take samples separated by steps_between_samples.
    L = cyclic_latin_square(10)

    # burn-in on the running chain
    for _ in range(burn_in):
        mcmc_step(L, rng, lazy_p=lazy_p, max_trials=max_trials_per_step)

    while len(out) < n:
        # advance chain
        for _ in range(steps_between_samples):
            mcmc_step(L, rng, lazy_p=lazy_p, max_trials=max_trials_per_step)

        sample = [row[:] for row in L]
        key = tuple(tuple(row) for row in sample)
        if key in seen:
            continue
        # Safety check (can be removed for speed)
        if not is_latin_square(sample):
            raise RuntimeError("Internal error: produced a non-Latin square (should not happen).")

        seen.add(key)
        out.append(sample)

    return out

functions = make_functions(n=n)

print(functions)

#print(xxx)

def generate_samples_anchored_global(num_samples):
    samples = []
    
    vocab = '0123456789'
    for _ in range(num_samples):
        # 1. 随机明文 (数字列表)
        plain_digits = [random.randint(0, 9) for _ in range(n)]
        
        cipher_digits = [0] * n
        
        # 2. 设置“锚点”
        # cipher[0] = plain[0]
        cipher_digits[0] = plain_digits[0]
        
        # 3. 生成全局依赖
        for i in range(1, n):
            # cipher[i] = (plain[i] + plain[(i + k) % n] + C[i]) % 10
            j = (i + k_offset) % n
            val = functions[i][plain_digits[i]][plain_digits[j]]
            #(plain_digits[i] + plain_digits[j] + pos_const[i]) % 10
            cipher_digits[i] = val

            
        # 转换回字符串
        #plain_str = ''.join(map(str, plain_digits))
        #cipher_str = ''.join(map(str, cipher_digits))
        
        #samples.append({"input": cipher_str, "output": plain_str})
        samples.append(cipher_digits+plain_digits)
        #test_samples.append(cipher_digits+plain_digits)
        
    return numpy.array(samples,dtype=numpy.uint16)

# --- 生成文件 ---
train_samples = generate_samples_anchored_global(num_train)

print(train_samples[0])
#print(xxx)
train_samples.tofile('train.bin')


#with open(f'{n}_anchored_global_mod10_train.jsonl', 'w') as f:
#    for s in train_samples:
#        f.write(json.dumps(s) + '\n')

test_samples = generate_samples_anchored_global(num_test)
test_samples.tofile('test.bin')
#with open(f'{n}_anchored_global_mod10_test.jsonl', 'w') as f:
#    for s in test_samples:
#        f.write(json.dumps(s) + '\n')

print(f"Generated {num_train} train samples and {num_test} test samples for ANCHORED GLOBAL (mod 10) task.")
print(f"n={n}, k_offset={k_offset}")

meta = {
    'vocab_size': 11,
    'block_size': n * 2, 
    'functions': functions
}
with open('meta.pkl', 'wb') as f:
    pickle.dump(meta, f)



# --- 验证逻辑 ---
# 打印一个样本的解密过程,用于验证
print("\n--- Verification Sample ---")
if test_samples is None:
    print("No test samples generated for verification.")
else:

    for t in range(len(test_samples)):
        c_str = test_samples[0,0:n]
        p_str = test_samples[0,n:2*n]
        #print(f"Cipher: {c_str}")
        #print(f"Plain:  {p_str}")

        # 手动验证解密链
        c = [int(x) for x in c_str]
        p_actual = [int(x) for x in p_str]
        p_solved = [-1] * n # -1 表示未知

        #print("\nSolving sequence (MDM's perspective):")
        p_solved[0] = c[0]
        #print(f"Step 0: Solved p[0] = c[0] = {p_solved[0]}")

        # (n=13, k=5) 的求解顺序
        # 求解 p[i] 需要 p[(i+k)%n]
        # 反过来看,p[0] -> p[i] s.t. (i+5)%13 = 0 => i = 8
        # p[8] -> p[i] s.t. (i+5)%13 = 8 => i = 3
        # p[3] -> p[i] s.t. (i+5)%13 = 3 => i = -2 % 13 = 11
        # 链条: 0 -> 8 -> 3 -> 11 -> 6 -> 1 -> 9 -> 4 -> 12 -> 7 -> 2 -> 10 -> 5
        solve_order = [12, 7, 2, 14, 9, 4, 16, 11, 6, 1, 13, 8, 3, 15, 10, 5]
        
        for i_solve in solve_order:
            # 找到它依赖谁
            i_depend_on = (i_solve + k_offset) % n
            # plain[i] = (cipher[i] - plain[j] - C[i]) % 10
            val = -1
            for j in range(10):
                if functions[i_solve][j][p_solved[i_depend_on]] == c[i_solve]:
                    val = j
                    break
            if(val == -1):
                print("Oh no, what happens!")
            
            #(c[i_solve] - p_solved[i_depend_on] - pos_const[i_solve]) % 10
            p_solved[i_solve] = val
            #print(f"Step N: Solved p[{i_solve}] = (c[{i_solve}] - p[{i_depend_on}] - C[{i_solve}]) % 10 = {val}")

        #print("\nSolved Plain:", numpy.array(p_solved))
        #print("Actual Plain:", p_str)
        
        if (p_str == numpy.array(p_solved)).all():
            #print("Verification SUCCESSFUL.")
            continue
        else:
            print("Verification FAILED.")
            print(xxxxx)