# compute the average deficiency for flats of small matroids

from sage.all import *
from sage.matroids.all import *
from sage.graphs.all import *
import gurobipy as gp
from gurobipy import GRB

import json

def check(M):
    data={}
    # collect the largest hyperplane and optimal F*
    strength=1000000
    for r in range(0,M.rank()):
        #enumerate all flats
        rank_deficiency=M.rank()-r
        max_size=0
        for F in M.flats(r):
            max_size=max(len(F),max_size)
        avg_deficiency=(M.size()-max_size)/rank_deficiency
        strength=min(strength,avg_deficiency)
        data["avg "+str(rank_deficiency)+"-cocycle"]=str(avg_deficiency)
    data["strength"]=str(strength)
    return data
counter=0

with open("flat_deficiency.jsonl", "a") as f:   # .jsonl = JSON Lines
    for N in range(10):
        for M in matroids.AllMatroids(N):
            counter += 1
            record = { "id": str(counter), "value": check(M) }
            f.write(json.dumps(record) + "\n")
            f.flush()     # ensure write hits disk