Beispiel #1
0
def test_computation():
    c = Computation((1, 2), (3,))
    d = Computation((1, 0), (3,))

    assert run(0, 0, eq(c, d)) == ()

    with variables(0):
        assert run(0, 0, eq(c, d)) == (2,)
Beispiel #2
0
def test_composite_computation():
    c = Computation((1, 2), (3,)) + Computation((3, 4), (5, 6))
    d = Computation((1, 2), (0,)) + Computation((0, 4), (5, 6))
    e = Computation((0, 4), (5, 6)) + Computation((1, 2), (0,))

    assert run(0, 0, eq(c, d)) == ()

    with variables(0):
        assert run(0, 0, eq(c, d)) == (3,)
Beispiel #3
0
def test_run_objects_with_context_manager():
    f = Foo(1, 1234)
    g = Foo(1, 2)
    _unify.add((Foo, Foo, dict), unify_object)
    _reify.add((Foo, dict), reify_object)
    with variables(1234):
        assert unify_object(f, g, {})
        assert run(1, 1234, (eq, f, g)) == (2,)
        assert run(1, Foo(1234, 1234), (eq, f, g)) == (Foo(2, 2),)
Beispiel #4
0
def test_run_objects_with_context_manager():
    f = Foo(1, 1234)
    g = Foo(1, 2)
    _unify.add((Foo, Foo, dict), unify_object)
    _reify.add((Foo, dict), reify_object)
    with variables(1234):
        assert unify_object(f, g, {})
        assert run(1, 1234, (eq, f, g)) == (2, )
        assert run(1, Foo(1234, 1234), (eq, f, g)) == (Foo(2, 2), )
Beispiel #5
0
def test_list_1():
    _unify.add((Foo, Foo, dict), unify_object)
    _reify.add((Foo, dict), reify_object)

    x = var('x')
    y = var('y')
    rval = run(0, (x, y), (eq, Foo(1, [2]), Foo(x, [y])))
    assert rval == ((1, 2), )

    rval = run(0, (x, y), (eq, Foo(1, [2]), Foo(x, y)))
    assert rval == ((1, [2]), )
Beispiel #6
0
def test_list_1():
    _unify.add((Foo, Foo, dict), unify_object)
    _reify.add((Foo, dict), reify_object)

    x = var('x')
    y = var('y')
    rval = run(0, (x, y), (eq, Foo(1, [2]), Foo(x, [y])))
    assert rval == ((1, 2),)

    rval = run(0, (x, y), (eq, Foo(1, [2]), Foo(x, y)))
    assert rval == ((1, [2]),)
Beispiel #7
0
def test_run_objects_with_context_manager():
    f = Foo(1, 1234)
    g = Foo(1, 2)
    unify_dispatch[(Foo, Foo)] = unify_object
    reify_dispatch[Foo] = reify_object
    with variables(1234):
        assert unify_object(f, g, {})
        assert run(1, 1234, (eq, f, g)) == (2,)
        assert run(1, Foo(1234, 1234), (eq, f, g)) == (Foo(2, 2),)

    del reify_dispatch[Foo]
    del unify_dispatch[(Foo, Foo)]
Beispiel #8
0
def test_list_1():
    from logpy.unification import unify_dispatch, reify_dispatch
    unify_dispatch[(Foo, Foo)] = unify_object
    reify_dispatch[Foo] = reify_object

    x = var('x')
    y = var('y')
    rval = run(0, (x, y), (eq, Foo(1, [2]), Foo(x, [y])))
    assert rval == ((1, 2),)

    rval = run(0, (x, y), (eq, Foo(1, [2]), Foo(x, y)))
    assert rval == ((1, [2]),)

    del reify_dispatch[Foo]
    del unify_dispatch[(Foo, Foo)]
def test_logpy():
    x = tensor.vector()
    y = tensor.vector()
    z = tensor.inc_subtensor(x[1:3], y)
    node = z.owner

    # otw theano chokes on var attributes when nose tries to print a traceback
    # XXX this should be un-monkey-patched after the test runs by e.g. a
    # context manager decorator
    theano.gof.Apply.__repr__ = object.__repr__
    theano.gof.Apply.__str__ = object.__str__

    w = dict((name, var(name)) for name in [
        'start', 'stop', 'step', 'set_instead_of_inc', 'inputs', 'outputs',
        'inplace', 'whole_op', 'dta',
        ])

    pattern = raw_init(theano.Apply,
        op=raw_init(theano.tensor.IncSubtensor,
            idx_list=[slice(w['start'], w['stop'], w['step'])],
            inplace=w['inplace'],
            set_instead_of_inc=w['set_instead_of_inc'],
            destroyhandler_tolerate_aliased=w['dta']),
        inputs=w['inputs'],
        outputs=w['outputs'])

    match, = run(0, w, (eq, node, pattern))

    assert match['stop'] == 3
    assert match['inputs'] == [x, y]
Beispiel #10
0
def logpy_join(node):
    if isinstance(node.op, tensor.Join):
        axis = node.inputs[0]
        tsrs = node.inputs[1:]
        if len(tsrs) < 2:
            return

        for i, (t0, t1) in enumerate(zip(tsrs[:-1], tsrs[1:])):
            reb_op = tensor.Rebroadcast((0, 0))
            x0 = reb_op(t0.type())
            x1 = reb_op(t1.type())
            op0 = var('op0')
            with variables(x0, x1):
                op(x[i], x[i+1])
                match = run(
                    1, [x0, x1, op0],
                    (eq, [t0, t1], [reb_op(x0), reb_op(x1)]),
                    (getattrreco, (x0, 'owner', 'op'), op0),
                    (getattrreco, (x1, 'owner', 'op'), op0),
                    (isinstanceo, op0, tensor.Elemwise),

                   )
                if match:
                    print 'MATCH', match
                else:
                    return
