Beispiel #1
0
    def manual_constructs(self):
        p1 = c_const("p1")
        p2 = c_const("p2")
        p3 = c_const("p3")

        parent = c_pred("parent", 2)
        grandparent = c_pred("grandparent", 2)

        f1 = parent(p1, p2)
        f2 = parent(p2, p3)

        v1 = c_var("X")
        v2 = c_var("Y")
        v3 = c_var("Z")

        cl = grandparent(v1, v3) <= parent(v1, v2) & parent(v2, v3)

        assert isinstance(p1, Constant)
        assert isinstance(p2, Constant)
        assert isinstance(p3, Constant)

        assert isinstance(parent, Predicate)
        assert isinstance(grandparent, Predicate)

        assert isinstance(v1, Variable)
        assert isinstance(v2, Variable)
        assert isinstance(v2, Variable)

        assert isinstance(cl, Clause)

        assert isinstance(f1, Atom)
        assert isinstance(f2, Atom)
Beispiel #2
0
    def graph_connectivity(self):
        v1 = c_const("v1")
        v2 = c_const("v2")
        v3 = c_const("v3")
        v4 = c_const("v4")

        edge = c_pred("edge", 2)
        path = c_pred("path", 2)

        f1 = edge(v1, v2)
        f2 = edge(v1, v3)
        f3 = edge(v2, v4)

        X = c_var("X")
        Y = c_var("Y")
        Z = c_var("Z")

        cl1 = path(X, Y) <= edge(X, Y)
        cl2 = path(X, Y) <= path(X, Z) & edge(Z, Y)

        solver = MuZ()

        solver.assert_fact(f1)
        solver.assert_fact(f2)
        solver.assert_fact(f3)

        solver.assert_rule(cl1)
        solver.assert_rule(cl2)

        # assert solver.has_solution(path(v1, v2))
        # assert solver.has_solution(path(v1, v4))
        # assert not solver.has_solution(path(v3, v4))
        #
        # assert len(solver.one_solution(path(v1, X))) == 1
        # assert len(solver.one_solution(path(X, v4))) == 1
        # assert len(solver.one_solution(path(X, Y))) == 2
        #
        # assert len(solver.all_solutions(path(v1, X))) == 3
        # assert len(solver.all_solutions(path(X, Y))) == 4

        assert solver.has_solution(path(v1, v2))
        assert solver.has_solution(path(v1, v4))
        assert not solver.has_solution(path(v3, v4))

        assert len(solver.query(path(v1, X), max_solutions=1)[0]) == 1
        assert len(solver.query(path(X, v4), max_solutions=1)[0]) == 1
        assert len(solver.query(path(X, Y), max_solutions=1)[0]) == 2

        assert len(solver.query(path(v1, X))) == 3
        assert len(solver.query(path(X, Y))) == 4
Beispiel #3
0
 def variables(self, y, l):
     number = min(26, y)
     self._encodingvariables = []
     self._variablesindices = {}
     index = 0
     for code in range(ord('A'), ord('A') + number):
         self._variablesindices[c_var(chr(code))] = index
         index = index + l
         for i in range(0, l):
             self._encodingvariables.append(0)
Beispiel #4
0
 def all_possible_atoms(self) -> Sequence[Atom]:
     """
     Creates all possible argument configurations for the atom
     """
     head_variables = [c_var(chr(x))
                       for x in range(ord("A"), ord("Z"))][:self._arity]
     if self._arity is not None:
         return [
             Atom(self.new(), list(x))
             for x in product(head_variables, repeat=self._arity)
         ]
     else:
         combos = []
         for i in range(self._min_arity, self._max_arity):
             combos += [
                 Atom(self.new(arity=i), list(x))
                 for x in product(head_variables, repeat=i)
             ]
         return combos
def new_variable(
    existing_variables: typing.Set[Variable], type: Type = None
) -> Variable:
    existing_variable_names = {x.get_name() for x in existing_variables}
    if len(existing_variables) < 27:
        potential_names = [
            chr(x)
            for x in range(ord("A"), ord("Z") + 1)
            if chr(x) not in existing_variable_names
        ]
    else:
        potential_names = [
            f"{chr(x)}{chr(y)}"
            for x in range(ord("A"), ord("Z") + 1)
            for y in range(ord("A"), ord("Z") + 1)
            if f"{chr(x)}{chr(y)}" not in existing_variable_names
        ]

    return c_var(potential_names[0], type)
