practice / tests /test_harris_matrix.py
birgermoell's picture
Add Practice generators, indices, verification and documentation
2983a9c verified
Raw History Blame Contribute Delete
2.8 kB
"""Hand-worked graph examples and adversarial sequence checks."""
import sys
from pathlib import Path
sys.path.insert(0,str(Path(__file__).resolve().parents[1]))
from envs.harris_matrix.gen import earlier_sets,unit_levels,redundant_pairs,unrelated_count,tpq_taq,classes_on_cycle
from envs.harris_matrix.validators import valid_sequence
# A -> B -> C: ancestors {},{A},{A,B}, levels 1,2,3.
assert earlier_sets(3,[(0,1),(1,2)])==[set(),{0},{0,1}]
assert unit_levels(3,[(0,1),(1,2)])==[1,2,3]
assert unit_levels(3,[])==[1,1,1]
assert unit_levels(4,[(0,2),(1,2),(2,3)])==[1,1,2,3]
# Reduction: triangle removes only A->C; chain and fork have no redundant edges.
assert redundant_pairs(3,[(0,1),(1,2),(0,2)])=={(0,2)}
assert redundant_pairs(3,[(0,1),(1,2)])==set()
assert redundant_pairs(3,[(0,1),(0,2)])==set()
# TPQ inherits newest find below, TAQ propagates documented date downwards.
assert tpq_taq(3,[(0,1),(1,2)],{0:[100],1:[150],2:[]},{})==([100,150,150],[None,None,None])
assert tpq_taq(2,[(0,1)],{0:[],1:[]},{1:200})==([None,200],[200,200])
assert tpq_taq(2,[],{0:[100],1:[]},{})==([100,None],[None,None])
assert classes_on_cycle(3,[(0,1),(1,0),(1,2)])==[[0,1]]
assert classes_on_cycle(3,[(0,1),(1,2),(2,0)])==[[0,1,2]]
assert classes_on_cycle(3,[(0,1),(1,2)])==[]
args={'contexts':['A','B','C','D'],'relations':[['A','same as','B'],['C','overlies','A']]}
assert valid_sequence({'sequence':['A','B','C','D']},args)
for wrong in [None,{}, {'sequence':['A','B','C']},{'sequence':['A','A','C','D']},{'sequence':['C','A','B','D']},{'sequence':['A','D','B','C']},{'sequence':['A','B','C',{}]}]: assert not valid_sequence(wrong,args)
print('harris_matrix: 3 hand-worked cases per family and validator rejection cases passed')
# Exhaustively verify uniqueness of the planted repair for each difficulty.
# Deleting a same-as row must never offer an alternative way to hide the cycle.
from itertools import combinations
from envs.harris_matrix.gen import generate,record_consistent
import csv,io
for difficulty in (1,2,3):
task=generate(7,difficulty,'errors')
contexts=[r['context_id'] for r in csv.DictReader(io.StringIO(task.files['contexts.csv']))]
relations=list(csv.DictReader(io.StringIO(task.files['relations.csv'])))
k=2 if difficulty==3 else 1
expected=next(c['value'] for c in task.checks if c.get('path')=='faulty_relations')
repairs=[]
for n in range(1,k+1):
for drop in combinations(range(len(relations)),n):
rows=[(r['context_a'],r['relation'],r['context_b']) for i,r in enumerate(relations) if i not in drop]
if record_consistent(contexts,rows): repairs.append(sorted(relations[i]['relation_id'] for i in drop))
assert repairs==[expected],repairs
print('harris_matrix: unique minimal repair verified at all 3 difficulties')