Beispiel #11
0
def test_reification_of_computations():
    d = Computation((1, 2), (0,)) + Computation((0, 4), (5, 6))

    with variables(0):
        assert set(run(0, d, membero(0, (10, 11)))) == set((
                Computation((1, 2), (10,)) + Computation((10, 4), (5, 6)),
                Computation((1, 2), (11,)) + Computation((11, 4), (5, 6))))
Beispiel #12
0
def logpy_group_incsubtensor(node):
    # TODO: how to design re-usable patterns? (dtype, ndim, etc.)

    shape_of = node.fgraph.shape_feature.shape_of
    shape_dimo = goalifyN(
        shape_dim(shape_of))
    ndimo = goalify(lambda x: getattr(x, 'ndim'))
    x = node.outputs[0].type()
    if x.ndim == 0:
        return
    y = x[0].type()
    z = tensor.set_subtensor(x[1001], y)
    incs = []
    orig_out = node.outputs[0]
    while node:
        with variables(x, y, 1001):
            match = run(1, (x, y, 1001), (eq, node.outputs[0], z))
            if match:
                xx, yy, ii = match[0]
                incs.append((ii, xx, yy))
                node = xx.owner
                continue
        break
    if not incs:
        return
    incs.sort()
    if zip(*incs)[0] == tuple(range(shape_dim(shape_of)(xx, 0))):
        iin = tensor.concatenate([
            tensor.shape_padleft(yy)
            for ii, _, yy in incs])
        print 'INCS', incs
        return [iin]
def test_context_type_not_matter():
    x1 = theano.tensor.fmatrix() # -- type doesn't really matter
    y1 = theano.tensor.fmatrix() # -- type doesn't really matter
    x2 = theano.tensor.dmatrix() # -- type doesn't really matter
    y2 = theano.tensor.dmatrix() # -- type doesn't really matter

    with variables(x2, y2):
        assert run(1, (x2, y2), (eq, tensor.dot(x1, y1).owner, tensor.dot(x2, y2).owner))
Beispiel #14
0
def test_complex():
    from logpy import run, membero
    numbers = tuple(range(10))
    results = set(
        run(0, x, (sub, y, x, 1), (membero, y, numbers), (mod, y, 2, 0),
            (membero, x, numbers)))
    expected = set((1, 3, 5, 7))
    print(results)
    assert results == expected
Beispiel #15
0
def computations_for(expr):
    """ Computations that can break down expr """
    c = var('comp')
    e = var('expr')
    pred = var('predicate')
    result = run(None, c, (computes, e, c, pred),
                          (eqac, e, expr),
                          (asko, pred, True))
    return result
Beispiel #16
0
def test_complex():
    from logpy import run, membero
    numbers = tuple(range(10))
    results = set(run(0, x, (sub, y, x, 1),
                            (membero, y, numbers),
                            (mod, y, 2, 0),
                            (membero, x, numbers)))
    expected = set((1, 3, 5, 7))
    print(results)
    assert results == expected
Beispiel #17
0
def test3():
    parent = Relation()
    male = Relation()

    def son(father, boy):
        return conde((parent(father, boy), male(boy)))

    fact(parent, "Abraham", "Isaac")
    fact(male, "Abraham")
    fact(male, "Isaac")

    x = var()
    assert ("Isaac",) == run(0, x, son("Abraham", x))
def test_context_manager():
    x = tensor.vector()
    y = tensor.vector()
    z = tensor.inc_subtensor(x[1:3], y)

    xp = tensor.vector()
    yp = tensor.vector()
    zp = tensor.inc_subtensor(xp[1:1234], yp)

    vars = (1234, xp, yp)

    with variables(*vars):
        match, = run(0, vars, (eq, z, zp))

    assert match == (3, x, y)
Beispiel #19
0
def logpy_remove_dot_scalar_matrix(node):
    # TODO: how to design re-usable patterns? (dtype, ndim, etc.)
    shape_of = node.fgraph.shape_feature.shape_of
    shape_dimo = goalifyN(
        shape_dim(shape_of))
    ndimo = goalify(lambda x: getattr(x, 'ndim'))
    x = theano.tensor.matrix() # -- XXX type should not matter
    y = theano.tensor.matrix() # -- XXX type should not matter
    if isinstance(node.op, theano.tensor.Dot):
        with variables(x, y):
            #theano.printing.debugprint(tensor.dot(x, y))
            result = run(1, (x, y),
                    (eq, node, tensor.dot(x, y).owner),
                    (ndimo, x, 2),
                    (shape_dimo, (x, 0), 1),
                    (shape_dimo, (x, 1), 1),
               )
        if result:
            xx, yy = result[0]
            #print 'MATCHED xx!', xx, shape_of[xx], xx.type
            #print 'MATCHED yy!', yy, shape_of[yy], yy.type
            #theano.printing.debugprint(xx)
            return [tensor.addbroadcast(xx, 0, 1).dimshuffle() * yy]
