Example #1
0
def tableau_test(c, ps=None, verbose=False):
    lp = LogicParser()
    pc = lp.parse(c)
    pps = ([lp.parse(p) for p in ps] if ps else [])
    if not ps:
        ps = []
    print('%s |- %s: %s' % (', '.join(ps), pc, TableauProver().prove(pc, pps, verbose=verbose)))
Example #2
0
def demo():
    from nltk_contrib.drt import DRT

    DRT.testTp_equals()
    print '\n'
    
    lp = LogicParser()
    a = lp.parse(r'some x.((man x) and (walks x))')
    b = lp.parse(r'some x.((walks x) and (man x))')
    bicond = ApplicationExpression(ApplicationExpression(Operator('iff'), a), b)
    print "Trying to prove:\n '%s <-> %s'" % (a.infixify(), b.infixify())
    print 'tableau: %s' % get_prover(bicond, prover_name='tableau').prove()
    print 'Prover9: %s' % get_prover(bicond, prover_name='Prover9').prove()
    print '\n'
    
    demo_drt_glue_remove_duplicates()

    lp = LogicParser()
    a = lp.parse(r'all x.((man x) implies (mortal x))')
    b = lp.parse(r'(man socrates)')
    c1 = lp.parse(r'(mortal socrates)')
    c2 = lp.parse(r'(not (mortal socrates))')

    print get_prover(c1, [a,b], 'prover9').prove()
    print get_prover(c2, [a,b], 'prover9').prove()
    print get_model_builder(c1, [a,b], 'mace').build_model()
    print get_model_builder(c2, [a,b], 'mace').build_model()
def tableau_test(c, ps=None, verbose=False):
    lp = LogicParser()
    pc = lp.parse(c)
    pps = ([lp.parse(p) for p in ps] if ps else [])
    if not ps:
        ps = []
    print('%s |- %s: %s' % (', '.join(ps), pc, TableauProver().prove(pc, pps, verbose=verbose)))
Example #4
0
def combination_prover_demo():
    lp = LogicParser()

    p1 = lp.parse(r'see(Socrates, John)')
    p2 = lp.parse(r'see(John, Mary)')
    c = lp.parse(r'-see(Socrates, Mary)')
    prover = Prover9Command(c, [p1, p2])
    print(prover.prove())
    command = ClosedDomainProver(UniqueNamesProver(ClosedWorldProver(prover)))
    for a in command.assumptions():
        print(a)
    print(command.prove())
Example #5
0
def combination_prover_demo():
    lp = LogicParser()

    p1 = lp.parse(r'see(Socrates, John)')
    p2 = lp.parse(r'see(John, Mary)')
    c = lp.parse(r'-see(Socrates, Mary)')
    prover = Prover9Command(c, [p1,p2])
    print(prover.prove())
    command = ClosedDomainProver(
                  UniqueNamesProver(
                      ClosedWorldProver(prover)))
    for a in command.assumptions(): print(a)
    print(command.prove())
Example #6
0
def satdemo(trace=None):
    """Satisfiers of an open formula in a first order model."""

    print
    print '*' * mult
    print "Satisfiers Demo"
    print '*' * mult

    folmodel(quiet=True)

    formulas = [
               'boy(x)',
               '(x = x)',
               '(boy(x) | girl(x))',
               '(boy(x) & girl(x))',
               'love(adam, x)',
               'love(x, adam)',
               '-(x = adam)',
               'exists z22. love(x, z22)',
               'exists y. love(y, x)',
               'all y. (girl(y) -> love(x, y))',
               'all y. (girl(y) -> love(y, x))',
               'all y. (girl(y) -> (boy(x) & love(y, x)))',
               '(boy(x) & all y. (girl(y) -> love(x, y)))',
               '(boy(x) & all y. (girl(y) -> love(y, x)))',
               '(boy(x) & exists y. (girl(y) & love(y, x)))',
               '(girl(x) -> dog(x))',
               'all y. (dog(y) -> (x = y))',
               'exists y. love(y, x)',
               'exists y. (love(adam, y) & love(y, x))'
                ]

    if trace:
        print m2

    lp = LogicParser()
    for fmla in formulas:
        print fmla
        lp.parse(fmla)

    parsed = [lp.parse(fmla) for fmla in formulas]

    for p in parsed:
        g2.purge()
        print "The satisfiers of '%s' are: %s" % (p, m2.satisfiers(p, 'x', g2, trace))
