def test_build_model(arguments): """ Try to build a ``nltk.sem.Valuation``. """ g = Expression.fromstring('all x.man(x)') alist = [ Expression.fromstring(a) for a in [ 'man(John)', 'man(Socrates)', 'man(Bill)', 'some x.(-(x = John) & man(x) & sees(John,x))', 'some x.(-(x = Bill) & man(x))', 'all x.some y.(man(x) -> gives(Socrates,x,y))', ] ] m = MaceCommand(g, assumptions=alist) m.build_model() spacer() print("Assumptions and Goal") spacer() for a in alist: print(' %s' % a) print('|- %s: %s\n' % (g, decode_result(m.build_model()))) spacer() # print m.model('standard') # print m.model('cooked') print("Valuation") spacer() print(m.valuation, '\n')
def test_build_model(arguments): """ Try to build a ``nltk.sem.Valuation``. """ g = Expression.fromstring("all x.man(x)") alist = [ Expression.fromstring(a) for a in [ "man(John)", "man(Socrates)", "man(Bill)", "some x.(-(x = John) & man(x) & sees(John,x))", "some x.(-(x = Bill) & man(x))", "all x.some y.(man(x) -> gives(Socrates,x,y))", ] ] m = MaceCommand(g, assumptions=alist) m.build_model() spacer() print("Assumptions and Goal") spacer() for a in alist: print(" %s" % a) print(f"|- {g}: {decode_result(m.build_model())}\n") spacer() # print(m.model('standard')) # print(m.model('cooked')) print("Valuation") spacer() print(m.valuation, "\n")
def check_csv(kb): error = False for expr in kb: negative_expr = Expression.negate(expr) if ResolutionProver().prove(negative_expr, kb, verbose=True): error = True return error
def check_contradicts(expr, kb): contradicts = False negative_expr = Expression.negate(expr) res = ResolutionProver().prove(negative_expr, kb, verbose=True) if res: contradicts = True return contradicts
def solve_fol_inference(prem_fol, hypo_fol, str_axioms=[], prover=Prover9(timeout=5), p_number=0): '''Given FOL formulas of a premise and a hypothesis, extract relevant knowledge axioms from WordNet, and solve the inference ''' # if one of the formulas is not derived, return neutral if not prem_fol or not hypo_fol: return 'NEUTRAL', 'No closed formulas' # retrieve knowledge from WordNet based on the predicates found in the formulas axioms = [ semexp.fromstring(a) for a in str_axioms ] axioms = axioms + wn_axioms([prem_fol, hypo_fol], p_number) if axioms: info("Extracted axioms: {}".format(axioms)) info("Premise Formula: {}".format(prem_fol)) info("Hypothesis Formula: {}".format(hypo_fol)) # run prover two times, for checking entailment and contradiction relations try: Entails = prover.prove(hypo_fol, [prem_fol] + axioms) Contradicts = prover.prove(hypo_fol.negate(), [prem_fol] + axioms) except Exception as e: warning(e) return 'NEUTRAL', e # if only one of Entails and Contradicts is true, then return that label # in all other cases return NEUTRAL, # but give a warning if both Entails and Contradicts are true if Entails: if not Contradicts: return 'ENTAILMENT', 'Definite answer' warning('Both ENTAILMENT and CONTRADICTION') return 'NEUTRAL', 'Mixed answers' if Contradicts: return 'CONTRADICTION', 'Definite answer' return 'NEUTRAL', 'Definite answer'
def test_model_found(arguments): """ Try some proofs and exhibit the results. """ for (goal, assumptions) in arguments: g = Expression.fromstring(goal) alist = [lp.parse(a) for a in assumptions] m = MaceCommand(g, assumptions=alist, max_models=50) found = m.build_model() for a in alist: print(' %s' % a) print('|- %s: %s\n' % (g, decode_result(found)))
def get_hypernym_axioms(synsets, ss_pred): '''Detect hypernym relations among synsets''' axioms = set() ss_hypers = [(ss, all_hypernyms(ss)) for ss in synsets] for ss1, hypers1 in ss_hypers: for ss2, _ in ss_hypers: if ss1 != ss2 and ss2 in hypers1: # ss2 is a direct hypernym of ss1 axiom = "all x.({}(x) -> {}(x))".format( ss_pred[ss1], ss_pred[ss2]) axiom = semexp.fromstring(axiom) axioms.add(axiom) return axioms
def test_transform_output(argument_pair): """ Transform the model into various Mace4 ``interpformat`` formats. """ g = Expression.fromstring(argument_pair[0]) alist = [lp.parse(a) for a in argument_pair[1]] m = MaceCommand(g, assumptions=alist) m.build_model() for a in alist: print(' %s' % a) print('|- %s: %s\n' % (g, m.build_model())) for format in ['standard', 'portable', 'xml', 'cooked']: spacer() print("Using '%s' format" % format) spacer() print(m.model(format=format))
def test_transform_output(argument_pair): """ Transform the model into various Mace4 ``interpformat`` formats. """ g = Expression.fromstring(argument_pair[0]) alist = [lp.parse(a) for a in argument_pair[1]] m = MaceCommand(g, assumptions=alist) m.build_model() for a in alist: print(" %s" % a) print(f"|- {g}: {m.build_model()}\n") for format in ["standard", "portable", "xml", "cooked"]: spacer() print("Using '%s' format" % format) spacer() print(m.model(format=format))
def get_antonym_axioms(synsets, ss_pred): """Detect antonyms for each synset pair :param li synsets: the synsets returned from the premise and hypothesis formula :param dict ss_pred: the dictionary that maps synsets back to their formula form, since only the antonyms for these synsets are relevant in this formula. :rtype: set() :return: antonym axioms for each synsets """ axioms = set() antonym_already_used = set() for ss in synsets: for lemma in ss.lemmas(): """TODO: pertainyms do not occur. so not model it?""" # pertainyms = lemma.pertainyms() # for p in pertainyms: # if p.synset() in synsets: # continue # antonym relations are captured in lemmas, not in synsets for antonym_lemma in lemma.antonyms(): antonym = antonym_lemma.synset( ) # return lemma form to synset form if antonym in ss_pred.keys( ) and antonym not in antonym_already_used: # only if the antonym occurs in the set of synsets form the formulas do we append it # only if the antonym-relation has not already been added previously axiom = "all x.-({}(x) -> {}(x))".format( ss_pred[ss], ss_pred[antonym]) antonym_already_used.add( ss) # add antonym so it cannot be re-used axiom = semexp.fromstring(axiom) axioms.add(axiom) if axioms: print("ANTONYMS", axioms) return axioms
def get_more_hypernym_axioms(synsets, ss_pred): """Detect more hypernym relations for each synset pair :param li synsets: the synsets returned from the premise and hypothesis formula :param dict ss_pred: the dictionary that maps synsets back to their formula form, since only the antonyms for these synsets are relevant in this formula. :rtype: set() :return: synonym axioms for each synsets """ axioms = set() for ss1 in synsets: if ss1.entailments(): # denotes how verbs are involved entailment_li = ss1.entailments() for entailment in entailment_li: if entailment in synsets: # Got one: Synset('watch.v.01') Synset('look.v.01') axiom = "all x.({}(x) -> {}(x))".format( ss_pred[ss1], ss_pred[entailment]) axiom = semexp.fromstring(axiom) print("ENTAILMENT", axiom) axioms.add(axiom) if ss1.part_meronyms(): for meronym in ss1.part_meronyms(): # meronym is a part of ss1 as in "stump" is a part of "tree" or "hand" is a part of "body" if meronym in synsets: # only if the meronym is another synset that occurs in the FOL formulas axiom = "all x.({}(x) -> {}(x))".format( ss_pred[meronym], ss_pred[ss1]) axiom = semexp.fromstring(axiom) print("MERONYM: ", axiom) axioms.add(axiom) if len(ss1.member_holonyms()) > 1: # ss is a member of each ss.member_holonyms(): # in the way that "fish" is a part of "pesces" and a "school (of fish)" for member_holonym in ss1.member_holonyms(): if member_holonym in synsets: axiom = "all x.({}(x) -> {}(x))".format( ss_pred[ss1], ss_pred[member_holonym]) print("MEMBER HOLONYM: ", axiom) axiom = semexp.fromstring(axiom) axioms.add(axiom) # TODO: I need the p.names for each synset, which I do not know how to get, so... for ss1 in synsets: for ss2 in synsets: lowest_hypernym = ss1.lowest_common_hypernyms(ss2) if ss1 != ss2 and lowest_hypernym: # ss1 and ss2 have a common hypernym (so they are at least somewhat related) if lowest_hypernym[0].min_depth() > 5: # it is not a top common hypernym (such as "person", "whole" or "artifact") # ss1 and ss2 share a hypernym indirectly! # if ss1.path_similarity(ss2) > 0.5: # checks if they are similar according to similarity measure of WordNet # print("{0} and {1} in common: {2} ({3})".format(ss1, ss2, ss1.lowest_common_hypernyms(ss2), ss1.path_similarity(ss2))) string_synset = str(lowest_hypernym[0]).split("'")[1] predicate_li = string_synset.split('.') predicate = "{0}_{1}{2}".format(*predicate_li) # # Synset('road.n.01') and Synset('street.n.02') in common: [Synset('road.n.01')](0.3333333333333333) try: axiom = "all x.({}(x) -> {}(x))".format( ss_pred[ss1], predicate) axiom = semexp.fromstring(axiom) axioms.add(axiom) axiom = "all x.({}(x) -> {}(x))".format( ss_pred[ss2], predicate) axiom = semexp.fromstring(axiom) axioms.add(axiom) # print("{0} and {1} have {2} in common".format(ss1, ss2, predicate)) except: pass if axioms: print("EXTRA HYPERNYMS", axioms) return axioms