Beispiel #20
0
            Account('Carl', 'Marx', 2, 3),
            Account('John', 'Rockefeller', 3, 1000))

# variables are arbitrary Python objects, not LogPy Var objects
first = 'FIRST'
last = 'LAST'
ident = -1111
balance = -2222
newbalance = -3333
vars = {first, last, ident, balance, newbalance}


# Describe a couple of transformations on accounts
source = Account(first, last, ident, balance)
target = Account(first, last, ident, newbalance)

theorists = ('Adam', 'Carl')
# Give $10 to theorists
theorist_bonus = lall((membero, source, accounts),
                      (membero, first, theorists),
                      (add, 10, balance, newbalance))

# Take $10 from anyone with more than $100
tax_the_rich = lall((membero, source, accounts),
                    (gt, balance, 100),
                    (sub, balance, 10, newbalance))

with variables(*vars):
    print run(0, target, tax_the_rich)
    print run(0, target, theorist_bonus)
Beispiel #21
0
def test_rs1_11():
    q = var()
    eq((True,), run(0, q, unify(True, q)))
Beispiel #22
0
def test_rs1_12():
    q = var()
    eq((), run(0, q, fail, unify(True, q)))
Beispiel #23
0
def test_rs1_16():
    q = var()
    eq(("corn",), run(0, q,
                      success,
                      unify("corn", q)))
Beispiel #24
0
def test1():
    x = var()
    eq((5,), run(0, x,
                 unify(x, 5)))
Beispiel #25
0
              ('Sonny', 'Frank'),
              ('Sonny', 'Santino'))

facts(mother, ('Carmela', 'Michael'),
              ('Carmela', 'Sonny'),
              ('Carmela', 'Fredo'),
              ('Kay', 'Mary'),
              ('Kay', 'Anthony'),
              ('Sandra', 'Francesca'),
              ('Sandra', 'Kathryn'),
              ('Sandra', 'Frank'),
              ('Sandra', 'Santino'))

q = var()
# Vito is the father of who?
run(0, q, father('Vito', q))            # prints ('Sonny', 'Michael', 'Fredo')

# Who is the father of Michael?
run(0, q, father(q, 'Michael'))         # prints ('Vito',)

def parent(p, child):
    return conde([father(p, child)], [mother(p, child)])

# Who is a parent of Michael
run(0, q, parent(q, 'Michael'))         # prints ('Vito', 'Carmela')

def grandparent(gparent, child):
    p = var()
    return conde((parent(gparent, p), parent(p, child)))

# Who is a grandparent of Anthony
Beispiel #26
0
def test_rs1_47():
    x = var()
    eq(("olive", "oil"), run(0, x,
                             conde((unify("olive", x),),
                                   (unify("oil", x),))))
Beispiel #27
0
father = Relation()
mother = Relation()

facts(father, ('Vito', 'Michael'), ('Vito', 'Sonny'), ('Vito', 'Fredo'),
      ('Michael', 'Anthony'), ('Michael', 'Mary'), ('Sonny', 'Vicent'),
      ('Sonny', 'Francesca'), ('Sonny', 'Kathryn'), ('Sonny', 'Frank'),
      ('Sonny', 'Santino'))

facts(mother, ('Carmela', 'Michael'), ('Carmela', 'Sonny'),
      ('Carmela', 'Fredo'), ('Kay', 'Mary'), ('Kay', 'Anthony'),
      ('Sandra', 'Francesca'), ('Sandra', 'Kathryn'), ('Sandra', 'Frank'),
      ('Sandra', 'Santino'))

q = var()

print run(0, q, father('Vito', q))  # Vito is the father of who?
# ('Sonny', 'Michael', 'Fredo')

print run(0, q, father(q, 'Michael'))  # Who is the father of Michael?
# ('Vito',)


def parent(p, child):
    return conde([father(p, child)], [mother(p, child)])


print run(0, q, parent(q, 'Michael'))  # Who is a parent of Michael?
# ('Vito', 'Carmela')


def grandparent(gparent, child):
Beispiel #28
0
from logpy import run, var, fact
from logpy.assoccomm import eq_assoccomm as eq
from logpy.assoccomm import commutative, associative

# Define some dummy Operationss
add = 'add'
mul = 'mul'
# Declare that these ops are commutative using the facts system
fact(commutative, mul)
fact(commutative, add)
fact(associative, mul)
fact(associative, add)

# Define some wild variables
x, y = var('x'), var('y')

# Two expressions to match
pattern = (mul, (add, 1, x), y)                # (1 + x) * y
expr    = (mul, 2, (add, 3, 1))                # 2 * (3 + 1)
print run(0, (x,y), eq(pattern, expr))         # prints ((3, 2),) meaning
                                               #   x matches to 3
                                               #   y matches to 2