Example #7
0
def unique_names_demo():
    lp = LogicParser()

    p1 = lp.parse(r'man(Socrates)')
    p2 = lp.parse(r'man(Bill)')
    c = lp.parse(r'exists x.exists y.(x != y)')
    prover = Prover9Command(c, [p1, p2])
    print(prover.prove())
    unp = UniqueNamesProver(prover)
    print('assumptions:')
    for a in unp.assumptions():
        print('   ', a)
    print('goal:', unp.goal())
    print(unp.prove())

    p1 = lp.parse(r'all x.(walk(x) -> (x = Socrates))')
    p2 = lp.parse(r'Bill = William')
    p3 = lp.parse(r'Bill = Billy')
    c = lp.parse(r'-walk(William)')
    prover = Prover9Command(c, [p1, p2, p3])
    print(prover.prove())
    unp = UniqueNamesProver(prover)
    print('assumptions:')
    for a in unp.assumptions():
        print('   ', a)
    print('goal:', unp.goal())
    print(unp.prove())
def folmodel(quiet=False, trace=None):
    """Example of a first-order model."""

    global val2, v2, dom2, m2, g2

    v2 = [('adam', 'b1'), ('betty', 'g1'), ('fido', 'd1'),\
         ('girl', set(['g1', 'g2'])), ('boy', set(['b1', 'b2'])), ('dog', set(['d1'])),
         ('love', set([('b1', 'g1'), ('b2', 'g2'), ('g1', 'b1'), ('g2', 'b1')]))]
    val2 = Valuation(v2)
    dom2 = val2.domain
    m2 = Model(dom2, val2)
    g2 = Assignment(dom2, [('x', 'b1'), ('y', 'g2')])

    if not quiet:
        print()
        print('*' * mult)
        print("Models Demo")
        print("*" * mult)
        print("Model m2:\n", "-" * 14, "\n", m2)
        print("Variable assignment = ", g2)

        exprs = ['adam', 'boy', 'love', 'walks', 'x', 'y', 'z']
        lp = LogicParser()
        parsed_exprs = [lp.parse(e) for e in exprs]

        print()
        for parsed in parsed_exprs:
            try:
                print("The interpretation of '%s' in m2 is %s" %
                      (parsed, m2.i(parsed, g2)))
            except Undefined:
                print("The interpretation of '%s' in m2 is Undefined" % parsed)

        applications = [('boy', ('adam')), ('walks', ('adam', )),
                        ('love', ('adam', 'y')), ('love', ('y', 'adam'))]

        for (fun, args) in applications:
            try:
                funval = m2.i(lp.parse(fun), g2)
                argsval = tuple(m2.i(lp.parse(arg), g2) for arg in args)
                print("%s(%s) evaluates to %s" %
                      (fun, args, argsval in funval))
            except Undefined:
                print("%s(%s) evaluates to Undefined" % (fun, args))
def process(SEM):
    # parse string object to TLP type
    tlp = LogicParser(True)
    SEM = tlp.parse(SEM)
    expression_list = []
    # extract individual logic statements
    while type(SEM) is nltk.sem.logic.AndExpression:

        # parse unique entity
        expression_list.append(parse(SEM.second))
        SEM = SEM.first

    # process trailing logic statement
    expression_list.append(parse(SEM))
    return ([expression for expression in expression_list])
