예제 #1
0
    def new(self,
            arity: int = None,
            argument_types: Sequence[Type] = None) -> Predicate:
        """
        Creates a new predicate from the template

        if the FillerPredicate is constructed with arity set, it returns a new predicate with that arity
        if the
        """
        assert (arity is not None or self._arity is not None
                or argument_types is not None)
        self._instance_counter += 1

        if argument_types is not None:
            assert (len(argument_types) == self._arity
                    or len(argument_types) >= self._min_arity
                    or len(argument_types) <= self._max_arity)
            return c_pred(
                f"{self._prefix_name}_{self._instance_counter}",
                self._arity,
                argument_types,
            )
        elif arity is not None:
            return c_pred(f"{self._prefix_name}_{self._instance_counter}",
                          arity)
        else:
            return c_pred(f"{self._prefix_name}_{self._instance_counter}",
                          self._arity)
예제 #2
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)
예제 #3
0
def learn_with_constants():
    """
    Consider a row of blocks [ block1 block2 block3 block4 block5 block6 ]
    The order of this row is expressed using follows(X,Y)
    The color of a block is expressed using color(X,Color)
    
    Goal: learn a function f that says: a block is positive when it is followed by a red block
    pos(X) :- next(X,Y), color(Y,red)
    """
    block = c_type("block")
    col = c_type("col")

    block1 = c_const("block1", domain=block)  # blue -> positive
    block2 = c_const("block2", domain=block)  # red
    block3 = c_const("block3", domain=block)  # green -> positive
    block4 = c_const("block4", domain=block)  # red -> positive
    block5 = c_const("block5", domain=block)  # red
    block6 = c_const("block6", domain=block)  # green
    block7 = c_const("block7", domain=block)  # blue
    block8 = c_const("block8", domain=block)  # blue

    red = c_const("red", domain="col")
    green = c_const("green", domain="col")
    blue = c_const("blue", domain="col")

    follows = c_pred("follows", 2, domains=[block, block])
    color = c_pred("color", 2, domains=[block, col])

    # Predicate to learn:
    f = c_pred("f", 1, domains=[block])

    bk = Knowledge(follows(block1, block2), follows(block2, block3),
                   follows(block3, block4), follows(block4, block5),
                   follows(block5, block6), follows(block6, block7),
                   follows(block7, block8), color(block1, blue),
                   color(block2, red), color(block3,
                                             green), color(block4, red),
                   color(block5, red), color(block6, green),
                   color(block7, blue), color(block8, blue))

    pos = {f(x) for x in [block1, block3, block4]}
    neg = {f(x) for x in [block2, block5, block6, block7, block8]}

    task = Task(positive_examples=pos, negative_examples=neg)
    solver = SWIProlog()

    # EvalFn must return an upper bound on quality to prune search space.
    eval_fn1 = Coverage(return_upperbound=True)
    eval_fn2 = Compression(return_upperbound=True)
    eval_fn3 = Accuracy(return_upperbound=True)

    learners = [
        Aleph(solver, eval_fn, max_body_literals=4, do_print=False)
        for eval_fn in [eval_fn1, eval_fn3]
    ]

    for learner in learners:
        res = learner.learn(task, bk, None, minimum_freq=1)
        print(res)
예제 #4
0
def learn_simpsons():
    # define the predicates
    father = c_pred("father", 2)
    mother = c_pred("mother", 2)
    grandparent = c_pred("grandparent", 2)

    # specify the background knowledge
    background = Knowledge(father("homer", "bart"), father("homer", "lisa"),
                           father("homer", "maggie"), mother("marge", "bart"),
                           mother("marge", "lisa"), mother("marge", "maggie"),
                           mother("mona", "homer"), father("abe", "homer"),
                           mother("jacqueline", "marge"),
                           father("clancy", "marge"))

    # positive examples
    pos = {
        grandparent("abe", "bart"),
        grandparent("abe", "lisa"),
        grandparent("abe", "maggie"),
        grandparent("mona", "bart"),
        grandparent("abe", "lisa"),
        grandparent("abe", "maggie"),
        grandparent("jacqueline", "bart"),
        grandparent("jacqueline", "lisa"),
        grandparent("jacqueline", "maggie"),
        grandparent("clancy", "bart"),
        grandparent("clancy", "lisa"),
        grandparent("clancy", "maggie"),
    }

    # negative examples
    neg = {
        grandparent("abe", "marge"),
        grandparent("abe", "homer"),
        grandparent("abe", "clancy"),
        grandparent("abe", "jacqueline"),
        grandparent("homer", "marge"),
        grandparent("homer", "jacqueline"),
        grandparent("jacqueline", "marge"),
        grandparent("clancy", "homer"),
        grandparent("clancy", "abe")
    }

    task = Task(positive_examples=pos, negative_examples=neg)
    solver = SWIProlog()

    # EvalFn must return an upper bound on quality to prune search space.
    eval_fn = Coverage(return_upperbound=True)
    eval_fn2 = Compression(return_upperbound=True)
    eval_fn3 = Compression(return_upperbound=True)

    learner = Aleph(solver, eval_fn, max_body_literals=4, do_print=False)
    learner2 = Aleph(solver, eval_fn2, max_body_literals=4, do_print=False)
    learner3 = Aleph(solver, eval_fn3, max_body_literals=4, do_print=False)

    result = learner.learn(task, background, None)
    print(result)
