コード例 #1
0
ファイル: grounder.py プロジェクト: orsinif/kProbLog
    def run(self):
        global DEBUG_FLAG
        data = self.preprocess_metafunctions()
        if DEBUG_FLAG:
            self.display_preprocessed_code(data)
        model = PrologString(data)
        if DEBUG_FLAG:
            print '=' * 80
            print "BEFORE ESCAPING"
            print '=' * 80
            for elem in model: print clause2str(elem)
            print '=' * 80

        model = escape_metafunctions(model)

        if DEBUG_FLAG:
            print '=' * 80
            print "AFTER ESCAPING"
            print '=' * 80
            for elem in model: print clause2str(elem)
            print '=' * 80

        engine = DefaultEngine(label_all=True)
        engine.add_builtin(METAMETAFUNCTION_FUNCTOR, 2, BooleanBuiltIn(self.builtin_metafunction))
        engine.add_builtin('declare', 2, BooleanBuiltIn(self.builtin_declare))
        engine.add_builtin('declare', 3, BooleanBuiltIn(self.builtin_declare))

        db = engine.prepare(model)
        if DEBUG_FLAG:
            print "=" * 80
            print "DATABASE"
            print "=" * 80
            for elem in db: print elem
            print "=" * 80

        gp = LogicFormula(
            keep_all=True,
            keep_order=True,
            keep_duplicates=True,
            avoid_name_clash=True
        )

        gp = engine.ground_all(db, target=gp)
        if DEBUG_FLAG:
            print "=" * 80
            print "GROUND PROGRAM (GROUNDER)"
            print "=" * 80
            for elem in gp.enum_clauses():
                print elem
            print "=" * 80
        clauses = []
        facts = []
        for clause in unescape_metafunctions(gp.enum_clauses()):
            if isinstance(clause, Clause):
                clauses.append(clause)
            else:
                facts.append(clause)

        query_atoms = gp._names['query']
        return self.builtin_declare.declarations, clauses + facts, query_atoms
コード例 #2
0
    def sample(self, model, queries=None):
        """Sample one assignment to the queries of the given model.
        
        Returns a tuple containing:
            queries : list of pairs (name, value)
            facts: list of probabilistic facts with their sampled value (name, value)
            probability: overall probability of the assignment
        """

        engine = self
        db = engine.prepare(model)

        if queries == None:
            queries = [q[0] for q in engine.query(db, Term('query', None))]

        # if evidence == None :
        #     evidence = engine.query(db, Term( 'evidence', None, None ))

        target = LogicFormula()

        for query in queries:
            target = engine.ground(db, query, target, label=target.LABEL_QUERY)

        # for query in evidence :
        #     if str(query[1]) == 'true' :
        #         target = engine.ground(db, query[0], target, label=LABEL_EVIDENCE_POS)
        #     elif str(query[1]) == 'false' :
        #         target = engine.ground(db, query[0], target, label=LABEL_EVIDENCE_NEG)
        #     else :
        #         target = engine.ground(db, query[0], target, label=LABEL_EVIDENCE_MAYBE)

        # Take into account remaining probabilities of no-choice nodes for annotated disjunctions.
        for k, p in self.groups.items():
            if p != None:
                self.probability *= p

        translate = lambda x: (x[0], x[1] == 0)
        facts = []
        for f, v in self.facts.items():
            if v:
                if type(f) == tuple:
                    node = db.get_node(f[0])
                    args = f[1]
                else:
                    node = db.get_node(f)
                    args = node.args
                if node.functor != 'query':
                    if args:
                        facts.append('%s(%s)' %
                                     (node.functor, ', '.join(map(str, args))))
                    else:
                        facts.append('%s' % (node.functor))

        result = map(translate, target.queries()), facts, self.probability

        self.reset()

        return result
コード例 #3
0
ファイル: sample.py プロジェクト: PietroTotis/ArgProblog
def init_db(engine, model, propagate_evidence=False):
    db = engine.prepare(model)

    if propagate_evidence:
        evidence = engine.query(db, Term("evidence", None, None))
        evidence += engine.query(db, Term("evidence", None))

        ev_target = LogicFormula()
        engine.ground_evidence(db, ev_target, evidence)
        ev_target.lookup_evidence = {}
        ev_nodes = [
            node for name, node in ev_target.evidence()
            if node != 0 and node is not None
        ]
        ev_target.propagate(ev_nodes, ev_target.lookup_evidence)

        evidence_facts = []
        for index, value in ev_target.lookup_evidence.items():
            node = ev_target.get_node(index)
            if ev_target.is_true(value):
                evidence_facts.append((node[0], 1.0) + node[2:])
            elif ev_target.is_false(value):
                evidence_facts.append((node[0], 0.0) + node[2:])
    else:
        evidence_facts = []
        ev_target = None

    return db, evidence_facts, ev_target
