示例#1
0
 def solve(self, *args, **kwargs):
     # set external prev/1
     for atom in self.last_prev:
         self.control.assign_external(clingo.Function(PREV, atom), False)
     for atom in self.prev:
         self.control.assign_external(clingo.Function(PREV, atom),  True)
     # set external first/0
     if self.calls == 0:
         self.control.assign_external(clingo.Function(FIRST, []),  True)
     elif self.calls == 1:
         self.control.release_external(clingo.Function(FIRST, []))
     # add constraint for last model
     if self.calls == 0:
         self.backend.__enter__()
     if self.calls > 0:
         body = self.model + [-a for a in self.atoms if a not in self.model]
         self.backend.add_rule([], body, False)
     # if calls == 1 and optimization: add constraint
     if self.calls == 1 and self.cost != []:
         # just in case:
         if len(self.cost) != len(self.minimization):
             raise Exception("ERROR (multiclingo): implementation error")
         # iterate over levels adding a weight constraint
         for idx, cost in enumerate(self.cost):
             level = self.minimization[idx]
             self.backend.add_weight_rule([], cost+1, level, False)
             total = sum([abs(w) for _, w in level])
             body = [(-l,w) for l, w in level]
             self.backend.add_weight_rule([], total-cost+1, body, False)
     # solve and return result
     self.result = UNSATISFIABLE
     self.calls += 1
     self.control.solve(on_model = self.on_model, *args, **kwargs)
     return self.result
示例#2
0
    def test_function(self):
        nc = noclingo.Function("atest")
        c = clingo.Function("atest")
        self.assertEqual(str(nc), str(c))
        self.assertEqual(nc.type, noclingo.SymbolType.Function)

        nc1 = noclingo.Function("aaaa")
        nc2 = noclingo.String("bbb")
        nc3 = noclingo.Function("ccc", [noclingo.Number(10)])
        c1 = clingo.Function("aaaa")
        c2 = clingo.String("bbb")
        c3 = clingo.Function("ccc", [clingo.Number(10)])

        nc = noclingo.Function("atest", [nc1, nc2, nc3])
        c = clingo.Function("atest", [c1, c2, c3])

        self.assertEqual(str(nc), str(c))
        self.assertEqual(nc.name, c.name)
        self.assertEqual(nc.name, "atest")
        self.assertEqual(len(nc.arguments), len(c.arguments))
        self.assertEqual(nc.arguments[0].name, c.arguments[0].name)
        self.assertEqual(nc.arguments[0].name, "aaaa")
        self.assertEqual(nc.arguments[1].string, c.arguments[1].string)

        nc4 = noclingo.Function("ccc", [noclingo.Number(10)], False)
        c4 = clingo.Function("ccc", [clingo.Number(10)], False)
        self.assertEqual(str(nc4), str(c4))
        self.assertEqual(nc4.positive, c4.positive)
        self.assertEqual(nc4.negative, c4.negative)
示例#3
0
    def setStep(self, index):
        if self.debug:
            print "Setting horizon to ", index

        oldqu = self.horizon

        if self.optimize:
            self.control.assign_external(clingo.Function("utility", [oldqu]),
                                         False)
            if not index in self.transitions:
                if self.debug:
                    print "Grounding transition and utility ", index
                self.control.ground([("transition", [index]),
                                     ("utility", [index])])
                self.transitions.append(index)
            self.control.assign_external(clingo.Function("utility", [index]),
                                         True)
        else:
            self.control.assign_external(clingo.Function("query", [oldqu]),
                                         False)
            if not index in self.transitions:
                if self.debug:
                    print "Grounding transition and query ", index
                self.control.ground([("transition", [index]),
                                     ("query", [index])])
                self.transitions.append(index)
            self.control.assign_external(clingo.Function("query", [index]),
                                         True)

        self.horizon = index
示例#4
0
 def test_tuple(self):
     nc1 = noclingo.Function("aaaa")
     nc2 = noclingo.String("bbb")
     c1 = clingo.Function("aaaa")
     c2 = clingo.String("bbb")
     nc = noclingo.Function("", [nc1, nc2])
     c = clingo.Function("", [c1, c2])