예제 #5
0
    def plain_clause_extensions_connected(self):
        parent = c_pred("parent", 2)
        grandparent = c_pred("grandparent", 2)

        cl1 = grandparent("X", "Y") <= parent("X", "Z")

        extensions = plain_extension(cl1, parent, connected_clauses=True)

        assert len(extensions) == 15
예제 #6
0
    def plain_procedure_extension(self):
        parent = c_pred("parent", 2)
        ancestor = c_pred("ancestor", 2)

        cl1 = ancestor("X", "Y") <= parent("X", "Y")
        cl2 = ancestor("X", "Y") <= parent("X", "Z") & parent("Z", "Y")

        proc = Disjunction([cl1, cl2])

        extensions = plain_extension(proc, parent, connected_clauses=False)

        assert len(extensions) == 25
예제 #7
0
    def recursions(self):
        parent = c_pred("parent", 2)
        ancestor = c_pred("ancestor", 2)

        hs = TopDownHypothesisSpace(primitives=[
            lambda x: plain_extension(x, parent, connected_clauses=True)
        ],
                                    head_constructor=ancestor,
                                    recursive_procedures=True)

        cls = hs.get_current_candidate()
        cls2 = hs.expand(cls[1])
        print(cls2)
예제 #8
0
    def _from_body_fixed_arity(
        self,
        body: Body,
        arity: int = None,
        arg_types: Sequence[Type] = None,
        use_as_head_predicate: Predicate = None,
    ) -> Sequence[Atom]:
        """
        Creates a head atom given the body of the clause
        :param body:
        :param arity: (optional) desired arity if specified with min/max when constructing the FillerPredicate
        :param arg_types: (optional) argument types to use
        :return:
        """
        assert bool(arity) != bool(arg_types)
        vars = body.get_variables()

        if use_as_head_predicate and arg_types is None:
            arg_types = use_as_head_predicate.get_arg_types()

        if arg_types is None:
            base = [vars] * arity
        else:
            matches = {}

            for t_ind in range(len(arg_types)):
                matches[t_ind] = []
                for v_ind in range(len(vars)):
                    if vars[v_ind].get_type() == arg_types[t_ind]:
                        matches[t_ind].append(vars[v_ind])

            base = [matches[x] for x in range(arity)]

        heads = []
        for comb in product(*base):
            self._instance_counter += 1
            if use_as_head_predicate is not None:
                pred = use_as_head_predicate
            elif arg_types is None:
                pred = c_pred(f"{self._prefix_name}_{self._instance_counter}",
                              arity)
            else:
                pred = c_pred(
                    f"{self._prefix_name}_{self._instance_counter}",
                    len(arg_types),
                    arg_types,
                )

            heads.append(Atom(pred, list(comb)))

        return heads
예제 #9
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
예제 #10
0
    def shorthand_constructs(self):
        parent = c_pred("parent", 2)
        grandparent = c_pred("grandparent", 2)

        f1 = parent("p1", "p2")
        f2 = parent("p2", "p3")
        f3 = grandparent("p1", "X")

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

        assert isinstance(f1, Atom)
        assert isinstance(f2, Atom)
        assert isinstance(f3, Atom)

        assert isinstance(f1.arguments[0], Constant)
        assert isinstance(f1.arguments[1], Constant)
        assert isinstance(f3.arguments[1], Variable)
