Пример #1
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
Пример #2
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
Пример #3
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
Пример #4
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
Пример #5
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)
Пример #6
0
 def __init__(
     self,
     primitives: typing.Sequence,
     head_constructor: typing.Union[Predicate, FillerPredicate],
     connected_clauses: bool = True,
     recursive_procedures: bool = False,
     expansion_hooks_keep: typing.Sequence = (),
     expansion_hooks_reject: typing.Sequence = ()
 ) -> None:
     self._primitives: typing.Sequence = primitives
     self._head_constructor: typing.Union[
         Predicate, FillerPredicate
     ] = head_constructor
     # Predicate -> use this predicate in the head
     # FillerPredicate -> create new head predicate for each clause/procedure
     self._hypothesis_space = None
     self._connected_clauses = connected_clauses
     self._use_recursions = recursive_procedures
     self._recursive_expansion = lambda x: plain_extension(x, self._head_constructor, connected_clauses=True) if (self._use_recursions and isinstance(self._head_constructor, Predicate)) else None
     self._pointers: typing.Dict[str, Body] = {"main": None}
     self._expansion_hooks_keep = expansion_hooks_keep
     self._expansion_hooks_reject = expansion_hooks_reject
Пример #7
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
                           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")}

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

    # create Prolog instance
    prolog = SWIProlog()

    learner = SimpleBreadthFirstLearner(prolog, max_body_literals=3)

    # create the hypothesis space
    hs = TopDownHypothesisSpace(primitives=[
        lambda x: plain_extension(x, father, connected_clauses=True),
        lambda x: plain_extension(x, mother, connected_clauses=True)
    ],
                                head_constructor=grandparent,
                                expansion_hooks_reject=[
                                    lambda x, y: has_singleton_vars(x, y),
                                    lambda x, y: has_duplicated_literal(x, y)
                                ])

    program = learner.learn(task, background, hs)

    print(program)
Пример #9
0
            Structure(s, [
                List([
                    Dz, Rz, space, Bz, Ez, Rz, Nz, Az, Rz, Dz, space, Rz, Iz,
                    Ez, Uz, Xz
                ]),
                List(['d', Rz, space, Rz, 'i', 'e', 'u', 'x'])
            ])
        ])
    }

    # create Prolog instance
    prolog = SWIProlog()

    # create the hypothesis space
    hs = TopDownHypothesisSpace(primitives=[
        lambda x: plain_extension(x, not_space, connected_clauses=True),
        lambda x: plain_extension(x, mk_uppercase, connected_clauses=True),
        lambda x: plain_extension(x, mk_lowercase, connected_clauses=True),
        lambda x: plain_extension(x, is_empty, connected_clauses=True),
        lambda x: plain_extension(x, is_space, connected_clauses=True),
        lambda x: plain_extension(x, is_uppercase, connected_clauses=True),
        lambda x: plain_extension(x, not_uppercase, connected_clauses=True),
        lambda x: plain_extension(x, is_lowercase, connected_clauses=True),
        lambda x: plain_extension(x, not_lowercase, connected_clauses=True),
        lambda x: plain_extension(x, is_letter, connected_clauses=True),
        lambda x: plain_extension(x, not_letter, connected_clauses=True),
        lambda x: plain_extension(x, is_number, connected_clauses=True),
        lambda x: plain_extension(x, not_number, connected_clauses=True),
        lambda x: plain_extension(x, skip1, connected_clauses=True),
        lambda x: plain_extension(x, copy1, connected_clauses=True),
        lambda x: plain_extension(x, write1, connected_clauses=True),
Пример #10
0
    # # create the hypothesis space
    # hs = TopDownHypothesisSpace(primitives=[lambda x: plain_extension(x, father, connected_clauses=True),
    #                                         lambda x: plain_extension(x, mother, connected_clauses=True)],
    #                             head_constructor=grandparent,
    #                             expansion_hooks_reject=[lambda x, y: has_singleton_vars(x, y),
    #                                                     lambda x, y: has_duplicated_literal(x, y)])

    totalextension = []
    filtered_predicates = []

    for predicate in predicates:
        if predicate.name not in ["s", chosen_pred
                                  ] and predicate not in filtered_predicates:
            totalextension.append(
                lambda x, predicate=predicate: plain_extension(
                    x, predicate, connected_clauses=True))
            filtered_predicates.append(predicate)

    # create the hypothesis space
    hs = TopDownHypothesisSpace(primitives=totalextension,
                                head_constructor=c_pred("train_task", 1),
                                expansion_hooks_reject=[
                                    lambda x, y: has_singleton_vars(x, y),
                                    lambda x, y: has_duplicated_literal(x, y)
                                ])

    program = learner.learn(task, background, hs)

    print(program)