示例#5
0
    def setUp(self):
        self.inf = clingo.Infimum
        self.sup = clingo.Supremum
        self.s1 = clingo.String("aaaa")
        self.s2 = clingo.String("bbbb")
        self.n1 = clingo.Number(24)
        self.n2 = clingo.Number(60)
        self.f1 = clingo.Function("",[self.s1, self.s2])
        self.f2 = clingo.Function("func1", [self.n1])
        self.f3 = clingo.Function("func2", [self.n2, self.f1])
        self.f4 = clingo.Function("func1", [], False)
        self.alls = [self.inf, self.sup, self.s1, self.s2, self.n1, \
                     self.n2, self.f1, self.f2, self.f3, self.f4 ]

        self.str_inf = '{"clingo.SymbolType": "Infimum"}'
        self.str_sup = '{"clingo.SymbolType": "Supremum"}'
        self.str_s1 = '{"clingo.SymbolType": "String", "string": "aaaa"}'
        self.str_s2 = '{"clingo.SymbolType": "String", "string": "bbbb"}'
        self.str_n1 = '{"clingo.SymbolType": "Number", "number": 24}'
        self.str_n2 = '{"clingo.SymbolType": "Number", "number": 60}'
        self.str_f1 = '{"clingo.SymbolType": "Function", "name": "", "arguments": [' \
            + self.str_s1 + ', ' + self.str_s2 + '], "positive": true}'
        self.str_f2 = '{"clingo.SymbolType": "Function", "name": "func1", "arguments": [' \
            + self.str_n1 + '], "positive": true}'
        self.str_f3 = '{"clingo.SymbolType": "Function", "name": "func2", "arguments": [' \
            + self.str_n2 + ', ' + self.str_f1 + '], "positive": true}'
        self.str_f4 = '{"clingo.SymbolType": "Function", "name": "func1", "arguments": []' \
            + ', "positive": false}'
        self.str_alls = '[' + self.str_inf + ', ' + self.str_sup + ', ' + \
             self.str_s1 + ', ' + self.str_s2 + ', ' + self.str_n1 + ', ' +\
             self.str_n2 + ', ' + self.str_f1 + ', ' + self.str_f2 + ', ' +\
             self.str_f3 + ', ' + self.str_f4 + ']'
示例#6
0
 def start(self, on_finish):
     if self.ret is not None and not self.ret.unknown():
         self.k = self.k + 1
         self.prg.ground([("sleep", [self.k])])
         self.prg.release_external(clingo.Function("sleep", [self.k-1]))
         self.prg.assign_external(clingo.Function("sleep", [self.k]), True)
     self.future = self.prg.solve(on_model=self.on_model, on_finish=on_finish, async=True)
示例#7
0
def incmode():
    

    #dlp = DynamicLogicProgramBackend(["example.lp"], clingo_options=sys.argv[1:])
    #dlp = DynamicLogicProgramBackend(["example.lp"], clingo_options=sys.argv[1:])

    dlp = DynamicLogicProgramBackendClingoPre(["example-clingo-pre.lp"], clingo_options=sys.argv[1:])
    dlp.start()
    print(dlp); return

    # loop
    step, ret = 1, None
    while True:
        if step > 2: return
        dlp.release_external(clingo.Function("query",[step-1]))
        dlp.ground(1)
        dlp.assign_external(clingo.Function("query",[step]), True)

        with dlp.control.solve(assumptions=dlp.get_assumptions(), yield_ = True) as handle:
            for m in handle:
                print("Step: {}\n{}\nSATISFIABLE".format(step, " ".join(
                    ["{}:{}".format(x,y) for x,y in dlp.get_answer(m, step)]
                )))
                return
            print("Step: {}\nUNSATISFIABLE".format(step))
        step += 1
    def parallel_plan(self):
        """Planning function for the parallel mode, based on clingo incremental mode
        Here no additional inputs are needed"""
        prg = clingo.Control(arguments=["-Wnone"])
        prg.load(self.encoding)
        prg.load(self.instance)

        imin = self.get(prg.get_const("imin"), clingo.Number(0))
        imax = prg.get_const("imax")
        istop = self.get(prg.get_const("istop"), clingo.String("SAT"))

        step, ret = 0, None
        while ((imax is None or step < imax.number)
               and (step == 0 or step < imin.number or
                    ((istop.string == "SAT" and not ret.satisfiable) or
                     (istop.string == "UNSAT" and not ret.unsatisfiable) or
                     (istop.string == "UNKNOWN" and not ret.unknown)))):
            parts = []
            parts.append(("check", [step]))
            if step > 0:
                prg.release_external(clingo.Function("query", [step - 1]))
                parts.append(("step", [step]))
                prg.cleanup()
            else:
                parts.append(("base", []))
            prg.ground(parts)
            prg.assign_external(clingo.Function("query", [step]), True)
            ret, step = prg.solve(on_model=self.get_parallel_plan), step + 1

        # save plan length for benchmark output
        self.plan_length = step - 1