예제 #11
0
    def bottom_up(self):
        a = c_pred("a", 2)
        b = c_pred("b", 2)
        c = c_pred("c", 1)
        h = c_pred("h", 2)

        cl = h("X", "Y") <= a("X", "Z") & b("Z", "Y") & c("X")

        bc = BottomClauseExpansion(cl)

        hs = TopDownHypothesisSpace(primitives=[lambda x: bc.expand(x)],
                                    head_constructor=h)

        cls = hs.get_current_candidate()
        assert len(cls) == 3

        exps = hs.expand(cls[1])
        assert len(exps) == 2

        exps2 = hs.expand(exps[0])
        assert len(exps2) == 4
예제 #12
0
    def top_down_plain(self):
        grandparent = c_pred("grandparent", 2)
        father = c_pred("father", 2)
        mother = c_pred("mother", 2)

        hs = TopDownHypothesisSpace(primitives=[
            lambda x: plain_extension(x, father),
            lambda x: plain_extension(x, mother)
        ],
                                    head_constructor=grandparent)

        current_cand = hs.get_current_candidate()
        assert len(current_cand) == 3

        expansions = hs.expand(current_cand[0])
        assert len(expansions) == 6

        expansions_2 = hs.expand(expansions[0])
        assert len(expansions_2) == 10

        expansions3 = hs.expand(expansions[1])
        assert len(expansions3) == 32

        hs.block(expansions[2])
        expansions4 = hs.expand(expansions[2])
        assert len(expansions4) == 0

        hs.remove(expansions[3])
        expansions5 = hs.get_successors_of(current_cand[0])
        assert len(expansions5) == 5

        hs.move_pointer_to(expansions[1])
        current_cand = hs.get_current_candidate()
        assert current_cand[0] == expansions[1]

        hs.ignore(expansions[4])
        hs.move_pointer_to(expansions[4])
        expansions6 = hs.get_current_candidate()
        assert len(expansions6) == 0
예제 #13
0
    def top_down_limited(self):
        grandparent = c_pred("grandparent", 2)
        father = c_pred("father", 2)
        mother = c_pred("mother", 2)

        hs = TopDownHypothesisSpace(
            primitives=[
                lambda x: plain_extension(x, father, connected_clauses=False),
                lambda x: plain_extension(x, mother, connected_clauses=False)
            ],
            head_constructor=grandparent,
            expansion_hooks_keep=[lambda x, y: connected_clause(x, y)],
            expansion_hooks_reject=[lambda x, y: has_singleton_vars(x, y)])

        current_cand = hs.get_current_candidate()
        assert len(current_cand) == 3

        expansions = hs.expand(current_cand[1])
        assert len(expansions) == 6

        expansion2 = hs.expand(expansions[1])
        assert len(expansion2) == 16
예제 #14
0
    def _add_to_body_fixed_arity(self, body: Body,
                                 arity: int) -> Sequence[Body]:
        new_pred_stash = {}  # arg_types tuple -> pred

        vars = body.get_variables()

        bodies = []

        args = list(combinations(vars, arity))
        for ind in range(len(args)):
            arg_types = (x.get_type() for x in args[ind])

            if arg_types in new_pred_stash:
                pred = new_pred_stash[arg_types]
            else:
                self._instance_counter += 1
                pred = c_pred(f"{self._prefix_name}{self._instance_counter}",
                              arity, arg_types)
                new_pred_stash[arg_types] = pred

            bodies.append(body + pred(*args[ind]))

        return bodies
예제 #15
0
        new_exps = []

        for ind in range(len(exps)):
            if exps[ind][1]:
                # keep it if it has solutions
                new_exps.append(exps[ind][0])
            else:
                # remove from hypothesis space if it does not
                hypothesis_space.remove(exps[ind][0])

        return new_exps


if __name__ == '__main__':
    # define the predicates
    father = c_pred("father", 2)
    mother = c_pred("mother", 2)
    grandparent = c_pred("grandparent", 2)

    # specify the background knowledge
    background = Knowledge(father("a", "b"), mother("a",
                                                    "b"), mother("b", "c"),
                           father("e", "f"), father("f", "g"),
                           mother("h", "i"), mother("i", "j"))

    # positive examples
    pos = {grandparent("a", "c"), grandparent("e", "g"), grandparent("h", "j")}

    # negative examples
    neg = {grandparent("a", "b"), grandparent("a", "g"), grandparent("i", "j")}
