Esempio n. 1
0
 def removeFirst(self, car_list):
     result = re.search("c\(.+?\)(]|,c)(.*)]", car_list.string)
     if result:
         rest = result.group(2)
         yield clingo.String(f"[c({rest}]")
     elif car_list.string != "[]":
         yield clingo.String("[]")
Esempio n. 2
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 + ']'
Esempio n. 3
0
 def argify(arg):
     if isinstance(arg, bool):
         return clingo.String(str(arg))
     elif isinstance(arg, int):
         return clingo.Number(arg)
     else:
         return clingo.String(str(arg))
Esempio n. 4
0
def to_symbol(obj):
    if isinstance(obj, int):
        return clingo.Number(obj)
    if isinstance(obj, str):
        return clingo.String(obj)
        return clingo.Number(obj)
    if isinstance(obj, str):
        return clingo.String(obj)
    raise NotImplementedError(f"conversion of {type(obj)} to {clingo.Symbol}")
Esempio n. 5
0
 def storeConstant(self, s: str):
     if len(s) == 0 or (s[0] == '"' and s[1] == '"'):
         # TODO this is only for backwards compatibility, should be removed in V2
         logging.warning(
             "storeConstant() was used on string '%s', use storeString in the future",
             s)
         if len(s) == 0:
             return ClingoID(self.ccontext, SymLit(clingo.String(''), None))
         else:
             return ClingoID(self.ccontext, SymLit(clingo.String(s), None))
     return ClingoID(self.ccontext, SymLit(clingo.Function(s), None))
Esempio n. 6
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]))
                    ])
                ])
Esempio n. 7
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)
Esempio n. 8
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)
Esempio n. 9
0
    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
Esempio n. 10
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])
Esempio n. 11
0
 def _copy_symbol(self, symbol) -> clingo.Symbol:
     if symbol.type == clingo.SymbolType.String:
         return clingo.String(symbol.string)
     elif symbol.type == clingo.SymbolType.Number:
         return clingo.Number(symbol.number)
     raise NotImplementedError(
         "_copy_symbol for symbol type {}".format(symbol.type)
     )
Esempio n. 12
0
def symbol_of_py(obj):
    if isinstance(obj, str):
        return asp.String(obj)
    elif isinstance(obj, int):
        return asp.Number(obj)
    elif isinstance(obj, tuple):
        return clingo_Tuple([symbol_of_py(o) for o in obj])
    return obj
Esempio n. 13
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)
Esempio n. 14
0
    def test_noclingo(self):
        from clingo import Control
        import clingo
        import clorm.noclingo as noclingo

        self.assertEqual(clingo.String("blah"), noclingo.String("blah"))
        self.assertEqual(clingo.Number(5), noclingo.Number(5))
        with self.assertRaises(TypeError) as ctx:
            instance = Control()
        with self.assertRaises(TypeError) as ctx:
            instance = clingo.Control()
Esempio n. 15
0
 def hex2clingo(self, term):
     if isinstance(term, ClingoID):
         return term.symlit.sym
     elif isinstance(term, str):
         if term[0] == '"':
             ret = clingo.String(term[1:-1])
         else:
             try:
                 ret = clingo.parse_term(term)
             except:
                 logging.warning(
                     "cannot parse external atom term {} with clingo! (creating a string out of it)"
                     .format(repr(term)))
                 ret = clingo.String(str(term))
     elif isinstance(term, int):
         ret = clingo.Number(term)
     else:
         raise Exception(
             "cannot convert external atom term {} to clingo term!".format(
                 repr(term)))
     return ret
Esempio n. 16
0
def noclingo_to_clingo(nclsym):
    if isinstance(nclsym, clingo.Symbol): return nclsym
    if nclsym.type == SymbolType.Infimum: return clingo.Infimum
    elif nclsym.type == SymbolType.Supremum: return clingo.Supremum
    elif nclsym.type == SymbolType.Number: return clingo.Number(nclsym.number)
    elif nclsym.type == SymbolType.String: return clingo.String(nclsym.string)
    elif nclsym.type != SymbolType.Function:
        raise TypeError(("Symbol '{}' ({}) is not of type noclingo.SymbolType."
                         "Function").format(nclsym, type(nclsym)))

    return clingo.Function(
        nclsym.name, tuple(noclingo_to_clingo(t) for t in nclsym.arguments),
        nclsym.positive)