Beispiel #6
0
from loreleai.language.lp import c_functor, c_pred, c_var, List
from loreleai.reasoning.lp.prolog import GNUProlog

pl = GNUProlog()

p = c_pred("p", 2)
f = c_functor("t", 3)
f1 = p("a", "b")

pl.assertz(f1)

X = c_var("X")
Y = c_var("Y")

query = p(X, Y)

r = pl.has_solution(query)
print("has solution", r)

rv = pl.query(query)
print("all solutions", rv)

f2 = p("a", "c")
pl.assertz(f2)

rv = pl.query(query)
print("all solutions after adding f2", rv)

func1 = f(1, 2, 3)
f3 = p(func1, "b")
Beispiel #7
0
 not_letter = c_pred("not_letter", 1)
 is_number = c_pred("is_number", 1)
 not_number = c_pred("not_number", 1)
 skip1 = c_pred("skip1", 2)
 copy1 = c_pred("copy1", 2)
 write1 = c_pred("write1", 3)
 copyskip1 = c_pred("copyskip1", 2)
 mk_uppercase = c_pred("mk_uppercase", 2)
 mk_lowercase = c_pred("mk_lowercase", 2)
 convert_case = c_pred("convert_case", 2)
 is_number_aux = c_pred("is_number_aux", 1)
 s = c_pred("s", 2)
 b45 = c_pred("b45", 2)
 is_uppercase = c_pred("is_uppercase", 1)
 # define the Variables
 H = c_var("H")
 Ta = c_var("Ta")
 Tb = c_var("Tb")
 A = c_var("A")
 B = c_var("B")
 C = c_var("C")
 D = c_var("D")
 E = c_var("E")
 H1 = c_var("H1")
 H2 = c_var("H2")
 Z = c_var("Z")
 O = c_var("O")
 N = c_var("N")
 # create clauses
 head = Atom(not_space, [A])
 body = Atom(is_space, [A])
