def evaluate_explicit_from_fsdd(self, custom_semiring=None): try: parser = DefaultPrologParser(ExtendedPrologFactory()) lf = PrologFile(filename, parser=parser) kc = _ForwardSDD.create_from(lf) # type: _ForwardSDD kc = kc.to_explicit_encoding() if custom_semiring is not None: semiring = custom_semiring # forces the custom semiring code. elif logspace: semiring = SemiringLogProbability() else: semiring = SemiringProbability() computed = kc.evaluate(semiring=semiring) computed = {str(k): v for k, v in computed.items()} except Exception as err: #print("exception %s" % err) e = err computed = None if computed is None: self.assertEqual(correct, type(e).__name__) else: self.assertIsInstance(correct, dict) self.assertSequenceEqual(correct, computed) for query in correct: self.assertAlmostEqual(correct[query], computed[query], msg=query)
def run_test_with_query_instance(): 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). """) from .formula_wrapper import FormulaWrapper s_qs, s_evs = ([Term("win")], [(Term("heads", Term("c1")), False)]) # For now engine = DefaultEngine() probsr = SemiringProbability() fw = FormulaWrapper(engine.prepare(p)) qobj = AMCQuery(s_qs, s_evs, fw, target_class=DDNNF, semiring=probsr) qobj.ground(engine) result, ground_evidence = qobj.evaluate(engine) print("evidence: ", ground_evidence) for r in result: print(r) print("---")
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("---")
def mpe_maxsat(dag, verbose=0, solver=None): if dag.queries(): print('%% WARNING: ignoring queries in file', file=sys.stderr) dag.clear_queries() logger = init_logger(verbose) logger.info('Ground program size: %s' % len(dag)) cnf = CNF.createFrom(dag) for qn, qi in cnf.evidence(): if not cnf.is_true(qi): cnf.add_constraint(TrueConstraint(qi)) queries = list(cnf.labeled()) logger.info('CNF size: %s' % cnf.clausecount) if not cnf.is_trivial(): solver = get_solver(solver) with Timer('Solving'): result = frozenset(solver.evaluate(cnf)) weights = cnf.extract_weights(SemiringProbability()) output_facts = None prob = 1.0 if result is not None: output_facts = [] if queries: for qn, qi, ql in queries: if qi in result: output_facts.append(qn) elif -qi in result: output_facts.append(-qn) for i, n, t in dag: if t == 'atom': if i in result: if not queries: output_facts.append(n.name) prob *= weights[i][0] elif -i in result: if not queries: output_facts.append(-n.name) prob *= weights[i][1] else: prob = 1.0 output_facts = [] return prob, output_facts
def main(inputfile, semiring, **kwdargs): pl = PrologFile(inputfile) if semiring == 'prob': sm = SemiringProbability() elif semiring == 'mpe': sm = SemiringMPE() elif semiring == 'mpe_state': sm = SemiringMPEState() result = solve(pl, semiring=sm) for k, v in result.items(): print ('%s: %s' % (k, v))
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)
def mpe_maxsat(dag, verbose=0, solver=None, minpe=False): logger = init_logger(verbose) logger.info("Ground program size: %s" % len(dag)) cnf = CNF.createFrom(dag, force_atoms=True) for qn, qi in cnf.evidence(): if not cnf.is_true(qi): cnf.add_constraint(TrueConstraint(qi)) queries = list(cnf.labeled()) logger.info("CNF size: %s" % cnf.clausecount) if not cnf.is_trivial(): solver = get_solver(solver) with Timer("Solving"): result = frozenset(solver.evaluate(cnf, invert_weights=minpe)) weights = cnf.extract_weights(SemiringProbability()) output_facts = None prob = 1.0 if result is not None: output_facts = [] if queries: for qn, qi, ql in queries: if qi in result: output_facts.append(qn) elif -qi in result: output_facts.append(-qn) for i, n, t in dag: if t == "atom": if i in result: if not queries: output_facts.append(n.name) prob *= weights[i][0] elif -i in result: if not queries: output_facts.append(-n.name) prob *= weights[i][1] else: prob = 1.0 output_facts = [] return prob, output_facts
def test(self) : try : parser = DefaultPrologParser(ExtendedPrologFactory()) sdd = SDD.createFrom(PrologFile(filename, parser=parser)) if logspace : semiring = SemiringLogProbability() else : semiring = SemiringProbability() computed = sdd.evaluate(semiring=semiring) computed = { str(k) : v for k,v in computed.items() } except Exception as err : e = err computed = None if computed is None : self.assertEqual(correct, type(e).__name__) else : self.assertIsInstance( correct, dict ) self.assertSequenceEqual(correct, computed) for query in correct : self.assertAlmostEqual(correct[query], computed[query], msg=query)
def create_query(query_type, queries, evidence, formula_wrapper, **kwargs): if query_type == QueryFactory.QueryType.PROBABILITY: return AMCQuery(queries, evidence, formula_wrapper, semiring=SemiringProbability(), **kwargs) elif query_type == QueryFactory.QueryType.MPE: return AMCQuery(queries, evidence, formula_wrapper, semiring=SemiringMPEState(), **kwargs) elif query_type == QueryFactory.QueryType.MINPE: return AMCQuery(queries, evidence, formula_wrapper, semiring=SemiringMinPEState(), **kwargs) elif query_type == QueryFactory.QueryType.SAMPLE: return SampleQuery(queries, evidence, formula_wrapper, **kwargs) else: raise NotImplementedError("query_type not yet supported: %s" % str(query_type))
def __init__(self): self._semiring = SemiringProbability()
class SemiringProbabilityCopy(Semiring): """Mocking SemiringProbability to force the 'custom semiring' code -> Must not extend SemiringProbability.""" def __init__(self): self._semiring = SemiringProbability() def one(self): return self._semiring.one() def zero(self): return self._semiring.zero() def is_one(self, value): return self._semiring.is_one(value) def is_zero(self, value): return self._semiring.is_zero(value) def plus(self, a, b): return self._semiring.plus(a, b) def times(self, a, b): return self._semiring.times(a, b) def negate(self, a): return self._semiring.negate(a) def normalize(self, a, z): return self._semiring.normalize(a, z) def value(self, a): return self._semiring.value(a) def is_dsp(self): return self._semiring.is_dsp() def in_domain(self, a): return self._semiring.in_domain(a)
def __init__(self, source, examples, max_iter=10000, min_improv=1e-10, verbose=0, knowledge=None, leakprob=None, propagate_evidence=True, normalize=False, **extra): """ :param source: filename of file containing input model :type source: str :param examples: list of observed terms / value :type examples: list[tuple(Term, bool)] :param max_iter: maximum number of iterations to run :type max_iter: int :param min_improv: minimum improvement in log-likelihood for convergence detection :type min_improv: float :param verbose: verbosity level :type verbose: int :param knowledge: class to use for knowledge compilation :type knowledge: class :param leakprob: Add all true evidence atoms with the given probability to avoid 'inconsistent evidence' errors. This also allows to learn a program without constants and retrieve the constants from the evidence file. (default: None) :type leakprob: float or None :param extra: catch all for additional parameters (not used) """ SemiringProbability.__init__(self) LogicProgram.__init__(self) self.source = source # The names of the atom for which we want to learn weights. self.names = [] # The weights to learn. # The initial weights are of type 'float'. # When necessary they are replaced by a dictionary [t(arg1, arg2, ...) -> float] # for weights of form t(SV, arg1, arg2, ...). self._weights = [] self.examples = examples self.leakprob = leakprob self.leakprobatoms = None self.propagate_evidence = propagate_evidence self._compiled_examples = None self.max_iter = max_iter self.min_improv = min_improv self.verbose = verbose self.iteration = 0 if knowledge is None: knowledge = get_evaluatable() self.knowledge = knowledge self.output_mode = False self.extra = extra self._enable_normalize = normalize self._adatoms = []
def __init__(self, weights): SemiringProbability.__init__(self) self._weights = weights