Esempio n. 17
0
 def hex2clingo(self, term):
   if isinstance(term, ClingoID):
     return term.symlit.sym
   elif isinstance(term, str):
     if term[0] == '"':
       ret = clingo.String(term[1:-1])
     else:
       ret = clingo.parse_term(term)
   elif isinstance(term, int):
     ret = clingo.Number(term)
   else:
     raise Exception("cannot convert external atom term {} to clingo term!".format(repr(term)))
   return ret
Esempio n. 18
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
Esempio n. 19
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))
Esempio n. 20
0
    def move_right(self, state):
        # print(type(state))
        cur_pos = re.search("robot_pos\((\d+)\)", state.string).group(1)
        end_pos = re.search("end_pos\((\d+)\)", state.string).group(1)

        if int(cur_pos) < int(end_pos):
            return [
                clingo.String(
                    re.sub(
                        "robot_pos\((\d+)\)",
                        f"robot_pos({int(cur_pos)+1})",
                        state.string,
                    ))
            ]
        return []
Esempio n. 21
0
    def setUp(self):

        class Fun(ComplexTerm):
            aint = IntegerField()
            astr = StringField()

        class Tup(ComplexTerm):
            aint = IntegerField()
            astr = StringField()
            class Meta: is_tuple = True

        class Afact(Predicate):
            aint = IntegerField()
            afun = Fun.Field()

        class Bfact(Predicate):
            astr = StringField()
            atup = Tup.Field()

        class Cfact(ComplexTerm):
            aint = IntegerField()
            astr = StringField()

        afact1 = Afact(aint=10, afun=Fun(aint=1, astr="a"))
        afact2 = Afact(aint=20, afun=Fun(aint=2, astr="b"))
        bfact1 = Bfact(astr="aa", atup=Tup(aint=1, astr="a"))
        bfact2 = Bfact(astr="bb", atup=Tup(aint=2, astr="b"))
        self.allf = [ afact1, bfact1, afact2, bfact2 ]

        self.Fun = Fun
        self.Tup = Tup
        self.Afact = Afact
        self.Bfact = Bfact
        self.Cfact = Cfact

        self.n1 = clingo.Number(60)
        self.s1 = clingo.String("aaaa")
        self.f1 = clingo.Function("",[self.n1, self.s1])
        self.p1 = Cfact(aint=60, astr="aaaa")
        self.fb1 = FactBase(facts=[self.p1])

        self.str_n1 = '{"clingo.SymbolType": "Number", "number": 60}'
        self.str_s1 = '{"clingo.SymbolType": "String", "string": "aaaa"}'
        self.str_f1 = '{"clingo.SymbolType": "Function", "name": "cfact", ' \
            + '"arguments": [' + self.str_n1 + ', ' + self.str_s1 + ']' + ', "positive": true}'
        self.str_p1 = '{"clorm.Predicate": "Cfact", "raw": ' + self.str_f1 + '}'
        self.str_fb1 = '{"clorm.FactBase": [], "facts": ['+ self.str_p1 + ']}'
Esempio n. 22
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])

        self.assertEqual(str(nc), str(c))

        # Check that a tuple with a single element is represented correctly
        nc_one_tuple = noclingo.Function("", [nc2])
        c_one_tuple = clingo.Function("", [c2])
        self.assertEqual(str(nc_one_tuple), str(c_one_tuple))

        # Check using the convenience Tuple_() function
        self.assertEqual(noclingo.Tuple_([nc2]), nc_one_tuple)
        self.assertEqual(noclingo.Tuple_([nc1, nc2]), nc)