コード例 #4
0
    def evaluate_custom_weights(self, eval_name=None):
        class TestSemiringProbabilityNSP(SemiringProbability):
            def is_nsp(self):
                return True

        program = """
                    0.25::a.
                    query(a).
                """
        pl = PrologString(program)
        lf = LogicFormula.create_from(pl,
                                      label_all=True,
                                      avoid_name_clash=True)
        semiring = TestSemiringProbabilityNSP()
        kc_class = get_evaluatable(name=eval_name, semiring=semiring)
        kc = kc_class.create_from(lf)
        a = Term('a')

        # without custom weights
        results = kc.evaluate(semiring=semiring)
        self.assertEqual(0.25, results[a])

        # with custom weights
        weights = {a: 0.1}
        results = kc.evaluate(semiring=semiring, weights=weights)
        self.assertEqual(0.1, results[a])
コード例 #5
0
def ground_problog_program(program):
    """ Grounds a Problog program using the problog library. """
    lf = LogicFormula.create_from(program,
                                  avoid_name_clash=True,
                                  keep_order=True,
                                  label_all=True)
    return lf.to_prolog()
コード例 #6
0
def run_tests_with_static_methods():
    from problog.program import PrologString
    from problog.engine import DefaultEngine
    from problog.logic import Term, Var
    p = PrologString("""
    coin(c1). coin(c2).
    0.4::heads(C); 0.6::tails(C) :- coin(C).
    win :- heads(C).
    """)

    qs, evs = ([Term("win")], [(Term("heads", Term("c1")), False)])  # For now

    engine = DefaultEngine()
    db = engine.prepare(p)
    labels = (LogicFormula.LABEL_QUERY, LogicFormula.LABEL_EVIDENCE_POS,
              LogicFormula.LABEL_EVIDENCE_NEG)
    lf = LogicFormula()
    lf = AMCQuery.ground_query_evidence(engine, db, qs, evs, lf, labels)

    circuit = AMCQuery.compile_to_circuit(lf, "ddnnf")
    prob_sr = SemiringProbability()
    results, ground_evidence = AMCQuery.evaluate_circuit(
        circuit, labels, prob_sr)
    print("evidence: ", ground_evidence)
    for r in results:
        print(r)
    print("---")
コード例 #7
0
def find_all_prob():
    ps = ""
    with open("prolog/problog_predicates.pl", "r") as f:
        for line in f:
            ps += line

    # Calcolo probabilità tramite problog
    ps += "query(infect(_))."
    p = PrologString(ps)
    dbp = engine.prepare(p)
    lf = LogicFormula.create_from(p)  # ground the program
    dag = LogicDAG.create_from(lf)  # break cycles in the ground program
    cnf = CNF.create_from(dag)  # convert to CNF
    ddnnf = DDNNF.create_from(cnf)  # compile CNF to ddnnf
    r = ddnnf.evaluate()

    # Siccome Problog restituisce un dizionario struttrato in questa maniera:
    # {query(infect(2)): 0.67, query(infect(3)): 0.8, ...}
    # Bisogna estrarre ogni id dalla chiave nel seguente modo
    items = []
    if len(RedNode.query.all()) > 0:
        for key, value in r.items():
            start = "infect("
            end = ")"
            result = str(key)[len(start):-len(end)]
            try:
                u = User.query.get(int(result))
                items.append((u, value))
            except ValueError:
                continue
    return items
コード例 #8
0
def main_mpe_semiring(args):
    inputfile = args.inputfile

    init_logger(args.verbose)

    if args.web:
        result_handler = print_result_json
    else:
        result_handler = print_result

    if args.output is not None:
        outf = open(args.output, 'w')
    else:
        outf = sys.stdout

    with Timer("Total"):
        try:
            pl = PrologFile(inputfile)

            lf = LogicFormula.create_from(model, label_all=True)

            prob, facts = mpe_semiring(lf, args.verbose)
            result_handler((True, (prob, facts)), outf)

        except Exception as err:
            trace = traceback.format_exc()
            err.trace = trace
            result_handler((False, err), outf)
