cyclic-constraint-engine 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.
- cyclic_constraint_engine/__init__.py +111 -0
- cyclic_constraint_engine/cipher_libraries.py +120 -0
- cyclic_constraint_engine/engine.py +895 -0
- cyclic_constraint_engine-0.1.0.dist-info/METADATA +5 -0
- cyclic_constraint_engine-0.1.0.dist-info/RECORD +7 -0
- cyclic_constraint_engine-0.1.0.dist-info/WHEEL +5 -0
- cyclic_constraint_engine-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
from .cipher_libraries import (
|
|
2
|
+
ALPHA_CIPHER_IDS,
|
|
3
|
+
DIGIT_SPECIAL,
|
|
4
|
+
KEYBOARD_CIPHER_LIBRARIES,
|
|
5
|
+
LETTER_PUNCTUATION,
|
|
6
|
+
NUMERIC_CIPHER_IDS,
|
|
7
|
+
SLOTS_PER_CIPHER,
|
|
8
|
+
SLOTS_PER_LIBRARY,
|
|
9
|
+
TOTAL_PAIR_SLOTS,
|
|
10
|
+
KeyboardCipherLibraries,
|
|
11
|
+
build_keyboard_cipher_libraries,
|
|
12
|
+
)
|
|
13
|
+
from .engine import (
|
|
14
|
+
SIX_BASE,
|
|
15
|
+
SIX_CYCLES,
|
|
16
|
+
SEVEN_BASE,
|
|
17
|
+
SEVEN_CYCLES,
|
|
18
|
+
TARGET_NUMBER_COUNT,
|
|
19
|
+
AlignmentSums,
|
|
20
|
+
CipherLibraries,
|
|
21
|
+
CompressionSums,
|
|
22
|
+
PairedPlacementSearchResult,
|
|
23
|
+
PairedRecoveryStats,
|
|
24
|
+
PlacementSearchResult,
|
|
25
|
+
ReportDatasetEvaluation,
|
|
26
|
+
ReportDifferentials,
|
|
27
|
+
ReportRecoveryStats,
|
|
28
|
+
SevenSlotReport,
|
|
29
|
+
SlotInconsistency,
|
|
30
|
+
SlotReport,
|
|
31
|
+
TraversalPlan,
|
|
32
|
+
accumulate_alignments,
|
|
33
|
+
analyze_paired_report,
|
|
34
|
+
build_cipher_libraries,
|
|
35
|
+
build_traversal_plan,
|
|
36
|
+
compress_sums,
|
|
37
|
+
decode_paired_report,
|
|
38
|
+
decode_text_file,
|
|
39
|
+
encode_text_file,
|
|
40
|
+
evaluate_paired_recovery,
|
|
41
|
+
evaluate_report_dataset,
|
|
42
|
+
evaluate_report_uniqueness,
|
|
43
|
+
moving_zero_changes,
|
|
44
|
+
multiplier_cycles,
|
|
45
|
+
ordered_alignment_report,
|
|
46
|
+
paired_alignment_report,
|
|
47
|
+
read_report_file,
|
|
48
|
+
rotations,
|
|
49
|
+
serialize_paired_report,
|
|
50
|
+
slot_averages,
|
|
51
|
+
solve_paired_report,
|
|
52
|
+
solve_paired_report_file,
|
|
53
|
+
solve_stream_report,
|
|
54
|
+
sums_payload,
|
|
55
|
+
target_relative_zero,
|
|
56
|
+
)
|
|
57
|
+
|
|
58
|
+
__all__ = [
|
|
59
|
+
"ALPHA_CIPHER_IDS",
|
|
60
|
+
"DIGIT_SPECIAL",
|
|
61
|
+
"KEYBOARD_CIPHER_LIBRARIES",
|
|
62
|
+
"LETTER_PUNCTUATION",
|
|
63
|
+
"NUMERIC_CIPHER_IDS",
|
|
64
|
+
"SLOTS_PER_CIPHER",
|
|
65
|
+
"SLOTS_PER_LIBRARY",
|
|
66
|
+
"TOTAL_PAIR_SLOTS",
|
|
67
|
+
"KeyboardCipherLibraries",
|
|
68
|
+
"build_keyboard_cipher_libraries",
|
|
69
|
+
"SIX_BASE",
|
|
70
|
+
"SIX_CYCLES",
|
|
71
|
+
"SEVEN_BASE",
|
|
72
|
+
"SEVEN_CYCLES",
|
|
73
|
+
"TARGET_NUMBER_COUNT",
|
|
74
|
+
"AlignmentSums",
|
|
75
|
+
"CipherLibraries",
|
|
76
|
+
"CompressionSums",
|
|
77
|
+
"PairedPlacementSearchResult",
|
|
78
|
+
"PairedRecoveryStats",
|
|
79
|
+
"PlacementSearchResult",
|
|
80
|
+
"ReportDatasetEvaluation",
|
|
81
|
+
"ReportDifferentials",
|
|
82
|
+
"ReportRecoveryStats",
|
|
83
|
+
"SevenSlotReport",
|
|
84
|
+
"SlotInconsistency",
|
|
85
|
+
"SlotReport",
|
|
86
|
+
"TraversalPlan",
|
|
87
|
+
"accumulate_alignments",
|
|
88
|
+
"analyze_paired_report",
|
|
89
|
+
"build_cipher_libraries",
|
|
90
|
+
"build_traversal_plan",
|
|
91
|
+
"compress_sums",
|
|
92
|
+
"decode_paired_report",
|
|
93
|
+
"decode_text_file",
|
|
94
|
+
"encode_text_file",
|
|
95
|
+
"evaluate_paired_recovery",
|
|
96
|
+
"evaluate_report_dataset",
|
|
97
|
+
"evaluate_report_uniqueness",
|
|
98
|
+
"moving_zero_changes",
|
|
99
|
+
"multiplier_cycles",
|
|
100
|
+
"ordered_alignment_report",
|
|
101
|
+
"paired_alignment_report",
|
|
102
|
+
"read_report_file",
|
|
103
|
+
"rotations",
|
|
104
|
+
"serialize_paired_report",
|
|
105
|
+
"slot_averages",
|
|
106
|
+
"solve_paired_report",
|
|
107
|
+
"solve_paired_report_file",
|
|
108
|
+
"solve_stream_report",
|
|
109
|
+
"sums_payload",
|
|
110
|
+
"target_relative_zero",
|
|
111
|
+
]
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
"""Two distinct six-group keyboard cipher libraries.
|
|
2
|
+
|
|
3
|
+
Cipher IDs 1-6 cover letters and punctuation. Cipher IDs a-f cover digits,
|
|
4
|
+
remaining special characters, and common text controls. Each symbol maps to a
|
|
5
|
+
(cipher ID, position within that ID's ordered string) pair.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from dataclasses import dataclass
|
|
11
|
+
from string import ascii_letters, digits, punctuation
|
|
12
|
+
from typing import Dict, Mapping, Tuple, Union
|
|
13
|
+
|
|
14
|
+
CipherId = Union[int, str]
|
|
15
|
+
|
|
16
|
+
LETTER_PUNCTUATION = ascii_letters + ".,!?:;'\"-()[]{}"
|
|
17
|
+
DIGIT_SPECIAL = digits + "@#$%^&*+=_/< >\\|~`".replace(" ", "") + " \t\n\r"
|
|
18
|
+
NUMERIC_CIPHER_IDS: Tuple[int, ...] = (1, 2, 3, 4, 5, 6)
|
|
19
|
+
ALPHA_CIPHER_IDS: Tuple[str, ...] = ("a", "b", "c", "d", "e", "f")
|
|
20
|
+
SLOTS_PER_CIPHER = 14
|
|
21
|
+
SLOTS_PER_LIBRARY = 6 * SLOTS_PER_CIPHER
|
|
22
|
+
TOTAL_PAIR_SLOTS = 2 * SLOTS_PER_LIBRARY
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _groups(chars: str, ids: Tuple[CipherId, ...]) -> Dict[CipherId, str]:
|
|
26
|
+
"""Split an ordered character set into six stable, disjoint strings."""
|
|
27
|
+
if len(set(chars)) != len(chars):
|
|
28
|
+
raise ValueError("library character sequence contains duplicates")
|
|
29
|
+
return {
|
|
30
|
+
group_id: "".join(chars[index] for index in range(len(chars)) if index % 6 == group_index)
|
|
31
|
+
for group_index, group_id in enumerate(ids)
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
@dataclass(frozen=True)
|
|
36
|
+
class KeyboardCipherLibraries:
|
|
37
|
+
"""Separate numeric-ID and letter-ID libraries with reversible positions."""
|
|
38
|
+
|
|
39
|
+
numeric_ciphers: Mapping[int, str]
|
|
40
|
+
alpha_ciphers: Mapping[str, str]
|
|
41
|
+
|
|
42
|
+
@property
|
|
43
|
+
def capacity(self) -> int:
|
|
44
|
+
"""Return total pair-slot capacity across both independent libraries."""
|
|
45
|
+
return TOTAL_PAIR_SLOTS
|
|
46
|
+
|
|
47
|
+
@property
|
|
48
|
+
def library_capacities(self) -> Tuple[int, int]:
|
|
49
|
+
"""Return numeric-library and letter-library slot capacities."""
|
|
50
|
+
return SLOTS_PER_LIBRARY, SLOTS_PER_LIBRARY
|
|
51
|
+
|
|
52
|
+
@property
|
|
53
|
+
def character_codes(self) -> Mapping[str, Tuple[CipherId, int]]:
|
|
54
|
+
codes: Dict[str, Tuple[CipherId, int]] = {}
|
|
55
|
+
for cipher_id, chars in self.numeric_ciphers.items():
|
|
56
|
+
for position, char in enumerate(chars):
|
|
57
|
+
codes[char] = (cipher_id, position)
|
|
58
|
+
for cipher_id, chars in self.alpha_ciphers.items():
|
|
59
|
+
for position, char in enumerate(chars):
|
|
60
|
+
if char in codes:
|
|
61
|
+
raise ValueError(f"character occurs in both libraries: {char!r}")
|
|
62
|
+
codes[char] = (cipher_id, position)
|
|
63
|
+
return codes
|
|
64
|
+
|
|
65
|
+
def validate(self) -> None:
|
|
66
|
+
if tuple(self.numeric_ciphers) != NUMERIC_CIPHER_IDS:
|
|
67
|
+
raise ValueError("numeric cipher IDs must be ordered 1 through 6")
|
|
68
|
+
if tuple(self.alpha_ciphers) != ALPHA_CIPHER_IDS:
|
|
69
|
+
raise ValueError("letter cipher IDs must be ordered a through f")
|
|
70
|
+
codes = self.character_codes
|
|
71
|
+
for cipher_id in NUMERIC_CIPHER_IDS:
|
|
72
|
+
if not self.numeric_ciphers[cipher_id]:
|
|
73
|
+
raise ValueError(f"numeric cipher {cipher_id} is empty")
|
|
74
|
+
if len(self.numeric_ciphers[cipher_id]) > SLOTS_PER_CIPHER:
|
|
75
|
+
raise ValueError(f"numeric cipher {cipher_id} exceeds {SLOTS_PER_CIPHER} slots")
|
|
76
|
+
for cipher_id in ALPHA_CIPHER_IDS:
|
|
77
|
+
if not self.alpha_ciphers[cipher_id]:
|
|
78
|
+
raise ValueError(f"letter cipher {cipher_id} is empty")
|
|
79
|
+
if len(self.alpha_ciphers[cipher_id]) > SLOTS_PER_CIPHER:
|
|
80
|
+
raise ValueError(f"letter cipher {cipher_id} exceeds {SLOTS_PER_CIPHER} slots")
|
|
81
|
+
expected = set(LETTER_PUNCTUATION) | set(DIGIT_SPECIAL)
|
|
82
|
+
if set(codes) != expected:
|
|
83
|
+
missing, extra = expected - set(codes), set(codes) - expected
|
|
84
|
+
raise ValueError(f"keyboard coverage mismatch; missing={missing}, extra={extra}")
|
|
85
|
+
|
|
86
|
+
def encode(self, text: str) -> Tuple[Tuple[CipherId, ...], Tuple[int, ...]]:
|
|
87
|
+
"""Encode text into parallel cipher IDs and within-cipher positions."""
|
|
88
|
+
codes = self.character_codes
|
|
89
|
+
try:
|
|
90
|
+
pairs = [codes[char] for char in text]
|
|
91
|
+
except KeyError as exc:
|
|
92
|
+
raise ValueError(f"character is outside the defined keyboard: {exc.args[0]!r}") from exc
|
|
93
|
+
return tuple(pair[0] for pair in pairs), tuple(pair[1] for pair in pairs)
|
|
94
|
+
|
|
95
|
+
def decode(self, cipher_ids: Tuple[CipherId, ...], positions: Tuple[int, ...]) -> str:
|
|
96
|
+
"""Rebuild text from parallel group identifiers and group positions."""
|
|
97
|
+
if len(cipher_ids) != len(positions):
|
|
98
|
+
raise ValueError("cipher ID and position streams must have equal length")
|
|
99
|
+
reverse = {
|
|
100
|
+
(cipher_id, position): char
|
|
101
|
+
for char, (cipher_id, position) in self.character_codes.items()
|
|
102
|
+
}
|
|
103
|
+
try:
|
|
104
|
+
return "".join(reverse[(cipher_id, position)] for cipher_id, position in zip(cipher_ids, positions))
|
|
105
|
+
except KeyError as exc:
|
|
106
|
+
raise ValueError(f"unknown cipher/position pair: {exc.args[0]!r}") from exc
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def build_keyboard_cipher_libraries() -> KeyboardCipherLibraries:
|
|
110
|
+
"""Return fixed 1-6 letter/punctuation and a-f digit/special libraries."""
|
|
111
|
+
# The order is part of the format: changing it changes character positions.
|
|
112
|
+
result = KeyboardCipherLibraries(
|
|
113
|
+
numeric_ciphers=_groups(LETTER_PUNCTUATION, NUMERIC_CIPHER_IDS),
|
|
114
|
+
alpha_ciphers=_groups(DIGIT_SPECIAL, ALPHA_CIPHER_IDS),
|
|
115
|
+
)
|
|
116
|
+
result.validate()
|
|
117
|
+
return result
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
KEYBOARD_CIPHER_LIBRARIES = build_keyboard_cipher_libraries()
|
|
@@ -0,0 +1,895 @@
|
|
|
1
|
+
"""Cyclic alignment reports and report-only slot differential analysis."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass, replace
|
|
6
|
+
from typing import Dict, List, Mapping, Sequence, Tuple
|
|
7
|
+
|
|
8
|
+
SIX_BASE: Tuple[int, ...] = (1, 4, 2, 8, 5, 7)
|
|
9
|
+
SEVEN_BASE: Tuple[int, ...] = (0, 1, 4, 2, 8, 5, 7)
|
|
10
|
+
TARGET_NUMBER_COUNT = 156
|
|
11
|
+
DEFAULT_KEYBOARD = (
|
|
12
|
+
"abcdefghijklmnopqrstuvwxyz"
|
|
13
|
+
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
|
|
14
|
+
"0123456789"
|
|
15
|
+
" .,!?;:'\"-()[]{}@#$%^&*+=_/<>\\|~`"
|
|
16
|
+
"\n\t\r"
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def rotations(values: Sequence[int]) -> Tuple[Tuple[int, ...], ...]:
|
|
21
|
+
cycle = tuple(values)
|
|
22
|
+
if not cycle:
|
|
23
|
+
raise ValueError("cycle must not be empty")
|
|
24
|
+
if len(set(cycle)) != len(cycle):
|
|
25
|
+
raise ValueError("cycle values must be unique")
|
|
26
|
+
return tuple(cycle[i:] + cycle[:i] for i in range(len(cycle)))
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def multiplier_cycles() -> Tuple[Tuple[int, ...], ...]:
|
|
30
|
+
return tuple(tuple(int(ch) for ch in str(142857 * k)) for k in range(1, 7))
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
SIX_CYCLES = multiplier_cycles()
|
|
34
|
+
SEVEN_CYCLES = rotations(SEVEN_BASE)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
@dataclass(frozen=True)
|
|
38
|
+
class AlignmentSums:
|
|
39
|
+
cycle_length: int
|
|
40
|
+
slot_order: Tuple[int, ...]
|
|
41
|
+
matrix: Tuple[Tuple[int, ...], ...]
|
|
42
|
+
opportunities: Tuple[Tuple[int, ...], ...]
|
|
43
|
+
total_matches: int
|
|
44
|
+
|
|
45
|
+
def as_lists(self) -> List[List[int]]:
|
|
46
|
+
return [list(row) for row in self.matrix]
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
@dataclass(frozen=True)
|
|
50
|
+
class CompressionSums:
|
|
51
|
+
six_by_six: AlignmentSums
|
|
52
|
+
seven_by_seven: AlignmentSums
|
|
53
|
+
input_length: int
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
@dataclass(frozen=True)
|
|
57
|
+
class CipherLibraries:
|
|
58
|
+
symbol_cipher_ids: Mapping[str, int]
|
|
59
|
+
cipher_string: Mapping[int, str]
|
|
60
|
+
cipher_symbol_values: Mapping[str, int]
|
|
61
|
+
|
|
62
|
+
def validate(self) -> None:
|
|
63
|
+
if not self.symbol_cipher_ids or not self.cipher_string:
|
|
64
|
+
raise ValueError("both cipher libraries must be non-empty")
|
|
65
|
+
for symbol, cipher_id in self.symbol_cipher_ids.items():
|
|
66
|
+
if len(symbol) != 1:
|
|
67
|
+
raise ValueError(f"symbol key must be one character: {symbol!r}")
|
|
68
|
+
if cipher_id not in self.cipher_string:
|
|
69
|
+
raise ValueError(f"cipher group {cipher_id} has no cipher string")
|
|
70
|
+
if symbol not in self.cipher_string[cipher_id]:
|
|
71
|
+
raise ValueError(f"{symbol!r} is not in cipher string {cipher_id}")
|
|
72
|
+
if symbol not in self.cipher_symbol_values:
|
|
73
|
+
raise ValueError(f"{symbol!r} has no cyclic value")
|
|
74
|
+
for cipher_id, group in self.cipher_string.items():
|
|
75
|
+
if len(set(group)) != len(group):
|
|
76
|
+
raise ValueError(f"cipher string {cipher_id} contains duplicate symbols")
|
|
77
|
+
pairs = [(cid, self.cipher_symbol_values[s]) for s, cid in self.symbol_cipher_ids.items()]
|
|
78
|
+
if len(set(pairs)) != len(pairs):
|
|
79
|
+
raise ValueError("cipher/cyclic pairs must uniquely identify symbols")
|
|
80
|
+
|
|
81
|
+
def encode(self, text: str) -> Tuple[Tuple[int, ...], Tuple[int, ...]]:
|
|
82
|
+
self.validate()
|
|
83
|
+
ids, vals = [], []
|
|
84
|
+
for symbol in text:
|
|
85
|
+
if symbol not in self.symbol_cipher_ids:
|
|
86
|
+
raise ValueError(f"symbol has no cipher mapping: {symbol!r}")
|
|
87
|
+
ids.append(self.symbol_cipher_ids[symbol])
|
|
88
|
+
vals.append(self.cipher_symbol_values[symbol])
|
|
89
|
+
return tuple(ids), tuple(vals)
|
|
90
|
+
|
|
91
|
+
def decode(self, cipher_ids: Sequence[int], cyclic_values: Sequence[int]) -> str:
|
|
92
|
+
self.validate()
|
|
93
|
+
if len(cipher_ids) != len(cyclic_values):
|
|
94
|
+
raise ValueError("parallel cipher and cyclic streams must have equal length")
|
|
95
|
+
reverse = {
|
|
96
|
+
(cid, self.cipher_symbol_values[symbol]): symbol
|
|
97
|
+
for symbol, cid in self.symbol_cipher_ids.items()
|
|
98
|
+
}
|
|
99
|
+
try:
|
|
100
|
+
return "".join(reverse[pair] for pair in zip(cipher_ids, cyclic_values))
|
|
101
|
+
except KeyError as exc:
|
|
102
|
+
raise ValueError(f"unknown cipher/cyclic pair: {exc.args[0]!r}") from exc
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def build_cipher_libraries(
|
|
106
|
+
keyboard: str = DEFAULT_KEYBOARD,
|
|
107
|
+
symbol_cipher_ids: Mapping[str, int] | None = None,
|
|
108
|
+
cipher_string: Mapping[int, str] | None = None,
|
|
109
|
+
cipher_symbol_values: Mapping[str, int] | None = None,
|
|
110
|
+
) -> CipherLibraries:
|
|
111
|
+
symbols = tuple(keyboard)
|
|
112
|
+
if len(set(symbols)) != len(symbols):
|
|
113
|
+
raise ValueError("keyboard symbols must be unique")
|
|
114
|
+
if symbol_cipher_ids is None:
|
|
115
|
+
symbol_cipher_ids = {s: i % 9 + 1 for i, s in enumerate(symbols)}
|
|
116
|
+
if cipher_string is None:
|
|
117
|
+
grouped: Dict[int, List[str]] = {}
|
|
118
|
+
for symbol, cid in symbol_cipher_ids.items():
|
|
119
|
+
grouped.setdefault(cid, []).append(symbol)
|
|
120
|
+
cipher_string = {cid: "".join(group) for cid, group in grouped.items()}
|
|
121
|
+
if cipher_symbol_values is None:
|
|
122
|
+
cipher_symbol_values = {
|
|
123
|
+
symbol: SIX_BASE[i % len(SIX_BASE)]
|
|
124
|
+
for group in cipher_string.values()
|
|
125
|
+
for i, symbol in enumerate(group)
|
|
126
|
+
}
|
|
127
|
+
result = CipherLibraries(dict(symbol_cipher_ids), dict(cipher_string), dict(cipher_symbol_values))
|
|
128
|
+
result.validate()
|
|
129
|
+
return result
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def serialize_paired_report(
|
|
133
|
+
cyclic_stream: str, cipher_stream: str, report_path: str
|
|
134
|
+
) -> int:
|
|
135
|
+
"""Write a paired 196-number report for two digit streams as compact JSON.
|
|
136
|
+
|
|
137
|
+
This is report serialization only. It does not encode arbitrary text or
|
|
138
|
+
claim reversible file reconstruction from aggregate sums.
|
|
139
|
+
"""
|
|
140
|
+
import json
|
|
141
|
+
from pathlib import Path
|
|
142
|
+
|
|
143
|
+
report = paired_alignment_report(cyclic_stream, cipher_stream)
|
|
144
|
+
with Path(report_path).open("w", encoding="utf-8", newline="") as stream:
|
|
145
|
+
json.dump(report, stream, separators=(",", ":"))
|
|
146
|
+
return Path(report_path).stat().st_size
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def read_report_file(report_path: str):
|
|
150
|
+
"""Read a serialized paired alignment report for decoder analysis."""
|
|
151
|
+
import json
|
|
152
|
+
from pathlib import Path
|
|
153
|
+
|
|
154
|
+
report = json.loads(Path(report_path).read_text(encoding="utf-8"))
|
|
155
|
+
if not isinstance(report, list) or len(report) != 2:
|
|
156
|
+
raise ValueError("serialized report must contain two parallel reports")
|
|
157
|
+
return report
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def encode_text_file(source_path: str, encoded_path: str, libraries: CipherLibraries) -> int:
|
|
161
|
+
import json
|
|
162
|
+
from pathlib import Path
|
|
163
|
+
|
|
164
|
+
with Path(source_path).open("r", encoding="utf-8", newline="") as stream:
|
|
165
|
+
text = stream.read()
|
|
166
|
+
ids, vals = libraries.encode(text)
|
|
167
|
+
with Path(encoded_path).open("w", encoding="utf-8", newline="") as stream:
|
|
168
|
+
json.dump([list(ids), list(vals)], stream, separators=(",", ":"))
|
|
169
|
+
return len(text)
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def decode_text_file(encoded_path: str, output_path: str, libraries: CipherLibraries) -> int:
|
|
173
|
+
import json
|
|
174
|
+
from pathlib import Path
|
|
175
|
+
|
|
176
|
+
payload = json.loads(Path(encoded_path).read_text(encoding="utf-8"))
|
|
177
|
+
if not isinstance(payload, list) or len(payload) != 2 or not all(isinstance(x, list) for x in payload):
|
|
178
|
+
raise ValueError("encoded text must contain exactly two parallel arrays")
|
|
179
|
+
text = libraries.decode(payload[0], payload[1])
|
|
180
|
+
with Path(output_path).open("w", encoding="utf-8", newline="") as stream:
|
|
181
|
+
stream.write(text)
|
|
182
|
+
return len(text)
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def _parse_symbols(data: str) -> Tuple[int, ...]:
|
|
186
|
+
if not isinstance(data, str):
|
|
187
|
+
raise TypeError("data must be a string of decimal digits")
|
|
188
|
+
if any(ch not in "0123456789" for ch in data):
|
|
189
|
+
raise ValueError("data must contain only decimal digits 0 through 9")
|
|
190
|
+
return tuple(map(int, data))
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def accumulate_alignments(data: str, cycles: Sequence[Sequence[int]], slot_order: Sequence[int]) -> AlignmentSums:
|
|
194
|
+
symbols = _parse_symbols(data)
|
|
195
|
+
rows, slots = tuple(map(tuple, cycles)), tuple(slot_order)
|
|
196
|
+
if not rows or not slots:
|
|
197
|
+
raise ValueError("cycles and slot_order must not be empty")
|
|
198
|
+
width = len(slots)
|
|
199
|
+
if len(rows) != width or any(len(row) != width for row in rows):
|
|
200
|
+
raise ValueError("expected a square N-phase system with N-wide cycles")
|
|
201
|
+
if len(set(slots)) != width:
|
|
202
|
+
raise ValueError("slot_order values must be unique")
|
|
203
|
+
slot_index = {v: i for i, v in enumerate(slots)}
|
|
204
|
+
if any(v not in slot_index for row in rows for v in row):
|
|
205
|
+
raise ValueError("every cycle value must appear in slot_order")
|
|
206
|
+
matrix, opportunities, matches = [[0] * width for _ in rows], [[0] * width for _ in rows], 0
|
|
207
|
+
for phase, row in enumerate(rows):
|
|
208
|
+
for pos, digit in enumerate(symbols):
|
|
209
|
+
expected = row[pos % width]
|
|
210
|
+
col = slot_index[expected]
|
|
211
|
+
opportunities[phase][col] += 1
|
|
212
|
+
if digit == expected:
|
|
213
|
+
matrix[phase][col] += 1
|
|
214
|
+
matches += 1
|
|
215
|
+
return AlignmentSums(width, slots, tuple(map(tuple, matrix)), tuple(map(tuple, opportunities)), matches)
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
def slot_averages(sums: AlignmentSums) -> Tuple[float, ...]:
|
|
219
|
+
return tuple(
|
|
220
|
+
sum(row[col] for row in sums.matrix) / sum(row[col] for row in sums.opportunities)
|
|
221
|
+
if sum(row[col] for row in sums.opportunities) else 0.0
|
|
222
|
+
for col in range(len(sums.slot_order))
|
|
223
|
+
)
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
def target_relative_zero(observed_average: float, target_average: float) -> float:
|
|
227
|
+
return target_average - observed_average
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
def moving_zero_changes(observed_averages: Sequence[float], target_averages: Sequence[float]) -> Tuple[float, ...]:
|
|
231
|
+
if len(observed_averages) != len(target_averages):
|
|
232
|
+
raise ValueError("observed and target average sequences must match")
|
|
233
|
+
missing = tuple(t - o for o, t in zip(observed_averages, target_averages))
|
|
234
|
+
return tuple(missing[i] - missing[i - 1] for i in range(1, len(missing)))
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
def compress_sums(data: str) -> CompressionSums:
|
|
238
|
+
symbols = _parse_symbols(data)
|
|
239
|
+
normalized = "".join(map(str, symbols))
|
|
240
|
+
return CompressionSums(
|
|
241
|
+
accumulate_alignments(normalized, SIX_CYCLES, SIX_BASE),
|
|
242
|
+
accumulate_alignments(normalized, SEVEN_CYCLES, SEVEN_BASE),
|
|
243
|
+
len(symbols),
|
|
244
|
+
)
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
@dataclass(frozen=True)
|
|
248
|
+
class PlacementSearchResult:
|
|
249
|
+
candidates: Tuple[str, ...]
|
|
250
|
+
explored_nodes: int
|
|
251
|
+
truncated: bool
|
|
252
|
+
recovered_length: int
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
def solve_stream_report(
|
|
256
|
+
stream_report,
|
|
257
|
+
max_solutions: int = 100,
|
|
258
|
+
) -> PlacementSearchResult:
|
|
259
|
+
"""Search candidate digit strings matching one six/seven stream report.
|
|
260
|
+
|
|
261
|
+
This bounded CSP solver uses only the reported per-multiplier/per-shift
|
|
262
|
+
match totals. It ignores the seven-cycle zero residual as a literal zero
|
|
263
|
+
match count, since that report field is defined as a residual. Returned
|
|
264
|
+
candidates are all proven to match the constraints unless ``truncated``
|
|
265
|
+
is true. This is practical for short streams, not yet a large-file solver.
|
|
266
|
+
"""
|
|
267
|
+
if max_solutions < 1:
|
|
268
|
+
raise ValueError("max_solutions must be positive")
|
|
269
|
+
if not isinstance(stream_report, (tuple, list)) or len(stream_report) != 2:
|
|
270
|
+
raise ValueError("stream report must contain six- and seven-cycle matrices")
|
|
271
|
+
six_rows, seven_rows = stream_report
|
|
272
|
+
if len(six_rows) != 6 or len(seven_rows) != 7:
|
|
273
|
+
raise ValueError("expected six multiplier rows and seven shift rows")
|
|
274
|
+
if any(len(row) != 7 for row in six_rows) or any(len(row) != 8 for row in seven_rows):
|
|
275
|
+
raise ValueError("report rows must include label plus slot totals")
|
|
276
|
+
if [row[0] for row in six_rows] != list(range(1, 7)) or [row[0] for row in seven_rows] != list(range(1, 8)):
|
|
277
|
+
raise ValueError("report labels must be ordered multiplier 1..6 and shift 1..7")
|
|
278
|
+
if any(isinstance(value, bool) or not isinstance(value, int) or value < 0
|
|
279
|
+
for rows in (six_rows, seven_rows) for row in rows for value in row):
|
|
280
|
+
raise ValueError("report values must be nonnegative integers")
|
|
281
|
+
|
|
282
|
+
length_candidates = {sum(row[1:]) for row in seven_rows}
|
|
283
|
+
if len(length_candidates) != 1:
|
|
284
|
+
raise ValueError("seven-shift row totals disagree on input length")
|
|
285
|
+
length = length_candidates.pop()
|
|
286
|
+
if length == 0:
|
|
287
|
+
return PlacementSearchResult(("",), 1, False, 0)
|
|
288
|
+
|
|
289
|
+
six_targets = [row[1:] for row in six_rows]
|
|
290
|
+
seven_targets = [row[1:] for row in seven_rows]
|
|
291
|
+
zero_column = SEVEN_BASE.index(0)
|
|
292
|
+
# Zero is a residual field, not an observed match counter.
|
|
293
|
+
for row in seven_targets:
|
|
294
|
+
row[zero_column] = 0
|
|
295
|
+
|
|
296
|
+
# Precompute each source position's expected symbol and corresponding slot.
|
|
297
|
+
six_expect = [[cycle[pos % 6] for pos in range(length)] for cycle in SIX_CYCLES]
|
|
298
|
+
seven_expect = [[cycle[pos % 7] for pos in range(length)] for cycle in SEVEN_CYCLES]
|
|
299
|
+
six_col = {value: idx for idx, value in enumerate(SIX_BASE)}
|
|
300
|
+
seven_col = {value: idx for idx, value in enumerate(SEVEN_BASE)}
|
|
301
|
+
|
|
302
|
+
# Remaining-availability upper bounds prune impossible partial assignments.
|
|
303
|
+
future_six = [[[0] * 6 for _ in range(6)] for _ in range(length + 1)]
|
|
304
|
+
future_seven = [[[0] * 7 for _ in range(7)] for _ in range(length + 1)]
|
|
305
|
+
for pos in range(length - 1, -1, -1):
|
|
306
|
+
future_six[pos] = [row[:] for row in future_six[pos + 1]]
|
|
307
|
+
future_seven[pos] = [row[:] for row in future_seven[pos + 1]]
|
|
308
|
+
for phase in range(6):
|
|
309
|
+
future_six[pos][phase][six_col[six_expect[phase][pos]]] += 1
|
|
310
|
+
for phase in range(7):
|
|
311
|
+
value = seven_expect[phase][pos]
|
|
312
|
+
if value != 0:
|
|
313
|
+
future_seven[pos][phase][seven_col[value]] += 1
|
|
314
|
+
|
|
315
|
+
remaining_six = [row[:] for row in six_targets]
|
|
316
|
+
remaining_seven = [row[:] for row in seven_targets]
|
|
317
|
+
candidates: List[str] = []
|
|
318
|
+
prefix: List[str] = []
|
|
319
|
+
explored = 0
|
|
320
|
+
truncated = False
|
|
321
|
+
alphabet = tuple("0123456789")
|
|
322
|
+
|
|
323
|
+
def feasible(next_pos: int) -> bool:
|
|
324
|
+
for phase in range(6):
|
|
325
|
+
for col in range(6):
|
|
326
|
+
rem = remaining_six[phase][col]
|
|
327
|
+
if rem < 0 or rem > future_six[next_pos][phase][col]:
|
|
328
|
+
return False
|
|
329
|
+
for phase in range(7):
|
|
330
|
+
for col, value in enumerate(SEVEN_BASE):
|
|
331
|
+
if value == 0:
|
|
332
|
+
continue
|
|
333
|
+
rem = remaining_seven[phase][col]
|
|
334
|
+
if rem < 0 or rem > future_seven[next_pos][phase][col]:
|
|
335
|
+
return False
|
|
336
|
+
return True
|
|
337
|
+
|
|
338
|
+
def visit(pos: int) -> None:
|
|
339
|
+
nonlocal explored, truncated
|
|
340
|
+
if len(candidates) >= max_solutions:
|
|
341
|
+
truncated = True
|
|
342
|
+
return
|
|
343
|
+
explored += 1
|
|
344
|
+
if pos == length:
|
|
345
|
+
if all(value == 0 for row in remaining_six for value in row) and all(
|
|
346
|
+
value == 0 for phase, row in enumerate(remaining_seven)
|
|
347
|
+
for col, value in enumerate(row) if SEVEN_BASE[col] != 0
|
|
348
|
+
):
|
|
349
|
+
candidates.append("".join(prefix))
|
|
350
|
+
return
|
|
351
|
+
# Search most constrained, report-supported digits first. This affects
|
|
352
|
+
# candidate discovery order under caps, not the report's information.
|
|
353
|
+
ranked_digits = []
|
|
354
|
+
for digit in alphabet:
|
|
355
|
+
score = 0.0
|
|
356
|
+
for phase in range(6):
|
|
357
|
+
expected = six_expect[phase][pos]
|
|
358
|
+
if digit == expected:
|
|
359
|
+
col = six_col[expected]
|
|
360
|
+
capacity = future_six[pos][phase][col]
|
|
361
|
+
score += remaining_six[phase][col] / capacity if capacity else 0.0
|
|
362
|
+
for phase in range(7):
|
|
363
|
+
expected = seven_expect[phase][pos]
|
|
364
|
+
if expected != 0 and digit == expected:
|
|
365
|
+
col = seven_col[expected]
|
|
366
|
+
capacity = future_seven[pos][phase][col]
|
|
367
|
+
score += remaining_seven[phase][col] / capacity if capacity else 0.0
|
|
368
|
+
ranked_digits.append((score, digit))
|
|
369
|
+
ranked_digits.sort(key=lambda item: (-item[0], item[1]))
|
|
370
|
+
|
|
371
|
+
for _, char in ranked_digits:
|
|
372
|
+
digit = int(char)
|
|
373
|
+
changes_six = []
|
|
374
|
+
changes_seven = []
|
|
375
|
+
for phase in range(6):
|
|
376
|
+
expected = six_expect[phase][pos]
|
|
377
|
+
if digit == expected:
|
|
378
|
+
col = six_col[expected]
|
|
379
|
+
remaining_six[phase][col] -= 1
|
|
380
|
+
changes_six.append((phase, col))
|
|
381
|
+
for phase in range(7):
|
|
382
|
+
expected = seven_expect[phase][pos]
|
|
383
|
+
if expected != 0 and digit == expected:
|
|
384
|
+
col = seven_col[expected]
|
|
385
|
+
remaining_seven[phase][col] -= 1
|
|
386
|
+
changes_seven.append((phase, col))
|
|
387
|
+
if feasible(pos + 1):
|
|
388
|
+
prefix.append(char)
|
|
389
|
+
visit(pos + 1)
|
|
390
|
+
prefix.pop()
|
|
391
|
+
for phase, col in changes_six:
|
|
392
|
+
remaining_six[phase][col] += 1
|
|
393
|
+
for phase, col in changes_seven:
|
|
394
|
+
remaining_seven[phase][col] += 1
|
|
395
|
+
if truncated:
|
|
396
|
+
return
|
|
397
|
+
|
|
398
|
+
visit(0)
|
|
399
|
+
return PlacementSearchResult(tuple(candidates), explored, truncated, length)
|
|
400
|
+
|
|
401
|
+
|
|
402
|
+
@dataclass(frozen=True)
|
|
403
|
+
class PairedPlacementSearchResult:
|
|
404
|
+
candidate_pairs: Tuple[Tuple[str, str], ...]
|
|
405
|
+
first_stream: PlacementSearchResult
|
|
406
|
+
second_stream: PlacementSearchResult
|
|
407
|
+
truncated: bool
|
|
408
|
+
|
|
409
|
+
|
|
410
|
+
def solve_paired_report(
|
|
411
|
+
report,
|
|
412
|
+
max_solutions_per_stream: int = 100,
|
|
413
|
+
max_candidate_pairs: int = 1000,
|
|
414
|
+
) -> PairedPlacementSearchResult:
|
|
415
|
+
"""Search both numeric streams in a paired report and retain pairings.
|
|
416
|
+
|
|
417
|
+
Each stream is solved independently from its own 6x6/7x7 row totals.
|
|
418
|
+
Candidate pairs are then formed only when stream lengths agree. The result
|
|
419
|
+
preserves ambiguity; it does not pick an arbitrary pair or claim symbol
|
|
420
|
+
reconstruction. Candidate pairing itself adds no new constraints because
|
|
421
|
+
the report contains no per-position cross-stream intersections.
|
|
422
|
+
"""
|
|
423
|
+
if not isinstance(report, (tuple, list)) or len(report) != 2:
|
|
424
|
+
raise ValueError("paired report must contain exactly two streams")
|
|
425
|
+
if max_candidate_pairs < 1:
|
|
426
|
+
raise ValueError("max_candidate_pairs must be positive")
|
|
427
|
+
first = solve_stream_report(report[0], max_solutions=max_solutions_per_stream)
|
|
428
|
+
second = solve_stream_report(report[1], max_solutions=max_solutions_per_stream)
|
|
429
|
+
pairs: List[Tuple[str, str]] = []
|
|
430
|
+
truncated = first.truncated or second.truncated
|
|
431
|
+
for left in first.candidates:
|
|
432
|
+
for right in second.candidates:
|
|
433
|
+
if len(left) != len(right):
|
|
434
|
+
continue
|
|
435
|
+
if len(pairs) >= max_candidate_pairs:
|
|
436
|
+
truncated = True
|
|
437
|
+
break
|
|
438
|
+
pairs.append((left, right))
|
|
439
|
+
if len(pairs) >= max_candidate_pairs:
|
|
440
|
+
break
|
|
441
|
+
return PairedPlacementSearchResult(tuple(pairs), first, second, truncated)
|
|
442
|
+
|
|
443
|
+
|
|
444
|
+
def solve_paired_report_file(report_path: str, max_solutions_per_stream: int = 100,
|
|
445
|
+
max_candidate_pairs: int = 1000) -> PairedPlacementSearchResult:
|
|
446
|
+
"""Read a serialized report and run the paired placement search."""
|
|
447
|
+
return solve_paired_report(
|
|
448
|
+
read_report_file(report_path),
|
|
449
|
+
max_solutions_per_stream=max_solutions_per_stream,
|
|
450
|
+
max_candidate_pairs=max_candidate_pairs,
|
|
451
|
+
)
|
|
452
|
+
|
|
453
|
+
|
|
454
|
+
@dataclass(frozen=True)
|
|
455
|
+
class ReportRecoveryStats:
|
|
456
|
+
"""Empirical report uniqueness; an upper bound, not decoder accuracy."""
|
|
457
|
+
|
|
458
|
+
sample_count: int
|
|
459
|
+
distinct_report_count: int
|
|
460
|
+
collision_group_count: int
|
|
461
|
+
samples_in_collisions: int
|
|
462
|
+
unique_report_rate: float
|
|
463
|
+
exact_recovery_upper_bound: float
|
|
464
|
+
|
|
465
|
+
|
|
466
|
+
@dataclass(frozen=True)
|
|
467
|
+
class PairedRecoveryStats:
|
|
468
|
+
sample_count: int
|
|
469
|
+
source_pairs_found: int
|
|
470
|
+
unique_pair_recoveries: int
|
|
471
|
+
top_pair_matches: int
|
|
472
|
+
truncated_searches: int
|
|
473
|
+
source_pair_rate: float
|
|
474
|
+
unique_pair_rate: float
|
|
475
|
+
top_pair_rate: float
|
|
476
|
+
|
|
477
|
+
|
|
478
|
+
def evaluate_paired_recovery(
|
|
479
|
+
samples: Sequence[Tuple[str, str, str]],
|
|
480
|
+
max_solutions_per_stream: int = 100,
|
|
481
|
+
max_candidate_pairs: int = 1000,
|
|
482
|
+
) -> PairedRecoveryStats:
|
|
483
|
+
"""Measure candidate recovery on known paired numeric streams.
|
|
484
|
+
|
|
485
|
+
Each sample is ``(ground_truth_label, cyclic_digit_stream, cipher_digit_stream)``.
|
|
486
|
+
Labels are used only for counting known source pairs; the solver receives
|
|
487
|
+
only the generated 196-number report. This is not a byte/text reconstruction
|
|
488
|
+
metric until the keyboard-library-to-digit-stream bridge is defined.
|
|
489
|
+
"""
|
|
490
|
+
if not samples:
|
|
491
|
+
raise ValueError("samples must contain at least one sample triple")
|
|
492
|
+
found = unique = top = truncated = 0
|
|
493
|
+
for _label, cyclic_stream, cipher_stream in samples:
|
|
494
|
+
result = solve_paired_report(
|
|
495
|
+
paired_alignment_report(cyclic_stream, cipher_stream),
|
|
496
|
+
max_solutions_per_stream=max_solutions_per_stream,
|
|
497
|
+
max_candidate_pairs=max_candidate_pairs,
|
|
498
|
+
)
|
|
499
|
+
original_pair = (cyclic_stream, cipher_stream)
|
|
500
|
+
found += int(original_pair in result.candidate_pairs)
|
|
501
|
+
unique += int(result.candidate_pairs == (original_pair,))
|
|
502
|
+
top += int(bool(result.candidate_pairs) and result.candidate_pairs[0] == original_pair)
|
|
503
|
+
truncated += int(result.truncated)
|
|
504
|
+
count = len(samples)
|
|
505
|
+
return PairedRecoveryStats(
|
|
506
|
+
sample_count=count,
|
|
507
|
+
source_pairs_found=found,
|
|
508
|
+
unique_pair_recoveries=unique,
|
|
509
|
+
top_pair_matches=top,
|
|
510
|
+
truncated_searches=truncated,
|
|
511
|
+
source_pair_rate=found / count,
|
|
512
|
+
unique_pair_rate=unique / count,
|
|
513
|
+
top_pair_rate=top / count,
|
|
514
|
+
)
|
|
515
|
+
|
|
516
|
+
|
|
517
|
+
def evaluate_report_uniqueness(
|
|
518
|
+
samples: Sequence[Tuple[str, str, str]],
|
|
519
|
+
) -> ReportRecoveryStats:
|
|
520
|
+
"""Measure whether paired reports distinguish known source strings.
|
|
521
|
+
|
|
522
|
+
Each sample is ``(source_text, cyclic_stream, cipher_stream)``. Source text
|
|
523
|
+
is used only as held-out ground truth; report construction uses only the
|
|
524
|
+
two provided streams. A collision bounds any report-only decoder's exact
|
|
525
|
+
recovery rate on this sample set.
|
|
526
|
+
"""
|
|
527
|
+
if not samples:
|
|
528
|
+
raise ValueError("samples must contain at least one sample triple")
|
|
529
|
+
report_sources: Dict[Tuple[object, ...], set[str]] = {}
|
|
530
|
+
for source_text, cyclic_stream, cipher_stream in samples:
|
|
531
|
+
report = paired_alignment_report(cyclic_stream, cipher_stream)
|
|
532
|
+
signature = tuple(
|
|
533
|
+
tuple(tuple(row) for row in rows)
|
|
534
|
+
for stream in report
|
|
535
|
+
for rows in stream
|
|
536
|
+
)
|
|
537
|
+
report_sources.setdefault(signature, set()).add(source_text)
|
|
538
|
+
collision_groups = [sources for sources in report_sources.values() if len(sources) > 1]
|
|
539
|
+
collided_sources = set().union(*collision_groups) if collision_groups else set()
|
|
540
|
+
total = len(samples)
|
|
541
|
+
distinct = len(report_sources)
|
|
542
|
+
unique_rate = distinct / total
|
|
543
|
+
return ReportRecoveryStats(
|
|
544
|
+
sample_count=total,
|
|
545
|
+
distinct_report_count=distinct,
|
|
546
|
+
collision_group_count=len(collision_groups),
|
|
547
|
+
samples_in_collisions=sum(1 for source, _, _ in samples if source in collided_sources),
|
|
548
|
+
unique_report_rate=unique_rate,
|
|
549
|
+
exact_recovery_upper_bound=unique_rate,
|
|
550
|
+
)
|
|
551
|
+
|
|
552
|
+
|
|
553
|
+
@dataclass(frozen=True)
|
|
554
|
+
class SlotInconsistency:
|
|
555
|
+
cyclic_number: int
|
|
556
|
+
mean_shared_difference: float
|
|
557
|
+
mean_zero_compensated_change: float
|
|
558
|
+
mean_support_gap: float
|
|
559
|
+
weighted_inconsistency: float
|
|
560
|
+
|
|
561
|
+
|
|
562
|
+
@dataclass(frozen=True)
|
|
563
|
+
class ReportDatasetEvaluation:
|
|
564
|
+
sample_count: int
|
|
565
|
+
distinct_report_count: int
|
|
566
|
+
collision_group_count: int
|
|
567
|
+
samples_in_collisions: int
|
|
568
|
+
unique_report_rate: float
|
|
569
|
+
exact_recovery_upper_bound: float
|
|
570
|
+
slot_inconsistencies: Tuple[SlotInconsistency, ...]
|
|
571
|
+
|
|
572
|
+
|
|
573
|
+
def evaluate_report_dataset(
|
|
574
|
+
samples: Sequence[Tuple[str, str, str]],
|
|
575
|
+
weights: Tuple[float, float, float] = (0.4, 0.4, 0.2),
|
|
576
|
+
) -> ReportDatasetEvaluation:
|
|
577
|
+
"""Report collision rates and per-value inconsistency diagnostics.
|
|
578
|
+
|
|
579
|
+
Samples are ``(ground_truth, cyclic_stream, cipher_stream)``. Ground truth
|
|
580
|
+
is used only to identify report collisions; all inconsistency inputs come
|
|
581
|
+
from report-derived slot totals, shared differences, and zero-compensated
|
|
582
|
+
shift changes. This evaluates reports, not a complete placement decoder.
|
|
583
|
+
"""
|
|
584
|
+
if not samples:
|
|
585
|
+
raise ValueError("samples must contain at least one sample triple")
|
|
586
|
+
if len(weights) != 3 or any(weight < 0 for weight in weights) or sum(weights) <= 0:
|
|
587
|
+
raise ValueError("weights must be three nonnegative values with positive total")
|
|
588
|
+
normalized = tuple(weight / sum(weights) for weight in weights)
|
|
589
|
+
report_sources: Dict[Tuple[object, ...], set[str]] = {}
|
|
590
|
+
accum = {value: [0.0, 0.0, 0.0] for value in SIX_BASE}
|
|
591
|
+
for ground_truth, cyclic_stream, cipher_stream in samples:
|
|
592
|
+
report = paired_alignment_report(cyclic_stream, cipher_stream)
|
|
593
|
+
signature = tuple(tuple(tuple(row) for row in rows) for stream in report for rows in stream)
|
|
594
|
+
report_sources.setdefault(signature, set()).add(ground_truth)
|
|
595
|
+
decoded = decode_paired_report(report)
|
|
596
|
+
for slots in decoded.slot_reports_by_stream:
|
|
597
|
+
six_total = sum(slot.cna for slot in slots)
|
|
598
|
+
seven_total = sum(slot.shift_total for slot in slots)
|
|
599
|
+
for slot in slots:
|
|
600
|
+
six_share = slot.cna / six_total if six_total else 0.0
|
|
601
|
+
seven_share = slot.shift_total / seven_total if seven_total else 0.0
|
|
602
|
+
item = accum[slot.cyclic_number]
|
|
603
|
+
item[0] += abs(slot.shared_difference)
|
|
604
|
+
item[1] += sum(abs(delta) for delta in slot.zero_compensated_shift_change) / 7
|
|
605
|
+
item[2] += abs(six_share - seven_share)
|
|
606
|
+
collisions = [sources for sources in report_sources.values() if len(sources) > 1]
|
|
607
|
+
collided_truths = set().union(*collisions) if collisions else set()
|
|
608
|
+
sample_count = len(samples)
|
|
609
|
+
denominator = sample_count * 2
|
|
610
|
+
inconsistencies = tuple(
|
|
611
|
+
SlotInconsistency(
|
|
612
|
+
cyclic_number=value,
|
|
613
|
+
mean_shared_difference=values[0] / denominator,
|
|
614
|
+
mean_zero_compensated_change=values[1] / denominator,
|
|
615
|
+
mean_support_gap=values[2] / denominator,
|
|
616
|
+
weighted_inconsistency=sum(w * values[i] / denominator for i, w in enumerate(normalized)),
|
|
617
|
+
)
|
|
618
|
+
for value, values in accum.items()
|
|
619
|
+
)
|
|
620
|
+
unique_rate = len(report_sources) / sample_count
|
|
621
|
+
return ReportDatasetEvaluation(
|
|
622
|
+
sample_count=sample_count,
|
|
623
|
+
distinct_report_count=len(report_sources),
|
|
624
|
+
collision_group_count=len(collisions),
|
|
625
|
+
samples_in_collisions=sum(1 for truth, _, _ in samples if truth in collided_truths),
|
|
626
|
+
unique_report_rate=unique_rate,
|
|
627
|
+
exact_recovery_upper_bound=unique_rate,
|
|
628
|
+
slot_inconsistencies=inconsistencies,
|
|
629
|
+
)
|
|
630
|
+
|
|
631
|
+
|
|
632
|
+
def ordered_alignment_report(data: str) -> Tuple[List[List[int]], List[List[int]]]:
|
|
633
|
+
sums = compress_sums(data)
|
|
634
|
+
six_rows = [[m, *row] for m, row in enumerate(sums.six_by_six.matrix, 1)]
|
|
635
|
+
seven_rows = []
|
|
636
|
+
for shift, row in enumerate(sums.seven_by_seven.matrix, 1):
|
|
637
|
+
zero_col = SEVEN_BASE.index(0)
|
|
638
|
+
nonzero_hits = sum(row[column] for column, value in enumerate(SEVEN_BASE) if value != 0)
|
|
639
|
+
residual = sums.input_length - nonzero_hits
|
|
640
|
+
reported = list(row)
|
|
641
|
+
reported[zero_col] = residual
|
|
642
|
+
seven_rows.append([shift, *reported])
|
|
643
|
+
return six_rows, seven_rows
|
|
644
|
+
|
|
645
|
+
|
|
646
|
+
def paired_alignment_report(cyclic_data: str, cipher_data: str):
|
|
647
|
+
return ordered_alignment_report(cyclic_data), ordered_alignment_report(cipher_data)
|
|
648
|
+
|
|
649
|
+
|
|
650
|
+
@dataclass(frozen=True)
|
|
651
|
+
class SlotReport:
|
|
652
|
+
slot_number: int
|
|
653
|
+
cyclic_number: int
|
|
654
|
+
multiplier_counts: Tuple[int, ...]
|
|
655
|
+
multiplier_change_states: Tuple[int, ...]
|
|
656
|
+
zero_effect_total: int
|
|
657
|
+
zero_effect_average: float
|
|
658
|
+
cna: int
|
|
659
|
+
cntv: int
|
|
660
|
+
gacn_sn: int
|
|
661
|
+
slot_total_change_from_previous: int
|
|
662
|
+
shift_counts: Tuple[int, ...]
|
|
663
|
+
shift_change_states: Tuple[int, ...]
|
|
664
|
+
shift_total: int
|
|
665
|
+
shared_difference: int
|
|
666
|
+
zero_by_shift: Tuple[int, ...]
|
|
667
|
+
zero_change_by_shift: Tuple[int, ...]
|
|
668
|
+
zero_compensated_shift_change: Tuple[int, ...]
|
|
669
|
+
multiplier_support: float
|
|
670
|
+
shift_support: float
|
|
671
|
+
cross_system_agreement: float
|
|
672
|
+
zero_effect_support: float
|
|
673
|
+
heuristic_probability: float
|
|
674
|
+
|
|
675
|
+
|
|
676
|
+
@dataclass(frozen=True)
|
|
677
|
+
class SevenSlotReport:
|
|
678
|
+
slot_number: int
|
|
679
|
+
cyclic_number: int
|
|
680
|
+
shift_counts: Tuple[int, ...]
|
|
681
|
+
shift_change_states: Tuple[int, ...]
|
|
682
|
+
alignment_total: int
|
|
683
|
+
zero_residual_by_shift: Tuple[int, ...]
|
|
684
|
+
zero_change_by_shift: Tuple[int, ...]
|
|
685
|
+
zero_compensated_change_by_shift: Tuple[int, ...]
|
|
686
|
+
|
|
687
|
+
|
|
688
|
+
@dataclass(frozen=True)
|
|
689
|
+
class ReportDifferentials:
|
|
690
|
+
slot_reports_by_stream: Tuple[Tuple[SlotReport, ...], ...]
|
|
691
|
+
seven_slot_reports_by_stream: Tuple[Tuple[SevenSlotReport, ...], ...]
|
|
692
|
+
slot_totals_by_stream: Tuple[Tuple[int, ...], ...]
|
|
693
|
+
shared_property_differences_by_stream: Tuple[Tuple[int, ...], ...]
|
|
694
|
+
zero_differences_by_stream: Tuple[Tuple[int, ...], ...]
|
|
695
|
+
traversal: "TraversalPlan"
|
|
696
|
+
|
|
697
|
+
|
|
698
|
+
@dataclass(frozen=True)
|
|
699
|
+
class TraversalPlan:
|
|
700
|
+
forward_multiplier_order: Tuple[int, ...]
|
|
701
|
+
forward_shift_order: Tuple[int, ...]
|
|
702
|
+
reverse_multiplier_order: Tuple[int, ...]
|
|
703
|
+
reverse_shift_order: Tuple[int, ...]
|
|
704
|
+
forward_slot_visits: Tuple[Tuple[int, int], ...]
|
|
705
|
+
reverse_slot_visits: Tuple[Tuple[int, int], ...]
|
|
706
|
+
|
|
707
|
+
|
|
708
|
+
def build_traversal_plan() -> TraversalPlan:
|
|
709
|
+
"""Create forward left-to-right and inverted right-to-left sweep order."""
|
|
710
|
+
forward_multipliers = tuple(range(1, 7))
|
|
711
|
+
forward_shifts = tuple(range(1, 8))
|
|
712
|
+
forward_visits = tuple(
|
|
713
|
+
(multiplier, shift)
|
|
714
|
+
for multiplier in forward_multipliers
|
|
715
|
+
for shift in forward_shifts
|
|
716
|
+
)
|
|
717
|
+
reverse_visits = tuple(reversed(forward_visits))
|
|
718
|
+
return TraversalPlan(
|
|
719
|
+
forward_multiplier_order=forward_multipliers,
|
|
720
|
+
forward_shift_order=forward_shifts,
|
|
721
|
+
reverse_multiplier_order=tuple(reversed(forward_multipliers)),
|
|
722
|
+
reverse_shift_order=tuple(reversed(forward_shifts)),
|
|
723
|
+
forward_slot_visits=forward_visits,
|
|
724
|
+
reverse_slot_visits=reverse_visits,
|
|
725
|
+
)
|
|
726
|
+
|
|
727
|
+
|
|
728
|
+
def analyze_paired_report(
|
|
729
|
+
report,
|
|
730
|
+
weights: Tuple[float, float, float, float] = (0.25, 0.25, 0.25, 0.25),
|
|
731
|
+
) -> ReportDifferentials:
|
|
732
|
+
"""Derive per-value evidence scores from the report alone.
|
|
733
|
+
|
|
734
|
+
The normalized probability is a configurable heuristic over multiplier
|
|
735
|
+
support, shift support, cross-system agreement, and zero-effect support.
|
|
736
|
+
It is a relative ranking, not a calibrated probability or recovered source
|
|
737
|
+
position. The report contains no ground-truth labels for calibration.
|
|
738
|
+
"""
|
|
739
|
+
if not isinstance(report, (tuple, list)) or len(report) != 2:
|
|
740
|
+
raise ValueError("paired report must contain exactly two streams")
|
|
741
|
+
if len(weights) != 4 or any(weight < 0 for weight in weights) or sum(weights) <= 0:
|
|
742
|
+
raise ValueError("weights must be four nonnegative values with positive total")
|
|
743
|
+
weight_total = sum(weights)
|
|
744
|
+
weights = tuple(weight / weight_total for weight in weights)
|
|
745
|
+
all_slots, all_seven_slots, all_totals, all_diffs, all_zero_diffs = [], [], [], [], []
|
|
746
|
+
for stream_index, stream in enumerate(report):
|
|
747
|
+
if not isinstance(stream, (tuple, list)) or len(stream) != 2:
|
|
748
|
+
raise ValueError(f"stream {stream_index} must contain six- and seven-cycle rows")
|
|
749
|
+
six_rows, seven_rows = stream
|
|
750
|
+
if len(six_rows) != 6 or any(len(r) != 7 for r in six_rows):
|
|
751
|
+
raise ValueError(f"stream {stream_index} six-cycle rows must be 6x7 including labels")
|
|
752
|
+
if len(seven_rows) != 7 or any(len(r) != 8 for r in seven_rows):
|
|
753
|
+
raise ValueError(f"stream {stream_index} seven-cycle rows must be 7x8 including labels")
|
|
754
|
+
if [r[0] for r in six_rows] != list(range(1, 7)):
|
|
755
|
+
raise ValueError(f"stream {stream_index} multiplier labels must be 1..6")
|
|
756
|
+
if [r[0] for r in seven_rows] != list(range(1, 8)):
|
|
757
|
+
raise ValueError(f"stream {stream_index} shift labels must be 1..7")
|
|
758
|
+
if any(isinstance(v, bool) or not isinstance(v, int) or v < 0
|
|
759
|
+
for rows in (six_rows, seven_rows) for row in rows for v in row):
|
|
760
|
+
raise ValueError(f"stream {stream_index} values must be nonnegative integers")
|
|
761
|
+
|
|
762
|
+
six_counts = {value: tuple(row[1 + col] for row in six_rows)
|
|
763
|
+
for col, value in enumerate(SIX_BASE)}
|
|
764
|
+
seven_counts = {value: tuple(row[1 + SEVEN_BASE.index(value)] for row in seven_rows)
|
|
765
|
+
for value in SIX_BASE}
|
|
766
|
+
zero_col = 1 + SEVEN_BASE.index(0)
|
|
767
|
+
zero_values = tuple(row[zero_col] for row in seven_rows)
|
|
768
|
+
zero_changes = tuple(zero_values[(i + 1) % 7] - zero_values[i] for i in range(7))
|
|
769
|
+
|
|
770
|
+
six_value_totals = {value: sum(six_counts[value]) for value in SIX_BASE}
|
|
771
|
+
seven_value_totals = {value: sum(seven_counts[value]) for value in SIX_BASE}
|
|
772
|
+
six_denominator = sum(six_value_totals.values())
|
|
773
|
+
seven_denominator = sum(seven_value_totals.values())
|
|
774
|
+
zero_effects = {
|
|
775
|
+
value: sum(six_counts[value][i + 1] - six_counts[value][i] for i in range(5))
|
|
776
|
+
for value in SIX_BASE
|
|
777
|
+
}
|
|
778
|
+
zero_denominator = sum(abs(value) for value in zero_effects.values())
|
|
779
|
+
components = {}
|
|
780
|
+
for value in SIX_BASE:
|
|
781
|
+
six_support = six_value_totals[value] / six_denominator if six_denominator else 0.0
|
|
782
|
+
seven_support = seven_value_totals[value] / seven_denominator if seven_denominator else 0.0
|
|
783
|
+
agreement = max(0.0, 1.0 - abs(six_support - seven_support))
|
|
784
|
+
zero_support = (abs(zero_effects[value]) / zero_denominator
|
|
785
|
+
if zero_denominator else 1.0 / len(SIX_BASE))
|
|
786
|
+
components[value] = (six_support, seven_support, agreement, zero_support)
|
|
787
|
+
raw_scores = {
|
|
788
|
+
value: sum(w * component for w, component in zip(weights, components[value]))
|
|
789
|
+
for value in SIX_BASE
|
|
790
|
+
}
|
|
791
|
+
score_total = sum(raw_scores.values())
|
|
792
|
+
probabilities = {
|
|
793
|
+
value: raw_scores[value] / score_total if score_total else 1.0 / len(SIX_BASE)
|
|
794
|
+
for value in SIX_BASE
|
|
795
|
+
}
|
|
796
|
+
|
|
797
|
+
slot_reports = []
|
|
798
|
+
six_totals = []
|
|
799
|
+
diffs = []
|
|
800
|
+
for slot_number, value in enumerate(SIX_BASE, start=1):
|
|
801
|
+
mcounts = six_counts[value]
|
|
802
|
+
scounts = seven_counts[value]
|
|
803
|
+
cna = sum(mcounts)
|
|
804
|
+
cntv = value * cna
|
|
805
|
+
shift_total = sum(scounts)
|
|
806
|
+
difference = cna - shift_total
|
|
807
|
+
previous_slot_total = sum(six_counts[SIX_BASE[(slot_number - 2) % 6]])
|
|
808
|
+
multiplier_change_states = tuple(
|
|
809
|
+
mcounts[index + 1] - mcounts[index] for index in range(5)
|
|
810
|
+
)
|
|
811
|
+
shift_change_states = tuple(
|
|
812
|
+
scounts[index + 1] - scounts[index] for index in range(6)
|
|
813
|
+
)
|
|
814
|
+
zero_effect_total = sum(multiplier_change_states)
|
|
815
|
+
zero_effect_average = zero_effect_total / len(multiplier_change_states) if multiplier_change_states else 0.0
|
|
816
|
+
zero_compensated = tuple(
|
|
817
|
+
shift_change_states[index] - zero_changes[index]
|
|
818
|
+
for index in range(6)
|
|
819
|
+
) + (scounts[0] - scounts[6] - zero_changes[6],)
|
|
820
|
+
slot_reports.append(
|
|
821
|
+
SlotReport(
|
|
822
|
+
slot_number=slot_number,
|
|
823
|
+
cyclic_number=value,
|
|
824
|
+
multiplier_counts=mcounts,
|
|
825
|
+
multiplier_change_states=multiplier_change_states,
|
|
826
|
+
zero_effect_total=zero_effect_total,
|
|
827
|
+
zero_effect_average=zero_effect_average,
|
|
828
|
+
cna=cna,
|
|
829
|
+
cntv=cntv,
|
|
830
|
+
gacn_sn=cna,
|
|
831
|
+
slot_total_change_from_previous=cna - previous_slot_total,
|
|
832
|
+
shift_counts=scounts,
|
|
833
|
+
shift_change_states=shift_change_states,
|
|
834
|
+
shift_total=shift_total,
|
|
835
|
+
shared_difference=difference,
|
|
836
|
+
zero_by_shift=zero_values,
|
|
837
|
+
zero_change_by_shift=zero_changes,
|
|
838
|
+
zero_compensated_shift_change=zero_compensated,
|
|
839
|
+
multiplier_support=components[value][0],
|
|
840
|
+
shift_support=components[value][1],
|
|
841
|
+
cross_system_agreement=components[value][2],
|
|
842
|
+
zero_effect_support=components[value][3],
|
|
843
|
+
heuristic_probability=probabilities[value],
|
|
844
|
+
)
|
|
845
|
+
)
|
|
846
|
+
six_totals.append(cna)
|
|
847
|
+
diffs.append(difference)
|
|
848
|
+
|
|
849
|
+
seven_slot_reports = []
|
|
850
|
+
for slot_number, value in enumerate(SEVEN_BASE, start=1):
|
|
851
|
+
shift_counts = tuple(row[slot_number] for row in seven_rows)
|
|
852
|
+
shift_changes = tuple(shift_counts[(i + 1) % 7] - shift_counts[i] for i in range(7))
|
|
853
|
+
compensated_changes = tuple(
|
|
854
|
+
shift_changes[i] - zero_changes[i] for i in range(7)
|
|
855
|
+
)
|
|
856
|
+
seven_slot_reports.append(
|
|
857
|
+
SevenSlotReport(
|
|
858
|
+
slot_number=slot_number,
|
|
859
|
+
cyclic_number=value,
|
|
860
|
+
shift_counts=shift_counts,
|
|
861
|
+
shift_change_states=shift_changes,
|
|
862
|
+
alignment_total=sum(shift_counts),
|
|
863
|
+
zero_residual_by_shift=zero_values,
|
|
864
|
+
zero_change_by_shift=zero_changes,
|
|
865
|
+
zero_compensated_change_by_shift=compensated_changes,
|
|
866
|
+
)
|
|
867
|
+
)
|
|
868
|
+
|
|
869
|
+
seven_totals = tuple(sum(row[1 + c] for row in seven_rows) for c in range(7))
|
|
870
|
+
all_slots.append(tuple(slot_reports))
|
|
871
|
+
all_seven_slots.append(tuple(seven_slot_reports))
|
|
872
|
+
all_totals.append(tuple(six_totals) + seven_totals)
|
|
873
|
+
all_diffs.append(tuple(diffs))
|
|
874
|
+
all_zero_diffs.append(zero_changes)
|
|
875
|
+
return ReportDifferentials(
|
|
876
|
+
tuple(all_slots), tuple(all_seven_slots), tuple(all_totals),
|
|
877
|
+
tuple(all_diffs), tuple(all_zero_diffs), build_traversal_plan()
|
|
878
|
+
)
|
|
879
|
+
|
|
880
|
+
|
|
881
|
+
def decode_paired_report(
|
|
882
|
+
report,
|
|
883
|
+
weights: Tuple[float, float, float, float] = (0.25, 0.25, 0.25, 0.25),
|
|
884
|
+
) -> ReportDifferentials:
|
|
885
|
+
"""Derive ranked slot evidence from the report, not source input.
|
|
886
|
+
|
|
887
|
+
Probabilities are heuristic rankings, not guarantees of placement or
|
|
888
|
+
calibrated statistical confidence.
|
|
889
|
+
"""
|
|
890
|
+
return analyze_paired_report(report, weights=weights)
|
|
891
|
+
|
|
892
|
+
|
|
893
|
+
def sums_payload(data: str) -> Tuple[List[List[int]], List[List[int]]]:
|
|
894
|
+
result = compress_sums(data)
|
|
895
|
+
return result.six_by_six.as_lists(), result.seven_by_seven.as_lists()
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
cyclic_constraint_engine/__init__.py,sha256=1Y91u0cT0yltZoMohzMAoPU7nbD6a3WFEoUJKaCFNDI,2677
|
|
2
|
+
cyclic_constraint_engine/cipher_libraries.py,sha256=I92e27YDmCm67_hc70vMv2qhjst_OxB8MHM-2Pm7_ds,5412
|
|
3
|
+
cyclic_constraint_engine/engine.py,sha256=QE-xIkpu94ltYLXJ646k26ZMGJffabzC5FuA3SpklPo,38091
|
|
4
|
+
cyclic_constraint_engine-0.1.0.dist-info/METADATA,sha256=yxzuuNf-dcRC2pzWeAcyEfNskWM5PeKLCQtv5VYbynI,164
|
|
5
|
+
cyclic_constraint_engine-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
6
|
+
cyclic_constraint_engine-0.1.0.dist-info/top_level.txt,sha256=RVw17SAco_maArlAwidWEfW3_tY-OiSwPSQsuJyqa7M,25
|
|
7
|
+
cyclic_constraint_engine-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
cyclic_constraint_engine
|