def main(prg):

    imin   = get(prg.get_const("imin"), 1)
    imax   = get(prg.get_const("imax"), 100)
    istop  = get(prg.get_const("istop"), "SAT")

    step   = 0

    prg.ground([("base", [])])

    ret = prg.solve(on_model = __on_model)

    while ((imax is None or step < imax) and
               (step == 0   or step < imin or (
                  (istop == "SAT"     and ret != clingo.SolveResult.satisfiable) or
                  (istop == "UNSAT"   and ret != clingo.SolveResult.unsatisfiable) or
                  (istop == "UNKNOWN" and ret != clingo.SolveResult.unknown)))):

            # print "=== Add cumulative rules to program"
            print "=== Set cumulative(" + str(step)  + ")"

            prg.ground([("step", [step])])

            # print "=== Set external query(" + str(step) +  ") to be true "
            prg.assign_external(clingo.Function("query", [step]), True)

            ret = prg.solve(on_model = __on_model)
            # print "=== Release external query(" + str(step) + ")   "
            prg.release_external(clingo.Function("query", [step]))

            if ret == clingo.SolveResult.SAT:
                 print "=== Found solution "
                 break

            step = step+1
示例#10
0
    def encode_BooleanFunction(self, n, f, ensure_dnf=True):
        def clauses_of_dnf(f):
            if f == self.ba.FALSE:
                return [False]
            if f == self.ba.TRUE:
                return [True]
            if isinstance(f, boolean.OR):
                return f.args
            else:
                return [f]

        def literals_of_clause(c):
            def make_literal(l):
                if isinstance(l, boolean.NOT):
                    return (l.args[0].obj, -1)
                else:
                    return (l.obj, 1)

            lits = c.args if isinstance(c, boolean.AND) else [c]
            return map(make_literal, lits)

        facts = []
        if ensure_dnf:
            f = self.ba.dnf(f).simplify()
        for cid, c in enumerate(clauses_of_dnf(f)):
            if isinstance(c, bool):
                facts.append(clingo.Function("constant", symbols(n, s2v(c))))
            else:
                for m, v in literals_of_clause(c):
                    facts.append(
                        clingo.Function("clause", symbols(n, cid + 1, m, v)))
        return facts
示例#11
0
def pkn_to_facts(pkn, maxclause=None, allow_skipping_nodes=False):
    facts = []
    if not allow_skipping_nodes:
        facts.append(asp.Function("nbnode", symbols(len(pkn.nodes()))))
        for n in pkn.nodes():
            facts.append(asp.Function("node", symbols(n)))
    else:
        facts.append("nbnode(NB) :- NB = #count{N: node(N)}")
        for n in pkn.nodes():
            facts.append("{{{}}}".format(asp.Function("node", symbols(n))))
    for (orig, dest, data) in pkn.edges(data=True):
        if data["sign"] in ["ukn", "?", "0", 0]:
            args = symbols(orig, dest)
            f = "in({},{},(-1;1))".format(*args)
            facts.append(f)
        else:
            ds = data["sign"]
            if ds in ["-", "+"]:
                ds += "1"
            s = int(ds)
            facts.append(asp.Function("in", symbols(orig, dest, s)))

    def bounded_nb_clauses(d):
        nbc = nb_clauses(d)
        if maxclause:
            nbc = min(maxclause, nbc)
        return nbc

    for n, i in pkn.in_degree(pkn.nodes()):
        facts.append(asp.Function("maxC", symbols(n, bounded_nb_clauses(i))))
    return facts
示例#12
0
    def process_model(self) -> bool:
        found_model = False

        if self.model:
            found_model = True
            for atom in self.model:
                if atom.name == "chooseShelf":
                    self.shelf = atom.arguments[0].number
                elif (atom.name == "putdown"
                      and self.domain == "b") or (atom.name == "pickup"):
                    self.plan_length = atom.arguments[1].number
                elif atom.name == "deliver" and self.domain == "b":
                    if self.plan_length < atom.arguments[3].number:
                        self.plan_length = atom.arguments[3].number

        if not found_model:
            self.plan_length = -1
            self.next_action = clingo.Function("", [])
            if self.shelf == -1:
                if self.external:
                    self.prg.assign_external(
                        clingo.Function("order", [
                            self.order[1], self.order[2], self.order[0],
                            self.id
                        ]), False)
                    for shelf in self.available_shelves:
                        self.prg.assign_external(
                            clingo.Function("available", [shelf]), False)
                self.available_shelves = []

        return found_model
