File size: 7,517 Bytes
c05989c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
"""Order-Selective Erasure Calculus (OSEC), finite reference implementation.

Only integer bit masks and exact Boolean operations are used.  An action never
creates a token.  The universal/permutation theorems concern distinct-action
words; this implementation rejects repeated actions in its protocol runner.
The erasers themselves are defined on every subset, including off-protocol ones.
"""
from __future__ import annotations
from dataclasses import dataclass
from itertools import combinations, permutations
from typing import Iterable, Iterator, Sequence


def sign(word: Sequence[int]) -> int:
    """Sign of the relative ordering of distinct, comparable labels."""
    if len(set(word)) != len(word):
        raise ValueError("Permutation labels must be distinct.")
    return -1 if sum(a > b for k, a in enumerate(word) for b in word[k+1:]) % 2 else 1


def parity_combine(left: tuple[bool, bool], right: tuple[bool, bool]) -> tuple[bool, bool]:
    """Dual-rail XOR using AND/OR only. Rails mean 'even/odd is possible'."""
    e, o = left
    f, p = right
    return (e and f) or (o and p), (e and p) or (o and f)


def parity_reduce(rails: Sequence[tuple[bool, bool]]) -> tuple[bool, bool]:
    """Balanced Boolean circuit; 6(q-1) binary gates for q >= 1 pairs."""
    if not rails:
        return True, False
    level = list(rails)
    while len(level) > 1:
        nxt = [parity_combine(level[j], level[j+1]) for j in range(0, len(level)-1, 2)]
        if len(level) % 2:
            nxt.append(level[-1])
        level = nxt
    return level[0]


@dataclass(frozen=True)
class ErasureSystem:
    """m independent n-label blocks. Each block has n markers and n(n-1) rails."""
    n: int = 3
    blocks: int = 1

    def __post_init__(self) -> None:
        if not isinstance(self.n, int) or isinstance(self.n, bool) or self.n < 2:
            raise ValueError("n must be an integer >= 2.")
        if not isinstance(self.blocks, int) or isinstance(self.blocks, bool) or self.blocks < 1:
            raise ValueError("blocks must be an integer >= 1.")

    @property
    def cells(self) -> int:
        return self.blocks * self.n * self.n

    @property
    def action_count(self) -> int:
        return self.blocks * self.n

    @property
    def pair_count(self) -> int:
        return self.blocks * self.n * (self.n-1) // 2

    @property
    def full(self) -> int:
        return (1 << self.cells) - 1

    @property
    def actions(self) -> tuple[tuple[int, int], ...]:
        return tuple((b, i) for b in range(self.blocks) for i in range(self.n))

    def _check_label(self, b: int, i: int) -> None:
        if not 0 <= b < self.blocks or not 0 <= i < self.n:
            raise ValueError("Invalid block or action label.")

    def marker(self, b: int, i: int) -> int:
        self._check_label(b, i)
        return 1 << (b*self.n*self.n + i)

    def rail(self, b: int, i: int, j: int) -> int:
        self._check_label(b, i)
        self._check_label(b, j)
        if i == j:
            raise ValueError("An order rail needs two different labels.")
        j_index = j if j < i else j-1
        return 1 << (b*self.n*self.n + self.n + i*(self.n-1) + j_index)

    def erase(self, state: int, action: tuple[int, int]) -> int:
        """E_i(S) removes c_i and r_ij for each absent marker c_j.

        Guards are evaluated on the input state. All removals are simultaneous.
        """
        if not isinstance(state, int) or isinstance(state, bool) or state < 0 or state & ~self.full:
            raise ValueError("State is not a valid subset of this universe.")
        b, i = action
        self._check_label(b, i)
        kill = self.marker(b, i)
        for j in range(self.n):
            if j != i and not state & self.marker(b, j):
                kill |= self.rail(b, i, j)
        return state & ~kill

    @staticmethod
    def flush(state: int) -> int:
        """A common terminal eraser. No log or observer memory is preserved."""
        return 0

    def run(self, word: Sequence[tuple[int, int]], *, flush: bool = False) -> list[int]:
        if len(set(word)) != len(word):
            raise ValueError("The certified protocol uses each action at most once.")
        trace = [self.full]
        for action in word:
            trace.append(self.erase(trace[-1], action))
        if flush:
            trace.append(0)
        return trace

    def parity_rails(self, state: int) -> tuple[bool, bool]:
        return parity_reduce([
            (bool(state & self.rail(b, i, j)), bool(state & self.rail(b, j, i)))
            for b in range(self.blocks) for i in range(self.n) for j in range(i+1, self.n)
        ])

    def observe(self, state: int, orientation: int = 1) -> bool:
        if orientation not in (-1, 1):
            raise ValueError("orientation is +1 or -1.")
        return self.parity_rails(state)[0 if orientation == 1 else 1]

    def extinction(self, word: Sequence[tuple[int, int]], orientation: int = 1) -> int | None:
        """First false readout, with a common flush appended (time zero included)."""
        for k, state in enumerate(self.run(word, flush=True)):
            if not self.observe(state, orientation):
                return k
        return None

    def induced_sign(self, word: Sequence[tuple[int, int]]) -> int:
        if len(set(word)) != len(word):
            raise ValueError("Repeated actions are outside the certified protocol.")
        product = 1
        for b in range(self.blocks):
            product *= sign([i for block, i in word if block == b])
        return product

    def saturated(self, local_orders: Sequence[Sequence[int]]) -> int:
        if len(local_orders) != self.blocks:
            raise ValueError("One local ordering is required per block.")
        state = 0
        for b, order in enumerate(local_orders):
            if sorted(order) != list(range(self.n)):
                raise ValueError("A local ordering must be a permutation of range(n).")
            for k, i in enumerate(order):
                for j in order[k+1:]:
                    state |= self.rail(b, i, j)
        return state

    def chain_certificate(self, local_orders: Sequence[Sequence[int]]) -> int:
        if len(local_orders) != self.blocks:
            raise ValueError("One local ordering is required per block.")
        state = 0
        for b, order in enumerate(local_orders):
            if sorted(order) != list(range(self.n)):
                raise ValueError("Invalid local permutation.")
            for i, j in zip(order, order[1:]):
                state |= self.rail(b, i, j)
        return state

    def describe(self, state: int) -> list[str]:
        tokens = []
        for b in range(self.blocks):
            for i in range(self.n):
                if state & self.marker(b, i):
                    tokens.append(f"c[{b},{i}]")
            for i in range(self.n):
                for j in range(self.n):
                    if i != j and state & self.rail(b, i, j):
                        tokens.append(f"r[{b},{i}<{j}]")
        return tokens


def all_distinct_words(actions: Sequence[tuple[int, int]]) -> Iterator[tuple[tuple[int, int], ...]]:
    for k in range(len(actions)+1):
        yield from permutations(actions, k)


def is_subsequence(word: Sequence[int], order: Sequence[int]) -> bool:
    it = iter(order)
    return all(any(x == y for y in it) for x in word)


def dnf_value(state: int, terms: Iterable[int]) -> bool:
    return any(state & term == term for term in terms)