Beispiel #29
0
     ('Англичанин', logpy.var(), logpy.var(), logpy.var(), 'красный'), people),
    (logpy.membero,
     ('Швед', logpy.var(), logpy.var(), 'собака', logpy.var()), people),
    (logpy.membero,
     ('Датчанин', logpy.var(), 'чай', logpy.var(), logpy.var()), people),
    (logpy.membero,
     (logpy.var(), logpy.var(), 'кофе', logpy.var(), 'зеленый'), people),
    (logpy.membero,
     (logpy.var(), 'Pall Mall', logpy.var(), 'птицы', logpy.var()), people),
    (logpy.membero,
     (logpy.var(), 'Dunhill', logpy.var(), logpy.var(), 'желтый'), people),
    (logpy.membero,
     (logpy.var(), 'Rothmans', logpy.var(), logpy.var(), logpy.var()), people),
    (logpy.membero,
     (logpy.var(), logpy.var(), 'молоко', logpy.var(), logpy.var()), people),
    (logpy.membero,
     (logpy.var(), 'Philip Morris', 'пиво', logpy.var(), logpy.var()), people),
    (logpy.membero,
     (logpy.var(), logpy.var(), 'вода', logpy.var(), logpy.var()), people),
    (logpy.membero,
     (logpy.var(), logpy.var(), logpy.var(), 'лошади', 'синий'), people),
    (logpy.membero,
     (logpy.var(), logpy.var(), logpy.var(), 'кошки', logpy.var()), people),
    (logpy.membero,
     ('Немец', 'Marlboro', logpy.var(), logpy.var(), logpy.var()), people),
    (logpy.membero,
     (logpy.var(), logpy.var(), logpy.var(), 'рыбки', logpy.var()), people))
solution = logpy.run(0, people, rules)
for item in solution[0]:
    print(item)
Beispiel #30
0
with open(
        'examples/data/adjacent-states.txt') as f:  # lines like 'CA,OR,NV,AZ'
    adjlist = [
        line.strip().split(',') for line in f if line and line[0].isalpha()
    ]

for L in adjlist:  # ['CA', 'OR', 'NV', 'AZ']
    head, tail = L[0], L[1:]  # 'CA', ['OR', 'NV', 'AZ']
    for state in tail:
        fact(adjacent, head, state)  # e.g. 'CA' is adjacent to 'OR',
        #      'CA' is adjacent to 'NV', etc...

x = var()
y = var()

print run(0, x, adjacent('CA', 'NY'))  # is California adjacent to New York?
# ()

print run(0, x, adjacent('CA', x))  # all states next to California
# ('OR', 'NV', 'AZ')

print run(
    0,
    x,
    adjacent('TX', x),  # all coastal states next to Texas
    coastal(x))
# ('LA',)

print run(
    5,
    x,
Beispiel #31
0
              ('Sonny', 'Frank'),
              ('Sonny', 'Santino'))

facts(mother, ('Carmela', 'Michael'),
              ('Carmela', 'Sonny'),
              ('Carmela', 'Fredo'),
              ('Kay', 'Mary'),
              ('Kay', 'Anthony'),
              ('Sandra', 'Francesca'),
              ('Sandra', 'Kathryn'),
              ('Sandra', 'Frank'),
              ('Sandra', 'Santino'))

q = var()

print run(0, q, father('Vito', q))          # Vito is the father of who?
# ('Sonny', 'Michael', 'Fredo')


print run(0, q, father(q, 'Michael'))       # Who is the father of Michael?
# ('Vito',)

def parent(p, child):
    return conde([father(p, child)], [mother(p, child)])


print run(0, q, parent(q, 'Michael'))       # Who is a parent of Michael?
# ('Vito', 'Carmela')

def grandparent(gparent, child):
    p = var()
