Example #1
0
def test_is_leap_year():
    answer = set(run("date_consider_month_2020.lp"))
    assert ({clingo.parse_term("is_leap_year(2020)")} <= answer)

    answer = set(run("date_consider_month_2021.lp"))
    assert (clingo.parse_term("is_leap_year(2021)") not in answer)

    answer = set(run("date_consider_month_2004.lp"))
    assert ({clingo.parse_term("is_leap_year(2004)")} <= answer)
Example #2
0
 def process_evidence(self,raw_evidence):
     evidSet = raw_evidence.split('.')
     self.evidence_atom_assignemnt = []
     for e in evidSet:
         e = e.strip('\n')
         if e == "":
             continue
         elif "not" in e:
             self.evidence_atom_assignemnt.append((clingo.parse_term((e.split("not")[1].strip(" "))), True))
         else:
             self.evidence_atom_assignemnt.append((clingo.parse_term((e.split(":-")[1].strip(" "))), False))
Example #3
0
 def parseEvidence(self,obs = None):
     if obs == None:
         evidSet = self.observation.split('.')
     else:
         evidSet = obs.split('.')
     atomAssignment = []
     for e in evidSet:
         e = e.strip()
         if e == "":
             continue
         elif "not" in e:
             atomAssignment.append((clingo.parse_term((e.split("not")[1].strip(" "))),1))
         else:
             atomAssignment.append((clingo.parse_term((e.split(":-")[1].strip(" "))),0))
     return atomAssignment
Example #4
0
def parse_signature(constraint) -> None:
    """
	Extract the signature information of the theory terms of the theory atom
	Populate the Signature data structure with that information

	:param constraint: clingo TheoryAtom
	"""
    for atom in constraint.elements:
        # this gives me the "type" of the term | e.g. for +~on(..) it would return +~
        term_type: str = atom.terms[0].name

        if "++" in term_type:
            sign = 1
        elif "--" in term_type:
            sign = -1
        else:
            raise TypeError(f"Wrong term type {term_type} for a signature")

        signature: Tuple[str,
                         int] = (atom.terms[0].arguments[0].name,
                                 len(atom.terms[0].arguments[0].arguments) + 1)
        Signatures.sigs.add((sign, signature))

        sig_tuple_term = (atom.terms[0].arguments[0].name,
                          tuple(atom.terms[0].arguments[0].arguments))
        s_atom = clingo.parse_term(str(atom.terms[0].arguments[0]))
        sig_tuple = (s_atom.name, tuple(s_atom.arguments))

        Signatures.add_fullsig(sig_tuple, sig_tuple_term)

        yield sign, signature
Example #5
0
 def _grounder(self, input_list, output_list, predicate):
     ground_atoms = []
     for out in output_list:
         symbol = clingo.parse_term(predicate + '(' + input_list[0] + "," +
                                    out + ')')
         ground_atoms.append(symbol)
     return ground_atoms
Example #6
0
    def d2asp(self, input):
        self._xml_processor(input)
        g_lpmln = ""
        for key, items in self.config_dic.items():
            out_dom = "dom_out_" + key
            in_dom = "input_" + key

            card_rule = items["cad_min"]+"{" + \
                        (items["predicate"][0] +'(I_'+ key+ ",D_" +key+ ')') + \
                        ":"+ (out_dom+'(D_' + key + ')')+\
                        "}" + items["cad_max"] + \
                        " :- " + (in_dom+'(I_' + key + ')') + ".\n"

            out_dom_rules = ""
            in_dom_rules = in_dom + '('
            for out in items["output_list"]:
                out_dom_rules += str(
                    clingo.parse_term(out_dom + '(' + out + ')')) + ".\n"

            for input in items["input_list"]:
                in_dom_rules += input[0] + ";"

            in_dom_rules = in_dom_rules[:-1] + ').\n'

            soft_atoms = self._weight_bounder(items)

            g_lpmln += card_rule + out_dom_rules + in_dom_rules + soft_atoms

        return g_lpmln
