def parse_background_knowledge_keys( file_name: Optional[str] = None, prediction_goal: Optional[Term] = None) -> BackgroundKnowledgeWrapper: if file_name is None: return BackgroundKnowledgeWrapper() logic_program = PrologFile(file_name) if prediction_goal is not None: prediction_goal_functor = prediction_goal.functor # type: str found_a_prediction_goal_clause = False prediction_goal_clauses = SimpleProgram() stripped_logic_program = SimpleProgram() for prolog_statement in logic_program: if str(prolog_statement).startswith(prediction_goal_functor): found_a_prediction_goal_clause = True prediction_goal_clauses += prolog_statement else: stripped_logic_program += prolog_statement if found_a_prediction_goal_clause: return BackgroundKnowledgeWrapper( logic_program=stripped_logic_program, prediction_goal_clauses=prediction_goal_clauses) else: return BackgroundKnowledgeWrapper(logic_program=logic_program) else: return BackgroundKnowledgeWrapper(logic_program=logic_program)
def __init__(self, pos_examples, neg_examples, extra_terms=[], target_name='target'): # Define the language of terms self.target = Term(target_name) self.equal = Term('equal') self.pos_examples = pos_examples self.neg_examples = neg_examples self.examples = pos_examples + neg_examples self.extra_terms = extra_terms #TODO: check extra terms arity, if greater than target arity, create more variables n_target_variables = len(self.examples[0]) target_variables_names = [ 'X' + str(i) for i in range(1, n_target_variables + 1) ] self.X = list(map(Var, target_variables_names)) constants = set() for example in self.examples: constants.update(example) self.c = list(map(Term, [str(constant) for constant in constants])) # Initialize the logic program self.pl = SimpleProgram() self.pl += self.equal(self.X[0], self.X[0]) self.pl += self.target(*tuple(self.X)) for extra_term in self.extra_terms: self.pl += PrologString(extra_term) self.predicates = [self.equal] # + list(extra_terms.keys()) self.engine = DefaultEngine() self.db = self.engine.prepare(self.pl) self.original_rule = list(self.pl)[1] self.new_body_literals = [] print(list(self.pl))
def create_rules(xs, ys): X, Y, Z = map(Var, ["X", "Y", "Z"]) sp = SimpleProgram() sp += xs["myself"](X, Y) << xs["myself"](X, Y) sp += xs["husband"](X, Y) << xs["wife"](Y, X) sp += xs["wife"](X, Y) << xs["husband"](Y, X) sp += xs["couple"](X, Y) << (xs["husband"](X, Y) | xs["wife"](X, Y)) sp += xs["couple"](X, Y) << xs["couple"](Y, X) sp += xs["son"](X, Y) << (xs["son"](X, Y) | (xs["couple"](X, Z) & xs["son"](Z, Y))) sp += xs["daughter"](X, Y) << (xs["daughter"](X, Y) | (xs["couple"](X, Z) & xs["daughter"](Z, Y))) sp += xs["child"](X, Y) << (xs["son"](X, Y) | xs["daughter"](X, Y)) sp += xs["child"](X, Y) << (xs["father"](Y, X) | xs["mother"](Y, X)) sp += xs["child"](X, Y) << (xs["couple"](X, Z) & xs["child"](Z, Y)) sp += xs["parent"](X, Y) << xs["child"](Y, X) sp += xs["mother"](X, Y) << (xs["wife"](Z, Y) & xs["child"](Y, X)) sp += xs["father"](X, Y) << (xs["husband"](Z, Y) & xs["child"](Y, X)) sp += xs["sibling"](X, Y) << (xs["parent"](X, Z) & xs["parent"](Y, Z)) sp += xs["grandfather"](X, Y) << (xs["father"](X, Z) & xs["father"](Z, Y)) sp += xs["grandmother"](X, Y) << (xs["father"](X, Z) & xs["mother"](Z, Y)) sp += xs["grandparents"]( X, Y) << (xs["grandfather"](X, Y) | xs["grandmother"](X, Y)) sp += xs["grandson"](X, Y) << (xs["son"](X, Z) & xs["son"](Z, Y)) sp += xs["granddaughter"](X, Y) << (xs["son"](X, Z) & xs["daughter"](Z, Y)) sp += xs["grandchildren"](X, Y) << (xs["son"](X, Z) & xs["child"](Z, Y)) sp += xs["grandfather_"](X, Y) << (xs["mother"](X, Z) & xs["father"](Z, Y)) sp += xs["grandmother_"](X, Y) << (xs["mother"](X, Z) & xs["mother"](Z, Y)) sp += xs["grandparents_"]( X, Y) << (xs["grandfather_"](X, Y) | xs["grandmother_"](X, Y)) sp += xs["grandson_"](X, Y) << (xs["daughter"](X, Z) & xs["son"](Z, Y)) sp += xs["granddaughter_"]( X, Y) << (xs["daughter"](X, Z) & xs["daughter"](Z, Y)) sp += xs["grandchildren_"](X, Y) << (xs["daughter"](X, Z) & xs["child"](Z, Y)) sp += xs["son-wife"](X, Y) << (xs["husband"](Y, Z) & xs["parent"](Z, X)) sp += xs["daughter-husband"](X, Y) << (xs["wife"](Y, Z) & xs["parent"](Z, X)) sp += xs["daughter-husband"](X, Y) << (xs["wife"](Y, Z) & xs["parent"](Z, X)) sp += xs["husband-mother"](X, Y) << (xs["husband"](X, Z) & xs["mother"](Z, Y)) sp += xs["husband-father"](X, Y) << (xs["husband"](X, Z) & xs["father"](Z, Y)) sp += xs["wife-mother"](X, Y) << (xs["wife"](X, Z) & xs["mother"](Z, Y)) sp += xs["wife-father"](X, Y) << (xs["wife"](X, Z) & xs["father"](Z, Y)) sp += xs["wife"](ys["林爸爸"], ys["林媽媽"]) # 林媽媽 是 林爸爸 的 妻子 sp += xs["son"](ys["林爸爸"], ys["林本人"]) # 林本人 是 林爸爸 的 兒子 sp += xs["daughter"](ys["林媽媽"], ys["林妹妹"]) # 林妹妹 是 林媽媽 的 女兒 sp += xs["husband"](ys["林太太"], ys["林本人"]) # 林本人 是 林太太 的 丈夫 sp += xs["father"](ys["林囡囡"], ys["林本人"]) # 林本人 是 林囡囡 的 爸爸 sp += xs["husband"](ys["林妹妹"], ys["男朋友"]) # 男朋友 是 林妹妹 的 丈夫 sp += xs["mother"](ys["林太太"], ys["張媽媽"]) # 張媽媽 是 林太太 的 媽媽 sp += xs["wife"](ys["張爸爸"], ys["張媽媽"]) # 張媽媽 是 張爸爸 的 妻子 return sp
def __init__(self, background_knowledge: Optional[LogicProgram] = None, engine: GenericEngine = None): super().__init__(engine=engine) if background_knowledge is None: self.db = self.engine.prepare(SimpleProgram()) # type: ClauseDB else: self.db = self.engine.prepare(background_knowledge) # type: ClauseDB self.db += Term('query')(self.to_query)
def parse_background_knowledge_models( file_name: Optional[str] = None, possible_labels: Optional[Iterable[Term]] = None ) -> BackgroundKnowledgeWrapper: if file_name is None: return BackgroundKnowledgeWrapper() logic_program = PrologFile(file_name) if possible_labels is not None: possible_labels_str = [str(label) for label in possible_labels] # type: List[str] found_a_prediction_clause = False prediction_goal_clauses = SimpleProgram() stripped_logic_program = SimpleProgram() for prolog_statement in logic_program: is_prediction_clause = False for possible_label_str in possible_labels_str: if str(prolog_statement).startswith(possible_label_str): is_prediction_clause = True found_a_prediction_clause = True break if is_prediction_clause: prediction_goal_clauses += prolog_statement else: stripped_logic_program += prolog_statement if found_a_prediction_clause: return BackgroundKnowledgeWrapper( logic_program=stripped_logic_program, prediction_goal_clauses=prediction_goal_clauses) else: return BackgroundKnowledgeWrapper(logic_program=logic_program) else: return BackgroundKnowledgeWrapper(logic_program=logic_program)
def add_literal_to_goal(self, literal): if len(self.new_body_literals) == 0: new_goal = self.original_rule << literal else: new_body = literal for l in self.new_body_literals: new_body = new_body & l new_goal = self.original_rule << new_body new_pl = SimpleProgram() new_pl += list(self.pl)[0] new_pl += new_goal new_db = self.engine.prepare(new_pl) return new_db, new_pl
def convert_tree_to_simple_program( self, tree_root: TreeNode, language: TypeModeLanguage) -> SimpleProgram: if self.debug_printing: print('\n=== START conversion of tree to program ===') print('tree to be converted:') print(str(tree_root)) self.predicate_generator = get_predicate_generator(language) self.program = SimpleProgram() self._decision_tree_to_simple_program(tree_root) if self.debug_printing: print('resulting program:') for statement in self.program: print(statement) print('=== END conversion of tree to program ===\n') return self.program
def parse(self, program=SimpleProgram()): cb = ClauseBuilder(self.__triple_mode) term_dict = dict() for row in self.__data: for triple in row: if term_dict.get(triple[1]) is None: term_dict[triple[1]] = get_type(triple[1]) if term_dict.get(triple[0]) is None: term_dict[triple[0]] = get_type(triple[0]) if term_dict.get(triple[2]) is None: term_dict[triple[2]] = get_type(triple[2]) pred = term_dict[triple[1]] subj = term_dict[triple[0]] obj = term_dict[triple[2]] program += cb.get_clause(subj, pred, obj) return program
def convert_tree_to_simple_program(tree_root: TreeNode, language: TypeModeLanguage, debug_printing=False) -> SimpleProgram: if debug_printing: print('\n=== START conversion of tree to program ===') print('tree to be converted:') print(str(tree_root)) predicate_generator = get_predicate_generator(language) program = SimpleProgram() decision_tree_to_simple_program(tree_root, program, predicate_generator, debug_printing=debug_printing) if debug_printing: print('resulting program:') for statement in program: print(str(statement) + ".") print('=== END conversion of tree to program ===\n') return program
def get_full_background_knowledge_simple_program( self) -> Optional[SimpleProgram]: if not self.has_background_knowledge(): return None elif self.logic_program is not None and self.prediction_goals_clauses is not None: full_bg_kw = SimpleProgram() for lp_statement in self.logic_program: full_bg_kw += lp_statement for pgc_statement in self.prediction_goals_clauses: full_bg_kw += pgc_statement return full_bg_kw elif self.logic_program is not None: return self.logic_program else: return self.prediction_goals_clauses
from problog.program import SimpleProgram from mai_version.probeersel.mach_tests.mach_definitions_logic import worn, replaceable, gear, engine, chain, control_unit, wheel ex1, ex2, ex3, ex4, ex5, ex6, ex7, ex8, ex9, ex10 = SimpleProgram(), SimpleProgram(), SimpleProgram(), SimpleProgram(), SimpleProgram(), SimpleProgram(), SimpleProgram(), SimpleProgram(), SimpleProgram(), SimpleProgram() ex1 += worn(gear) ex1 += worn(engine) ex1 += replaceable(gear) ex3 += worn(gear) ex4 += worn(engine) ex5 += worn(gear) ex5 += worn(chain) ex6 += worn(wheel) ex7 += worn(wheel) ex7 += worn(control_unit) ex9 += worn(wheel) ex9 += worn(chain) ex10 += worn(engine) ex10 += worn(chain) examples = [ex1, ex2, ex3, ex4, ex5, ex6, ex7, ex8, ex9, ex10]
def __init__(self, background_knowledge: Optional[LogicProgram]=None, engine:GenericEngine = None): super().__init__(engine=engine) if background_knowledge is None: self.db = self.engine.prepare(SimpleProgram()) else: self.db = self.engine.prepare(background_knowledge)
def __init__(self, label=None, key: Optional = None, logic_program: LogicProgram = None): if logic_program is None: logic_program = SimpleProgram() super().__init__(label=label, key=key, logic_program=logic_program)
from problog.program import SimpleProgram, PrologString, LogicProgram, PrologFile from problog.logic import Constant, Var, Term, AnnotatedDisjunction from problog import get_evaluatable true = Term('true') ok = Term('ok') query = Term('query') p = PrologFile("Try.pl") x = [p] for i in range(0, 2): s = SimpleProgram() brand = Term('brand') ind = Term('ind') prop = Term('prop') query = Term('query') X = Var('X') ford = Term('ford') seat = Term('seat') suzuki = Term('suzuki') audi = Term('audi') fiat = Term('fiat') s = SimpleProgram() s += AnnotatedDisjunction([ prop(ind, brand, ford, p=0.222222222222222), prop(ind, brand, seat, p=0.222222222222222), prop(ind, brand, suzuki, p=0.222222222222222), prop(ind, brand, audi, p=0.222222222222222), prop(ind, brand, fiat, p=0.111111111111111) ], true) if i == 1:
# -*- coding: utf-8 -*- """ Created on Fri Jan 31 14:04:54 2020 @author: PasqualeDeMarinis """ from problog.program import SimpleProgram from problog.logic import Constant, Var, Term, AnnotatedDisjunction from problog import get_evaluatable coin, heads, tails, win, query = Term('coin'), Term('heads'), Term( 'tails'), Term('win'), Term('query') C = Var('C') p = SimpleProgram() p += coin(Constant('c1')) p += coin(Constant('c2')) p += AnnotatedDisjunction([heads(C, p=0.4), tails(C, p=0.6)], coin(C)) p += (win << heads(C)) p += query(coin(C)) r = get_evaluatable().create_from(p).evaluate() print(r)
""" Simple ProbLog code for a classifying a machine example using Problog code to encode the rules """ from problog.program import SimpleProgram from mai_version.representation.example import SimpleProgramExampleWrapper from mai_version.probeersel.mach_tests.mach_definitions_logic import * from mai_version.classification.classification import get_labels_single_example_models ex1 = SimpleProgram() ex1 += worn(gear) ex1 += worn(engine) ex1 += replaceable(gear) rules = SimpleProgram() rules += (p0 << worn(X)) rules += (p1 << (worn(X) & ~replaceable(X))) rules += (sendback << (worn(X) & ~replaceable(X))) rules += (fix << (worn(X) & ~p1)) rules += (ok << ~p0) possible_labels = [sendback, fix, ok] labels = get_labels_single_example_models(ex1, rules, possible_labels) print(labels)
my_uniform(0,10)::a. 0.5::b. c :- value(a, A), A >= 3; b. query(a). query(b). query(c). """ modeltext_new = """ 0.5::b. c :- value(a, A), A >= 3; b. query(a). query(b). query(c). """ s = SimpleProgram() unif = Term('my_uniform')(Constant(0),Constant(10)) a = Term('a', p=unif) s += a for clause in PrologString(modeltext_new): s += clause model = PrologString(modeltext) # Pass the mapping between name and function using the distributions parameter. x = list(PrologString(modeltext).__iter__()) x2 = list(s.__iter__()) result = list(sample.sample(model, n=3, format='dict', distributions={'my_uniform': integer_uniform})) result2 = list(sample.sample(s, n=3, format='dict', distributions={'my_uniform': integer_uniform}))
# ex1.label = fix # # ex2 += worn(engine) # ex2 += worn(chain) # ex2.label = sendback # # ex3 += worn(wheel) # ex3.label = sendback # # ex4.label = ok labeled_examples = [ex1, ex2, ex3, ex4] possible_targets = [fix, sendback, ok] background_knowledge = SimpleProgram() background_knowledge += replaceable(gear) background_knowledge += replaceable(chain) background_knowledge += not_replaceable(engine) background_knowledge += not_replaceable(wheel) # Machine language language_machines = TypeModeLanguage(False) # manually adding the types worn_type_sign = 'worn' worn_type_args = ['part'] # type: TypeArguments language_machines.add_types(worn_type_sign, worn_type_args) replaceable_type_sign = 'replaceable'
from problog.program import SimpleProgram from mai_version.refinement.RefinementController import * X = Var('X') Y = Var('Y') Z = Var('Z') sendback, fix, ok, worn, replaceable = \ Term('sendback'), Term('fix'), Term('ok'), Term('worn'), Term('replaceable') not_replaceable = Term('not_replaceable') initial_query = SimpleProgram() initial_query += Term('true') conj_1 = replaceable(X) dict_1 = {X.name: '-'} rmode_1 = RefinementMode(5, conj_1, dict_1) conj_2 = not_replaceable(X) dict_2 = {X: '-'} rmode_2 = RefinementMode(5, conj_2, dict_2) conj_3 = not_replaceable(X) dict_3 = {X: '-'} rmode_3 = RefinementMode(5, conj_3, dict_3) r_controller = RefinementController([rmode_1, rmode_2, rmode_3]) literal = Term('test')(X, Y, Z)
def to_simple_program(self, program=SimpleProgram(), triple_mode=False): for prop in self.values(): program += prop.to_clause(triple_mode) return program