Beispiel #32
0
def start_main():
    def parents(x, y):
        return conde([Father(x, y)], [Mother(x, y)])

    def grandparents(x, y):
        z = var()
        return conde((parents(x, z), parents(z, y)))

    def grandfather(x, y):
        z = var()
        return conde((grandparents(x, y), Male(x)))

    def grandmother(x, y):
        z = var()
        return conde((grandparents(x, y), Female(x)))

    def uncle(m, y):
        z = var()
        x = var()
        return conde((Father(x, z), Father(x, m), Father(z, y), Male(m)))

    def sibling(x, y):
        z = var()
        return conde((parents(z, x), parents(z, y)))

    def brother(x, y):
        z = var()
        return conde((parents(z, x), parents(z, y), Male(x)))

    def sister(x, y):
        z = var()
        return conde((parents(z, x), parents(z, y), Female(x)))

    def aunty(x, y):
        z = var()
        return conde((uncle(z, y), Couple(z, x), Female(x)))

    def children(x, y):
        return ((parents(x, y)))

    def son(x, y):
        return ((parents(x, y), Male(y)))

    def daughter(x, y):
        return ((parents(x, y), Female(y)))

    global choice

    Father = Relation()

    Mother = Relation()

    Male = Relation()

    Female = Relation()

    Couple = Relation()

    facts(Couple, ('john', 'megan'),
          ('william', 'emma'),
          ('david', 'olivia'),
          ('adam', 'lily'))
    facts(Father, ('john', 'william'),
          ('john', 'david'),
          ('john', 'adam'),
          ('william', 'chris'),
          ('william', 'stephaine'),
          ('david', 'wayne'),
          ('david', 'tiffany'),
          ('david', 'julie'),
          ('david', 'neil'),
          ('david', 'peter'),
          ('adam', 'sophia'))

    facts(Mother, ('megan', 'william'),
          ('megan', 'david'),
          ('megan', 'adam'),
          ('emma', 'chris'),
          ('emma', 'stephaine'),
          ('olivia', 'wayne'),
          ('olivia', 'tiffany'),
          ('olivia', 'julie'),
          ('olivia', 'neil'),
          ('olivia', 'peter'),
          ('lily', 'sophia'))

    fact(Male, 'john')
    fact(Male, 'william')
    fact(Male, 'david')
    fact(Male, 'adam')
    fact(Male, 'chris')
    fact(Male, 'wayne')
    fact(Male, 'neil')
    fact(Male, 'peter')

    fact(Female, 'megan')
    fact(Female, 'emma')
    fact(Female, 'tiffany')
    fact(Female, 'julie')
    fact(Female, 'olivia')
    fact(Female, 'sophia')
    fact(Female, 'lily')
    fact(Female, 'stephaine')

    x = var()
    y = var()
    z = var()
    #
    # print(
    #     color.Bold + "---------------------------------Welcome to Relation Predicting Program------------------------------" + color.End + "\n\n")
    # print(
    #     color.Bold + "-----------------------------------------------------------------------------Created by:" + color.End,
    #     color.Darkcyan + color.Bold + "RUPESH YADAV" + color.End, "\n\n")
    # print("-----------------------------------------------------------------------------------------------------")
    # print(color.Bold + color.Blue + "Enter The Name Below From Above To Know There Realtives" + color.End)
    # print("-----------------------------------------------------------------------------------------------------")
    # print(color.Red + "1)JOHN\n2)WILLIAM\n3)DAVID\n4)ADAM\n5)CHRIS\n6)WAYNE\n7)NEIL\n8)PETER\n" + color.End)
    # print(
    #     color.Green + "9)MEGAN\n10)EMMA\n11)TIFFANY\n12)JULIE\n13)OLIVIA\n14)SOPHIA\n15)LILY\n16)STEPHAINE" + color.End)

    NameList = ['john', 'megan',
                'william', 'emma',
                'david', 'olivia',
                'adam', 'lily',
                'peter', 'neil',
                'sophia', 'julie',
                'tiffany', 'stephaine',
                'wayne', 'chris']

    name = input()
    FakeName = name.upper()
    name = name.lower()
    if name in NameList:
        print(color.Red + "Which Realtion Of" + color.End,
              color.Cyan + color.Bold + color.Underline + FakeName + color.End,
              color.Red + "You want to know?" + color.End)

        print(
            color.Blue + "1)PARENT\n2)SIBLING\n3)GRANDPARENT\n)4)UNCLE\n5)AUNTY\n6)CHILDREN\n7)COUPLE\n\n" + color.End)

        Relat = input()
        Relat = Relat.lower()
        if Relat == 'parent':
            print(
                color.Yellow + "Press 1 To Know The Name of Both Parent\nPress 2 To Know The Name Of Mother\nPress 3 To Know The Name Of Father" + color.End)
            option = int(input())
            if option == 1:
                out = (run(0, x, parents(x, name)))
            elif option == 2:
                out = (run(0, x, Mother(x, name)))
            else:
                out = (run(1, x, Father(x, name)))
            if len(out) == 0:
                print(color.Cyan + color.Bold + color.Underline + FakeName + color.End,
                      color.Green + "Parent Details Not In DataBase---SORRY" + color.End)
            else:
                print(out)
        elif Relat == 'sibling':
            print(
                color.Yellow + "Press 1 To Know The Name of Both Gender Sibling\nPress 2 To Know The Name Of Sisters\nPress 3 To Know The Name Of Brother" + color.End)
            option = int(input())
            if option == 1:
                out = (run(0, x, sibling(x, name)))
            elif option == 2:
                out = (run(1, x, sister(x, name)))
            else:
                out = (run(1, x, brother(x, name)))
            list1 = list(out)

            if name in list1:
                list1.remove(name)

            if len(list1) == 0:
                print(color.Cyan + color.Bold + color.Underline + FakeName + color.End,
                      color.Green + "Does not have Entered type sibling ---SORRY" + color.End)
            else:
                print(list1)
        elif Relat == 'grandparent':
            print(
                color.Yellow + "Press 1 To Know The Name of Both Grandmaa and Grandpaa\nPress 2 To Know The Name Of GrandFather\nPress 3 To Know The Name Of GrandMother" + color.End)
            option = int(input())
            if option == 1:
                out = (run(0, x, grandparents(x, name)))
            elif option == 2:
                out = (run(1, x, grandfather(x, name)))
            else:
                out = (run(1, x, grandmother(x, name)))
            list1 = list(out)

            if name in list1:
                list1.remove(name)

            if len(list1) == 0:
                print(color.Cyan + color.Bold + color.Underline + FakeName + color.End,
                      color.Green + "Does not have GrandParent data ---SORRY" + color.End)
            else:
                print(list1)
        elif Relat == 'uncle':
            out1 = run(1, x, Father(x, name))
            out = run(0, x, uncle(x, name))
            a = out1[0]
            list1 = list(out)
            if a in list1:
                list1.remove(a)
            print(list1)
        elif Relat == 'aunty':
            out = (run(0, x, aunty(x, name)))
            out1 = run(0, x, Mother(x, name))
            list1 = list(out)
            a = out1[0]
            if a in list1:
                list1.remove(a)
            print(list1)
        elif Relat == 'children':
            print(run(0, x, children(name, x)))
        elif Relat == 'couple':
            print(run(1, x, Couple(x, name)))
        else:
            print(color.Red + "The Relation You Is Wrong Or May Not Be In Database" + color.End)

    else:
        print(color.Blue + "The Name" + color.End, color.Red + color.Underline + FakeName + color.End,
              color.Blue + "You Have Entered Is Not In The DataBase" + color.End)
Beispiel #33
0
def test2():
    x = var()
    z = var()
    eq((5,), run(0, x,
                 unify(x, z),
                 unify(z, 5)))