示例#13
0
 def apply(self, qexpr, *args, **kwargs):
     """Applies query."""
     Query.ext_atom = self._gen_ext_atom()
     Query.session_step = self._session.step
     prg = self._session.state.prg
     enc_name = "query_" + str(self._session.step + 1)
     parse_result = QueryParser.queryexp.parseString(qexpr, True)
     parse_result_str = str(parse_result).strip("[]")
     parse_result_str = re.sub(
         r'\(\S*\)', '',
         parse_result_str.split()[0]
     ) + " " + parse_result_str.split(
         ' ', 1
     )[1]  # TODO: Hack to flatten top-level head. Adjust semantic action/parser to omit vars in body of top-level head
     debug(parse_result_str, "Query.apply: parse_result")
     prg.add(enc_name, [],
             parse_result_str)  # equivalent rules for query expr
     prg.add(enc_name, [], "#external {0}.".format(
         Query.ext_atom))  # external atom switch
     prg.ground([(enc_name, [])])
     prg.assign_external(clingo.Function(Query.ext_atom), True)
     query_head = clingo.Function(parse_result_str.split()[0])
     debug(query_head, "Query.apply: query_head")
     assumptions = list(
         self._session.state.assumptions
     )  # copy of assumptions to add query head atom for solving
     assumptions.append((query_head, True))
     output_on_model = []  # output returned by on_model
     self._session.state.prg.solve(
         on_model(self._shared_data['show_preds'], output_on_model),
         assumptions)
     self.prnt('\n'.join(output_on_model) + '\n')
     prg.release_external(clingo.Function(Query.ext_atom))
     self._update_session_log("query", "qexpr", qexpr)
示例#14
0
    def test_comparison_ops(self):
        nc1 = noclingo.Number(34)
        nc2 = noclingo.Number(43)
        self.assertTrue(nc1 <= nc2)
        self.assertTrue(nc1 < nc2)
        self.assertTrue(nc2 >= nc1)
        self.assertTrue(nc2 > nc1)

        nc3 = noclingo.String("abcd")
        nc4 = noclingo.String("bcde")
        self.assertTrue(nc3 <= nc4)
        self.assertTrue(nc3 < nc4)
        self.assertTrue(nc4 >= nc3)
        self.assertTrue(nc4 > nc3)

        nc5 = noclingo.Function("abc", [noclingo.Number(45)])
        nc6 = noclingo.Function("abc", [noclingo.String("45")])
        c5 = clingo.Function("abc", [clingo.Number(45)])
        c6 = clingo.Function("abc", [clingo.String("45")])
        if c5 < c6: self.assertTrue(nc5 < nc6)
        else: self.assertTrue(nc5 > nc6)

        nc7 = noclingo.Function(
            "abc",
            [noclingo.String("45"), noclingo.Number(5)])
        self.assertTrue(nc6 < nc7)

        if noclingo.SymbolType.Number < noclingo.SymbolType.String:
            self.assertTrue(nc1 < nc3)
        else:
            self.assertTrue(nc1 > nc3)
示例#15
0
    def solutions(self, on_model, on_model_weight=None, limit=0,
                    force_weight=None):

        control = self.default_control("0", "--project")

        do_subsets = self.opts.family == "subset" \
            or (self.opts.family =="mincard" and self.opts.mincard_tolerance)
        minsize = None

        self.setup_opt(control)

        control.load(aspf("show.lp"))
        control.ground([("base", [])])

        start = time.time()

        if self.nodataset:
            force_weight = 0

        if force_weight is None:
            control.assign_external(clingo.Function("tolerance"),False)
            dbg("# start initial solving")
            opt = []
            res = control.solve(on_model=lambda model: opt.append(model.cost))
            dbg("# initial solve took %s" % (time.time()-start))

            optimizations = opt.pop()
            dbg("# optimizations = %s" % optimizations)

            weight = optimizations[0]
            if self.do_mincard:
                minsize = optimizations[1]
            if weight > 0 and on_model_weight is not None:
                dbg("# model has weight, changing enumeration mode")
                for sample in self.solution_samples():
                    on_model_weight(sample)
                return

            control.assign_external(clingo.Function("tolerance"),True)
        else:
            weight = force_weight
            control.assign_external(clingo.Function("tolerance"),True)
            dbg("# force weight = %d" % weight)

        self.setup_weight(control, weight)
        self.setup_card(control, minsize)

        control.configuration.solve.opt_mode = "ignore"
        control.configuration.solve.models = limit
        control.configuration.solve.project = 1
        if do_subsets:
            control.configuration.solve.enum_mode = "domRec"
            control.configuration.solver[0].heuristic = "Domain"
            control.configuration.solver[0].dom_mod = "5,16"

        start = time.time()
        dbg("# begin enumeration")
        res = control.solve(on_model=on_model)
        dbg("# enumeration took %s" % (time.time()-start))