Example #10
0
class SemanticTester:
    def __init__(self):
        self.lp = LogicParser()
        self.lx = Lexicon()
        self.fb = FactBase()

    def run(self, s):
        if (s[-1] == '?'):
            sent = s[:-1] + ' ?'  # tolerate absence of space before '?'
            if len(sent) == 0:
                return ("Eh??")
            else:
                wds = sent.split()
                trees = all_valid_parses(self.lx, wds)
                if (len(trees) == 0):
                    return ("Eh??")
                elif (len(trees) > 1):
                    return ("Ambiguous!")
                else:
                    tr = restore_words(trees[0], wds)
                    lam_exp = self.lp.parse(sem(tr))
                    L = lam_exp.simplify()
                    #print L  # useful for debugging
                    entities = self.lx.getAll('P')
                    results = find_all_solutions(L, entities, self.fb)
                    if (results == []):
                        if (wds[0].lower() == 'who'):
                            return ("No one")
                        else:
                            return ("None")
                    else:
                        return results
        elif (s[-1] == '.'):
            s = s[:-1]  # tolerate final full stop
            if len(s) == 0:
                return ("Eh??")
            else:
                wds = s.split()
                msg = process_statement(self.lx, wds, self.fb)
                if (msg == ''):
                    return ("OK.")
                else:
                    return ("Sorry - " + msg)
        else:
            return ("Please end with \".\" or \"?\" to avoid confusion.")
 def evaluate(self, expr, g, trace=None):
     """
     Call the ``LogicParser`` to parse input expressions, and
     provide a handler for ``satisfy``
     that blocks further propagation of the ``Undefined`` error.
     :param expr: An ``Expression`` of ``logic``.
     :type g: Assignment
     :param g: an assignment to individual variables.
     :rtype: bool or 'Undefined'
     """
     try:
         lp = LogicParser()
         parsed = lp.parse(expr)
         value = self.satisfy(parsed, g, trace=trace)
         if trace:
             print()
             print("'%s' evaluates to %s under M, %s" % (expr, value, g))
         return value
     except Undefined:
         if trace:
             print()
             print("'%s' is undefined under M, %s" % (expr, g))
         return 'Undefined'
Example #12
0
def closed_domain_demo():
    lp = LogicParser()

    p1 = lp.parse(r'exists x.walk(x)')
    p2 = lp.parse(r'man(Socrates)')
    c = lp.parse(r'walk(Socrates)')
    prover = Prover9Command(c, [p1, p2])
    print(prover.prove())
    cdp = ClosedDomainProver(prover)
    print('assumptions:')
    for a in cdp.assumptions():
        print('   ', a)
    print('goal:', cdp.goal())
    print(cdp.prove())

    p1 = lp.parse(r'exists x.walk(x)')
    p2 = lp.parse(r'man(Socrates)')
    p3 = lp.parse(r'-walk(Bill)')
    c = lp.parse(r'walk(Socrates)')
    prover = Prover9Command(c, [p1, p2, p3])
    print(prover.prove())
    cdp = ClosedDomainProver(prover)
    print('assumptions:')
    for a in cdp.assumptions():
        print('   ', a)
    print('goal:', cdp.goal())
    print(cdp.prove())

    p1 = lp.parse(r'exists x.walk(x)')
    p2 = lp.parse(r'man(Socrates)')
    p3 = lp.parse(r'-walk(Bill)')
    c = lp.parse(r'walk(Socrates)')
    prover = Prover9Command(c, [p1, p2, p3])
    print(prover.prove())
    cdp = ClosedDomainProver(prover)
    print('assumptions:')
    for a in cdp.assumptions():
        print('   ', a)
    print('goal:', cdp.goal())
    print(cdp.prove())

    p1 = lp.parse(r'walk(Socrates)')
    p2 = lp.parse(r'walk(Bill)')
    c = lp.parse(r'all x.walk(x)')
    prover = Prover9Command(c, [p1, p2])
    print(prover.prove())
    cdp = ClosedDomainProver(prover)
    print('assumptions:')
    for a in cdp.assumptions():
        print('   ', a)
    print('goal:', cdp.goal())
    print(cdp.prove())

    p1 = lp.parse(r'girl(mary)')
    p2 = lp.parse(r'dog(rover)')
    p3 = lp.parse(r'all x.(girl(x) -> -dog(x))')
    p4 = lp.parse(r'all x.(dog(x) -> -girl(x))')
    p5 = lp.parse(r'chase(mary, rover)')
    c = lp.parse(r'exists y.(dog(y) & all x.(girl(x) -> chase(x,y)))')
    prover = Prover9Command(c, [p1, p2, p3, p4, p5])
    print(prover.prove())
    cdp = ClosedDomainProver(prover)
    print('assumptions:')
    for a in cdp.assumptions():
        print('   ', a)
    print('goal:', cdp.goal())
    print(cdp.prove())
Example #13
0
           'Kay Mann', 'Mark Taylor', 'Chris G', 'Kate Syemmes', 'Davis Pete',
           'Steven Kean', 'Sara Shackleton', 'James Steffes', 'Jeff Dasovich')
          ]))
]
val2 = nltk.sem.Valuation(v)
val3 = nltk.sem.Valuation(v1)
print(val2)
print(val3)

