예제 #1
0
 def main(self, ctl, files):
     with ast.ProgramBuilder(ctl) as bld:
         ptf = ProgramTransformer(Function("__t"))
         ast.parse_files(files, lambda stm: bld.add(ptf(stm)))
     ctl.add("initial", ["t"], "initially(t).")
     ctl.add("static", ["t"], "#external finally(t).")
     self._main(ctl)
예제 #2
0
    def main(self, ctl, files):
        if self.mode == "depth":
            self.nr_models = abs(int(ctl.configuration.solve.models))
        ctl.configuration.solve.models = 0

        thy = ClingoDLTheory()
        self.theory = thy
        thy.register(ctl)
        with ProgramBuilder(ctl) as bld:
            parse_files(files, lambda ast: thy.rewrite_ast(ast, bld.add))

        pareto_propagator = ParetoPropagator(thy, self.mode)
        self.propagator = pareto_propagator
        ctl.register_propagator(pareto_propagator)

        ctl.ground([('base', [])])
        thy.prepare(ctl)
        thy.configure("propagate", self.dl_propagation_mode)

        if self.mode == "breadth":
            ctl.solve(on_model=self.on_model,
                      on_finish=self.print_front,
                      on_statistics=self._on_statistics)
        elif self.mode == "depth":
            models = 0
            while models < self.nr_models or self.nr_models == 0:
                r = ctl.solve(
                    on_model=self.on_model,
                    on_finish=lambda m: self.print_single(models + 1, m),
                    on_statistics=self._on_statistics)
                if r.unsatisfiable: return
                models += 1
                self.propagator.save_best()
예제 #3
0
def parse_fact_files(files,
                     unifier,
                     *,
                     factbase=None,
                     raise_nomatch=False,
                     raise_nonfact=False):
    '''Parse the facts from a list of files into a FactBase

    Facts must be of a simple form that can correspond to clorm predicate
    instances. Rules that are NOT simple facts include: any rule with a body, a
    disjunctive fact, a choice rule, a theory atom, a literal with an external
    @-function reference, a literal that requires some mathematical calculation
    (eg., "p(1+1).")

    NOTE: Currently, this function is not safe when running in NOCLINGO mode and
    will raise a NotImplementedError if called.

    Args:
      files: a list of ASP files containing the facts
      factbase: if no factbase is specified then create a new one
      unifier: a list of clorm.Predicate classes to unify against
      raise_nomatch: raise UnifierNoMatchError on a fact that cannot unify
      raise_nonfact: raise FactParserError on any non simple fact (eg. complex rules)
    '''

    if get_symbol_mode() == SymbolMode.NOCLINGO:
        if not raise_nonfact:
            raise NotImplementedError(
                "Non-fact parsing not supported in NOCLINGO mode")
        return lark_parse_fact_files(files=files,
                                     unifier=unifier,
                                     factbase=factbase,
                                     raise_nomatch=raise_nomatch)

    ctrl = clingo.Control()
    un = Unifier(unifier)
    try:
        if raise_nonfact:
            with clast.ProgramBuilder(ctrl) as bld:
                nfv = NonFactVisitor()

                def on_rule(ast: AST):
                    nonlocal nfv, bld
                    if nfv: nfv(ast)
                    bld.add(ast)

                clast.parse_files(files, on_rule)
        else:
            for fn in files:
                ctrl.load(fn)
    except ClingoParserWrapperError as e:
        raise e.exc

    ctrl.ground([("base", [])])
    return un.unify([sa.symbol for sa in ctrl.symbolic_atoms if sa.is_fact],
                    factbase=factbase,
                    raise_nomatch=raise_nomatch)
예제 #4
0
    def main(self, ctl, files):
        self.__theory.register(ctl)

        with ast.ProgramBuilder(ctl) as bld:
            ast.parse_files(files, lambda stm: self.__theory.rewrite_ast(stm, bld.add))

        ctl.ground([("base", [])])
        self.__theory.prepare(ctl)

        ctl.solve(on_model=self.__on_model, on_statistics=self.__on_statistics)
예제 #5
0
    def main(self, ctl: Control, files: Sequence[str]):
        """
        The main function called with a Control object and a list of files
        passed on the command line.
        """
        if not files:
            files = ["-"]

        check: List[ast.AST] = []
        with ProgramBuilder(ctl) as bld:
            trans = Transformer(bld, check)
            parse_files(files, trans.add)

        ctl.register_propagator(CheckPropagator(check))

        ctl.ground([("base", [])])
        ctl.solve()
예제 #6
0
def sols(instance, compare, comp):
    files = [
        os.path.join("encodings", "encoding.lp"),
        os.path.join("encodings", "types.lp"), instance
    ]
    thy = ClingconTheory()
    ctl = Control(['0'])
    thy.register(ctl)
    with ProgramBuilder(ctl) as bld:
        parse_files(files, lambda ast: thy.rewrite_ast(ast, bld.add))

    ctl.ground([('base', [])])
    thy.prepare(ctl)
    models = []
    with ctl.solve(yield_=True, on_model=thy.on_model) as hnd:
        for mdl in hnd:
            model = [str(a) for a in mdl.symbols(shown=True)]
            model += [
                "{}={}".format(str(key).strip('"'), val)
                for key, val in thy.assignment(mdl.thread_id)
            ]
            models.append(set(model))

    bool_herbrand = set(
        [i for sl in compare for i in sl if i.startswith("var(")])

    compare = [set(c) for c in compare]

    assert comp(
        len(models), len(compare)
    ), f"{models}\n vs {compare}\ncomputed {len(models)} expected {len(compare)}"
    for c in compare:
        # for all in herbrand which are not in compare -> ensure that they are not in model
        found = False
        for m in models:
            if c.issubset(m):
                if ((bool_herbrand - c) & m) == set():
                    found = True
                    break
        assert found == True, f"{c} not in {models}"
예제 #7
0
def rewrite(ctl: Control, files: Sequence[str]):
    with ProgramBuilder(ctl) as bld:
        hbt = HeadBodyTransformer()
        parse_files(
            files,
            lambda stm: bld.add(cast(AST, hbt.visit(stm))))