"""Composition of typed binary relations with finitely many shared scenarios."""
from itertools import product
import json


def compose(left,right):
    return [[(left[i][0]&right[0][j]) | (left[i][1]&right[1][j])
             for j in range(2)] for i in range(2)]


def experiment():
    # Four scenarios, distinct intermediates. Compare with scenario-by-scenario reachability.
    inputs=[[[1,6],[12,10]],[[3,5],[6,9]],[[7,10],[4,11]]]
    x,y,z=inputs
    composed=compose(compose(x,y),z)
    assert composed==compose(x,compose(y,z))
    for i,j,s in product(range(2),range(2),range(4)):
        expected=any(all(a & (1<<s) for a in (x[i][k],y[k][m],z[m][j]))
                     for k,m in product(range(2),repeat=2))
        assert bool(composed[i][j] & (1<<s))==expected
    # Witnesses available on different ports cannot be joined.
    wrong=(1|2)&(2|1)
    typed=(1&2)|(2&1)
    assert wrong==3 and typed==0
    return dict(matrix=composed,scenario_checks=16,untyped=wrong,typed=typed)


if __name__=="__main__":print(json.dumps(experiment(),indent=2))