コード例 #9
0
ファイル: sample.py プロジェクト: PietroTotis/ArgProblog
 def add_and(self, content, **kwdargs):
     i = 0
     for c in content:
         if c is not None and c != 0:
             i += 1
         if i > 1:
             raise ValueError("Can't combine sampled predicates.")
     return LogicFormula.add_and(self, content)
コード例 #10
0
ファイル: sample.py プロジェクト: PietroTotis/ArgProblog
 def add_or(self, content, **kwd):
     i = 0
     for c in content:
         if c is not None and c != 0:
             i += 1
         if i > 1:
             raise ValueError(
                 "Bodies for same head should be mutually exclusive.")
     return LogicFormula.add_or(self, content, **kwd)
コード例 #11
0
ファイル: sample.py プロジェクト: miguelvidex/ProbLog
    def __init__(self, **kwargs):
        LogicFormula.__init__(self, **kwargs)
        self.facts = {}
        self.groups = {}
        self.probability = 1.0  # Try to compute
        self.values = []

        self.distributions = {
            'normal': random.normalvariate,
            'gaussian': random.normalvariate,
            'poisson': sample_poisson,
            'exponential': random.expovariate,
            'beta': random.betavariate,
            'gamma': random.gammavariate,
            'uniform': random.uniform,
            'triangular': random.triangular,
            'vonmises': random.vonmisesvariate,
            'weibull': random.weibullvariate,
        }
コード例 #12
0
ファイル: sample.py プロジェクト: PietroTotis/ArgProblog
    def __init__(self, **kwargs):
        LogicFormula.__init__(self, **kwargs)
        self.facts = {}
        self.groups = {}
        self.probability = 1.0  # Try to compute
        self.values = []

        self.distributions = {
            "normal": random.normalvariate,
            "gaussian": random.normalvariate,
            "poisson": sample_poisson,
            "exponential": random.expovariate,
            "beta": random.betavariate,
            "gamma": random.gammavariate,
            "uniform": random.uniform,
            "triangular": random.triangular,
            "vonmises": random.vonmisesvariate,
            "weibull": random.weibullvariate,
            "in_range": random.randint,
        }
コード例 #13
0
def main():
        p = PrologString("""
        increaseOsteoblasts :- calcium.
        0.5::\+increaseOsteoblasts :- calcium, bispho.
        reduceOsteoclasts :- bispho.
        1.0::\+reduceOsteoclasts :- calcium , bispho.
        osteoprosis :- initialOsteoprosis.
        0.85::\+osteoprosis :- reduceOsteoclasts.   % Bisphosphonates
        0.15::\+osteoprosis :- increaseOsteoblasts. % Calcium
        % Prior probabilities
        0.5::calcium. 0.5::bispho. 0.5::initialOsteoprosis.
        % Query probability of effect
        evidence(initialOsteoprosis, true).
        evidence(calcium, true).
        evidence(bispho, false).
        query(osteoprosis).
        """)

        #1.3: Create the CNF of the problog
        lf = LogicFormula.create_from(p,avoid_name_clash=True, keep_order=True, label_all=True)  # ground the program
        print("Ground program")
        print(LogicFormula.to_prolog(lf))
        dag = LogicDAG.create_from(lf,avoid_name_clash=True, keep_order=True, label_all=True)  # break cycles in the ground program
        cnf = CNF.create_from(dag)  # convert to CNF
        print(CNF.to_dimacs(cnf))
        ddnnf = DDNNF.create_from(cnf)  # compile CNF to ddnnf
        test = DDNNF.get_weights(ddnnf)
        print(test)
        print(ddnnf.evaluate())

        #3.1: Create 4 interpretations
        print("--Create 4 interpretations--")
        interpretations = create_interpretations(p_without_evidence, 4)
        for i in interpretations: print(i)

        #3.2: Create 100, 1000, 10000 interpretations and estimate p_n
        print("--Estimate parameters--")
        estimate_parameters(100)
        estimate_parameters(1000)
        estimate_parameters(10000)