示例#16
0
 def get_external(self, m1, m2):
     external = self.externals.get((m1, m2))
     if external is None:
         f1 = clingo.Function(self.model_str, [m1])
         f2 = clingo.Function(self.model_str, [m2])
         external = clingo.Function(self.volatile_str, [f1, f2])
         self.externals[(m1, m2)] = external
     return external
示例#17
0
 def encode_bind_cfg(self, cfg, obs, mutant=None):
     args = (cfg, obs)
     if mutant is not None:
         self.load_template_bind_cfg_mutant()
         args = args + (clingo.Function("mutant", symbols(mutant)), )
     else:
         self.load_template_bind_cfg()
     return [clingo.Function("bind_cfg", symbols(*args))]
示例#18
0
    def visit_TheoryAtom(self, atom):
        """
        Rewrites theory atoms related to temporal formulas.

        An atom of form `&tel {...}` is rewritten to `&tel(k) {...}`, atoms of
        form `&initial` and `&final` are rewritten to `__initial` and
        `__final`, and atoms of form `&true` and `&false` are rewritten to
        `#true` and `#false`.
        """
        if atom.term.ast_type == _ast.ASTType.Function and len(
                atom.term.arguments) == 0:
            time = lambda loc: _ast.SymbolicTerm(
                loc, _clingo.Function(_tf.g_time_parameter_name))
            wrap = lambda loc, atom: _ast.Literal(
                loc, _ast.Sign.DoubleNegation, atom) if self.__head else atom
            if atom.term.name == "del":
                if not self.__negation and not self.__constraint:
                    raise RuntimeError(
                        "dynamic formulas not supported in this context: {}".
                        format(_tf.str_location(atom.location)))
                atom.term.arguments = [
                    _ast.SymbolicTerm(atom.term.location,
                                      _clingo.Function("__t"))
                ]
            elif atom.term.name == "tel":
                if self.__head:
                    atom, rules = self.__head_transformer.transform(atom)
                    self.__aux_rules.extend(rules)
                else:
                    if not self.__negation and not self.__constraint:
                        raise RuntimeError(
                            "temporal formulas not supported in this context: {}"
                            .format(_tf.str_location(atom.location)))
                    for element in atom.elements:
                        if len(element.terms) != 1:
                            raise RuntimeError(
                                "invalid temporal formula: {}".format(
                                    _tf.str_location(atom.location)))
                        self.visit(element.condition)
                    atom.term = self.__term_transformer.visit(
                        atom.term, False, True, True, self.__max_shift)
            elif atom.term.name == "initial":
                atom = wrap(
                    atom.location,
                    _ast.SymbolicAtom(
                        _ast.Function(atom.location, "__initial",
                                      [time(atom.location)], False)))
            elif atom.term.name == "final":
                atom = wrap(
                    atom.location,
                    _ast.SymbolicAtom(
                        _ast.Function(atom.location, "__final",
                                      [time(atom.location)], False)))
            elif atom.term.name == "true":
                atom = wrap(atom.location, _ast.BooleanConstant(True))
            elif atom.term.name == "false":
                atom = wrap(atom.location, _ast.BooleanConstant(False))
        return atom
示例#19
0
 def __next(self):
     assert (self.__horizon < 30)
     self.__prg.assign_external(
         clingo.Function("horizon", [self.__horizon]), False)
     self.__horizon += 1
     self.__prg.ground([("trans", [self.__horizon]),
                        ("check", [self.__horizon]),
                        ("state", [self.__horizon])])
     self.__prg.assign_external(
         clingo.Function("horizon", [self.__horizon]), True)
