コード例 #1
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
コード例 #2
0
def evaluate_using_problog_library(program, print_steps=False):
    """ Evaluates a problog program using the problog library. """
    formula = ground_problog_program(program)
    if print_steps:
        print("GROUND PROGRAM:")
        print(formula.to_prolog())
        print(separator_1)

    cnf = CNF.create_from(formula)  # type: CNF
    if print_steps:
        print("DIMACS:")
        print(cnf.to_dimacs(weighted=True, names=True))
        print(separator_1)

    ddnnf = DDNNF.create_from(cnf)
    results = ddnnf.evaluate()
    results = sorted(results.items(), key=lambda kv: str(kv[0]))
    results = [(str(q), p) for q, p in results]
    if print_steps:
        print("EVALUATION:")
        query_str_len = max([len(q) for q, _ in results])
        for query, probability in results:
            print("{:<{}}: {}".format(query, query_str_len, probability))

    return results
コード例 #3
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
コード例 #4
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)
コード例 #5
0
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
# expr = Bool.parse_std("input.txt")
# expr = expr["main_expr"]
# expr = Bool.exp_cnf(expr)
# expr = Bool.simplify(expr)
# print(Bool.print_expr(expr))
# Bool.write_dimacs(Bool.cnf_list(expr), "/Users/Bruno/Desktop/dimacs.cnf")

# p3 = PrologString("""
# 0.2::stress(a).
# 0.2::stress(b).
コード例 #6
0
    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)
    ddnnf = DDNNF.create_from(cnf)
    print(ddnnf.evaluate())

print(times)
コード例 #7
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)