コード例 #14
0
def call_theorem_prover(theorem_prover,
                        instance_id,
                        question_id,
                        theory,
                        assertion,
                        gold_label,
                        print_log=True):
    """Function that takes a single theory/assertion example and runs it through the theorem prover
    to obtain a label. Returns the obtained label, elapsed time to solve it, and exception returned
    by the engine, if any.
    """
    obtained_result = False
    millisecs_elapsed = 0
    if print_log: print("=======ORIGINAL THEORY=========")
    theory_as_txt = theory.program(theorem_prover)
    if print_log: print(theory_as_txt)
    theory.preprocess(theorem_prover)
    theory_as_txt = theory.program(theorem_prover)
    if theorem_prover == "problog":
        assertion_lf = assertion.logical_form(theorem_prover, False)
        assertion_lf = f"query({assertion_lf})."
        program = f"{theory_as_txt}\n{assertion_lf}"
        if print_log:
            print("=======PROGRAM FROM PREPROCESSED THEORY=========")
            print(program)
            print("=======EXPECTED LABEL=========")
            print(f"    {gold_label}")
        start_millisecs = current_milli_time()
        try:
            lf = LogicFormula.create_from(program)  # ground the program
            dag = LogicDAG.create_from(
                lf)  # break cycles in the ground program
            sdd = SDD.create_from(dag)
            result = sdd.evaluate()
            end_millisecs = current_milli_time()
            elapsed_millisecs = end_millisecs - start_millisecs
            result_tuples = [(k, v) for k, v in result.items()]
            obtained_result = result_tuples[0][1] != float(0)
            return obtained_result, elapsed_millisecs, None
        except (NegativeCycle, NonGroundProbabilisticClause,
                UnknownClause) as e:
            end_millisecs = current_milli_time()
            elapsed_millisecs = end_millisecs - start_millisecs
            if print_log:
                print(
                    f"!!!Encountered Exception at instance id {instance_id}, question id {question_id}: {e}"
                )
            exception_name = str(type(e)).lstrip("<class '").rstrip("'>")
            return None, elapsed_millisecs, exception_name
    return obtained_result, elapsed_millisecs, None
コード例 #15
0
 def ad_atom_duplicate(self, eval_name=None):
     """
     This test must pickup the case where during the transformation, additional _extra atoms are created because
     add_atom(..., cr_extra=True) is used instead of cr_extra=False.
     """
     program = """
                 0.2::a ; 0.8::b.
                 query(a).
                 query(b).
             """
     pl = PrologString(program)
     lf = LogicFormula.create_from(pl, label_all=True, avoid_name_clash=True)
     semiring = SemiringProbability()
     kc_class = get_evaluatable(name=eval_name, semiring=semiring)
     kc = kc_class.create_from(lf)  # type: LogicFormula
     self.assertEqual(3, kc.atomcount)
コード例 #16
0
def run_theory_in_problog(theory, assertion):
    """Run the given theory and assertion through ProbLog engine to obtain a True/False label.
    If an exception is encountered, return None so that this example will not be part of output."""
    theorem_prover = "problog"
    try:
        program = theory.program(theorem_prover, assertion)
        lf = LogicFormula.create_from(program)  # ground the program
        dag = LogicDAG.create_from(lf)  # break cycles in the ground program
        sdd = SDD.create_from(dag)
        result = sdd.evaluate()
        result_tuples = [(k, v) for k, v in result.items()]
        if len(result_tuples) == 0:
            return False
        return result_tuples[0][1] != 0.0
    except (NegativeCycle, NonGroundProbabilisticClause, UnknownClause) as e:
        return None
    return None
