def test_nonground_query_ad(self): """Non-ground call to annotated disjunction""" program = """ 0.1::p(a); 0.2::p(b). query(p(_)). """ engine = DefaultEngine() db = engine.prepare(PrologString(program)) result = None for query in engine.query(db, Term("query", None)): result = engine.ground(db, query[0], result, label="query") found = [str(x) for x, y in result.queries()] self.assertCollectionEqual(found, ["p(a)", "p(b)"])
def main(argv, handle_output=None): args = argparser().parse_args(argv) verbose = args.verbose filename = args.filename if verbose: debug("Loading...") problog_model = PrologFile(filename, factory=ConstraintFactory()) engine = DefaultEngine() database = engine.prepare(problog_model) # Ground the constraints if verbose: debug("Grounding...") target = engine.ground(database, Term("constraint", None, None), label="constraint") queries = [q[0] for q in engine.query(database, Term("query", None))] for query in queries: target = engine.ground(database, query, label="query", target=target) if verbose > 1: print(target, file=sys.stderr) has_prob_constraint = False for name, index in target.get_names(label="constraint"): if index is not None: if name.args[1].functor == "ensure_prob": has_prob_constraint = True # Compile and turn into CP-problem if has_prob_constraint: if verbose: debug("Probabilistic constraints detected.") if verbose: debug("Compiling...") sdd = SDD.create_from(target) formula = sdd.to_formula() # Convert to flatzinc if verbose: debug("Converting...") fzn = formula_to_flatzinc_float(formula) sdd.clear_labeled("constraint") if verbose > 1: print(fzn, file=sys.stderr) # Solve the flatzinc model if verbose: debug("Solving...") sols = list(solve(fzn)) has_solution = False for i, res in enumerate(sols): if verbose: debug("Evaluating solution %s/%s..." % (i + 1, len(sols))) # target.lookup_evidence = {} weights = sdd.get_weights() # ev_nodes = [] for k, v in res.items(): sddvar = formula.get_node(k).identifier sddatom = sdd.var2atom[sddvar] sddname = sdd.get_name(sddatom) weights[sddatom] = v for k, v in sdd.evaluate().items(): if v > 0.0: print(k, v) print("----------") has_solution = True if has_solution: print("==========") else: print("=== UNSATISFIABLE ===") else: formula = LogicDAG() break_cycles(target, formula) if verbose: debug("Converting...") fzn = formula_to_flatzinc_bool(formula) if verbose > 1: print(fzn, file=sys.stderr) if verbose: debug("Solving...") sols = list(solve(fzn)) has_solution = False for i, res in enumerate(sols): if verbose: debug("Evaluating solution %s/%s..." % (i + 1, len(sols))) if verbose: debug("Compressing...") new_formula = compress(formula, res) if verbose: debug("Compiling...") sdd = SDD.create_from(new_formula) if verbose: debug("Evaluating...") for k, v in sdd.evaluate().items(): if v > 0.0: print(k, v) print("----------") has_solution = True if has_solution: print("==========") else: print("=== UNSATISFIABLE ===")