def find_allowed_reflexivity(knowledge: Knowledge): """ Returns the set of predicates in `knowledge` that allow all of its arguments to be equal. That is, if `knowledge` contains a fact pred(x,x,x), pred will be in the return value. """ facts = herbrand_model(list(knowledge.as_clauses())) allow_reflexivity = set() for atom in facts: args = atom.get_head().get_arguments() pred = atom.get_head().get_predicate() if len(args) > 0: # If all arguments are equal if all(args[i] == args[0] for i in range(len(args))): allow_reflexivity.add(pred) return allow_reflexivity
def find_allowed_positions(knowledge: Knowledge): """ Returns a dict x such that x[constant][predicate] contains all positions such i such that `predicate` can have `constant` as argument at position i in the background knowledge. This is used to restrict the number of clauses generated through variable instantiation. If an atom is not implied by the background theory (i.e. is not in the Herbrand Model), there is no point in considering it, because it will never be true. """ facts = herbrand_model(list(knowledge.as_clauses())) predicates = set() # Build dict that will restrict where constants are allowed to appear # e.g. allowed_positions[homer][father] = [0,1] allowed_positions = dict() for atom in facts: args = atom.get_head().get_arguments() pred = atom.get_head().get_predicate() predicates = predicates.union({pred}) for i in range(len(args)): arg = args[i] if isinstance(arg, Constant): # New constant, initialize allowed_positions[constant] if not arg in allowed_positions.keys(): allowed_positions[arg] = dict() # Known constant, but not for this predicate if not pred in allowed_positions[arg]: allowed_positions[arg][pred] = [i] # Known constant, and predicate already seen for this constant else: if i not in allowed_positions[arg][pred]: allowed_positions[arg][ pred] = allowed_positions[arg][pred] + [i] # Complete dict with empty lists for constant/predicate combinations # that were not observed in the background data for const in allowed_positions.keys(): for pred in list(predicates): if pred not in allowed_positions[const].keys(): allowed_positions[const][pred] = [] return allowed_positions
def find_frequent_constants(knowledge: Knowledge, min_frequency=0): """ Returns a list of all constants that occur at least `min_frequency` times in `knowledge` """ facts = herbrand_model(list(knowledge.as_clauses())) d = {} # Count occurrences of constants for atom in facts: args = atom.get_head().get_arguments() for arg in args: if isinstance(arg, Constant): if arg not in d.keys(): d[arg] = 0 else: d[arg] = d[arg] + 1 return [const for const in d.keys() if d[const] >= min_frequency]