from nltk.sem.logic import LogicParser
from nltk.inference import TableauProver
dom3 = val3.domain
m3 = nltk.sem.Model(dom3, val3)
g = nltk.sem.Assignment(dom3)
lpq = LogicParser()
fmla1 = lpq.parse('(POI(x) -> exists y.(CEO(y) and chase(x, y)))')
m3 = m3.satisfiers(fmla1, 'x', g)
print(m3)

from nltk.sem.drt import *
dexpr = DrtExpression.fromstring
CEO_a1 = dexpr('CEO(a1)')
EMPLOYEES_d1 = dexpr('EMPLOYEES(d1)')
x = dexpr('x')
print(DRS([x], [CEO_a1, EMPLOYEES_d1]))

drs1 = dexpr('([x],[CEO(a1),EMPLOYEES(d1)])')
print(drs1)

#merge attributes to nodes
drs2 = dexpr('([y],[ACTIVE(a2),NOTACTIVE(a3)])')
Example #14
0
def print_proof(goal, premises):
    lp = LogicParser()
    prover = Prover9Command(lp.parse(goal), premises)
    command = UniqueNamesProver(ClosedWorldProver(prover))
    print(goal, prover.prove(), command.prove())
Example #15
0
def default_reasoning_demo():
    lp = LogicParser()

    premises = []

    #define taxonomy
    premises.append(lp.parse(r'all x.(elephant(x)        -> animal(x))'))
    premises.append(lp.parse(r'all x.(bird(x)            -> animal(x))'))
    premises.append(lp.parse(r'all x.(dove(x)            -> bird(x))'))
    premises.append(lp.parse(r'all x.(ostrich(x)         -> bird(x))'))
    premises.append(lp.parse(r'all x.(flying_ostrich(x)  -> ostrich(x))'))

    #default properties
    premises.append(lp.parse(r'all x.((animal(x)  & -Ab1(x)) -> -fly(x))')
                    )  #normal animals don't fly
    premises.append(lp.parse(
        r'all x.((bird(x)    & -Ab2(x)) -> fly(x))'))  #normal birds fly
    premises.append(lp.parse(r'all x.((ostrich(x) & -Ab3(x)) -> -fly(x))')
                    )  #normal ostriches don't fly

    #specify abnormal entities
    premises.append(lp.parse(r'all x.(bird(x)           -> Ab1(x))'))  #flight
    premises.append(
        lp.parse(r'all x.(ostrich(x)        -> Ab2(x))'))  #non-flying bird
    premises.append(
        lp.parse(r'all x.(flying_ostrich(x) -> Ab3(x))'))  #flying ostrich

    #define entities
    premises.append(lp.parse(r'elephant(E)'))
    premises.append(lp.parse(r'dove(D)'))
    premises.append(lp.parse(r'ostrich(O)'))

    #print the assumptions
    prover = Prover9Command(None, premises)
    command = UniqueNamesProver(ClosedWorldProver(prover))
    for a in command.assumptions():
        print(a)

    print_proof('-fly(E)', premises)
    print_proof('fly(D)', premises)
    print_proof('-fly(O)', premises)
Example #16
0
def closed_world_demo():
    lp = LogicParser()

    p1 = lp.parse(r'walk(Socrates)')
    p2 = lp.parse(r'(Socrates != Bill)')
    c = lp.parse(r'-walk(Bill)')
    prover = Prover9Command(c, [p1, p2])
    print(prover.prove())
    cwp = ClosedWorldProver(prover)
    print('assumptions:')
    for a in cwp.assumptions():
        print('   ', a)
    print('goal:', cwp.goal())
    print(cwp.prove())

    p1 = lp.parse(r'see(Socrates, John)')
    p2 = lp.parse(r'see(John, Mary)')
    p3 = lp.parse(r'(Socrates != John)')
    p4 = lp.parse(r'(John != Mary)')
    c = lp.parse(r'-see(Socrates, Mary)')
    prover = Prover9Command(c, [p1, p2, p3, p4])
    print(prover.prove())
    cwp = ClosedWorldProver(prover)
    print('assumptions:')
    for a in cwp.assumptions():
        print('   ', a)
    print('goal:', cwp.goal())
    print(cwp.prove())

    p1 = lp.parse(r'all x.(ostrich(x) -> bird(x))')
    p2 = lp.parse(r'bird(Tweety)')
    p3 = lp.parse(r'-ostrich(Sam)')
    p4 = lp.parse(r'Sam != Tweety')
    c = lp.parse(r'-bird(Sam)')
    prover = Prover9Command(c, [p1, p2, p3, p4])
    print(prover.prove())
    cwp = ClosedWorldProver(prover)
    print('assumptions:')
    for a in cwp.assumptions():
        print('   ', a)
    print('goal:', cwp.goal())
    print(cwp.prove())