Example #7
0
    def enumerate_unknown(self):

        # if no unknowns, or computed all: return
        if not self.unknown:
            self.more_models = False
            return
        if self.computed_all():
            return
        # if quick: print message and update opt_models
        if self.options.improve_limit[3]:
            self.print_unknown_optimal_models(self.unknown, self.mapping)
            self.opt_models += len(self.unknown)
            return
        # if improve_no_check: print message
        if self.options.improve_limit[4]:
            self.print_unknown_nonoptimal_models(self.unknown, self.mapping)
            return

        # ELSE: print *shown* atoms
        # create boolean array representing unknown
        unknowns = [False] * (self.last_model + 1)
        for i in self.unknown:
            unknowns[i] = True
        # create holds dictionary for unknowns
        holds = {}
        for i in self.control.symbolic_atoms.by_signature(self.holds_str, 2):
            try:
                step = int(i.symbol.arguments[1].number)
                if unknowns[step]:
                    alist = holds.setdefault(step, [])
                    alist.append(i.symbol.arguments[0])
            except:
                pass

        # enumerate iterating over holds
        old = self.same_shown_function
        self.same_shown_function = self.same_shown_false
        for step in self.unknown:
            if self.computed_all():
                return
            # pre
            self.holds = holds.get(step, [])
            self.nholds = [
                x for x in self.holds_domain if x not in set(self.holds)
            ]
            delete_model = clingo.parse_term("{}({})".format(
                self.delete_str, step))
            self.control.assign_external(delete_model, True)
            if self.options.project:
                old = self.options.max_models
                self.options.max_models = self.opt_models + 1
            # enumerate
            self.enumerate(add_one=False)
            # post
            if self.options.project:
                self.options.max_models = old
            self.control.release_external(delete_model)
        self.same_shown_function = old
        self.more_models = False
    def _parse_minimize(self, val):
        var = parse_term(val)

        if var.type == SymbolType.Number:
            return False

        self._minimize = var
        return True
Example #9
0
 def __init__(self):
     if self.underscores is not None:
         return
     Helper.underscores = utils.underscores
     term = "{}({})".format(self.underscore(MODEL), self.underscore(M1))
     Helper.m1 = clingo.parse_term(term)
     term = "{}({})".format(self.underscore(MODEL), self.underscore(M2))
     Helper.m2 = clingo.parse_term(term)
     term = "{}".format(self.underscore(M1))  # for holds
     Helper.simple_m1 = clingo.parse_term(term)
     term = "{}".format(self.underscore(M2))  # for holds
     Helper.simple_m2 = clingo.parse_term(term)
     Helper.zero = clingo.parse_term("0")
     Helper.volatile = self.underscore(VOLATILE)
     Helper.unsat = self.underscore(UNSAT)
     Helper.show = self.underscore(SHOW)
     Helper.edge = self.underscore(EDGE)
Example #10
0
def getModelFromText(txt):
    #print txt
    model = []
    answers = txt.lstrip(' ').lstrip('\n').lstrip('\r')
    atoms = answers.split(' ')
    for atom in atoms:
        model.append(clingo.parse_term(atom))
    return model
Example #11
0
 def test_parse(self):
     '''
     Test term parsing.
     '''
     self.assertEqual(str(parse_term("p(3)")), "p(3)")
     log = []
     self.assertRaises(RuntimeError, parse_term, "p(1/0)", lambda code, message: log.append((code, message)))
     self.assertEqual(len(log), 0)
Example #12
0
def _decode_str(x: str, key: str) -> Any:
    if key == "location":
        return str_to_location(x)

    if key == "symbol":
        return clingo.parse_term(x)

    assert key in ("name", "id", "code", "elements", "term", "list", "operator_name")
    return x
Example #13
0
    def iniWMC(self):
        wmc = self.formula.wmc(log_mode=True)
        for key, items in self.nameMappingDic.items():
            symbol = clingo.parse_term(key)
            if (symbol.name == "unsat"):
                wmc.set_literal_weight(-eval(str(items)), eval(str(symbol.arguments[1]).strip('\"')))
        orgWMC = math.exp(wmc.propagate())

        return wmc,orgWMC
