# Exhaustive check on S={0,1,2}: for random presheaves Q on P(S) with Q(empty)=1, verify
# (a) Top_Q(S) is a down-set in Top(S); (b) find cases where it is not closed under binary joins.
import itertools, random
S=(0,1,2); subsets=[frozenset(c) for r in range(4) for c in itertools.combinations(S,r)]
def is_top(T):
    T=set(T)
    if frozenset() not in T or frozenset(S) not in T: return False
    return all(a|b in T and a&b in T for a in T for b in T)
tops=[frozenset(T) for r in range(2,9) for T in itertools.combinations(subsets,r) if is_top(T)]
print("topologies on 3 points:",len(tops))  # expect 29
def rand_presheaf():
    # Q(U) = subset of functions? use model: Q(U)= set of tuples; restriction = projection, then quotient/extra points
    # Simple rich model: Q(U) = {0..k_U-1}, restriction maps random but functorial: build via a random "global" structure
    # Use Q(U)= colorings c: U -> {0,1} modulo nothing, plus optional extra 'ghost' elements at chosen sets mapping to restrictions of a fixed coloring.
    ghosts={U:random.random()<0.3 for U in subsets if U}
    base={}
    for U in subsets:
        els=[('c',c) for c in itertools.product((0,1),repeat=len(U))]
        if ghosts.get(U): els.append(('g',))
        base[U]=els
    def res(U,V,x):  # V subset U
        if x[0]=='g': return ('c',(0,)*len(V)) if not ghosts.get(V) or V!=U else x
        d=dict(zip(sorted(U),x[1])); return ('c',tuple(d[i] for i in sorted(V)))
    return base,res
def ghost_res_ok(base,res):
    # check functoriality res(V,W,res(U,V,x))==res(U,W,x)
    for U in subsets:
        for V in subsets:
            if not V<=U: continue
            for W in subsets:
                if not W<=V: continue
                for x in base[U]:
                    if res(V,W,res(U,V,x))!=res(U,W,x): return False
    return True
def sheaf(T,base,res):
    T=list(T)
    for U in T:
        opens=[V for V in T if V<=U]
        for r in range(0,len(opens)+1):
            for cov in itertools.combinations(opens,r):
                if frozenset().union(*cov)!=U: continue
                matching=[fam for fam in itertools.product(*[base[V] for V in cov])
                          if all(res(A,A&B,a)==res(B,A&B,b) for (A,a),(B,b) in itertools.combinations(zip(cov,fam),2))]
                img=[tuple(res(U,V,x) for V in cov) for x in base[U]]
                if sorted(set(img))!=sorted(set(matching)) or len(set(img))!=len(img): return False
    return True
random.seed(0); downset_ok=True; joinfail=0; tried=0
while tried<40:
    base,res=rand_presheaf()
    if not ghost_res_ok(base,res): continue
    tried+=1
    good={T for T in tops if sheaf(T,base,res)}
    for T in good:
        for T2 in tops:
            if T2<=T and T2 not in good: downset_ok=False
    for A in good:
        for B in good:
            J=min((T for T in tops if A|B<=T),key=len)
            if J not in good: joinfail+=1
print("presheaves tried",tried,"down-set property held:",downset_ok,"join failures found:",joinfail)