コード例 #17
0
def find_user_prob(uid):
    ps = ""
    with open("prolog/problog_predicates.pl", "r") as f:
        for line in f:
            ps += line

    # Pulizia dei nodi dinamici date/1 all'interno di problog
    p = PrologString(ps)
    dbp = engine.prepare(p)
    query = Term("clean")
    res = engine.query(dbp, query)

    # Calcolo probabilità tramite problog
    ps += "query(infect(" + str(uid) + "))."
    p = PrologString(ps)
    dbp = engine.prepare(p)
    lf = LogicFormula.create_from(p)  # ground the program
    dag = LogicDAG.create_from(lf)  # break cycles in the ground program
    cnf = CNF.create_from(dag)  # convert to CNF
    ddnnf = DDNNF.create_from(cnf)  # compile CNF to ddnnf
    r = ddnnf.evaluate()

    # Salvataggio nel database SQLite della data del nodo rosso più vecchio con cui è stato a contatto
    term = Term("date", None)
    database = problog_export.database  # Database interno di Problog dove vengono salvati i fatti con assertz()
    node_key = database.find(term)
    if node_key is not None:
        node = database.get_node(node_key)
        dates = node.children.find(
            term.args)  # Tutti i fatti date/1 inseriti con assertz/1
        vals = []
        if dates:
            for date in dates:
                n = database.get_node(date)
                vals.append(int(n.args[0]))
        min_val = min(vals)  # Trova la data (in millisecondi) minima
        u = User.query.get(uid)
        u.oldest_risk_date = min_val
        db.session.commit()

    return r
コード例 #18
0
 def __init__(self, db):
     self.db = db
     self.lf = LogicFormula()
     self._current_version = 0
     self._compiled = {}
コード例 #19
0
    def evaluate_custom_weights(self, eval_name=None):
        class TestSemiringProbabilityNSP(SemiringProbability):
            def is_nsp(self):
                return True

            def pos_value(self, a, key=None):
                if isinstance(a, tuple):
                    return float(a[0])
                else:
                    return float(a)

            def neg_value(self, a, key=None):
                if isinstance(a, tuple):
                    return float(a[1])
                else:
                    return 1 - float(a)

        program = """
                    0.25::a.
                    query(a).
                """
        pl = PrologString(program)
        lf = LogicFormula.create_from(pl,
                                      label_all=True,
                                      avoid_name_clash=True)
        semiring = TestSemiringProbabilityNSP()
        kc_class = get_evaluatable(name=eval_name, semiring=semiring)
        kc = kc_class.create_from(lf)
        a = Term('a')

        # without custom weights
        results = kc.evaluate(semiring=semiring)
        self.assertEqual(0.25, results[a])

        # with custom weights
        weights = {a: 0.1}
        results = kc.evaluate(semiring=semiring, weights=weights)
        self.assertEqual(0.1, results[a])

        # with custom weights
        weights = {a: (0.1, 0.1)}
        results = kc.evaluate(semiring=semiring, weights=weights)
        self.assertEqual(0.5, results[a])

        # with custom weights based on index
        weights = {kc.get_node_by_name(a): 0.2}
        results = kc.evaluate(semiring=semiring, weights=weights)
        self.assertEqual(0.2, results[a])

        # Testing with weight on node 0 (True)
        weights = {0: 0.3, a: (0.1, 0.1)}
        results = kc.evaluate(semiring=semiring, weights=weights)
        self.assertEqual(0.5, results[a])

        # Testing query on node 0 (True)
        class TestSemiringProbabilityIgnoreNormalize(SemiringProbabilityNSPCopy
                                                     ):
            def normalize(self, a, z):
                return a

        weights = {0: (0.3, 0.7), a: (0.1, 0.1)}
        results = kc.evaluate(
            index=0,
            semiring=TestSemiringProbabilityIgnoreNormalize(),
            weights=weights)
        self.assertEqual(0.06, results)
コード例 #20
0
 def __init__(self) :
     LogicFormula.__init__(self)
     self.facts = {}
     self.groups = {}
     self.probability = 1.0
コード例 #21
0
    m = model.read()
times = []
door_num = range(3, 10)
for i in door_num:
    start = timeit.default_timer()
    model = m.format(door_num=i)
    p = PrologString(model)
    formula = get_evaluatable().create_from(p)
    print(formula.evaluate())
    stop = timeit.default_timer()
    times.append(stop - start)

for i in door_num:
    model = m.format(door_num=i)
    p = PrologString(model)
    lf = LogicFormula.create_from(p)
    lfs.append(lf)
    dag = LogicDAG.create_from(lf)
    dags.append(dag)
    cnf = CNF.create_from(dag)
    cnfs.append(cnf)

for i in door_num:
    model = m.format(door_num=i)
    p = PrologString(model)
    lf = LogicFormula.create_from(p)
    lfs.append(lf)
    dag = LogicDAG.create_from(lf)
    dags.append(dag)
    cnf = CNF.create_from(dag)
    cnfs.append(cnf)