Beispiel #8
0
def learn_text():
    """
    We describe piece of text spanning multiple lines:
    "node A red <newline> node B green <newline> node C blue <newline>"
    using the next\2, linestart\2, lineend\2, tokenlength\2 predicates
    """
    token = c_type("token")
    num = c_type("num")

    next = c_pred("next", 2, ("token", "token"))
    linestart = c_pred("linestart", 2, ("token", "token"))
    lineend = c_pred("lineend", 2, ("token", "token"))
    tokenlength = c_pred("tokenlength", 2, ("token", "num"))

    n1 = c_const("n1", num)
    n3 = c_const("n3", num)
    n4 = c_const("n4", num)
    n5 = c_const("n5", num)
    node1 = c_const("node1", token)
    node2 = c_const("node2", token)
    node3 = c_const("node3", token)
    red = c_const("red", token)
    green = c_const("green", token)
    blue = c_const("blue", token)
    a_c = c_const("a_c", token)
    b_c = c_const("b_c", token)
    c_c = c_const("c_c", token)
    start = c_const("c_START", token)
    end = c_const("c_END", token)

    bk = Knowledge(next(start, node1), next(node1, a_c), next(a_c, red),
                   next(red, node2), next(node2, green), next(green, b_c),
                   next(b_c, node3), next(node3, c_c), next(c_c, blue),
                   next(blue, end), tokenlength(node1, n4),
                   tokenlength(node2, n4), tokenlength(node3, n4),
                   tokenlength(a_c, n1), tokenlength(b_c, n1),
                   tokenlength(c_c, n1), tokenlength(red, n3),
                   tokenlength(green, n5), tokenlength(blue, n4),
                   linestart(node1, node1), linestart(a_c, node1),
                   linestart(red, node1), linestart(node2, node2),
                   linestart(b_c, node2), linestart(green, node2),
                   linestart(node3, node3), linestart(c_c, node3),
                   linestart(blue, node3), lineend(node1, a_c),
                   lineend(a_c, red), lineend(node2, red), lineend(b_c, green),
                   lineend(node3, blue), lineend(c_c, blue), lineend(red, red),
                   lineend(green, green), lineend(blue, blue))

    solver = SWIProlog()
    eval_fn1 = Coverage(return_upperbound=True)
    learner = Aleph(solver, eval_fn1, max_body_literals=3, do_print=False)

    # 1. Consider the hypothesis: f1(word) :- word is the second word on a line
    if True:
        f1 = c_pred("f1", 1, [token])
        neg = {f1(x) for x in [node1, node2, node3, blue, green, red]}
        pos = {f1(x) for x in [a_c, b_c, c_c]}
        task = Task(positive_examples=pos, negative_examples=neg)

        res = learner.learn(task, bk, None)
        print(res)

    # 2. Consider the hypothesis: f2(word) :- word is the first word on a line
    if True:
        f2 = c_pred("f2", 1, [token])
        neg = {f1(x) for x in [a_c, b_c, c_c, blue, green, red]}
        pos = {f1(x) for x in [node1, node2, node3]}
        task2 = Task(positive_examples=pos, negative_examples=neg)

        res = learner.learn(task2, bk, None)
        print(res)

    # 3. Assume we have learned the predicate node(X) before (A, B and C and nodes).
    # We want to learn f3(Node,X) :- X is the next token after Node
    if True:
        node = c_pred("node", 1, [token])
        color = c_pred("color", 1, [token])
        nodecolor = c_pred("nodecolor", 2, [token, token])
        a = c_var("A", token)
        b = c_var("B", token)
        bk_old = bk.get_all()
        bk = Knowledge(*bk_old, node(a_c), node(b_c), node(c_c), node(a_c),
                       node(b_c), node(c_c), color(red), color(green),
                       color(blue))
        pos = {
            nodecolor(a_c, red),
            nodecolor(b_c, green),
            nodecolor(c_c, blue)
        }
        neg = set()
        neg = {
            nodecolor(node1, red),
            nodecolor(node2, red),
            nodecolor(node3, red),
            nodecolor(node1, blue),
            nodecolor(node2, blue),
            nodecolor(node2, blue),
            nodecolor(node1, green),
            nodecolor(node2, green),
            nodecolor(node3, green),
            nodecolor(a_c, green),
            nodecolor(a_c, blue),
            nodecolor(b_c, blue),
            nodecolor(b_c, red),
            nodecolor(c_c, red),
            nodecolor(c_c, green)
        }
        task3 = Task(positive_examples=pos, negative_examples=neg)

        # prog = learner.learn(task3,bk,None,initial_clause=Body(node(a),color(b)))
        result = learner.learn(task3,
                               bk,
                               None,
                               initial_clause=Body(node(a), color(b)),
                               minimum_freq=3)
        print(result)
 not_letter = c_pred("not_letter", 1)
 is_number = c_pred("is_number", 1)
 not_number = c_pred("not_number", 1)
 skip1 = c_pred("skip1", 2)
 copy1 = c_pred("copy1", 2)
 write1 = c_pred("write1", 3)
 copyskip1 = c_pred("copyskip1", 2)
 mk_uppercase = c_pred("mk_uppercase", 2)
 mk_lowercase = c_pred("mk_lowercase", 2)
 convert_case = c_pred("convert_case", 2)
 is_number_aux = c_pred("is_number_aux", 1)
 s = c_pred("s", 2)
 b45 = c_pred("b45", 2)
 is_uppercase = c_pred("is_uppercase", 1)
 # define the Variables
 H = c_var("H")
 Ta = c_var("Ta")
 Tb = c_var("Tb")
 A = c_var("A")
 B = c_var("B")
 H1 = c_var("H1")
 H2 = c_var("H2")
 Z = c_var("Z")
 O = c_var("O")
 N = c_var("N")
 # create clauses
 head = Atom(not_space, [A])
 body = Atom(is_space, [A])
 clause1 = Clause(head, Body(Not(body)))
 head = Atom(is_uppercase, [Structure(s, [Pair(H, Z), O])])
 body = Atom(is_uppercase_aux, [H])