Example #17
0
#!/usr/bin/python
# -*- coding: utf-8 -*-

from nltk.sem.logic import LogicParser
tlp = LogicParser(True)
print(tlp.parse(r'man(x)').type)
print(tlp.parse(r'walk(angus)').type)
print(tlp.parse(r'-man(x)').type)
print(tlp.parse(r'(man(x) <-> tall(x))').type)
print(tlp.parse(r'exists x.(man(x) & tall(x))').type)
print(tlp.parse(r'\x.man(x)').type)
print(tlp.parse(r'john').type)
print(tlp.parse(r'\x y.sees(x,y)').type)
print(tlp.parse(r'\x.man(x)(john)').type)
print(tlp.parse(r'\x.\y.sees(x,y)(john)').type)
print(tlp.parse(r'\x.\y.sees(x,y)(john)(mary)').type)
print(tlp.parse(r'\P.\Q.exists x.(P(x) & Q(x))').type)
print(tlp.parse(r'\x.y').type)
print(tlp.parse(r'\P.P(x)').type)
parsed = tlp.parse('see(john,mary)')
print(parsed.type)
print(parsed.function)
print(parsed.function.type)
print(parsed.function.function)
print(parsed.function.function.type)
parsed = tlp.parse('P(x,y)')
print(parsed)
print(parsed.type)
print(parsed.function)
print(parsed.function.type)
print(parsed.function.function)
Example #18
0
def test_clausify():
    lp = LogicParser()

    print(clausify(lp.parse('P(x) | Q(x)')))
    print(clausify(lp.parse('(P(x) & Q(x)) | R(x)')))
    print(clausify(lp.parse('P(x) | (Q(x) & R(x))')))
    print(clausify(lp.parse('(P(x) & Q(x)) | (R(x) & S(x))')))

    print(clausify(lp.parse('P(x) | Q(x) | R(x)')))
    print(clausify(lp.parse('P(x) | (Q(x) & R(x)) | S(x)')))

    print(clausify(lp.parse('exists x.P(x) | Q(x)')))

    print(clausify(lp.parse('-(-P(x) & Q(x))')))
    print(clausify(lp.parse('P(x) <-> Q(x)')))
    print(clausify(lp.parse('-(P(x) <-> Q(x))')))
    print(clausify(lp.parse('-(all x.P(x))')))
    print(clausify(lp.parse('-(some x.P(x))')))

    print(clausify(lp.parse('some x.P(x)')))
    print(clausify(lp.parse('some x.all y.P(x,y)')))
    print(clausify(lp.parse('all y.some x.P(x,y)')))
    print(clausify(lp.parse('all z.all y.some x.P(x,y,z)')))
    print(
        clausify(
            lp.parse('all x.(all y.P(x,y) -> -all y.(Q(x,y) -> R(x,y)))')))
Example #19
0
print(read_expr('A(B(C))'))
print(read_expr('(A)(B(C))'))
print(read_expr('(((A)))(((B))(((C))))'))
print(read_expr(r'A != B'))
print(read_expr('P(x) & x=y & P(y)'))

try:
    print(read_expr(r'\walk.walk(x)'))
except LogicalExpressionException as e:
    print(e)

try:
    print(read_expr(r'all walk.walk(john)'))
except LogicalExpressionException as e:
    print(e)

try:
    print(read_expr(r'x(john)'))
except LogicalExpressionException as e:
    print(e)

from nltk.sem.logic import LogicParser # hack to give access to custom quote chars
lpq = LogicParser()
lpq.quote_chars = [("'", "'", "\\", False)]
print(lpq.parse(r"(man(x) & 'tall\'s,' (x) & walks (x) )"))
lpq.quote_chars = [("'", "'", "\\", True)]
print(lpq.parse(r"'tall\'s,'"))
print(lpq.parse(r"'spaced name(x)'"))
print(lpq.parse(r"-'tall\'s,'(x)"))
print(lpq.parse(r"(man(x) & 'tall\'s,' (x) & walks (x) )"))