コード例 #22
0
    def evaluate(self, examples, engine):
        # UITLEG subst
        # bij elke refinement wordt er 1 predicaat toegevoegd aan de body of head (in ons geval enkel aan de body, aangezien we enkel in de modes '\+' gebruiken)
        # het toegevoegde predicaat zit vervat in 'rule_literal'
        # elke failing bevat een aantal lijsten, subst is telkens een pointer naar een van deze lijsten
        # het i-de element van subst is telkens de waarde van parameter Ai
        # Bv example: p(a). p(b). q(a,b)
        # huidige hypothese: p(A1) -> false
        #    ----> rule_literal is dus p(A1)!!
        # de originele failing zou dan zijn [[]] (zie evaluate van EmptyClause)
        # de nieuwe failing is nu [[a],[b]] aangezien er in het voorbeeld twee keer p(A1) voorkomt
        # aangezien de body nu true en de head false (want die is altijd false in dit voorbeeld) dekt dit het voorbeeld niet
        # daarom staat er een 'if not head_literal and i == None' wat betekent dat als de rule_literal een body_literal is en als die true is in het voorbeeld
        # dan wordt het voorbeeld niet gedekt

        # gather the failings from the parent
        # the failings list contains for every example information about that example
        # if a failing element is just an empty list ([]) then the clause covers that example
        if self.parent.failings is not None:
            failings = self.parent.failings
        else:
            self.parent.evaluate(examples, engine)
            failings = self.parent.failings

        # check whether the literal is a body or a head literal
        # body literals are negated
        rule_literal = abs(self.literal)
        if not self.literal.is_negated():
            head_literal = True
        else:
            head_literal = False

        # boolean indicating whether there is an example which is not covered by this clause
        fails = False

        # the list that will contain the updated failings
        # later on self.failings will be set to this list
        new_failings = []

        # boolean indicating whether this clause is an improvement of its parent clause
        improvement = False
        if head_literal:
            improvement = True
        # loop through the examples and failings at the same time
        # 'example' contains the example and 'failing' contains information about coverage of the example by the parent
        for k, (example, failing) in enumerate(zip(examples, failings)):
            #print("-----------------------------------------------------")
            #print("testing",self,"on example",k+1)
            if failing:  # equivalent to if 'failing != []' so if this if succeeds, the parent does not cover the example

                # TODO: find out why this is necessary
                if hasattr(example, '_ground'):
                    formula = example._ground
                    formula.clear_queries()
                else:
                    formula = LogicFormula()  # Load from cache
                # formula = LogicFormula()

                # construct a new list to store the failing information for this example
                # later on 'failing' will be replaced by 'new_failing'
                new_failing = []

                # calculate the contents of new_failing
                for subst in failing:
                    #print("rule_literal:",rule_literal)
                    #print("original subst:",subst)
                    # for every new variable this clause introduces, add a None element to the substances
                    if len(subst) < self.variable_count:
                        subst = subst + [None
                                         ] * (self.variable_count - len(subst))
                        improvement = True  # adds a variable
                    #print("new subst:",subst)
                    # subst now contains a list where the ith element contains the value for the ith parameter of the rule_literal
                    # bv. instantiate(pred(A1,A2,A3),[a,b,None]) would result in pred(a,b,_)
                    literal = instantiate(rule_literal, subst)
                    #print("literal:",literal)

                    # formula contains a list queries
                    # this list contains all the facts in the example of the literal
                    # bv example: pred1(a). pred1(b). pred2(b). pred3(a,b).
                    #  literal = pred1(_)
                    #   queries: [pred1(a),pred1(b)]
                    formula = engine.ground(example.database,
                                            literal,
                                            target=formula,
                                            label='query')
                    #print("formula:",formula)
                    # q is the query
                    # if i == 0, the query is true
                    # if i == None, the query is false
                    # de uitbreiding van een clause dekt het positieve voorbeeld als rule_literal een body_literal is die naar false evalueert of
                    # of als rule_literal een head_literal is die naar true evalueert
                    for q, i in formula.queries():
                        # create a copy of the subst_new
                        subst_new = subst[:]
                        #print("q:",q)
                        try:
                            # try to unify the query with the rule literal and put the unifications in subst_new
                            unify(q, rule_literal, subst_new)

                            #print("subst_new:",subst_new)
                            if len(set(subst_new)) == len(subst_new):
                                # TODO check subst_new is all different
                                # the head_literal evaluated to false
                                if head_literal and i is None:
                                    if None in subst_new:
                                        get_logger('claudette').error(' '.join(
                                            map(str,
                                                (list(example.database), self,
                                                 failing, formula))))
                                        raise RuntimeError(
                                            'This shouldn\'t happen!')
                                    #print("head query",q,"evaluated to false")
                                    new_failing.append(subst_new)
                                # the body literal evaluated in true
                                elif not head_literal and i == 0:
                                    new_failing.append(subst_new)
                                    #print("body query",q,"evaluated to true")
                        except UnifyError:
                            # if we have a unify error then the literal is not unifyable with the query
                            #print("unify error")
                            pass
                        #print("==========")

                example._ground = formula
                new_failings.append(new_failing)
                #print("failing:",failing)
                #print("new_failing:",new_failing)
                # we check whether new_failing contains any items
                # if it doesn't then we know that the refinement covers the example
                if new_failing:
                    # if new_failing contains less items than failing than this clause covers it 'more' than the parent so there is an improvement
                    if len(new_failing) < len(
                            failing
                    ) or self.variable_count == 0:  # the last statement is needed for terminal (otherwise terminal gives no contribution)
                        improvement = True
                    fails = True
                else:  # new_failing == [] thus this example is now covered
                    assert failing
                    improvement = True  # failing eliminated
            else:
                # the parent covers this example, so the refinement covers this to
                new_failings.append([])
        self.failings = new_failings
        self.improvement = improvement

        # if fails is set to True, then the clause didn't cover a positive example so it is not a valid one and needs to be refined
        return not fails