示例#20
0
    def test_symbol_generator(self):
        csg = get_symbol_generator(SymbolMode.CLINGO)
        ncsg = get_symbol_generator(SymbolMode.NOCLINGO)

        self.assertEqual(csg.mode, SymbolMode.CLINGO)
        self.assertEqual(ncsg.mode, SymbolMode.NOCLINGO)

        cli = clingo.Infimum
        cls = clingo.Supremum
        cl1 = clingo.Function("const")
        cl2 = clingo.Number(3)
        cl3 = clingo.String("No")
        cl4 = clingo.Function("", [cl1, cl2])
        cl5 = clingo.Function("f", [cl3, cl4, cl1], False)

        ncli = noclingo.Infimum
        ncls = noclingo.Supremum
        ncl1 = noclingo.Function("const")
        ncl2 = noclingo.Number(3)
        ncl3 = noclingo.String("No")
        ncl4 = noclingo.Function("", [ncl1, ncl2])
        ncl5 = noclingo.Function("f", [ncl3, ncl4, ncl1], False)

        csg_cli = csg.Infimum
        csg_cls = csg.Supremum
        csg_cl1 = csg.Function("const")
        csg_cl2 = csg.Number(3)
        csg_cl3 = csg.String("No")
        csg_cl4 = csg.Function("", [cl1, cl2])
        csg_cl5 = csg.Function("f", [cl3, cl4, cl1], False)

        ncsg_ncli = ncsg.Infimum
        ncsg_ncls = ncsg.Supremum
        ncsg_ncl1 = ncsg.Function("const")
        ncsg_ncl2 = ncsg.Number(3)
        ncsg_ncl3 = ncsg.String("No")
        ncsg_ncl4 = ncsg.Function("", [ncsg_ncl1, ncsg_ncl2])
        ncsg_ncl5 = ncsg.Function("f", [ncsg_ncl3, ncsg_ncl4, ncsg_ncl1],
                                  False)

        self.assertEqual(cli, csg_cli)
        self.assertEqual(cls, csg_cls)
        self.assertEqual(cl1, csg_cl1)
        self.assertEqual(cl2, csg_cl2)
        self.assertEqual(cl3, csg_cl3)
        self.assertEqual(cl4, csg_cl4)
        self.assertEqual(cl5, csg_cl5)

        self.assertEqual(ncli, ncsg_ncli)
        self.assertEqual(ncls, ncsg_ncls)
        self.assertEqual(ncl1, ncsg_ncl1)
        self.assertEqual(ncl2, ncsg_ncl2)
        self.assertEqual(ncl3, ncsg_ncl3)
        self.assertEqual(ncl4, ncsg_ncl4)
        self.assertEqual(ncl5, ncsg_ncl5)
示例#21
0
def imain(prg, future_sigs, program_parts, on_model, imin = 0, imax = None, istop = "SAT"):
    """
    Take a program object and runs the incremental main solving loop.

    For each pair (name, arity) in future_sigs all atoms in the program base
    with the time parameter referring to the future are set to false. For
    example, given (p, 2) and atoms  p(x,1) in step 0, the atom would p(x,1)
    would be set to false via an assumption. In the following time steps, it
    would not be set to False.

    The list program_parts contains all program parts appearing in the program
    in form of triples (root, name, range) where root is either "initial" (time
    step 0), "always" (time steps >= 0), or "dynamic" (time steps > 0) and
    range is a list of integers for which the part has to be grounded
    backwards. Given range [0, 1] and root "always", at each iteration the
    program part would be grounded at horizon and horizon-1. The latter only if
    the horizon is greater than 0.

    Arguments:
    prg           -- Control object holding the program.
    future_sigs   -- Signatures of predicates whose future incarnations have to
                     be set to False.
    program_parts -- Program parts to ground.
    imin          -- Minimum number of iterations.
    imax          -- Maximum number of iterations.
    istop         -- When to stop.
    """
    f = _ty.Theory()
    step, ret = 0, None
    while ((imax is None or step < imax) and
           (step == 0 or step < imin or (
              (istop == "SAT"     and not ret.satisfiable) or
              (istop == "UNSAT"   and not ret.unsatisfiable) or
              (istop == "UNKNOWN" and not ret.unknown)))):
        parts = []
        for root_name, part_name, rng in program_parts:
            for i in rng:
                if ((step - i >= 0 and root_name == "always") or
                    (step - i  > 0 and root_name == "dynamic") or
                    (step - i == 0 and root_name == "initial")):
                    parts.append((part_name, [step - i, step]))
        if step > 0:
            prg.release_external(_clingo.Function("__final", [step-1]))
            prg.cleanup()

        prg.ground(parts)
        f.translate(step, prg)
        prg.assign_external(_clingo.Function("__final", [step]), True)
        assumptions = []
        for name, arity, positive in future_sigs:
            for atom in prg.symbolic_atoms.by_signature(name, arity, positive):
                if atom.symbol.arguments[-1].number > step:
                    assumptions.append(-atom.literal)
        ret, step = prg.solve(on_model=lambda m: on_model(m, step), assumptions=assumptions), step+1
