File size: 1,746 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
"""Small exhaustive reference. Does not use the production carry/compiler code."""
from collections import defaultdict
from fractions import Fraction as Q


def multiply_add(coeff,clock,digit,polynomial):
    d=len(polynomial)
    work=[0]*clock+list(coeff)
    for j in range(len(work)-1,d-1,-1):
        c=work[j]
        for k,p in enumerate(polynomial):
            work[j-d+k]-=c*p
        work[j]=0
    work+=([0]*max(0,d-len(work)))
    return tuple(work[i]+digit[i] for i in range(d))


def distributions(source,n):
    all_starts=[]
    for start in range(source.states):
        table={(start,0,(0,)*source.field.degree):Q(1)}
        for _ in range(n):
            nxt=defaultdict(Q)
            for (state,clock,u),weight in table.items():
                for e in source.edges:
                    if e.start==state:
                        v=multiply_add(u,e.clock,e.digit,source.field.polynomial)
                        nxt[(e.end,clock+e.clock,v)]+=weight*e.probability
            table=dict(nxt)
        all_starts.append(table)
    return all_starts


def moment_matrix(source,n,q):
    rows=distributions(source,n)
    return [[sum((p**q for (end,clock,u),p in row.items() if end==b),Q(0))
              for b in range(source.states)] for row in rows]


def aggregate(source,n):
    out=defaultdict(Q)
    for a,row in enumerate(distributions(source,n)):
        for (b,clock,u),p in row.items():
            out[(clock,u)]+=source.initial[a]*p
    return dict(out)


def paths(source,n,start):
    if n==0:
        yield (),start,Q(1)
        return
    for i,e in enumerate(source.edges):
        if e.start==start:
            for rest,end,p in paths(source,n-1,e.end):
                yield (i,)+rest,end,e.probability*p