Beispiel #34
0
from logpy import run, var, conde, Relation, facts
parent = Relation()
facts(parent, ('Homer', 'Lisa'), ('Homer', 'Bart'), ('Abe', 'Homer'))

x = var()
y = var()
print(run(1, x, parent(x, 'Bart')))
print(run(2, x, parent(
    'Homer',
    x,
)))
y = var()
print(run(1, x, parent(x, y), parent(y, 'Bart')))


def grandparent(x, z):
    y = var()
    return conde((parent(x, y), parent(y, z)))


print(run(1, x, grandparent(x, 'Bart')))
Beispiel #35
0
def test_rs1_56():
    def teacupo(x):
        return conde((unify("tea", x),),
                     (unify("cup", x),))
    x = var()
    eq(("tea", "cup"), run(0, x, teacupo(x)))
Beispiel #36
0
    with open('LAB1/relationships.json') as f:
        d = json.loads(f.read())

    #Read the data and add them to our fact base
    for item in d['father']:
        facts(father, (list(item.keys())[0], list(item.values())[0]))

    for item in d['mother']:
        facts(mother, (list(item.keys())[0], list(item.values())[0]))

    #define the variable x
    x = var()

    #let's ask who John's children are.
    name = 'John'
    output = run(0, x, father(name, x))
    print("\n list of" + name + " 's children:")
    for item in output:
        print(item)

    #who is William's mother?
    name = 'William'
    output = run(0, x, mother(x, name))[0]
    print('\n' + name + " 's mother:\n" + output)

    #who are Adam's parents?
    name = 'Adam'
    output = run(0, x, parent(x, name))
    print("\n list of" + name + " 's parents:")
    for item in output:
        print(item)
Beispiel #37
0
# Read the file containing the coastal states
with open(file_adjacent, 'r') as f:
    adjlist = [line.strip().split(',') for line in f if line and line[0].isalpha()]

# Add the info to the fact base
for L in adjlist:
    head, tail = L[0], L[1:]
    for state in tail:
        fact(adjacent, head, state)

# Initialize the variables
x = var()
y = var()

# Is Nevada adjacent to Louisiana?
output = run(0, x, adjacent('Nevada', 'Louisiana'))
print('\nIs Nevada adjacent to Louisiana?:')
print('Yes' if len(output) else 'No')

# States adjacent to Oregon
output = run(0, x, adjacent('Oregon', x))
print('\nList of states adjacent to Oregon:')
for item in output:
    print(item)

# States adjacent to Mississippi that are coastal
output = run(0, x, adjacent('Mississippi', x), coastal(x))
print('\nList of coastal states adjacent to Mississippi:')
for item in output:
    print(item)
Beispiel #38
0
from logpy import run, var, conde, Relation, facts
parent = Relation()
facts(parent, ('Homer', 'Lisa'),
      ('Homer', 'Bart'),
      ('Abe', 'Homer'))

x = var()
y = var()
print(run(1, x, parent(x, 'Bart')))
print(run(2, x, parent('Homer', x,)))
y = var()
print(run(1, x, parent(x, y),parent(y, 'Bart')))


def grandparent(x, z):
    y = var()
    return conde((parent(x,y), parent(y,z)))

print(run (1,x,grandparent(x, 'Bart')))


Beispiel #39
0
    mother = Relation()

    with open('relationships.json') as f:
        d = json.loads(f.read())

    for item in d['father']:
        facts(father, (list(item.keys())[0], list(item.values())[0]))

    for item in d['mother']:
        facts(mother, (list(item.keys())[0], list(item.values())[0]))

    x = var()

    # John's children
    name = 'John'
    output = run(0, x, father(name, x))
    print("\nList of" + name + "'s children:")
    for item in output:
        print(item)

    # William's mother
    name = 'William'
    output = run(0, x, mother(x, name))[0]
    print("\n" + name + "'s mother:\n" + output)

    # Adam's parents
    name = 'Adam'
    output = run(0, x, parent(x, name))
    print("\nList of " + name + "'s parents:")
    for item in output:
        print(item)
Beispiel #40
0
def test_composite_commutativity():
    c = Computation((1, 2), (3,)) + Computation((3, 4), (5, 6))
    e = Computation((0, 4), (5, 6)) + Computation((1, 2), (0,))

    with variables(0):
        assert run(0, 0, eqac(c, e)) == (3,)