示例#22
0
 def release_order(self):
     """Deactivate external for current order"""
     if self.external:
         self.prg.assign_external(
             clingo.Function(
                 "order",
                 [self.order[1], self.order[2], self.order[0], self.id]),
             False)
         for shelf in self.available_shelves:
             self.prg.assign_external(clingo.Function("available", [shelf]),
                                      False)
     self.shelf = -1
示例#23
0
 def __init__(self, t):
     super(PA_Functionc, self).__init__(t)
     arg_fun_objects = []
     try:
         arg_fun_objects = list(arg.ggfun for arg in t[0][1])
     except IndexError:
         pass
     if arg_fun_objects:
         self.ggfun = clingo.Function(t[0][0], arg_fun_objects)
     else:
         self.ggfun = clingo.Function(t[0][0])
     debug("ggfun " + type(self.ggfun).__name__ + " " + str(self.ggfun))
示例#24
0
 def term_to_symbol(self, term):
     """
     Converts theory terms in the form of function symbols to clingo function symbols.
     """
     if term.type == clingo.TheoryTermType.Function:
         return clingo.Function(
             term.name,
             [self.term_to_symbol(arg) for arg in term.arguments])
     if term.type == clingo.TheoryTermType.Symbol:
         return clingo.Function(term.name)
     if term.type == clingo.TheoryTermType.Number:
         return clingo.Number(term.number)
     raise RuntimeError("Incorrect Term Type")
示例#25
0
def _evaluate_term(term):
    # pylint: disable=too-many-return-statements

    # tuples
    if term.type == clingo.TheoryTermType.Tuple:
        return clingo.Tuple(_evaluate_term(x) for x in term.arguments)

    # functions and arithmetic operations
    if term.type == clingo.TheoryTermType.Function:
        # binary operations
        if term.name in _BOP and len(term.arguments) == 2:
            a = _evaluate_term(term.arguments[0])
            b = _evaluate_term(term.arguments[1])

            if a.type != clingo.SymbolType.Number or b.type != clingo.SymbolType.Number:
                raise RuntimeError("Invalid Binary Operation")

            if term.name in ("/", "\\") and b.number == 0:
                raise RuntimeError("Division by Zero")

            return clingo.Number(_BOP[term.name](a.number, b.number))

        # unary operations
        if term.name == "-" and len(term.arguments) == 1:
            a = _evaluate_term(term.arguments[0])

            if a.type == clingo.SymbolType.Number:
                return clingo.Number(-a.number)

            if a.type == clingo.SymbolType.Function and a.name:
                return clingo.Function(a.name, a.arguments, not a.positive)

            raise RuntimeError("Invalid Unary Operation")

        # invalid operators
        if term.name == ".." and len(term.arguments) == 2:
            raise RuntimeError("Invalid Interval")

        # functions
        return clingo.Function(term.name,
                               (_evaluate_term(x) for x in term.arguments))

    # constants
    if term.type == clingo.TheoryTermType.Symbol:
        return clingo.Function(term.name)

    # numbers
    if term.type == clingo.TheoryTermType.Number:
        return clingo.Number(term.number)

    raise RuntimeError("Invalid Syntax")
示例#26
0
 def handle_message(self, msg):
     if msg == "interrupt":
         self.state = SolveThread.STATE_IDLE
     elif msg == "exit":
         self.state = SolveThread.STATE_EXIT
     elif msg == "less_pigeon_please":
         self.prg.assign_external(clingo.Function("p"), False)
         self.state = SolveThread.STATE_IDLE
     elif msg == "more_pigeon_please":
         self.prg.assign_external(clingo.Function("p"), True)
         self.state = SolveThread.STATE_IDLE
     elif msg == "solve":
         self.state = SolveThread.STATE_SOLVE
     else: raise(RuntimeError("unexpected message: " + msg))
示例#27
0
    def __on_model(self, model):
        ass = self.prop.assignment(model.thread_id)
        if ass is not None:
            (opt, values) = ass
            model.extend(
                [clingo.Function('_lp_optimum', [clingo.String(str(opt))])])

            for name in values:
                model.extend([
                    clingo.Function('_lp_solution', [
                        clingo.Function(name, []),
                        clingo.String(str(values[name]))
                    ])
                ])