Example #14
0
 def adjustSDDWeight(self,wmc,adj):
     for key, items in self.nameMappingDic.items():
         symbol = clingo.parse_term(key)
         for tuple in adj:
             if str(symbol) == str(tuple[0]):
                 if tuple[1]:
                     wmc.set_literal_weight(-eval(str(items)), -float("inf"))
                 else:
                     wmc.set_literal_weight(eval(str(items)), -float("inf"))
     orgWMC = math.exp(wmc.propagate())
     return wmc, orgWMC
Example #15
0
 def do_base(self):
     options, control = self.__options, self.__control
     programs = self.__programs
     # constants
     constants = options['constants'].items()
     old = [key for key, value in constants]
     new = [clingo.parse_term(value) for key, value in constants]
     # add and ground
     string = programs[BASE][""].get_string()
     self.__add_and_ground(BASE, old, string, [(BASE, new)])
     string = programs[GENERATE][""].get_string()
     self.__add_and_ground(GENERATE, [], string, [(GENERATE, [])])
Example #16
0
 def interpretationInfer(self,interpretation):
     wmc, orgWNC = self.iniWMC()
     for atoms in interpretation:
         for key, items in self.nameMappingDic.items():
             symbol = clingo.parse_term(key)
             if (str(symbol) == str(atoms[0])):
                 if atoms[1]:
                     wmc.set_literal_weight(-eval(str(items)), -float("inf"))
                 else:
                     wmc.set_literal_weight(eval(str(items)), -float("inf"))
     after =math.exp(wmc.propagate())
     return after/orgWNC
Example #17
0
    def do_spec(self):

        control, programs = self.__control, self.__programs
        u, options = self.__underscores, self.__options

        # specification
        constants = options['constants'].items()
        old = [ key                      for key, value in constants ]
        new = [ clingo.parse_term(value) for key, value in constants ]
        string  = programs[SPEC][""].get_string() 
        if options['check']:
            string += CHECK_SPEC.replace("##",u)
        self.__add_and_ground(SPEC,old,string,[(SPEC,new)])

        pr = printer.Printer()
        errors = False

        if options['check']:
            # get specification warnings and errors
            for atom in control.symbolic_atoms.by_signature(u+WARN_PRED, 1):
                string = self.__cat(atom.symbol.arguments[0]) + "\n"
                pr.print_spec_warning(string)
            for atom in control.symbolic_atoms.by_signature(u+ERROR_PRED, 1):
                string = self.__cat(atom.symbol.arguments[0]) + "\n"
                pr.print_spec_error(string)
                errors = True
            # get non domain errors
            for i in [(PREFERENCE,2),(PREFERENCE,5),(OPTIMIZE,1)]:
                ui0 = u + i[0]
                for atom in control.symbolic_atoms.by_signature(ui0, i[1]):
                    if not atom.is_fact:
                        pr.print_spec_error(self.__non_domain_message(atom, i))
                        errors = True

        # get preference types, and test for corresponding programs
        out = set()
        upreference = u + PREFERENCE
        for atom in control.symbolic_atoms.by_signature(upreference,2):
            out.add(str(atom.symbol.arguments[1]))
            if options['check']:
                ok = self.__program_exists(atom)
                if not ok:
                    errors = True

        # observe
        if self.__observer:
            self.__observer.add_specification(string, old, new)
        
        # if errors
        if errors:
            raise Exception("parsing failed")

        return out
