def test_reify_object(): obj = reify_object(Foo(1, var(3)), {var(3): 4}) assert obj.a == 1 assert obj.b == 4 f = Foo(1, 2) assert reify_object(f, {}) is f
def test_unify_slice(): x = var('x') y = var('y') assert unify(slice(1), slice(1), {}) == {} assert unify(slice(1, 2, 3), x, {}) == {x: slice(1, 2, 3)} assert unify(slice(1, 2, None), slice(x, y), {}) == {x: 1, y: 2}
def test_reify_object_attrs(): x, y = var('x'), var('y') f, g = Foo(1, 2), Foo(x, y) s = {x: 1, y: 2} assert reify_object_attrs(g, s, ['a', 'b']) == f assert reify_object_attrs(g, s, ['a']) == Foo(1, y) assert reify_object_attrs(g, s, ['b']) == Foo(x, 2) assert reify_object_attrs(g, s, []) is g
def test_reify(): x, y, z = var(), var(), var() s = {x: 1, y: 2, z: (x, y)} assert reify(x, s) == 1 assert reify(10, s) == 10 assert reify((1, y), s) == (1, 2) assert reify((1, (x, (y, 2))), s) == (1, (1, (2, 2))) assert reify(z, s) == (1, 2)
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
def test_seq_registry(): seq_registry.append((Foo, lambda x: (type(x), x.a, x.b))) x = var('x') y = var('y') f, g = Foo(1, 2), Foo(x, y) assert unify(f, g, {}) == {x: 1, y: 2} seq_registry.pop()
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]), )
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]),)
def test_unify_isinstance_list(): class Foo2(Foo): pass x = var('x') y = var('y') f, g = Foo2(1, 2), Foo2(x, y) _unify.add((Foo, Foo, dict), unify_object) _reify.add((Foo, dict), reify_object) assert unify(f, g, {}) assert reify(g, {x: 1, y: 2}) == f
def test_unify_isinstance_list(): class Foo2(Foo): pass x = var('x') y = var('y') f, g = Foo2(1, 2), Foo2(x, y) unify_isinstance_list.append(((Foo, Foo), unify_object)) reify_isinstance_list.append((Foo, reify_object)) assert unify(f, g, {}) assert reify(g, {x: 1, y: 2}) == f unify_isinstance_list.pop() reify_isinstance_list.pop()
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 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
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]
def test_unifiable_with_term(): add = Op('add') t = MyTerm(add, (1, 2)) assert arguments(t) == (1, 2) assert operator(t) == add assert term(operator(t), arguments(t)) == t x = var('x') assert unify(MyTerm(add, (1, x)), MyTerm(add, (1, 2)), {}) == {x: 2}
def test_logify_slots(): x = var('x') f = Aslot() f.a = 1 f.b = 2 g = Aslot() g.a = 1 g.b = x assert unify(f, g, {}) == {x: 2} assert reify(g, {x: 2}) == f
def test_unify_complex(): assert unify((1, {2: 3}), (1, {2: 3}), {}) == {} assert unify((1, {2: 3}), (1, {2: 4}), {}) == False assert unify((1, {2: var(5)}), (1, {2: 4}), {}) == {var(5): 4} assert unify({1: (2, 3)}, {1: (2, var(5))}, {}) == {var(5): 3} assert unify({1: [2, 3]}, {1: [2, var(5)]}, {}) == {var(5): 3}
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_objects_full(): _unify.add((Foo, Foo, dict), unify_object) _unify.add((Bar, Bar, dict), unify_object) _reify.add((Foo, dict), reify_object) _reify.add((Bar, dict), reify_object) assert unify_object(Foo(1, Bar(2)), Foo(1, Bar(var(3))), {}) == {var(3): 2} assert reify(Foo(var('a'), Bar(Foo(var('b'), 3))), {var('a'): 1, var('b'): 2}) == Foo(1, Bar(Foo(2, 3)))
def test_objects_full(): _unify.add((Foo, Foo, dict), unify_object) _unify.add((Bar, Bar, dict), unify_object) _reify.add((Foo, dict), reify_object) _reify.add((Bar, dict), reify_object) assert unify_object(Foo(1, Bar(2)), Foo(1, Bar(var(3))), {}) == {var(3): 2} assert reify(Foo(var('a'), Bar(Foo(var('b'), 3))), { var('a'): 1, var('b'): 2 }) == Foo(1, Bar(Foo(2, 3)))
def test_objects_full(): unify_dispatch[(Foo, Foo)] = unify_object unify_dispatch[(Bar, Bar)] = unify_object reify_dispatch[Foo] = reify_object reify_dispatch[Bar] = reify_object assert unify_object(Foo(1, Bar(2)), Foo(1, Bar(var(3))), {}) == {var(3): 2} assert reify(Foo(var('a'), Bar(Foo(var('b'), 3))), {var('a'): 1, var('b'): 2}) == Foo(1, Bar(Foo(2, 3))) del reify_dispatch[Bar] del reify_dispatch[Foo] del unify_dispatch[(Foo, Foo)] del unify_dispatch[(Bar, Bar)]
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')))
def grandparent(x, z): y = var() return conde((parent(x,y), parent(y,z)))
def aunty(x, y): z = var() return conde((uncle(z, y), Couple(z, x), Female(x)))
def sister(x, y): z = var() return conde((parents(z, x), parents(z, y), Female(x)))
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')))
def grandparent(x, y): temp = var() return conde((parent(x, temp), parent(temp, y)))
def uncle(x, y): temp = var() return conde((father(temp, x), grandparent(temp, y)))
def grandparents(x, y): z = var() return conde((parents(x, z), parents(z, y)))
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
def grandfather(x, y): z = var() return conde((grandparents(x, y), Male(x)))
def test_unify_seq(): assert unify((1, 2), (1, 2), {}) == {} assert unify([1, 2], [1, 2], {}) == {} assert unify((1, 2), (1, 2, 3), {}) == False assert unify((1, var(1)), (1, 2), {}) == {var(1): 2} assert unify((1, var(1)), (1, 2), {var(1): 3}) == False
def test_reify_list(): x, y = var(), var() s = {x: 2, y: 4} e = [1, [x, 3], y] assert reify(e, s) == [1, [2, 3], 4]
def grandparent(x, z): y = var() return conde((parent(x, y), parent(y, z)))
def grandmother(x, y): z = var() return conde((grandparents(x, y), Female(x)))
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" )
def sibling(x, y): z = var() return conde((parents(z, x), parents(z, y)))
def test_reify_dict(): x, y = var(), var() s = {x: 2, y: 4} e = {1: x, 3: {5: y}} assert reify(e, s) == {1: 2, 3: {5: 4}}
def test_reify_slice(): x = var('x') assert reify(slice(1, var(2), 3), {var(2): 10}) == slice(1, 10, 3)
def test_reify_complex(): x, y = var(), var() s = {x: 2, y: 4} e = {1: [x], 3: (y, 5)} assert reify(e, s) == {1: [2], 3: (4, 5)}
def test_unify_object_attrs(): x, y = var('x'), var('y') f, g = Foo(1, 2), Foo(x, y) assert unify_object_attrs(f, g, {}, ['a']) == {x: 1} assert unify_object_attrs(f, g, {}, ['b']) == {y: 2} assert unify_object_attrs(f, g, {}, []) == {}
def test_unify(): assert unify(1, 1, {}) == {} assert unify(1, 2, {}) == False assert unify(var(1), 2, {}) == {var(1): 2} assert unify(2, var(1), {}) == {var(1): 2}
from logpy import Relation, facts, run, conde, var, eq 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 test_unify_dict(): assert unify({1: 2}, {1: 2}, {}) == {} assert unify({1: 2}, {1: 3}, {}) == False assert unify({2: 2}, {1: 2}, {}) == False assert unify({1: var(5)}, {1: 2}, {}) == {var(5): 2}
def grandparent(gparent, child): p = var() return conde((parent(gparent, p), parent(p, child)))
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)))
def sibling(a, b): p = var() return conde((parent(p, a), parent(p, b)))
return conde((mother(x, temp), parent(temp, y))) if __name__ == '__main__': father = Relation() 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:")
if __name__ == '__main__': father = Relation() mother = Relation() 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'
def sibling(x, y): temp = var() return conde((parent(temp, x), parent(temp, y)))
from logpy import var from logpy.arith import lt, gt, lte, gte, add, sub, mul, mod x = var('x') y = var('y') def results(g): return list(g({})) def test_lt(): assert results(lt(1, 2)) assert not results(lt(2, 1)) assert not results(lt(2, 2)) def test_gt(): assert results(gt(2, 1)) assert not results(gt(1, 2)) assert not results(gt(2, 2)) def test_lte(): assert results(lte(2, 2)) def test_gte(): assert results(gte(2, 2)) def test_add(): assert results(add(1, 2, 3)) assert not results(add(1, 2, 4)) assert results(add(1, 2, 3)) assert results(add(1, 2, x)) == [{x: 3}] assert results(add(1, x, 3)) == [{x: 2}]
def grandmother(x, y): temp = var() return conde((mother(x, temp), parent(temp, y)))
def brother(x, y): z = var() return conde((parents(z, x), parents(z, y), Male(x)))