File size: 7,245 Bytes
1c08905
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Exact boundary collision kernels and target-fibre probabilities.

Clock-slot expansion is injective on labelled branch paths. Replica copies
are synchronized by contraction clock, not by branch count; separate branch
counters prevent clock aliases. No floating-point rejection is used.
"""
from __future__ import annotations
from collections import defaultdict
from fractions import Fraction as Q
from functools import lru_cache
from itertools import product
from .arithmetic import ReturnCone, positive_int
from .source import Source


class ResourceLimit(RuntimeError):
    """A complete exact calculation was not produced; never a partial certificate."""


def _check_budget(size,budget):
    if size>budget:
        raise ResourceLimit(f"layer has {size} states, exceeding budget {budget}; no certificate issued")


def collision_matrix(source:Source,depth:int,order:int,max_states:int=500000):
    """Q_n(a,b)=sum_x P_a(X_n=x,Z_n=b)**q, for integer q>=2.

    Returns the exact rational matrix and reproducibility diagnostics.
    Arbitrary zero transitions and reducible/periodic sources are allowed.
    """
    positive_int(depth,"depth");positive_int(order,"order");positive_int(max_states,"max_states")
    if order<2:
        raise ValueError("replica order must be an integer at least two")
    if source.kmin==source.kmax==1:
        return _unit_matrix(source,depth,order,max_states)
    return _clock_matrix(source,depth,order,max_states)


def _unit_matrix(source,n,q,budget):
    field=source.field
    gate=ReturnCone(field,source.digits,n)
    zero=tuple(field.zero for _ in range(q-1))
    matrix=[[Q(0) for _ in range(source.states)] for _ in range(source.states)]
    widest,visited=1,0

    @lru_cache(maxsize=100000)
    def options(states):
        out=defaultdict(int)
        for ids in product(*(source.outgoing[s] for s in states)):
            es=tuple(source.edges[i] for i in ids)
            ends=tuple(e.end for e in es)
            ds=tuple(tuple(x-y for x,y in zip(e.digit,es[0].digit)) for e in es[1:])
            weight=1
            for i in ids:
                weight*=source.integer_weights[i]
            out[(ends,ds)]+=weight
        return tuple((ends,ds,w) for (ends,ds),w in out.items())

    @lru_cache(maxsize=250000)
    def step(c,delta):
        return field.step(c,delta)

    for start in range(source.states):
        table={((start,)*q,zero):1}
        for t in range(1,n+1):
            nxt=defaultdict(int)
            for (states,carries),weight in table.items():
                for ends,deltas,w in options(states):
                    cs=tuple(step(c,d) for c,d in zip(carries,deltas))
                    if all(gate.allows(c,t) for c in cs):
                        nxt[(ends,cs)]+=weight*w
            _check_budget(len(nxt),budget)
            visited+=len(nxt);widest=max(widest,len(nxt));table=nxt
        for (states,cs),weight in table.items():
            if cs==zero and len(set(states))==1:
                matrix[start][states[0]]+=Q(weight,source.denominator**(q*n))
    return matrix,{"depth":n,"order":q,"engine":"unit-clock integer replica",
                   "max_layer_states":widest,"visited_layer_states":visited,
                   "exact":True,"truncated":False,"cone":gate.certificate}


def _clock_matrix(source,n,q,budget):
    field=source.field
    horizon=n*source.kmax
    gate=ReturnCone(field,source.digits,horizon)
    zero=tuple(field.zero for _ in range(q-1))
    matrix=[[Q(0) for _ in range(source.states)] for _ in range(source.states)]
    widest,visited=1,0
    completed_by_clock={}
    for start in range(source.states):
        table={(((start,0),)*q,(0,)*q,zero):Q(1)}
        for t in range(1,horizon+1):
            nxt=defaultdict(Q)
            for (slots,counts,carries),weight in table.items():
                moves=tuple(source.slot_successors(s,c,n) for s,c in zip(slots,counts))
                for selected in product(*moves):
                    slots2=tuple(x[0] for x in selected)
                    counts2=tuple(x[1] for x in selected)
                    ds=tuple(x[2] for x in selected)
                    w=weight
                    for x in selected:
                        w*=x[3]
                    cs=tuple(field.step(c,tuple(a-b for a,b in zip(d,ds[0])))
                             for c,d in zip(carries,ds[1:]))
                    if not all(gate.allows(c,t) for c in cs):
                        continue
                    if n in counts2:
                        # A completed replica cannot acquire extra clock padding.
                        if all(c==n for c in counts2) and all(s[1]==0 for s in slots2):
                            ends=tuple(s[0] for s in slots2)
                            if cs==zero and len(set(ends))==1:
                                matrix[start][ends[0]]+=w
                                completed_by_clock[t]=completed_by_clock.get(t,Q(0))+w
                        continue
                    nxt[(slots2,counts2,cs)]+=w
            _check_budget(len(nxt),budget)
            visited+=len(nxt);widest=max(widest,len(nxt));table=nxt
            if not table:
                break
    return matrix,{"depth":n,"order":q,"engine":"asynchronous clock-slot replica",
                   "max_layer_states":widest,"visited_layer_states":visited,
                   "completed_mass_by_total_clock":completed_by_clock,
                   "exact":True,"truncated":False,"cone":gate.certificate}


def target_mass(source:Source,path,max_states:int=500000,start=None,end=None):
    """Exact mass of the full-map fibre of a supplied n-edge witness path."""
    path=tuple(path)
    n=positive_int(len(path),"path length")
    positive_int(max_states,"max_states")
    target,units=source.path_map(path)
    total_clock=target[0]
    field=source.field
    gate=ReturnCone(field,source.digits,total_clock)
    for value,name in ((start,"start"),(end,"end")):
        if value is not None and (isinstance(value,bool) or not isinstance(value,int) or not 0<=value<source.states):
            raise ValueError(f"invalid conditional {name} state")
    initial=source.initial if start is None else tuple(Q(int(s==start)) for s in range(source.states))
    table={((s,0),0,field.zero):p for s,p in enumerate(initial) if p}
    widest,visited=len(table),0
    for t,reference in enumerate(units,1):
        nxt=defaultdict(Q)
        for (slot,count,carry),weight in table.items():
            for next_slot,count2,digit,w in source.slot_successors(slot,count,n):
                c=field.step(carry,tuple(a-b for a,b in zip(digit,reference)))
                if gate.allows(c,t):
                    nxt[(next_slot,count2,c)]+=weight*w
        _check_budget(len(nxt),max_states)
        visited+=len(nxt);widest=max(widest,len(nxt));table=nxt
    mass=sum((w for (slot,count,c),w in table.items()
              if slot[1]==0 and count==n and c==field.zero and (end is None or slot[0]==end)),Q(0))
    return mass,{"depth":n,"total_clock":total_clock,"target":target,
                 "max_layer_states":widest,"visited_layer_states":visited,
                 "conditional_start":start,"specified_end":end,
                 "exact":True,"truncated":False,"cone":gate.certificate}