def cal_relation():
    txt.delete(0.0, 'end')
    name = e1.get()
    name2 = e2.get()
    if __name__ == '__main__':
        Root = Relation()
    with open('project.json') as f:
        d = json.loads(f.read())

    for item in d['Root']:
        facts(Root, (list(item.keys())[0], list(item.values())[0]))

    x = var()

    # Depository
    if (name == 'Depository' or name2 == 'Depository'):
        if (name == 'Depository'):
            output = run(0, x, Root(name, x))
        else:
            output = run(0, x, Root(name2, x))

        ##print("\nList of " + name + "'s children:")
        for item in output:
            if ((name2 == "Stock Exchange" and name == "Depository")
                    or (name == "Stock Exchange" and name2 == "Depository")):
                txt.insert(
                    END,
                    "It is regulator of Shares where all the Share of Stock exchange are strored"
                )
                break
            if ((name2 == "Customer" and name == "Depository")
                    or (name == "Customer" and name2 == "Depository")):
                txt.insert(
                    END,
                    "Individual Shares of Each Person are Contained by depository"
                )
                break
            if ((name2 == "Broker" and name == "Depository")
                    or (name == "Broker" and name2 == "Depository")):
                txt.insert(
                    END,
                    "A stock broker connects the buyers and sellers of stocks,While a depository participant is described as an agent of the depository"
                )
                break
            if ((name2 == "Divident" and name == "Depository")
                    or (name == "Divident" and name2 == "Depository")):
                txt.insert(
                    END,
                    "Globally, distribution of dividends is by depositories")
                break
            else:
                txt.insert(
                    END,
                    "This relationship is Not Defined Directly or may be some Alphabeticall Error"
                )
                break

    #Customer
    elif (name == 'Customer' or name2 == 'Customer'):
        if (name == 'Customer'):
            output = run(0, x, Root(name, x))
        else:
            output = run(0, x, Root(name2, x))

        ##print("\nList of " + name + "'s children:")
        for item in output:
            if ((name2 == "Stock Exchange" and name == "Customer")
                    or (name == "Stock Exchange" and name2 == "Customer")):
                txt.insert(
                    END,
                    "Stock exchange is a place where the trading is executed and from here Customer get the idea to buy any share or not"
                )
                break
            if ((name2 == "Seller" and name == "Customer")
                    or (name == "Seller" and name2 == "Customer")):
                txt.insert(
                    END,
                    "Seller who sells and Customer who are ready to buy the shares"
                )
                break
            if ((name2 == "Divident" and name == "Customer")
                    or (name == "Divident" and name2 == "Customer")):
                txt.insert(
                    END,
                    "After Earning From the shares as a profit we get a divident as we get a interest in Banks"
                )
                break
            if ((name2 == "DEMAT ACC." and name == "Customer")
                    or (name == "DEMAT ACC." and name2 == "Customer")):
                txt.insert(
                    END,
                    "Where Customer Can go through the detail of the personal invested shares through Demat Account"
                )
                break
            if ((name2 == "Broker" and name == "Customer")
                    or (name == "Broker" and name2 == "Customer")):
                txt.insert(
                    END,
                    "Who acts as a intermediate between Customer and Stock market and helps him to invest in shares"
                )
                break
            if ((name2 == "Registrar" and name == "Customer")
                    or (name == "Registrar" and name2 == "Customer")):
                txt.insert(
                    END,
                    "A registrar is a bank or a similar company that is responsible for recordkeeping of bondholders and shareholders. "
                )
                break
            else:
                txt.insert(
                    END,
                    "This relationship is Not Defined Directly or may be some Alphabeticall Error"
                )
                break

    #Demat Acc.
    elif (name == "DEMAT ACC." or name2 == "DEMAT ACC."):
        if (name == "DEMAT ACC."):
            output = run(0, x, Root(name, x))
        else:
            output = run(0, x, Root(name2, x))

        ##print("\nList of " + name + "'s children:")
        for item in output:
            if ((name2 == "Seller" and name == "DEMAT ACC.")
                    or (name == "Seller" and name2 == "DEMAT ACC.")):
                txt.insert(
                    END,
                    "Seller sells their share after it collect the remaining shares informtion from DEMAT Account"
                )
                break
            if ((name2 == "Divident" and name == "DEMAT ACC.")
                    or (name == "Divident" and name2 == "DEMAT ACC.")):
                txt.insert(
                    END,
                    "Divident is Generated only u have Demat acc. becoz it contain all your information"
                )
                break
            if ((name2 == "Broker" and name == "DEMAT ACC.")
                    or (name == "Broker" and name2 == "DEMAT ACC.")):
                txt.insert(
                    END,
                    "Broker Provide you the Demat Account Where u get the information of all Shares"
                )
                break
            if ((name2 == "Stock Exchange" and name == "DEMAT ACC.")
                    or (name == "Stock Exchange" and name2 == "DEMAT ACC.")):
                txt.insert(
                    END,
                    "After invested in Shares with the help of Stock exchange we are ready to update our Demat Account"
                )
                break
            else:
                txt.insert(
                    END,
                    "This relationship is Not Defined Directly or may be some Alphabeticall Error"
                )
                break

    #Clearing House
    elif (name == "Clearing House" or name2 == "Clearing House"):
        if (name == "Clearing House"):
            output = run(0, x, Root(name, x))
        else:
            output = run(0, x, Root(name2, x))

        ##print("\nList of " + name + "'s children:")
        for item in output:
            if ((name2 == "Stock Exchange" and name == "Clearing House") or
                (name == "Stock Exchange" and name2 == "Clearing House")):
                txt.insert(
                    END,
                    "A clearing house acts as an intermediary between a buyer and seller and seeks to ensure that the process from trade inception to settlement is smooth."
                )
                break
            else:
                txt.insert(
                    END,
                    "This relationship is Not Defined Directly or may be some Alphabeticall Error"
                )
                break
    #Divident
    elif (name == "Divident" or name2 == "Divident"):
        if (name == "Divident"):
            output = run(0, x, Root(name, x))
        else:
            output = run(0, x, Root(name2, x))

        ##print("\nList of " + name + "'s children:")
        for item in output:
            if ((name2 == "Registrar" and name == "Divident")
                    or (name == "Registrar" and name2 == "Divident")):
                txt.insert(
                    END,
                    "The registrar determines which shareholders are paid a cash or stock dividend."
                )
                break
            else:
                txt.insert(
                    END,
                    "This relationship is Not Defined Directly or may be some Alphabeticall Error"
                )
                break
    else:
        txt.insert(
            END,
            "This relationship is Not Defined Directly or may be some Alphabeticall Error"
        )