コード例 #23
0
def main():
    program = PrologFile('model.txt')
    formula = LogicFormula.create_from(program)
    modelEvaluatable = get_evaluatable().create_from(formula)
    print modelEvaluatable.evaluate()
コード例 #24
0
#

p2 = PrologString("""
person(a). 
person(b). 
person(c). 
0.2::stress(X) :- person(X). 
0.1::friends(X,Y) :- person(X), person(Y). 
0.3::smokes(X) :- stress(X). 
0.4::smokes(X) :- friends(X,Y), smokes(Y).
evidence(friends(a,b), true).
evidence(friends(a,c), true).
query(smokes(a)).
""")
lf2 = LogicFormula.create_from(p2,
                               avoid_name_clash=True,
                               keep_order=True,
                               label_all=True)
# print(LogicFormula.to_prolog(lf2))
dag2 = LogicDAG.create_from(lf2,
                            avoid_name_clash=False,
                            keep_order=True,
                            label_all=True)

# # print(dag2)
# # print(LogicFormula.to_prolog(dag2))
cnf2 = CNF.create_from(dag2)
# # print(cnf2.to_dimacs(weighted=True, invert_weights=True))
ddnnf2 = DDNNF.create_from(cnf2)
#print(ddnnf2.evaluate())
#
# import PyBool_public_interface as Bool
コード例 #25
0
    def verify(self, examples, engine):
        if self.parent.verifications is not None:
            verifications = self.parent.verifications
        else:
            self.parent.verify(examples, engine)
            verifications = self.parent.verifications

        # check whether the literal is a body or a head literal
        # body literals are negated
        rule_literal = abs(self.literal)
        if not self.literal.is_negated():
            head_literal = True
        else:
            head_literal = False

        verifies = False
        new_verifications = []

        for k, (example,
                verification) in enumerate(zip(examples, verifications)):
            #print("-----------------------------------------------------")
            #print("testing",self,"on example",k+1)
            if verification:
                if hasattr(example, '_ground'):
                    formula = example._ground
                    formula.clear_queries()
                else:
                    formula = LogicFormula()

                new_verification = []

                for subst in verification:
                    #print("rule_literal:",rule_literal)
                    #print("original subst:",subst)

                    if len(subst) < self.variable_count:
                        subst = subst + [None
                                         ] * (self.variable_count - len(subst))
                    #print("new subst:",subst)

                    literal = instantiate(rule_literal, subst)
                    #print("literal:",literal)

                    formula = engine.ground(example.database,
                                            literal,
                                            target=formula,
                                            label='query')
                    #print("formula:",formula)

                    for q, i in formula.queries():
                        subst_new = subst[:]
                        #print("q:",q)
                        try:
                            unify(q, rule_literal, subst_new)

                            #print("subst_new:",subst_new)
                            #if len(set(subst_new)) == len(subst_new):
                            if head_literal and i == 0:
                                if None in subst_new:
                                    get_logger('claudette').error(' '.join(
                                        map(str, (list(example.database), self,
                                                  failing, formula))))
                                    raise RuntimeError(
                                        'This shouldn\'t happen!')
                                #print("head query",q,"evaluated to true")
                                new_verification.append(subst_new)
                            # the body literal evaluated in true
                            elif not head_literal and i == 0:
                                new_verification.append(subst_new)
                                #print("body query",q,"evaluated to true")
                        except UnifyError:
                            # if we have a unify error then the literal is not unifyable with the query
                            #print("unify error")
                            pass
                        #print("==========")

                example._ground = formula
                if str(rule_literal)[0] == '#':
                    new_verifications.append([[]])
                else:
                    new_verifications.append(new_verification)
                #print("verification:",verification)
                #print("new_verification:",new_verification)

                if new_verification:
                    verifies = True

            else:
                new_verifications.append([])
        self.verifications = new_verifications

        return verifies