示例#28
0
    def plan(self):
        """Planning function for the sequential mode, based on clingo incremental mode
        Additionally adds atoms for which robot and for which orders a plan needs to be found,
        and plans of all previous robots are added as input"""
        prg = clingo.Control(arguments=["-Wnone"])
        prg.load(self.encoding)
        prg.load(self.instance)
        # which robot is planning
        prg.add("base", [],
                "planning(robot(" + str(self.current_robot) + ")).")
        # which orders need to be planned
        for oid in self.assignment[self.current_robot]:
            prg.add("base", [], "process(order(" + str(oid) + ")).")
        prg.add("base", [], "planLength(" + str(self.plan_length) + ").")

        # add plans of all previous robots
        if self.current_robot != 1:
            for i in range(1, self.current_robot):
                for atom in self.plans[i]:
                    prg.add("base", [], str(atom) + ".")

        # incremental solving
        imin = self.get(prg.get_const("imin"), clingo.Number(0))
        imax = prg.get_const("imax")
        istop = self.get(prg.get_const("istop"), clingo.String("SAT"))

        step, ret = 0, None
        while ((imax is None or step < imax.number)
               and (step == 0 or step < imin.number or
                    ((istop.string == "SAT" and not ret.satisfiable) or
                     (istop.string == "UNSAT" and not ret.unsatisfiable) or
                     (istop.string == "UNKNOWN" and not ret.unknown)))):
            parts = []
            parts.append(("check", [step]))
            if step > 0:
                prg.release_external(clingo.Function("query", [step - 1]))
                parts.append(("step", [step]))
                prg.cleanup()
            else:
                parts.append(("base", []))
            prg.ground(parts)
            prg.assign_external(clingo.Function("query", [step]), True)
            ret, step = prg.solve(on_model=self.get_plan), step + 1

            if self.debug:
                print(str(step - 1))

        # save maximum plan length
        if self.plan_length < step - 1:
            self.plan_length = step - 1
示例#29
0
 def start(self, pos, target):
     self.__assign = []
     for (robot, x, y) in pos:
         self.__last_position[robot] = (x, y)
         self.__assign.append(
             clingo.Function("pos", [clingo.Function(robot), x, y, 0]))
     print target
     self.__assign.append(
         clingo.Function(
             "target", [clingo.Function(target[0]), target[1], target[2]]))
     for x in self.__assign:
         self.__prg.assign_external(x, True)
     self.__solution = None
     self.__future = self.__prg.solve(on_model=self.__on_model, async=True)
示例#30
0
    def test_comparison_ops(self):
        nc1 = noclingo.Number(34)
        nc2 = noclingo.Number(43)
        self.assertTrue(nc1 <= nc2)
        self.assertTrue(nc1 < nc2)
        self.assertTrue(nc2 >= nc1)
        self.assertTrue(nc2 > nc1)

        nc3 = noclingo.String("abcd")
        nc4 = noclingo.String("bcde")
        self.assertTrue(nc3 <= nc4)
        self.assertTrue(nc3 < nc4)
        self.assertTrue(nc4 >= nc3)
        self.assertTrue(nc4 > nc3)

        nc5 = noclingo.Function("abc", [noclingo.Number(45)])
        nc6 = noclingo.Function("abc", [noclingo.String("45")])
        c5 = clingo.Function("abc", [clingo.Number(45)])
        c6 = clingo.Function("abc", [clingo.String("45")])
        if c5 < c6: self.assertTrue(nc5 < nc6)
        else: self.assertTrue(nc5 > nc6)

        nc7 = noclingo.Function(
            "abc",
            [noclingo.String("45"), noclingo.Number(5)])
        self.assertTrue(nc6 < nc7)

        def compare_ordering(a, b):
            if noclingo_to_clingo(a) < noclingo_to_clingo(b):
                self.assertTrue(a < b)
            elif noclingo_to_clingo(b) < noclingo_to_clingo(a):
                self.assertTrue(b < a)
            else:
                self.assertEqual(a, b)

        compare_ordering(noclingo.String("1"), noclingo.Number(2))
        compare_ordering(noclingo.Number(1), noclingo.String("2"))
        compare_ordering(noclingo.String("1"), noclingo.Function("2"))
        compare_ordering(noclingo.Function("2"), noclingo.String("1"))
        compare_ordering(noclingo.Number(1), noclingo.Function("2"))
        compare_ordering(noclingo.Function("1"), noclingo.Number(2))
        compare_ordering(noclingo.Infimum, noclingo.Supremum)
        compare_ordering(noclingo.Supremum, noclingo.Infimum)
        compare_ordering(noclingo.Infimum, noclingo.Number(2))
        compare_ordering(noclingo.Infimum, noclingo.String("2"))
        compare_ordering(noclingo.Infimum, noclingo.Function("2"))
        compare_ordering(noclingo.Supremum, noclingo.Function("2"))
        compare_ordering(noclingo.Supremum, noclingo.String("2"))
        compare_ordering(noclingo.Supremum, noclingo.Number(2))