Beispiel #42
0
x = var()
y = var()
z = var()

if name == "":
    quit()

FakeName = name.upper()
name = name.lower()
if name in NameList:

    Relat = Relat.lower()
    if Relat == 'parent' or Relat == 'parents' or Relat == "father" or Relat == "mother":
        option = Relat
        if option == 'parent' or option == 'parents':
            out = (run(0, x, parents(x, name)))
        elif option == 'mother':
            out = (run(0, x, Mother(x, name)))
        else:
            out = (run(1, x, Father(x, name)))
        list1 = list(out)
        if len(out) == 0:
            print(
                color.Cyan + color.Bold + color.Underline + FakeName +
                color.End, color.Green +
                "Parent Details Not In DataBase---SORRY" + color.End)

    elif Relat == 'sibling' or Relat == 'sister' or Relat == 'brother' or Relat == 'siblings':
        option = Relat
        if option == 'sibling' or option == 'siblings':
            out = (run(0, x, sibling(x, name)))
Beispiel #43
0
def test_rs1_13():
    q = var()
    eq((True,), run(0, q,
                    success,
                    unify(True, q)))
Beispiel #44
0
from logpy import run, var, fact
import logpy.assoccomm as la

# Define mathematical operations
add = 'addition'
mul = 'multiplication'

# Declare that these operations are commutative
# using the facts system
fact(la.commutative, mul)
fact(la.commutative, add)
fact(la.associative, mul)
fact(la.associative, add)

# Define some variables
a, b, c = var('a'), var('b'), var('c')

# Generate expressions
expression_orig = (add, (mul, 3, -2), (mul, (add, 1, (mul, 2, 3)), -1))
expression1 = (add, (mul, (add, 1, (mul, 2, a)), b), (mul, 3, c))
expression2 = (add, (mul, c, 3), (mul, b, (add, (mul, 2, a), 1)))
expression3 = (add, (add, (mul, (mul, 2, a), b), b), (mul, 3, c))

# Compare expressions
print(run(0, (a, b, c), la.eq_assoccomm(expression1, expression_orig)))
print(run(0, (a, b, c), la.eq_assoccomm(expression2, expression_orig)))
print(run(0, (a, b, c), la.eq_assoccomm(expression3, expression_orig)))
Beispiel #45
0
unifiable(Account)  # Register Account class

accounts = (Account('Adam', 'Smith', 1,
                    20), Account('Carl', 'Marx', 2,
                                 3), Account('John', 'Rockefeller', 3, 1000))

# variables are arbitrary Python objects, not LogPy Var objects
first = 'FIRST'
last = 'LAST'
ident = -1111
balance = -2222
newbalance = -3333
vars = {first, last, ident, balance, newbalance}

# Describe a couple of transformations on accounts
source = Account(first, last, ident, balance)
target = Account(first, last, ident, newbalance)

theorists = ('Adam', 'Carl')
# Give $10 to theorists
theorist_bonus = lall((membero, source, accounts), (membero, first, theorists),
                      (add, 10, balance, newbalance))

# Take $10 from anyone with more than $100
tax_the_rich = lall((membero, source, accounts), (gt, balance, 100),
                    (sub, balance, 10, newbalance))

with variables(*vars):
    print run(0, target, tax_the_rich)
    print run(0, target, theorist_bonus)
Beispiel #46
0
    name = 'Tiffany'
    name_father = run(0, x, father(x, name))[0]
    output = run(0, x, uncle(x, name))
    output = [x for x in output if x != name_father]
    print("\nList of " + name + "'s uncles:")
    for item in output:
        print(item)
    # All spouses
    a, b, c = var(), var(), var()
    output = run(0, (a, b), (father, a, c), (mother, b, c))
    print("\nList of all spouses:")
    for item in output:
        print('Husband:', item[0], '<==> Wife:', item[1])'''

    name = "Megan"
    output = run(0, x, mother(name, x))
    print("\nList of " + name + "'s children:")
    for item in output:
        print(item)

        # Родители Neil
    name = "Neil"
    output = run(0, x, parent(x, name))
    print("\nList of " + name + "'s parents:")
    for item in output:
        print(item)

        # Sophia grandparents
    name = 'Sophia'
    output = run(0, x, grandmother(x, name))
    print("\nList of " + name + "'s grandmother:")
Beispiel #47
0
    # David's siblings
    name = 'David'
    output = run(0, x, sibling(x, name))
    siblings = [x for x in output if x != name]
    print("\nList of " + name + "'s siblings:")
    for item in siblings:
        print(item)

    # Tiffany's uncles
    name = 'Tiffany'
    name_father = run(0, x, father(x, name))[0]
    output = run(0, x, uncle(x, name))
    output = [x for x in output if x != name_father]
    print("\nList of " + name + "'s uncles:")
    for item in output:
        print(item)

    # All spouses
    a, b, c = var(), var(), var()
    output = run(0, (a, b), (father, a, c), (mother, b, c))
    print("\nList of all spouses:")
    for item in output:
        print('Husband:', item[0], '<==> Wife:', item[1])'''

    name = "Megan"
    output = run(0, x, mother(name, x))
    print("\nList of " + name + "'s children:")
    for item in output:
        print(item)