Esempio n. 23
0
    def test_clingo_to_noclingo(self):

        # Converting the Infimum and Supremum
        cli = clingo.Infimum
        ncli = noclingo.Infimum
        cls = clingo.Supremum
        ncls = noclingo.Supremum

        self.assertEqual(clingo_to_noclingo(cli), ncli)
        self.assertEqual(clingo_to_noclingo(cls), ncls)
        self.assertEqual(noclingo_to_clingo(ncli), cli)
        self.assertEqual(noclingo_to_clingo(ncls), cls)

        # Converting simple structures
        cl1 = clingo.Function("const")
        ncl1 = noclingo.Function("const")
        cl2 = clingo.Number(3)
        ncl2 = noclingo.Number(3)
        cl3 = clingo.String("No")
        ncl3 = noclingo.String("No")

        self.assertEqual(clingo_to_noclingo(cl1), ncl1)
        self.assertEqual(clingo_to_noclingo(cl2), ncl2)
        self.assertEqual(clingo_to_noclingo(cl3), ncl3)
        self.assertEqual(noclingo_to_clingo(ncl1), cl1)
        self.assertEqual(noclingo_to_clingo(ncl2), cl2)
        self.assertEqual(noclingo_to_clingo(ncl3), cl3)

        # More complex function structures
        cl4 = clingo.Function("", [cl1, cl2])
        ncl4 = noclingo.Function("", [ncl1, ncl2])
        self.assertEqual(clingo_to_noclingo(cl4), ncl4)
        self.assertEqual(noclingo_to_clingo(ncl4), cl4)

        cl5 = clingo.Function("f", [cl3, cl4, cl1], False)
        ncl5 = noclingo.Function("f", [ncl3, ncl4, ncl1], False)
        self.assertEqual(clingo_to_noclingo(cl5), ncl5)
        self.assertEqual(noclingo_to_clingo(ncl5), cl5)

        # If it is already the correct symbol type then no conversion required
        self.assertEqual(clingo_to_noclingo(ncl1), ncl1)
        self.assertEqual(noclingo_to_clingo(cl1), cl1)
        self.assertTrue(clingo_to_noclingo(ncl1) is ncl1)
        self.assertTrue(noclingo_to_clingo(cl1) is cl1)
Esempio n. 24
0
    def pour_coffee(self, state):
        cur_pos = re.search("robot_pos\((\d+)\)", state.string).group(1)
        end_pos = re.search("end_pos\((\d+)\)", state.string).group(1)
        if int(cur_pos) < int(end_pos):
            cup_state = re.search(f"place\({cur_pos},\w+,cup\((.+?)\)",
                                  state.string).group(1)
            wants = re.search(f"place\({cur_pos},(\w+),cup",
                              state.string).group(1)

            if cup_state == "up,empty":
                return [
                    clingo.String(
                        re.sub(
                            f"place\({cur_pos},\w+,cup\((.+?)\)",
                            f"place({cur_pos},{wants},cup(up,coffee)",
                            state.string,
                        ))
                ]
        return []
Esempio n. 25
0
    def turn_cup_over(self, state):
        cur_pos = re.search("robot_pos\((\d+)\)", state.string).group(1)
        end_pos = re.search("end_pos\((\d+)\)", state.string).group(1)
        if int(cur_pos) < int(end_pos):
            cup_state = re.search(f"place\({cur_pos},\w+,cup\((.+?),",
                                  state.string).group(1)
            wants = re.search(f"place\({cur_pos},(\w+),cup",
                              state.string).group(1)

            if cup_state == "down":
                return [
                    clingo.String(
                        re.sub(
                            f"place\({cur_pos},\w+,cup\((.+?),",
                            f"place({cur_pos},{wants},cup(up,",
                            state.string,
                        ))
                ]
        return []