Beispiel #10
0
    def simple_grandparent(self):
        p1 = c_const("p1")
        p2 = c_const("p2")
        p3 = c_const("p3")

        parent = c_pred("parent", 2)
        grandparent = c_pred("grandparent", 2)

        f1 = parent(p1, p2)
        f2 = parent(p2, p3)

        v1 = c_var("X")
        v2 = c_var("Y")
        v3 = c_var("Z")

        cl = (grandparent(v1, v3) <= parent(v1, v2) & parent(v2, v3))

        solver = MuZ()

        solver.assert_fact(f1)
        solver.assert_fact(f2)
        solver.assert_rule(cl)

        # assert solver.has_solution(parent(v1, v2))
        # assert not solver.has_solution(parent(v1, v1))
        # assert len(solver.all_solutions(parent(v1, v2))) == 2
        # assert len(solver.all_solutions(parent(p1, v1))) == 1
        # assert solver.has_solution(parent(p1, p2))
        # assert not solver.has_solution(parent(p2, p1))
        # assert len(solver.one_solution(parent(p1, v1))) == 1
        #
        # assert solver.has_solution(grandparent(v1, v2))
        # assert solver.has_solution(grandparent(p1, v1))
        # assert len(solver.one_solution(grandparent(p1, v1))) == 1
        # assert solver.has_solution(grandparent(p1, p3))
        # assert not solver.has_solution(grandparent(p2, v1))
        # assert len(solver.one_solution(grandparent(p1, v1))) == 1
        # ans = solver.one_solution(grandparent(p1, v1))
        # assert ans[v1] == p3
        # ans = solver.one_solution(grandparent(v1, v2))
        # assert ans[v1] == p1 and ans[v2] == p3
        #
        # assert solver.has_solution(cl)
        # ans = solver.one_solution(cl)
        # assert ans[v1] == p1 and ans[v3] == p3
        # assert len(solver.all_solutions(cl)) == 1

        assert solver.has_solution(parent(v1, v2))
        assert not solver.has_solution(parent(v1, v1))
        assert len(solver.query(parent(v1, v2))) == 2
        assert len(solver.query(parent(p1, v1))) == 1
        assert solver.has_solution(parent(p1, p2))
        assert not solver.has_solution(parent(p2, p1))
        assert len(solver.query(parent(p1, v1), max_solutions=1)) == 1

        assert solver.has_solution(grandparent(v1, v2))
        assert solver.has_solution(grandparent(p1, v1))
        assert len(solver.query(grandparent(p1, v1), max_solutions=1)) == 1
        assert solver.has_solution(grandparent(p1, p3))
        assert not solver.has_solution(grandparent(p2, v1))
        assert len(solver.query(grandparent(p1, v1), max_solutions=1)) == 1
        ans = solver.query(grandparent(p1, v1), max_solutions=1)[0]
        assert ans[v1] == p3
        ans = solver.query(grandparent(v1, v2), max_solutions=1)[0]
        assert ans[v1] == p1 and ans[v2] == p3

        assert solver.has_solution(*cl.get_literals())
        ans = solver.query(*cl.get_literals(), max_solutions=1)[0]
        assert ans[v1] == p1 and ans[v3] == p3
        assert len(solver.query(*cl.get_literals())) == 1
Beispiel #11
0
from filereaders.taskreader import readPositiveOfType
from loreleai.language.lp import c_pred, c_functor, c_var, List
from loreleai.reasoning.lp.prolog import SWIProlog

# Test for the given background knowledge
pl = SWIProlog()
pl.consult("../inputfiles/StringTransformations_BackgroundKnowledge.pl")

# Load all test tasks in a dictionary. The key is the id of a task and the value is a set of all tasks
test = readPositiveOfType("../inputfiles/StringTransformationProblems",
                          "test_task")

# Basic variables
test_task = c_pred("test_task", 1)
A = c_var("A")
B = c_var("B")

# one of the examples: test_task(s(['o','x','1',' ','3','c','p'],['O','X','1','3','C','P']))
# Everything in this set starts with lowercase 'o' in the input and uppercase 'O' in output, like the example above
# One example in this set is used to test if it's covered by the clauses below.
tex = test.get("b113").pop()
print(tex)

# We test whether the example starts without a space, this should be true
not_space = c_pred("not_space", 1)  # not_space(A):- \+is_space(A).
cl = test_task(A) <= not_space(A)
pl.asserta(cl)
sol = pl.has_solution(tex)  # Returns true, good
print(sol)
pl.retract(cl)