예제 #16
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
예제 #17
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)
예제 #18
0
if __name__ == '__main__':

    chosen_pred = "b45"

    backgroundknow, predicates = createKnowledge(
        "../inputfiles/StringTransformations_BackgroundKnowledge.pl",
        chosen_pred)
    train = readPositiveOfType("../inputfiles/StringTransformationProblems",
                               "train_task")
    # print(len(kip))
    test = readPositiveOfType("../inputfiles/StringTransformationProblems",
                              "test_task")
    # print(len(kip))

    # define the predicates
    father = c_pred("father", 2)
    mother = c_pred("mother", 2)
    grandparent = c_pred("grandparent", 2)

    # specify the background knowledge
    background = Knowledge(father("a", "b"), mother("a",
                                                    "b"), mother("b", "c"),
                           father("e", "f"), father("f", "g"),
                           mother("h", "i"), mother("i", "j"))

    # # positive examples
    # pos = {grandparent("a", "c"), grandparent("e", "g"), grandparent("h", "j")}
    #
    # # negative examples
    # neg = {grandparent("a", "b"), grandparent("a", "g"), grandparent("i", "j")}
    #
예제 #19
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")
예제 #20
0
                return newList
            if len(var2) == 1:
                newList = []
                newList.append(list[0].get_predicate()('Y', 'Z', 'U'))
                newList.append(list[1].get_predicate()('Y'))
                return newList
            if len(var2) == 2:
                newList = []
                newList.append(list[0].get_predicate()('Y', 'Z', 'U'))
                newList.append(list[1].get_predicate()('Y', 'Z'))
                return newList


if __name__ == '__main__':
    # define the predicates
    is_empty = c_pred("is_empty", 1)
    not_empty = c_pred("not_empty", 1)
    is_space = c_pred("is_space", 1)
    not_space = c_pred("not_space", 1)
    is_uppercase_aux = c_pred("is_uppercase_aux", 1)
    is_lowercase_aux = c_pred("is_lowercase_aux", 1)
    not_uppercase = c_pred("not_uppercase", 1)
    is_lowercase = c_pred("is_lowercase", 1)
    not_lowercase = c_pred("not_lowercase", 1)
    is_letter = c_pred("is_letter", 1)
    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)
예제 #21
0
def train_task(task_id: string,
               pos_multiplier: int,
               neg_example_offset: int,
               nn_amount: int,
               pos=None,
               neg=None):
    # Load needed files
    bk, predicates = createKnowledge(
        "../inputfiles/StringTransformations_BackgroundKnowledge.pl", task_id)

    if pos is None and neg is None:
        pos, neg = generate_examples(task_id, pos_multiplier,
                                     neg_example_offset)

    task = Task(positive_examples=pos, negative_examples=neg)

    # Calculate predicates
    total_predicates = []
    filtered_predicates = []
    for predicate in predicates:
        if predicate.name not in ["s", task_id
                                  ] and predicate not in filtered_predicates:
            total_predicates.append(lambda x, pred=predicate: plain_extension(
                x, pred, connected_clauses=True))
            filtered_predicates.append(predicate)

    # create the hypothesis space
    hs = TopDownHypothesisSpace(
        primitives=total_predicates,
        head_constructor=c_pred("test_task", 1),
        recursive_procedures=True,
        expansion_hooks_keep=[
            lambda x, y: connected_clause(x, y),
            lambda x, y: only_1_pred_for_1_var(x, y),
            lambda x, y: head_first(x, y)
        ],
        expansion_hooks_reject=[  # lambda x, y: has_singleton_vars(x, y),
            # Singleton-vars constraint is reduced to this constraint
            lambda x, y: has_not_previous_output_as_input(x, y),  # Strict
            # lambda x, y: has_new_input(x, y), # Not as strict
            # lambda x, y: has_unexplained_last_var(x, y), # For the 'write' predicate
            lambda x, y: has_unexplained_last_var_strict(
                x, y),  # Strict version of above
            lambda x, y: has_duplicated_literal(x, y),
            lambda x, y: has_g1_same_vars_in_literal(x, y),
            lambda x, y: has_duplicated_var_set(x, y),
            lambda x, y: has_double_recursion(x, y),
            lambda x, y: has_endless_recursion(x, y)
        ])

    learner = NeuralSearcher1(solver_instance=prolog,
                              primitives=filtered_predicates,
                              model_location="../utility/Saved_model_covered",
                              max_body_literals=10,
                              amount_chosen_from_nn=nn_amount,
                              filter_amount=30,
                              threshold=0.1)

    # Try to learn the program
    program, ss = learner.learn(
        task, "../inputfiles/StringTransformations_BackgroundKnowledge.pl", hs)
    print(program)

    return ss
예제 #22
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)