コード例 #26
0
from problog.program import PrologString
from problog.formula import LogicFormula, LogicDAG
from problog.logic import Term
from problog.ddnnf_formula import DDNNF
from problog.cnf_formula import CNF

p = PrologString("""
coin(c1). coin(c2).
0.4::heads(C); 0.6::tails(C) :- coin(C).
win :- heads(C).
evidence(heads(c1), false).
query(win).
query(coin(X)).
""")

lf = LogicFormula.create_from(p)   # ground the program
dag = LogicDAG.create_from(lf)     # break cycles in the ground program
cnf = CNF.create_from(dag)         # convert to CNF
ddnnf = DDNNF.create_from(cnf)       # compile CNF to ddnnf

results = ddnnf.evaluate()

print(results)
コード例 #27
0
ファイル: test.py プロジェクト: BrunoVandekerkhove/problog
# 0.4::b.
# 0.3::a :- b.
# 0.5::b :- a.
# query(a).
# evidence(b).
# """)

p = PrologString("""
0.4::heads(1). 0.7::heads(2). 0.5::heads(3). 
win :- heads(1). 
win :- heads(2), heads(3).
query(win).
""")

lf = LogicFormula.create_from(p,
                              avoid_name_clash=True,
                              keep_order=True,
                              label_all=True)  # ground the program
# print(lf)
# print(LogicFormula.to_prolog(lf))
dag = LogicDAG.create_from(
    lf, avoid_name_clash=True, keep_order=True,
    label_all=True)  # break cycles in the ground program
# print(dag)
# print(LogicFormula.to_prolog(dag))
cnf = CNF.create_from(dag)  # convert to CNF
# for clause in cnf._clauses:
#     print(clause)
ddnnf = DDNNF.create_from(cnf)  # compile CNF to ddnnf
# Outcome for the a/b thing with query(a) is 0,2+(0,8*0,3*0,4)
#  but if evidence(b) : (0,2*0,4+0,2*0,5*0,6+0,4*0,3*0,8) / (0,4+0,6*0,5*0,2) [Formula for conditional probability P(a|b) = ...]
# For coin thing : 1-0,6*0,3*0,5-0,6*0,3*0,5-0,6*0,7*0,5 = 0,61
コード例 #28
0
ファイル: PL.py プロジェクト: BrunoVandekerkhove/problog
    return new_weights, iters


# Read in the progam with tunable parameters
#ground_progam = file_to_string("test_learn.pl")

# Assign to each tunable parameter a random initialization value
#ground_progam_tunable = init_tunable(ground_progam)

# Write back the prolog file with random initialized tunable probabilities
#f = open('test_learn_tunable.pl', 'w')
#f.write(ground_progam_tunable)

pf = PrologFile("test_learn_tunable.pl")
formula = LogicFormula.create_from(pf)
sdd = SDD.create_from(formula)

queries = [
    Term('stress', Term('a')),
    Term('stress', Term('b')),
    Term('stress', Term('c')),
    Term('smokes', Term('a')),
    Term('smokes', Term('b')),
    Term('smokes', Term('c'))
]

# File which holds all the evidence examples
examples = file_to_string('data.pl')

# Retrieve the amount of interpretations that has been specified