Example #18
0
def main():

    # preprocessing
    generator_class = temporal.DLPGenerator
    if len(sys.argv) >= 2 and sys.argv[1] == "simple":
        generator_class = temporal.DLPGeneratorSimplifier
    generator = generator_class(
        files=["test.lp"],
        #adds  = [("base", [], base)],
        parts=[("base", [])],
        #options = ["0"],
        #compute_cautious = False,
        #compute_brave = False,
    )

    # start
    dlp = generator.run()
    #print(generator)
    ctl = clingo.Control(["0"])
    dlp.start(ctl)
    #print(dlp)

    # ground and set externals
    steps = 3
    dlp.ground(steps - 1)
    dlp.ground(1)
    for i in range(1, steps):
        dlp.release_external(i, clingo.parse_term("last"))
    dlp.assign_external(steps, clingo.parse_term("last"), True)

    # solve
    with ctl.solve(assumptions=dlp.get_assumptions(), yield_=True) as handle:
        answers = 0
        for m in handle:
            answers += 1
            print("Answer: {}".format(answers))
            answer = dlp.get_answer(m, steps)
            print(" ".join(["{}:{}".format(x, y) for x, y in answer]))
        if not answers:
            print("UNSATISFIABLE")
Example #19
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
Example #20
0
 def on_raw_data(self, raw_data):
     data = raw_data.split('.')
     for atom in data:
         if not (len(atom) == 1 and atom[0] == '\n'):
             if atom[0] == '%' and atom[1] == '$':
                 atom = atom[2 :].lower()
                 self.on_control_symbol(clingo.parse_term(atom))
             else:
                 self._data.append(atom)
     self._raw_data = ''
     if len(self._data) > 0:
         self.on_data(self._data)
     self._data = []
Example #21
0
 def learn_ini_WMC_with_observation(self, parsed_observation):
     wmc = self.formula.wmc(log_mode=False)
     for key, items in self.nameMappingDic.items():
         symbol = clingo.parse_term(key)
         if (symbol.name == "unsat"):
             wmc.set_literal_weight(-eval(str(items)), math.exp(eval(str(symbol.arguments[1]).strip('\"'))))
         for tuple in parsed_observation:
             if str(symbol) == str(tuple[0]):
                 if tuple[1] == 0:
                     wmc.set_literal_weight(eval(str(items)),0)
                 else:
                     wmc.set_literal_weight(-eval(str(items)),0)
     orgWMC = wmc.propagate()
     return wmc,orgWMC
Example #22
0
 def print(self, res: 'Results') -> None:
     for fact in res.already:
         print(fact + '.')
     for act in res.acts:
         print(act + '!')
     if res.status:
         print(res.status + '.')
     if res.shows:
         terms = [clingo.parse_term(r) for r in res.shows]
         terms.sort()
         that = ' | '.join(res.replace_names(str(t)) for t in terms)
         if len(that) / len(terms) > 30:
             that = that.replace(' | ', '\n    | ')
         print(f'that: {that}.')
     print()
    def _assumptionFromModel(self, mdl):
        # mdl contains the answer set candidate
        # we here create assumptions for compatible set auxiliaries
        ret = []

        #
        # for all atoms in Pi that are not replatoms we create an assumption
        #

        # symbolic atoms that are not replatoms
        for iatm, atm in self.po.int2atom.items():
            if iatm in self.po.replatoms:
                continue
            # TODO cache csAtom <-> iatm
            csAtom = clingo.parse_term(prefixAtom(str(atm), Aux.CSATOM))
            # TODO maybe use is_true here too (iatm) TODO benchmark this
            ret.append((csAtom, mdl.contains(atm)))

        # clasp auxiliaries (that are implicitly never replatoms)
        for iauxatm in self.po.auxatoms:
            # TODO cache csAtom <-> iauxatm
            csAtom = clingo.Function(
                name=prefixAtom(self.po.formatAtom(iauxatm), Aux.CSATOM))
            ret.append((csAtom, mdl.is_true(iauxatm)))

        #
        # additionally, for choice auxiliaries of chatoms in Pi we create assumptions
        # these assumptions are the negation of the positive chatom value
        #

        # choice auxiliaries of chatoms
        for ichatom, chauxatom in self.chauxatoms.items():
            # TODO cache csAtom <-> iauxatm
            csAtom = clingo.parse_term(prefixAtom(chauxatom, Aux.CSATOM))
            ret.append((csAtom, not mdl.is_true(ichatom)))
        return ret