Esempio n. 26
0
def create_symbol(rep):
    """
    Returns the symbolic representation of the given theory term.

    Throws an error if rep it is not a valid symbol.

    Arguments:
    rep -- Theory term to translate.
    """
    if rep.type == _clingo.TheoryTermType.Number:
        return _clingo.Number(rep.number)
    elif rep.type in [_clingo.TheoryTermType.List, _clingo.TheoryTermType.Set]:
        raise RuntimeError("invalid symbol: {}".format(rep))
    elif rep.type == _clingo.TheoryTermType.Function and rep.name in g_arithmetic_operators:
        if len(rep.arguments) == 1:
            rhs = create_symbol(rep.arguments[0])
            if rep.name == "-":
                if rhs.type == _clingo.SymbolType.Number:
                    return _clingo.Number(-rhs.number)
                elif rhs.type == _clingo.SymbolType.Function and len(
                        rep.name) > 0:
                    return _clingo.Function(rhs.name, rhs.arguments,
                                            not rhs.positive)
        elif len(rep.arguments) == 2:
            return _clingo.Number(create_number(rep))

        raise RuntimeError("invalid symbol: {}".format(rep))
    else:
        name = "" if rep.type == _clingo.TheoryTermType.Tuple else rep.name
        if name in g_binary_operators or name in g_unary_operators or name in g_tel_operators:
            raise RuntimeError("invalid symbol: {}".format(rep))
        args = [] if rep.type == _clingo.TheoryTermType.Symbol else rep.arguments
        if len(args) == 0:
            if name == "#inf":
                return _clingo.Infimum
            elif name == "#sup":
                return _clingo.Supremum
            elif len(name) > 1 and name.startswith('"') and name.endswith('"'):
                return _clingo.String(name[1:-1])
        return _clingo.Function(name, [create_symbol(arg) for arg in args])
Esempio n. 27
0
def symbol_decoder(obj):
    '''A JSON Decoder for clingo.Symbol objects.

    Example usage:
    symbol = json.loads(json, default=encoder)

    Args:
      obj: a JSON object
    '''
    if not isinstance(obj, Mapping): return obj
    if "clingo.SymbolType" not in obj: return obj
    stype_str = obj["clingo.SymbolType"]
    if stype_str == "Infimum": return clingo.Infimum
    if stype_str == "Supremum": return clingo.Supremum
    if stype_str == "String": return clingo.String(obj["string"])
    if stype_str == "Number": return clingo.Number(obj["number"])
    if stype_str == "Function":
        args = [ symbol_decoder(a) for a in obj["arguments"] ]
        positive = obj["positive"]
        return clingo.Function(obj["name"], args, positive)

    # A bad encoding?
    return obj
Esempio n. 28
0
    def test_is_functions(self):
        cli = clingo.Infimum
        cls = clingo.Supremum
        cl1 = clingo.Function("const")
        cl2 = clingo.Number(3)
        cl3 = clingo.String("No")
        cl4 = clingo.Function("", [cl1, cl2])

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

        self.assertTrue(is_Infimum(cli))
        self.assertTrue(is_Infimum(ncli))

        self.assertTrue(is_Supremum(cls))
        self.assertTrue(is_Supremum(ncls))

        self.assertTrue(is_Number(cl2))
        self.assertTrue(is_Number(ncl2))

        self.assertTrue(is_String(cl3))
        self.assertTrue(is_String(ncl3))

        self.assertTrue(is_Function(cl4))
        self.assertTrue(is_Function(ncl4))

        self.assertFalse(is_Infimum(cls))
        self.assertFalse(is_Supremum(cli))
        self.assertFalse(is_Function(cli))
        self.assertFalse(is_Number(cli))
        self.assertFalse(is_String(cli))
        self.assertFalse(is_Supremum(4))
Esempio n. 29
0
 def switch(self, string):
     cs = [c for c in string.string if c not in "[,]"]
     if len(cs) >= 2:
         yield clingo.String(f"[{','.join([cs[1], cs[0]] + cs[2:])}]")
Esempio n. 30
0
 def remove(self, string):
     cs = [c for c in string.string if c not in "[,]"]
     if len(cs) > 0:
         yield clingo.String(f"[{','.join(cs[1:])}]")