cyclic-text-compressor 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- alignment_mvp.py +203 -0
- cycle_compressor.py +969 -0
- cyclic_text_compressor/__init__.py +24 -0
- cyclic_text_compressor/__main__.py +3 -0
- cyclic_text_compressor-0.1.0.dist-info/METADATA +89 -0
- cyclic_text_compressor-0.1.0.dist-info/RECORD +12 -0
- cyclic_text_compressor-0.1.0.dist-info/WHEEL +5 -0
- cyclic_text_compressor-0.1.0.dist-info/entry_points.txt +2 -0
- cyclic_text_compressor-0.1.0.dist-info/licenses/LICENSE +21 -0
- cyclic_text_compressor-0.1.0.dist-info/top_level.txt +5 -0
- pattern_library.py +1414 -0
- pin_only_12block.py +1061 -0
cycle_compressor.py
ADDED
|
@@ -0,0 +1,969 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""Randall's Cyclic Compression Engine.
|
|
3
|
+
|
|
4
|
+
Copyright (c) 2026 Randall Lujan. All rights reserved.
|
|
5
|
+
Patent pending for the cyclic compression and rotor-folding system described herein.
|
|
6
|
+
|
|
7
|
+
Includes:
|
|
8
|
+
- Canonical 142857 cyclic rotor and character cipher mapping
|
|
9
|
+
- Deterministic stride-2 overlapping tri-sum folding (LR & RL bidirectional verification)
|
|
10
|
+
- 369 multiplication duality verification and high-digit anchor flags
|
|
11
|
+
- 12-Block Pin-Only Lossless Reconstruction integration (Oct 2026 paper:
|
|
12
|
+
residue erasure of 3,6 and repeats, 9 as technical 1 / functional 0 signpost,
|
|
13
|
+
uniform apex 452152 and forward/backward pins 298-1 / 882-7)
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
from collections import Counter
|
|
19
|
+
from dataclasses import dataclass
|
|
20
|
+
from math import comb
|
|
21
|
+
from typing import Dict, Iterable, List, Tuple
|
|
22
|
+
|
|
23
|
+
from pin_only_12block import (
|
|
24
|
+
DEFAULT_LOGIC,
|
|
25
|
+
FixedLogic,
|
|
26
|
+
compress_12block_stream,
|
|
27
|
+
decode_pin,
|
|
28
|
+
decompress_12block_stream,
|
|
29
|
+
encode_12block,
|
|
30
|
+
left_to_right_digital_root,
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
PROJECT_NAME = "Randall's Cyclic Compression"
|
|
34
|
+
COPYRIGHT_NOTICE = "Copyright (c) 2026 Randall Lujan. All rights reserved. Patent pending."
|
|
35
|
+
CYCLIC = [1, 4, 2, 8, 5, 7]
|
|
36
|
+
ANCHOR_ALIGNMENTS = {
|
|
37
|
+
1: (3,),
|
|
38
|
+
4: (3, 6, 9),
|
|
39
|
+
2: (6,),
|
|
40
|
+
8: (3, 6),
|
|
41
|
+
5: (9,),
|
|
42
|
+
7: (6, 9),
|
|
43
|
+
}
|
|
44
|
+
BASE_NUMBER = 142_857
|
|
45
|
+
|
|
46
|
+
# The rotor is the core 142857 cycle used by the project.
|
|
47
|
+
ROTOR_ROTATIONS = [
|
|
48
|
+
[1, 4, 2, 8, 5, 7],
|
|
49
|
+
[4, 2, 8, 5, 7, 1],
|
|
50
|
+
[2, 8, 5, 7, 1, 4],
|
|
51
|
+
[8, 5, 7, 1, 4, 2],
|
|
52
|
+
[5, 7, 1, 4, 2, 8],
|
|
53
|
+
[7, 1, 4, 2, 8, 5],
|
|
54
|
+
]
|
|
55
|
+
|
|
56
|
+
# Keyboard sequence maps characters to the canonical cycle in order.
|
|
57
|
+
KEYBOARD_ORDER = "qwertyuiopasdfghjklzxcvbnm"
|
|
58
|
+
CHARACTER_MAP = {
|
|
59
|
+
ch: CYCLIC[index % len(CYCLIC)]
|
|
60
|
+
for index, ch in enumerate(KEYBOARD_ORDER)
|
|
61
|
+
}
|
|
62
|
+
CHARACTER_MAP.update({" ": 5, ".": 5, ",": 5, "/": 5})
|
|
63
|
+
|
|
64
|
+
# Cypher Order by Number map: each 6-character group is assigned its cypher number (1..5),
|
|
65
|
+
# multiplied by its cyclic slot to produce the second string (cypher order by number).
|
|
66
|
+
CYPHER_NUMBER_MAP = {
|
|
67
|
+
ch: ((index // len(CYCLIC)) + 1)
|
|
68
|
+
for index, ch in enumerate(KEYBOARD_ORDER)
|
|
69
|
+
}
|
|
70
|
+
CYPHER_NUMBER_MAP.update({" ": 5, ".": 5, ",": 5, "/": 5})
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
@dataclass(frozen=True)
|
|
74
|
+
class CyclicRotor:
|
|
75
|
+
"""Represents the canonical 142857 rotor and its rotations."""
|
|
76
|
+
|
|
77
|
+
cycle: Tuple[int, ...] = (1, 4, 2, 8, 5, 7)
|
|
78
|
+
|
|
79
|
+
def rotations(self) -> List[List[int]]:
|
|
80
|
+
"""Return the six valid circular rotations of the cycle."""
|
|
81
|
+
rotated: List[List[int]] = []
|
|
82
|
+
for offset in range(len(self.cycle)):
|
|
83
|
+
rotated.append(list(self.cycle[offset:] + self.cycle[:offset]))
|
|
84
|
+
return rotated
|
|
85
|
+
|
|
86
|
+
def as_string(self) -> str:
|
|
87
|
+
return " ".join(str(value) for value in self.cycle)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def collapse(value: int) -> int:
|
|
91
|
+
"""Reduce an integer to a single digit using a deterministic fold rule."""
|
|
92
|
+
n = int(value)
|
|
93
|
+
while n > 9:
|
|
94
|
+
if n % 2 == 0:
|
|
95
|
+
n = n // 2
|
|
96
|
+
else:
|
|
97
|
+
n = sum(int(ch) for ch in str(n))
|
|
98
|
+
return n
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def build_rotor_matrix() -> List[List[int]]:
|
|
102
|
+
"""Return the canonical rotor matrix in rotation order."""
|
|
103
|
+
return CyclicRotor().rotations()
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def _build_sequence(text: str) -> Tuple[List[int], List[str], Dict[int, List[str]], Dict[int, List[str]]]:
|
|
107
|
+
"""Map supported characters while preserving their original order."""
|
|
108
|
+
by_cipher: Dict[int, List[str]] = {}
|
|
109
|
+
sequence: List[str] = []
|
|
110
|
+
for ch in text.lower():
|
|
111
|
+
bucket = CHARACTER_MAP.get(ch)
|
|
112
|
+
if bucket is not None:
|
|
113
|
+
by_cipher.setdefault(bucket, []).append(ch)
|
|
114
|
+
sequence.append(ch)
|
|
115
|
+
order = [cipher for cipher in sorted(by_cipher) if by_cipher[cipher]]
|
|
116
|
+
counts = {cipher: list(by_cipher[cipher]) for cipher in order}
|
|
117
|
+
return order, sequence, counts, by_cipher
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def fold_triplets(values: Iterable[int]) -> List[int]:
|
|
121
|
+
"""Fold overlapping triplets at stride 2 with left-to-right digital roots."""
|
|
122
|
+
items = list(values)
|
|
123
|
+
if len(items) < 3:
|
|
124
|
+
return []
|
|
125
|
+
return [
|
|
126
|
+
left_to_right_digital_root(items[i : i + 3])
|
|
127
|
+
for i in range(0, len(items) - 2, 2)
|
|
128
|
+
]
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def fold_triplets_with_flag(values: Iterable[int]) -> List[int]:
|
|
132
|
+
"""Fold triplets while encoding the tens-digit flag alongside the collapsed digit."""
|
|
133
|
+
items = list(values)
|
|
134
|
+
if len(items) < 3:
|
|
135
|
+
return []
|
|
136
|
+
folded: List[int] = []
|
|
137
|
+
for idx in range(0, len(items) - 2, 2):
|
|
138
|
+
a, b, c = items[idx : idx + 3]
|
|
139
|
+
raw_sum = a + b + c
|
|
140
|
+
digit = left_to_right_digital_root((a, b, c))
|
|
141
|
+
encoded = 10 * digit + (raw_sum // 10)
|
|
142
|
+
folded.append(encoded)
|
|
143
|
+
return folded
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def fold_trisums_lr(values: List[int]) -> List[int]:
|
|
147
|
+
"""Trisum fold left-to-right at stride 2.
|
|
148
|
+
|
|
149
|
+
Walks overlapping triplets (0,1,2), (2,3,4), (4,5,6) …
|
|
150
|
+
Each triplet collapses to a single digit. This is the canonical
|
|
151
|
+
direction that advances the pyramid.
|
|
152
|
+
"""
|
|
153
|
+
return fold_triplets(values)
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def fold_trisums_rl(values: List[int]) -> List[int]:
|
|
157
|
+
"""Trisum fold right-to-left — the mirror of fold_trisums_lr.
|
|
158
|
+
|
|
159
|
+
Reverses the input, applies fold_trisums_lr, then reverses the result.
|
|
160
|
+
By the stride-2 overlap property, fold_trisums_rl(v) == fold_trisums_lr(v)
|
|
161
|
+
for any odd-length input, providing bidirectional confirmation.
|
|
162
|
+
"""
|
|
163
|
+
return list(reversed(fold_trisums_lr(list(reversed(values)))))
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def check_bidirectional_pairs(lr: List[int], rl: List[int]) -> Dict[str, object]:
|
|
167
|
+
"""Verify the bidirectional fold and extract the last-4 apex pairs."""
|
|
168
|
+
bidir_verified = (lr == rl)
|
|
169
|
+
tail = lr[-4:] if len(lr) >= 4 else lr[:]
|
|
170
|
+
pairs: List[Dict[str, int]] = []
|
|
171
|
+
for i in range(0, len(tail) - 1, 2):
|
|
172
|
+
pairs.append({"a": tail[i], "b": tail[i + 1]})
|
|
173
|
+
return {
|
|
174
|
+
"bidir_verified": bidir_verified,
|
|
175
|
+
"apex_pairs": pairs,
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def _map_anchor_to_nine(digit: int) -> int:
|
|
180
|
+
"""Map any anchor (3, 6, 9) to the visible digit 9.
|
|
181
|
+
Non-anchor digits are returned unchanged.
|
|
182
|
+
"""
|
|
183
|
+
return 9 if digit in (3, 6, 9) else digit
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def _compute_anchor_flags(values: Iterable[int]) -> List[int]:
|
|
187
|
+
"""Compute high-digit flags for 3/6/9 anchors (0: non-anchor/3, 1: 6, 2: 9)."""
|
|
188
|
+
flags: List[int] = []
|
|
189
|
+
for v in values:
|
|
190
|
+
if v == 6:
|
|
191
|
+
flags.append(1)
|
|
192
|
+
elif v == 9:
|
|
193
|
+
flags.append(2)
|
|
194
|
+
else:
|
|
195
|
+
flags.append(0)
|
|
196
|
+
return flags
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def _count_repeat_excess(values: List[int]) -> Dict[str, int]:
|
|
200
|
+
"""Count repeated values beyond the first value in each consecutive run."""
|
|
201
|
+
repeats: Counter[int] = Counter()
|
|
202
|
+
index = 0
|
|
203
|
+
while index < len(values):
|
|
204
|
+
end = index + 1
|
|
205
|
+
while end < len(values) and values[end] == values[index]:
|
|
206
|
+
end += 1
|
|
207
|
+
if end - index > 1:
|
|
208
|
+
repeats[values[index]] += end - index - 1
|
|
209
|
+
index = end
|
|
210
|
+
return {str(value): count for value, count in sorted(repeats.items())}
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def _count_anchor_alignments(values: List[int]) -> Dict[str, Dict[str, int]]:
|
|
214
|
+
"""Count anchor-compatible cyclic matrix alignments at each multiplier."""
|
|
215
|
+
counts = {
|
|
216
|
+
str(multiplier): {str(anchor): 0 for anchor in (3, 6, 9)}
|
|
217
|
+
for multiplier in range(1, 7)
|
|
218
|
+
}
|
|
219
|
+
for position, value in enumerate(values):
|
|
220
|
+
if value not in (3, 6, 9):
|
|
221
|
+
continue
|
|
222
|
+
for multiplier in range(1, 7):
|
|
223
|
+
row_digit = int(str(BASE_NUMBER * multiplier)[position % 6])
|
|
224
|
+
if value in ANCHOR_ALIGNMENTS[row_digit]:
|
|
225
|
+
counts[str(multiplier)][str(value)] += 1
|
|
226
|
+
return counts
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
def _count_cyclic_alignments(values: List[int]) -> Dict[str, List[int]]:
|
|
230
|
+
"""Count cyclic-symbol alignments by multiplier and matrix slot."""
|
|
231
|
+
counts = {
|
|
232
|
+
str(multiplier): [0] * len(CYCLIC)
|
|
233
|
+
for multiplier in range(1, 7)
|
|
234
|
+
}
|
|
235
|
+
for position, value in enumerate(values):
|
|
236
|
+
if value not in CYCLIC:
|
|
237
|
+
continue
|
|
238
|
+
multiplier = position % 6 + 1
|
|
239
|
+
row = tuple(int(digit) for digit in str(BASE_NUMBER * multiplier))
|
|
240
|
+
counts[str(multiplier)][row.index(value)] += 1
|
|
241
|
+
return counts
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
def _count_anchor_values(values: List[int]) -> Dict[str, int]:
|
|
245
|
+
anchors = Counter(value for value in values if value in (3, 6, 9))
|
|
246
|
+
return {str(value): count for value, count in sorted(anchors.items())}
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
def _to_base36(value: int) -> str:
|
|
250
|
+
if value < 0:
|
|
251
|
+
raise ValueError("Base-36 values cannot be negative")
|
|
252
|
+
alphabet = "0123456789abcdefghijklmnopqrstuvwxyz"
|
|
253
|
+
if value == 0:
|
|
254
|
+
return "0"
|
|
255
|
+
digits: List[str] = []
|
|
256
|
+
while value:
|
|
257
|
+
value, remainder = divmod(value, 36)
|
|
258
|
+
digits.append(alphabet[remainder])
|
|
259
|
+
return "".join(reversed(digits))
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
def _from_base36(value: str) -> int:
|
|
263
|
+
if not value or any(char not in "0123456789abcdefghijklmnopqrstuvwxyz" for char in value):
|
|
264
|
+
raise ValueError("Malformed base-36 tier count")
|
|
265
|
+
return int(value, 36)
|
|
266
|
+
|
|
267
|
+
|
|
268
|
+
def _rank_counts(counts: List[int]) -> int:
|
|
269
|
+
remaining = sum(counts)
|
|
270
|
+
rank = 0
|
|
271
|
+
for index, count in enumerate(counts[:-1]):
|
|
272
|
+
bins_after = len(counts) - index - 1
|
|
273
|
+
rank += sum(
|
|
274
|
+
comb(remaining - candidate + bins_after - 1, bins_after - 1)
|
|
275
|
+
for candidate in range(count)
|
|
276
|
+
)
|
|
277
|
+
remaining -= count
|
|
278
|
+
return rank
|
|
279
|
+
|
|
280
|
+
|
|
281
|
+
def _unrank_counts(total: int, rank: int, width: int = 6) -> List[int]:
|
|
282
|
+
if total < 0 or rank < 0:
|
|
283
|
+
raise ValueError("Tier alignment rank is out of range")
|
|
284
|
+
maximum_rank = comb(total + width - 1, width - 1) - 1
|
|
285
|
+
if rank > maximum_rank:
|
|
286
|
+
raise ValueError("Tier alignment rank is out of range")
|
|
287
|
+
counts: List[int] = []
|
|
288
|
+
remaining = total
|
|
289
|
+
for index in range(width - 1):
|
|
290
|
+
bins_after = width - index - 1
|
|
291
|
+
for count in range(remaining + 1):
|
|
292
|
+
ways = comb(remaining - count + bins_after - 1, bins_after - 1)
|
|
293
|
+
if rank < ways:
|
|
294
|
+
counts.append(count)
|
|
295
|
+
remaining -= count
|
|
296
|
+
break
|
|
297
|
+
rank -= ways
|
|
298
|
+
counts.append(remaining)
|
|
299
|
+
if rank:
|
|
300
|
+
raise ValueError("Tier alignment rank is invalid")
|
|
301
|
+
return counts
|
|
302
|
+
|
|
303
|
+
|
|
304
|
+
def _fixed_base36(value: int, width: int) -> str:
|
|
305
|
+
encoded = _to_base36(value)
|
|
306
|
+
if len(encoded) > width:
|
|
307
|
+
raise ValueError("Tier count exceeds its encoded width")
|
|
308
|
+
return encoded.rjust(width, "0")
|
|
309
|
+
|
|
310
|
+
|
|
311
|
+
def _encode_sparse_counts(counts: Dict[str, int]) -> str:
|
|
312
|
+
return ",".join(
|
|
313
|
+
f"{_to_base36(int(key))}.{_to_base36(count)}"
|
|
314
|
+
for key, count in sorted(counts.items(), key=lambda item: int(item[0]))
|
|
315
|
+
if count
|
|
316
|
+
) or "-"
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
def _encode_sparse_anchor_alignments(counts: Dict[str, Dict[str, int]]) -> str:
|
|
320
|
+
return ",".join(
|
|
321
|
+
f"{_to_base36(int(multiplier))}.{_to_base36(int(anchor))}.{_to_base36(count)}"
|
|
322
|
+
for multiplier, anchors in sorted(counts.items(), key=lambda item: int(item[0]))
|
|
323
|
+
for anchor, count in sorted(anchors.items(), key=lambda item: int(item[0]))
|
|
324
|
+
if count
|
|
325
|
+
) or "-"
|
|
326
|
+
|
|
327
|
+
|
|
328
|
+
def _format_tier_pin_code(apex_pin: str, folds: List[Dict[str, object]]) -> str:
|
|
329
|
+
"""Serialize the apex pin and per-input-tier reconstruction counts."""
|
|
330
|
+
tiers: List[str] = []
|
|
331
|
+
for fold in folds:
|
|
332
|
+
input_count = fold["input_count"]
|
|
333
|
+
lane_counts = fold["source_alignment_counts"]
|
|
334
|
+
if not isinstance(input_count, int) or not isinstance(lane_counts, dict):
|
|
335
|
+
raise ValueError("Malformed tier source counts")
|
|
336
|
+
lane_totals = [
|
|
337
|
+
sum(lane_counts[str(multiplier)])
|
|
338
|
+
for multiplier in range(1, 7)
|
|
339
|
+
]
|
|
340
|
+
lane_width = max(1, len(_to_base36((input_count + 5) // 6)))
|
|
341
|
+
packed_totals = "".join(
|
|
342
|
+
_fixed_base36(total, lane_width)
|
|
343
|
+
for total in lane_totals
|
|
344
|
+
)
|
|
345
|
+
packed_ranks = "".join(
|
|
346
|
+
_fixed_base36(
|
|
347
|
+
_rank_counts(lane_counts[str(multiplier)]),
|
|
348
|
+
max(
|
|
349
|
+
1,
|
|
350
|
+
len(
|
|
351
|
+
_to_base36(
|
|
352
|
+
comb(lane_totals[multiplier - 1] + 5, 5) - 1
|
|
353
|
+
)
|
|
354
|
+
),
|
|
355
|
+
),
|
|
356
|
+
)
|
|
357
|
+
for multiplier in range(1, 7)
|
|
358
|
+
)
|
|
359
|
+
anchors = fold["source_anchor_counts"]
|
|
360
|
+
repeats = fold["source_repeat_counts"]
|
|
361
|
+
anchor_alignments = fold["source_anchor_alignment_counts"]
|
|
362
|
+
if (
|
|
363
|
+
not isinstance(anchors, dict)
|
|
364
|
+
or not isinstance(repeats, dict)
|
|
365
|
+
or not isinstance(anchor_alignments, dict)
|
|
366
|
+
):
|
|
367
|
+
raise ValueError("Malformed tier marker counts")
|
|
368
|
+
tiers.append(
|
|
369
|
+
"~".join((
|
|
370
|
+
_to_base36(input_count),
|
|
371
|
+
packed_totals,
|
|
372
|
+
packed_ranks,
|
|
373
|
+
_encode_sparse_counts(anchors),
|
|
374
|
+
_encode_sparse_counts(repeats),
|
|
375
|
+
_encode_sparse_anchor_alignments(anchor_alignments),
|
|
376
|
+
))
|
|
377
|
+
)
|
|
378
|
+
return f"{apex_pin}|{';'.join(tiers) or '-'}"
|
|
379
|
+
|
|
380
|
+
|
|
381
|
+
def _tier_preimages(
|
|
382
|
+
target: List[int],
|
|
383
|
+
tier: Dict[str, object],
|
|
384
|
+
*,
|
|
385
|
+
max_nodes: int = 250_000,
|
|
386
|
+
max_results: int = 10_000,
|
|
387
|
+
) -> List[List[int]]:
|
|
388
|
+
input_count = tier["n"]
|
|
389
|
+
expected_anchors = tier["a"]
|
|
390
|
+
expected_repeats = tier["r"]
|
|
391
|
+
expected_cyclic = tier["c"]
|
|
392
|
+
expected_anchor_alignments = tier["x"]
|
|
393
|
+
if (
|
|
394
|
+
isinstance(input_count, bool)
|
|
395
|
+
or not isinstance(input_count, int)
|
|
396
|
+
or not isinstance(expected_anchors, dict)
|
|
397
|
+
or not isinstance(expected_repeats, dict)
|
|
398
|
+
or not isinstance(expected_cyclic, dict)
|
|
399
|
+
or not isinstance(expected_anchor_alignments, dict)
|
|
400
|
+
):
|
|
401
|
+
raise ValueError("Malformed tier reconstruction counts")
|
|
402
|
+
|
|
403
|
+
output_count = len(target)
|
|
404
|
+
if output_count != (input_count - 1) // 2 or input_count < 3:
|
|
405
|
+
raise ValueError("Tier lengths are inconsistent with stride-2 folding")
|
|
406
|
+
tail_count = input_count - (2 * output_count + 1)
|
|
407
|
+
allowed_values = list(CYCLIC) + [
|
|
408
|
+
anchor
|
|
409
|
+
for anchor in (3, 6, 9)
|
|
410
|
+
if expected_anchors.get(str(anchor), 0)
|
|
411
|
+
]
|
|
412
|
+
if any(
|
|
413
|
+
not isinstance(count, int) or count < 0
|
|
414
|
+
for counts in (expected_anchors, expected_repeats)
|
|
415
|
+
for count in counts.values()
|
|
416
|
+
):
|
|
417
|
+
raise ValueError("Tier counts must be non-negative integers")
|
|
418
|
+
for multiplier in range(1, 7):
|
|
419
|
+
key = str(multiplier)
|
|
420
|
+
if (
|
|
421
|
+
not isinstance(expected_cyclic.get(key), list)
|
|
422
|
+
or len(expected_cyclic[key]) != len(CYCLIC)
|
|
423
|
+
or any(
|
|
424
|
+
not isinstance(count, int) or count < 0
|
|
425
|
+
for count in expected_cyclic[key]
|
|
426
|
+
)
|
|
427
|
+
):
|
|
428
|
+
raise ValueError("Malformed cyclic alignment counts")
|
|
429
|
+
if not isinstance(expected_anchor_alignments.get(key), dict) or any(
|
|
430
|
+
not isinstance(expected_anchor_alignments[key].get(str(anchor)), int)
|
|
431
|
+
or expected_anchor_alignments[key][str(anchor)] < 0
|
|
432
|
+
for anchor in (3, 6, 9)
|
|
433
|
+
):
|
|
434
|
+
raise ValueError("Malformed anchor alignment counts")
|
|
435
|
+
|
|
436
|
+
options_by_target: List[List[Tuple[int, int, int]]] = []
|
|
437
|
+
for result in target:
|
|
438
|
+
options = [
|
|
439
|
+
(a, b, c)
|
|
440
|
+
for a in allowed_values
|
|
441
|
+
for b in allowed_values
|
|
442
|
+
for c in allowed_values
|
|
443
|
+
if left_to_right_digital_root((a, b, c)) == result
|
|
444
|
+
]
|
|
445
|
+
options_by_target.append(options)
|
|
446
|
+
|
|
447
|
+
results: List[List[int]] = []
|
|
448
|
+
nodes = 0
|
|
449
|
+
sequence: List[int] = []
|
|
450
|
+
actual_anchors: Counter[int] = Counter()
|
|
451
|
+
actual_repeats: Counter[int] = Counter()
|
|
452
|
+
actual_cyclic = {
|
|
453
|
+
str(multiplier): [0] * len(CYCLIC)
|
|
454
|
+
for multiplier in range(1, 7)
|
|
455
|
+
}
|
|
456
|
+
actual_anchor_alignments = {
|
|
457
|
+
str(multiplier): {str(anchor): 0 for anchor in (3, 6, 9)}
|
|
458
|
+
for multiplier in range(1, 7)
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
def append_value(value: int) -> bool:
|
|
462
|
+
position = len(sequence)
|
|
463
|
+
previous = sequence[-1] if sequence else None
|
|
464
|
+
if value in (3, 6, 9):
|
|
465
|
+
actual_anchors[value] += 1
|
|
466
|
+
if actual_anchors[value] > expected_anchors.get(str(value), 0):
|
|
467
|
+
actual_anchors[value] -= 1
|
|
468
|
+
return False
|
|
469
|
+
if previous == value:
|
|
470
|
+
actual_repeats[value] += 1
|
|
471
|
+
if actual_repeats[value] > expected_repeats.get(str(value), 0):
|
|
472
|
+
actual_repeats[value] -= 1
|
|
473
|
+
if value in (3, 6, 9):
|
|
474
|
+
actual_anchors[value] -= 1
|
|
475
|
+
return False
|
|
476
|
+
|
|
477
|
+
if value in CYCLIC:
|
|
478
|
+
multiplier = position % 6 + 1
|
|
479
|
+
row = tuple(int(digit) for digit in str(BASE_NUMBER * multiplier))
|
|
480
|
+
slot = row.index(value)
|
|
481
|
+
actual_cyclic[str(multiplier)][slot] += 1
|
|
482
|
+
if actual_cyclic[str(multiplier)][slot] > expected_cyclic[str(multiplier)][slot]:
|
|
483
|
+
actual_cyclic[str(multiplier)][slot] -= 1
|
|
484
|
+
if previous == value:
|
|
485
|
+
actual_repeats[value] -= 1
|
|
486
|
+
return False
|
|
487
|
+
else:
|
|
488
|
+
for multiplier in range(1, 7):
|
|
489
|
+
row_digit = int(str(BASE_NUMBER * multiplier)[position % 6])
|
|
490
|
+
if value in ANCHOR_ALIGNMENTS[row_digit]:
|
|
491
|
+
actual_anchor_alignments[str(multiplier)][str(value)] += 1
|
|
492
|
+
if (
|
|
493
|
+
actual_anchor_alignments[str(multiplier)][str(value)]
|
|
494
|
+
> expected_anchor_alignments[str(multiplier)][str(value)]
|
|
495
|
+
):
|
|
496
|
+
for prior_multiplier in range(1, multiplier + 1):
|
|
497
|
+
prior_row_digit = int(
|
|
498
|
+
str(BASE_NUMBER * prior_multiplier)[position % 6]
|
|
499
|
+
)
|
|
500
|
+
if value in ANCHOR_ALIGNMENTS[prior_row_digit]:
|
|
501
|
+
actual_anchor_alignments[str(prior_multiplier)][str(value)] -= 1
|
|
502
|
+
if previous == value:
|
|
503
|
+
actual_repeats[value] -= 1
|
|
504
|
+
actual_anchors[value] -= 1
|
|
505
|
+
return False
|
|
506
|
+
|
|
507
|
+
sequence.append(value)
|
|
508
|
+
if not prefix_viable():
|
|
509
|
+
remove_last_value()
|
|
510
|
+
return False
|
|
511
|
+
return True
|
|
512
|
+
|
|
513
|
+
def remove_last_value() -> None:
|
|
514
|
+
value = sequence.pop()
|
|
515
|
+
position = len(sequence)
|
|
516
|
+
if value in (3, 6, 9):
|
|
517
|
+
actual_anchors[value] -= 1
|
|
518
|
+
for multiplier in range(1, 7):
|
|
519
|
+
row_digit = int(str(BASE_NUMBER * multiplier)[position % 6])
|
|
520
|
+
if value in ANCHOR_ALIGNMENTS[row_digit]:
|
|
521
|
+
actual_anchor_alignments[str(multiplier)][str(value)] -= 1
|
|
522
|
+
else:
|
|
523
|
+
multiplier = position % 6 + 1
|
|
524
|
+
row = tuple(int(digit) for digit in str(BASE_NUMBER * multiplier))
|
|
525
|
+
actual_cyclic[str(multiplier)][row.index(value)] -= 1
|
|
526
|
+
if sequence and sequence[-1] == value:
|
|
527
|
+
actual_repeats[value] -= 1
|
|
528
|
+
|
|
529
|
+
def prefix_viable() -> bool:
|
|
530
|
+
remaining_positions = input_count - len(sequence)
|
|
531
|
+
anchors_remaining = sum(expected_anchors.values()) - sum(actual_anchors.values())
|
|
532
|
+
cyclic_remaining = sum(
|
|
533
|
+
sum(expected_cyclic[str(multiplier)])
|
|
534
|
+
- sum(actual_cyclic[str(multiplier)])
|
|
535
|
+
for multiplier in range(1, 7)
|
|
536
|
+
)
|
|
537
|
+
if (
|
|
538
|
+
anchors_remaining < 0
|
|
539
|
+
or cyclic_remaining < 0
|
|
540
|
+
or anchors_remaining + cyclic_remaining != remaining_positions
|
|
541
|
+
):
|
|
542
|
+
return False
|
|
543
|
+
if sum(expected_repeats.values()) - sum(actual_repeats.values()) > remaining_positions:
|
|
544
|
+
return False
|
|
545
|
+
|
|
546
|
+
for multiplier in range(1, 7):
|
|
547
|
+
key = str(multiplier)
|
|
548
|
+
remaining_lane_positions = sum(
|
|
549
|
+
position % 6 + 1 == multiplier
|
|
550
|
+
for position in range(len(sequence), input_count)
|
|
551
|
+
)
|
|
552
|
+
lane_needed = sum(expected_cyclic[key]) - sum(actual_cyclic[key])
|
|
553
|
+
if lane_needed < 0 or lane_needed > remaining_lane_positions:
|
|
554
|
+
return False
|
|
555
|
+
for anchor in (3, 6, 9):
|
|
556
|
+
needed = (
|
|
557
|
+
expected_anchor_alignments[key][str(anchor)]
|
|
558
|
+
- actual_anchor_alignments[key][str(anchor)]
|
|
559
|
+
)
|
|
560
|
+
capacity = sum(
|
|
561
|
+
anchor in ANCHOR_ALIGNMENTS[
|
|
562
|
+
int(str(BASE_NUMBER * multiplier)[position % 6])
|
|
563
|
+
]
|
|
564
|
+
for position in range(len(sequence), input_count)
|
|
565
|
+
)
|
|
566
|
+
if needed < 0 or needed > capacity:
|
|
567
|
+
return False
|
|
568
|
+
return True
|
|
569
|
+
|
|
570
|
+
def signature_matches() -> bool:
|
|
571
|
+
return (
|
|
572
|
+
{
|
|
573
|
+
str(value): count
|
|
574
|
+
for value, count in sorted(actual_anchors.items())
|
|
575
|
+
if count
|
|
576
|
+
}
|
|
577
|
+
== expected_anchors
|
|
578
|
+
and _count_repeat_excess(sequence) == expected_repeats
|
|
579
|
+
and actual_cyclic == expected_cyclic
|
|
580
|
+
and actual_anchor_alignments == expected_anchor_alignments
|
|
581
|
+
)
|
|
582
|
+
|
|
583
|
+
def visit(window: int) -> None:
|
|
584
|
+
nonlocal nodes
|
|
585
|
+
nodes += 1
|
|
586
|
+
if nodes > max_nodes:
|
|
587
|
+
raise ValueError("Tier reconstruction exceeded the candidate-search limit")
|
|
588
|
+
|
|
589
|
+
if window == output_count:
|
|
590
|
+
if tail_count:
|
|
591
|
+
for value in allowed_values:
|
|
592
|
+
if append_value(value):
|
|
593
|
+
if signature_matches():
|
|
594
|
+
results.append(sequence.copy())
|
|
595
|
+
remove_last_value()
|
|
596
|
+
if len(results) > max_results:
|
|
597
|
+
raise ValueError("Tier reconstruction remains too ambiguous")
|
|
598
|
+
elif signature_matches():
|
|
599
|
+
results.append(sequence.copy())
|
|
600
|
+
if len(results) > max_results:
|
|
601
|
+
raise ValueError("Tier reconstruction remains too ambiguous")
|
|
602
|
+
return
|
|
603
|
+
|
|
604
|
+
for triple in options_by_target[window]:
|
|
605
|
+
if window and triple[0] != sequence[-1]:
|
|
606
|
+
continue
|
|
607
|
+
additions = triple if window == 0 else triple[1:]
|
|
608
|
+
appended = 0
|
|
609
|
+
for value in additions:
|
|
610
|
+
if not append_value(value):
|
|
611
|
+
break
|
|
612
|
+
appended += 1
|
|
613
|
+
if appended == len(additions):
|
|
614
|
+
visit(window + 1)
|
|
615
|
+
for _ in range(appended):
|
|
616
|
+
remove_last_value()
|
|
617
|
+
if len(results) > max_results:
|
|
618
|
+
raise ValueError("Tier reconstruction remains too ambiguous")
|
|
619
|
+
|
|
620
|
+
visit(0)
|
|
621
|
+
return results
|
|
622
|
+
|
|
623
|
+
|
|
624
|
+
def decode_tier_pin_code(pin_code: str) -> str:
|
|
625
|
+
"""Reconstruct a numeric stream from its apex pin and tier counts alone."""
|
|
626
|
+
if not isinstance(pin_code, str) or "|" not in pin_code:
|
|
627
|
+
raise ValueError("Tier pin must contain an apex and tier-count payload")
|
|
628
|
+
apex_pin, encoded_tiers = pin_code.split("|", 1)
|
|
629
|
+
if not apex_pin or any(digit not in "123456789" for digit in apex_pin):
|
|
630
|
+
raise ValueError("Apex pin must contain digits 1 through 9")
|
|
631
|
+
|
|
632
|
+
def parse_sparse_counts(value: str, allowed: set[int]) -> Dict[str, int]:
|
|
633
|
+
parsed: Dict[str, int] = {}
|
|
634
|
+
if value == "-":
|
|
635
|
+
return parsed
|
|
636
|
+
for item in value.split(","):
|
|
637
|
+
pieces = item.split(".")
|
|
638
|
+
if len(pieces) != 2:
|
|
639
|
+
raise ValueError("Malformed sparse tier count")
|
|
640
|
+
key = _from_base36(pieces[0])
|
|
641
|
+
count = _from_base36(pieces[1])
|
|
642
|
+
if key not in allowed or count == 0 or str(key) in parsed:
|
|
643
|
+
raise ValueError("Invalid sparse tier count")
|
|
644
|
+
parsed[str(key)] = count
|
|
645
|
+
return parsed
|
|
646
|
+
|
|
647
|
+
tiers: List[Dict[str, object]] = []
|
|
648
|
+
if encoded_tiers != "-":
|
|
649
|
+
for record in encoded_tiers.split(";"):
|
|
650
|
+
fields = record.split("~")
|
|
651
|
+
if len(fields) != 6:
|
|
652
|
+
raise ValueError("Malformed tier-count record")
|
|
653
|
+
input_count = _from_base36(fields[0])
|
|
654
|
+
if input_count <= 6:
|
|
655
|
+
raise ValueError("Tier input count must be greater than six")
|
|
656
|
+
lane_width = max(1, len(_to_base36((input_count + 5) // 6)))
|
|
657
|
+
if len(fields[1]) != lane_width * 6:
|
|
658
|
+
raise ValueError("Malformed multiplier totals")
|
|
659
|
+
lane_totals = [
|
|
660
|
+
_from_base36(fields[1][index * lane_width : (index + 1) * lane_width])
|
|
661
|
+
for index in range(6)
|
|
662
|
+
]
|
|
663
|
+
rank_widths = [
|
|
664
|
+
max(1, len(_to_base36(comb(total + 5, 5) - 1)))
|
|
665
|
+
for total in lane_totals
|
|
666
|
+
]
|
|
667
|
+
if len(fields[2]) != sum(rank_widths):
|
|
668
|
+
raise ValueError("Malformed multiplier alignment ranks")
|
|
669
|
+
cyclic_counts: Dict[str, List[int]] = {}
|
|
670
|
+
offset = 0
|
|
671
|
+
for multiplier, (total, width) in enumerate(
|
|
672
|
+
zip(lane_totals, rank_widths),
|
|
673
|
+
start=1,
|
|
674
|
+
):
|
|
675
|
+
rank = _from_base36(fields[2][offset : offset + width])
|
|
676
|
+
offset += width
|
|
677
|
+
cyclic_counts[str(multiplier)] = _unrank_counts(total, rank)
|
|
678
|
+
anchor_counts = parse_sparse_counts(fields[3], {3, 6, 9})
|
|
679
|
+
repeat_counts = parse_sparse_counts(fields[4], set(range(1, 10)))
|
|
680
|
+
anchor_alignments: Dict[str, Dict[str, int]] = {
|
|
681
|
+
str(multiplier): {str(anchor): 0 for anchor in (3, 6, 9)}
|
|
682
|
+
for multiplier in range(1, 7)
|
|
683
|
+
}
|
|
684
|
+
if fields[5] != "-":
|
|
685
|
+
for item in fields[5].split(","):
|
|
686
|
+
pieces = item.split(".")
|
|
687
|
+
if len(pieces) != 3:
|
|
688
|
+
raise ValueError("Malformed anchor alignment count")
|
|
689
|
+
multiplier, anchor, count = map(_from_base36, pieces)
|
|
690
|
+
if (
|
|
691
|
+
multiplier not in range(1, 7)
|
|
692
|
+
or anchor not in (3, 6, 9)
|
|
693
|
+
or count == 0
|
|
694
|
+
or anchor_alignments[str(multiplier)][str(anchor)] != 0
|
|
695
|
+
):
|
|
696
|
+
raise ValueError("Invalid anchor alignment count")
|
|
697
|
+
anchor_alignments[str(multiplier)][str(anchor)] = count
|
|
698
|
+
tiers.append({
|
|
699
|
+
"n": input_count,
|
|
700
|
+
"a": anchor_counts,
|
|
701
|
+
"r": repeat_counts,
|
|
702
|
+
"c": cyclic_counts,
|
|
703
|
+
"x": anchor_alignments,
|
|
704
|
+
})
|
|
705
|
+
|
|
706
|
+
candidates = [[int(digit) for digit in apex_pin]]
|
|
707
|
+
for tier in reversed(tiers):
|
|
708
|
+
expanded: List[List[int]] = []
|
|
709
|
+
for target in candidates:
|
|
710
|
+
expanded.extend(_tier_preimages(target, tier))
|
|
711
|
+
if len(expanded) > 10_000:
|
|
712
|
+
raise ValueError("Tier reconstruction remains too ambiguous")
|
|
713
|
+
candidates = list({tuple(candidate) for candidate in expanded})
|
|
714
|
+
if not candidates:
|
|
715
|
+
raise ValueError("Tier pin counts do not match any valid reconstruction")
|
|
716
|
+
if len(candidates) != 1:
|
|
717
|
+
raise ValueError("Tier pin is ambiguous; counts do not identify one input")
|
|
718
|
+
return "".join(map(str, candidates[0]))
|
|
719
|
+
|
|
720
|
+
|
|
721
|
+
def _fold_values_to_pin(
|
|
722
|
+
values: List[int],
|
|
723
|
+
) -> Tuple[List[int], List[Dict[str, object]], Counter[int], int]:
|
|
724
|
+
current = values[:]
|
|
725
|
+
folds: List[Dict[str, object]] = []
|
|
726
|
+
anchor_counts: Counter[int] = Counter()
|
|
727
|
+
duality_checks = 0
|
|
728
|
+
|
|
729
|
+
while len(current) > 6:
|
|
730
|
+
lr = fold_trisums_lr(current)
|
|
731
|
+
rl = fold_trisums_rl(current)
|
|
732
|
+
if not lr or len(lr) >= len(current) or len(lr) < 6:
|
|
733
|
+
break
|
|
734
|
+
bidir = check_bidirectional_pairs(lr, rl)
|
|
735
|
+
fold_anchor_counts = Counter(value for value in lr if value in (3, 6, 9))
|
|
736
|
+
checks = sum(fold_anchor_counts.values())
|
|
737
|
+
if fold_anchor_counts and not all(
|
|
738
|
+
verify_369_duality(value)["verified"] for value in fold_anchor_counts
|
|
739
|
+
):
|
|
740
|
+
raise ValueError("A 369 multiplication duality failed verification")
|
|
741
|
+
|
|
742
|
+
anchor_counts.update(fold_anchor_counts)
|
|
743
|
+
duality_checks += checks
|
|
744
|
+
folds.append({
|
|
745
|
+
"fold": len(folds) + 1,
|
|
746
|
+
"input_count": len(current),
|
|
747
|
+
"output_count": len(lr),
|
|
748
|
+
"source_anchor_counts": _count_anchor_values(current),
|
|
749
|
+
"source_repeat_counts": _count_repeat_excess(current),
|
|
750
|
+
"source_alignment_counts": _count_cyclic_alignments(current),
|
|
751
|
+
"source_anchor_alignment_counts": _count_anchor_alignments(current),
|
|
752
|
+
"bidir_verified": bidir["bidir_verified"],
|
|
753
|
+
"apex_pairs": bidir["apex_pairs"],
|
|
754
|
+
"anchor_counts": {str(value): count for value, count in fold_anchor_counts.items()},
|
|
755
|
+
"repeat_counts": _count_repeat_excess(lr),
|
|
756
|
+
"alignment_counts": _count_anchor_alignments(lr),
|
|
757
|
+
"duality_checks": checks,
|
|
758
|
+
})
|
|
759
|
+
current = lr
|
|
760
|
+
return current, folds, anchor_counts, duality_checks
|
|
761
|
+
|
|
762
|
+
|
|
763
|
+
def compress_numeric_stream(digits: str | Iterable[int]) -> Dict[str, object]:
|
|
764
|
+
"""Create a whole-stream tier pin for numeric values 1 through 9."""
|
|
765
|
+
if isinstance(digits, str):
|
|
766
|
+
if not digits or not digits.isdigit() or "0" in digits:
|
|
767
|
+
raise ValueError("Numeric streams must contain digits 1 through 9 only")
|
|
768
|
+
values = [int(digit) for digit in digits]
|
|
769
|
+
else:
|
|
770
|
+
values = list(digits)
|
|
771
|
+
if not values or any(
|
|
772
|
+
isinstance(value, bool)
|
|
773
|
+
or not isinstance(value, int)
|
|
774
|
+
or not 1 <= value <= 9
|
|
775
|
+
for value in values
|
|
776
|
+
):
|
|
777
|
+
raise ValueError("Numeric streams must contain integers 1 through 9 only")
|
|
778
|
+
|
|
779
|
+
pin, folds, anchors, duality_checks = _fold_values_to_pin(values)
|
|
780
|
+
apex_pin = "".join(map(str, pin))
|
|
781
|
+
tier_pin_code = _format_tier_pin_code(apex_pin, folds)
|
|
782
|
+
storage_chars = len(tier_pin_code)
|
|
783
|
+
return {
|
|
784
|
+
"format": "whole-stream-tier-pin-v1",
|
|
785
|
+
"input_length": len(values),
|
|
786
|
+
"pin": pin,
|
|
787
|
+
"apex_pin": apex_pin,
|
|
788
|
+
"fold_log": folds,
|
|
789
|
+
"tier_pin_code": tier_pin_code,
|
|
790
|
+
"anchor_counts": {str(value): count for value, count in sorted(anchors.items())},
|
|
791
|
+
"duality_checks": duality_checks,
|
|
792
|
+
"storage_chars": storage_chars,
|
|
793
|
+
"reduction_percent": round(
|
|
794
|
+
(1 - storage_chars / len(values)) * 100,
|
|
795
|
+
1,
|
|
796
|
+
),
|
|
797
|
+
}
|
|
798
|
+
|
|
799
|
+
|
|
800
|
+
def compress_text(text: str) -> Dict[str, object]:
|
|
801
|
+
"""Fold an ordered cipher stream to its smallest tier of at least six values.
|
|
802
|
+
|
|
803
|
+
Records LR/RL bidirectional verification, apex pairs, per-tier anchor and
|
|
804
|
+
repeat counts, and the separate 12-block pin encoding.
|
|
805
|
+
"""
|
|
806
|
+
order, raw_sequence, counts, _ = _build_sequence(text)
|
|
807
|
+
if not raw_sequence:
|
|
808
|
+
return {
|
|
809
|
+
"input_length": len(text),
|
|
810
|
+
"cipher_order": [],
|
|
811
|
+
"counts": {},
|
|
812
|
+
"sequence": [],
|
|
813
|
+
"ordered_cypher_values": [],
|
|
814
|
+
"pin": [],
|
|
815
|
+
"apex_pin": None,
|
|
816
|
+
"tier_pin_code": None,
|
|
817
|
+
"flags": [],
|
|
818
|
+
"folded_values": [],
|
|
819
|
+
"pin_lr": [],
|
|
820
|
+
"pin_rl": [],
|
|
821
|
+
"apex_pairs": [],
|
|
822
|
+
"bidir_verified": True,
|
|
823
|
+
"fold_log": [],
|
|
824
|
+
"fold_amount": 0,
|
|
825
|
+
"unfolds_to_complete": 0,
|
|
826
|
+
"cypher_fold_amount": 0,
|
|
827
|
+
"cypher_unfolds_to_complete": 0,
|
|
828
|
+
"anchor_counts": {},
|
|
829
|
+
"duality_checks": 0,
|
|
830
|
+
"pin_only_12block": compress_12block_stream([]),
|
|
831
|
+
"cyclic": CYCLIC,
|
|
832
|
+
"rotor": CyclicRotor().rotations(),
|
|
833
|
+
"project": PROJECT_NAME,
|
|
834
|
+
}
|
|
835
|
+
|
|
836
|
+
ordered_values = [CHARACTER_MAP[ch] for ch in raw_sequence]
|
|
837
|
+
ordered_cypher_numbers = [
|
|
838
|
+
collapse(CYPHER_NUMBER_MAP.get(ch, 1) * CHARACTER_MAP[ch])
|
|
839
|
+
for ch in raw_sequence
|
|
840
|
+
]
|
|
841
|
+
current, folds, anchor_counts, duality_checks = _fold_values_to_pin(ordered_values)
|
|
842
|
+
folds_count = len(folds)
|
|
843
|
+
|
|
844
|
+
lr_final = fold_trisums_lr(current) or current
|
|
845
|
+
rl_final = fold_trisums_rl(current) or current
|
|
846
|
+
if not fold_trisums_lr(current):
|
|
847
|
+
lr_final = current
|
|
848
|
+
rl_final = current
|
|
849
|
+
apex_bidir = check_bidirectional_pairs(lr_final, rl_final)
|
|
850
|
+
|
|
851
|
+
pin12_data = compress_12block_stream(
|
|
852
|
+
ordered_values,
|
|
853
|
+
cypher_order_stream=ordered_cypher_numbers,
|
|
854
|
+
)
|
|
855
|
+
folds_to_7 = int(pin12_data.get("folds_to_7") or folds_count)
|
|
856
|
+
cypher_folds_to_7 = int(pin12_data.get("cypher_folds_to_7") or folds_to_7)
|
|
857
|
+
apex_pin = "".join(map(str, current))
|
|
858
|
+
|
|
859
|
+
return {
|
|
860
|
+
"input_length": len(text),
|
|
861
|
+
"cipher_order": order,
|
|
862
|
+
"counts": counts,
|
|
863
|
+
"sequence": raw_sequence,
|
|
864
|
+
"ordered_cypher_values": ordered_values,
|
|
865
|
+
"pin": current[:],
|
|
866
|
+
"apex_pin": apex_pin,
|
|
867
|
+
"tier_pin_code": _format_tier_pin_code(apex_pin, folds),
|
|
868
|
+
"flags": _compute_anchor_flags(current),
|
|
869
|
+
"folded_values": current[:],
|
|
870
|
+
"pin_lr": lr_final,
|
|
871
|
+
"pin_rl": rl_final,
|
|
872
|
+
"apex_pairs": apex_bidir["apex_pairs"],
|
|
873
|
+
"bidir_verified": apex_bidir["bidir_verified"],
|
|
874
|
+
"fold_log": folds,
|
|
875
|
+
"fold_amount": folds_to_7,
|
|
876
|
+
"unfolds_to_complete": folds_to_7,
|
|
877
|
+
"cypher_fold_amount": cypher_folds_to_7,
|
|
878
|
+
"cypher_unfolds_to_complete": cypher_folds_to_7,
|
|
879
|
+
"anchor_counts": {str(v): c for v, c in anchor_counts.items()},
|
|
880
|
+
"duality_checks": duality_checks,
|
|
881
|
+
"pin_only_12block": pin12_data,
|
|
882
|
+
"cyclic": CYCLIC,
|
|
883
|
+
"rotor": build_rotor_matrix(),
|
|
884
|
+
"project": PROJECT_NAME,
|
|
885
|
+
}
|
|
886
|
+
|
|
887
|
+
|
|
888
|
+
def verify_369_duality(value: int) -> Dict[str, object]:
|
|
889
|
+
"""Verify a 369 anchor using the 3x1 and 3x2 multiplication dualities."""
|
|
890
|
+
multipliers = {3: (1,), 6: (2,), 9: (1, 2)}
|
|
891
|
+
if value not in multipliers:
|
|
892
|
+
raise ValueError(f"{value} is not a 369 anchor")
|
|
893
|
+
products = [3 * multiplier for multiplier in multipliers[value]]
|
|
894
|
+
return {
|
|
895
|
+
"value": value,
|
|
896
|
+
"products": products,
|
|
897
|
+
"verified": sum(products) == value,
|
|
898
|
+
}
|
|
899
|
+
|
|
900
|
+
|
|
901
|
+
def unfold_numeric(
|
|
902
|
+
ordered_values: Iterable[int],
|
|
903
|
+
fold_log: Iterable[Dict[str, object]],
|
|
904
|
+
folded_values: Iterable[int],
|
|
905
|
+
) -> List[int]:
|
|
906
|
+
"""Return the stored ordered cipher stream after verifying its fold chain."""
|
|
907
|
+
source = list(ordered_values)
|
|
908
|
+
current = source[:]
|
|
909
|
+
|
|
910
|
+
folds = list(fold_log)
|
|
911
|
+
for expected_fold, fold in enumerate(folds, start=1):
|
|
912
|
+
if fold["fold"] != expected_fold or fold["input_count"] != len(current):
|
|
913
|
+
raise ValueError(f"Fold {expected_fold} does not match the ordered stream")
|
|
914
|
+
|
|
915
|
+
next_values = fold_triplets(current)
|
|
916
|
+
if fold["output_count"] != len(next_values):
|
|
917
|
+
raise ValueError(f"Fold {expected_fold} has an invalid output count")
|
|
918
|
+
anchors = Counter(value for value in next_values if value in (3, 6, 9))
|
|
919
|
+
serialized_anchors = {str(value): count for value, count in anchors.items()}
|
|
920
|
+
if serialized_anchors != fold["anchor_counts"] or sum(anchors.values()) != fold["duality_checks"]:
|
|
921
|
+
raise ValueError(f"Fold {expected_fold} has invalid 369 verification counts")
|
|
922
|
+
if not all(verify_369_duality(value)["verified"] for value in anchors):
|
|
923
|
+
raise ValueError(f"Fold {expected_fold} failed a 369 multiplication check")
|
|
924
|
+
if fold.get("repeat_counts") != _count_repeat_excess(next_values):
|
|
925
|
+
raise ValueError(f"Fold {expected_fold} has invalid repeat counts")
|
|
926
|
+
if fold.get("alignment_counts") != _count_anchor_alignments(next_values):
|
|
927
|
+
raise ValueError(f"Fold {expected_fold} has invalid anchor alignment counts")
|
|
928
|
+
current = next_values
|
|
929
|
+
|
|
930
|
+
if len(current) > 6:
|
|
931
|
+
next_values = fold_triplets(current)
|
|
932
|
+
if next_values and len(next_values) >= 6:
|
|
933
|
+
raise ValueError("The fold log stops before the smallest tier of at least six values")
|
|
934
|
+
|
|
935
|
+
if current != list(folded_values):
|
|
936
|
+
raise ValueError("The ordered cipher stream does not produce the stored folded values")
|
|
937
|
+
|
|
938
|
+
return source
|
|
939
|
+
|
|
940
|
+
|
|
941
|
+
def unfold_sequence(pin: Iterable[int], cipher_order: Iterable[int], counts: Dict[int, List[str]]) -> List[str]:
|
|
942
|
+
"""Reverse the fold by replaying the stored per-bucket symbols."""
|
|
943
|
+
ordered_cipher_values = list(cipher_order)
|
|
944
|
+
unfolded: List[str] = []
|
|
945
|
+
for cipher in ordered_cipher_values:
|
|
946
|
+
bucket_values = counts.get(cipher, [])
|
|
947
|
+
if not bucket_values:
|
|
948
|
+
continue
|
|
949
|
+
unfolded.extend(bucket_values)
|
|
950
|
+
return unfolded
|
|
951
|
+
|
|
952
|
+
|
|
953
|
+
def rebuild_sequence(sequence: Iterable[int]) -> List[int]:
|
|
954
|
+
"""Rebuild a deterministic sequence from the compressed representation."""
|
|
955
|
+
return list(sequence)
|
|
956
|
+
|
|
957
|
+
|
|
958
|
+
if __name__ == "__main__":
|
|
959
|
+
sample = "hello world"
|
|
960
|
+
result = compress_text(sample)
|
|
961
|
+
print(f"Project: {result['project']}")
|
|
962
|
+
print("Rotor:", result["rotor"])
|
|
963
|
+
print("Input:", sample)
|
|
964
|
+
print("Cipher order:", result["cipher_order"])
|
|
965
|
+
print("PIN:", result["pin"])
|
|
966
|
+
print("Flags:", result["flags"])
|
|
967
|
+
print("12-Block Forward Pins:", result["pin_only_12block"]["forward_pins"])
|
|
968
|
+
print("12-Block Backward Pins:", result["pin_only_12block"]["backward_pins"])
|
|
969
|
+
print("Unfolded:", unfold_sequence(result["pin"], result["cipher_order"], result["counts"]))
|