Example #24
0
 def on_raw_data(self, raw_data):
     #the visualizer seperates every atom and control symbol with the '.' character
     data = raw_data.split('.')
     for atom in data:
         if len(atom) > 0:
             if not (len(atom) == 1 and atom[0] == '\n'):    #the split function returns the string "\n" as last string which should not be processed
                 if atom[0] == '%' and atom[1] == '$':       #strings that begin with '%$' are control symbols and are handles by the on_control_symbol function
                     atom = atom[2 :].lower()
                     self.on_control_symbol(clingo.parse_term(atom))
                 else:
                     self._data.append(atom)
     self._raw_data = ''
     if len(self._data) > 0:
         #processed asp atoms
         self.on_data(self._data)
     self._data = []
Example #25
0
    def inferencePrtQuery(self):
        self.fillQueryAtoms()
        for queryAtom in self.queryAtoms:
            if self.observation == "":
                wmc,orgWNC = self.iniWMC()
            else:
                wmc,orgWNC = self.ini_WMC_with_observation()

            for key, items in self.nameMappingDic.items():
                symbol = clingo.parse_term(key)
                if (str(symbol) == str(queryAtom[0])):
                    wmc.set_literal_weight(-eval(str(items)), -float("inf"))
                    after = math.exp(wmc.propagate())
                    queryAtom[1] = after / orgWNC
                    break
        for atom in self.queryAtoms:
            print(atom)
Example #26
0
    def receive(self):
        if self._s is None or self._parser is None:
            return -1

        data = self._receive_data()
        if data is None:
            return
        if data == '':
            return

        for str_atom in data.split('.'): 
            if len(str_atom) != 0 and not (len(str_atom) == 1 and str_atom[0] == '\n'):
                if str_atom == '%$RESET':
                    self._parser.clear_model()
                else:
                    self._parser.on_atom(clingo.parse_term(str_atom))
        self._parser.done_instance()
Example #27
0
    def receive(self):
        if self._s is None or self._parser is None or self._model is None:
            return -1

        data = self._receive_data()
        if data is None:
            return
        if data == '':
            return

        for str_atom in data.split('.'):
            if len(str_atom) != 0 and not (len(str_atom) == 1 and str_atom[0] == '\n'):
                if str_atom == '%$RESET':
                    self._parser.clear_model_actions(True)
                else:
                    self._parser.on_atom(clingo.parse_term(str_atom))
        self._model.update_windows()
Example #28
0
    def ini_WMC_with_observation(self):
        wmc = self.formula.wmc(log_mode=True)
        for key, items in self.nameMappingDic.items():
            symbol = clingo.parse_term(key)
            if (symbol.name == "unsat"):
                wmc.set_literal_weight(-eval(str(items)), eval(str(symbol.arguments[1]).strip('\"')))
            for tuple in self.evidenceAssignment:
                if str(symbol) == str(tuple[0]):
                    if tuple[1] == 0:
                        wmc.set_literal_weight(eval(str(items)),-float("inf"))

                    else:
                        wmc.set_literal_weight(-eval(str(items)),-float("inf"))

        orgWMC = math.exp(wmc.propagate())

        return wmc,orgWMC
Example #29
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
Example #30
0
    def receive(self):
        if self._s is None or self._parser is None:
            return -1

        data = self._receive_data()
        empty = True
        reset = False
        if data is None:
            return
        if data == '':
            return
        self._waiting = False
        for str_atom in data.split('.'):
            if len(str_atom) != 0 and not (len(str_atom) == 1
                                           and str_atom[0] == '\n'):
                if str_atom == '%$RESET':
                    self._parser.clear_model()
                    reset = True
                    empty = False
                else:
                    self._parser.on_atom(clingo.parse_term(str_atom))
                    empty = False
        if not empty:
            self._parser.done_instance(reset)