Exemple #1
0
 def apply(self, raw, *args, **kwargs):
     """Application depending on the type of args."""
     rules_dat = self._data['dynrules']
     match_toggle = re.match(r'\s*(on|off)\s+([[0-9]*)\s*', raw)
     if match_toggle: # Turn ON/OFF previously defined dynamic program
         ext_tv = False
         if match_toggle.group(1) == 'on':
             ext_tv = True
         handle = match_toggle.group(2)
         ext_atom = ''
         try:
             ext_atom = rules_dat[int(handle)][1]
         except IndexError:
             self.prnt("Dynamic program with handle {0} does NOT exist!".format(handle))
             self._update_session_log("definedyn", match_toggle.group(1), handle)
             return
         ggfun = self.parse_literal(ext_atom)[0]
         debug(ggfun, "Assigning {0} to: ".format(str(ext_tv)))
         self._session.state.prg.assign_external(ggfun, ext_tv)
         if ext_tv:
             rules_dat[int(handle)][2] = 'on'
             self.prnt('Turned ON dynamic program with handle {0}.'.format(handle))
         else:
             rules_dat[int(handle)][2] = 'off'
             self.prnt('Turned OFF dynamic program with handle {0}.'.format(handle))
         self._update_session_log("definedyn", match_toggle.group(1), handle)
     elif raw: # Define new dynamic program
         self._add_rules(raw)
     else: # Print out existing dynamic programs
         output = 'List of dynamically added programs:\n'
         for i in range(len(rules_dat)):
             output += '\n**Dynamic-Program {0} ({2}):\n{1}\n'.format(str(i),
                                                                      rules_dat[i][0],
                                                                      rules_dat[i][2])
         self.prnt(output)
Exemple #2
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)
Exemple #3
0
    def preparse(self, raw, **kwargs):
        """Overriding `cmd2.preparse` hook to single-quote arguments for the query
        command.

        This is necessary to prevent certain symbols to be recognized
        as built-in keywords by `cmd2.parser`

        """
        aspic_exp = raw
        pipe = ''

        # Split off part that should piped to OS shell, indicated by '\|''
        if raw.find('\|') != -1:
            aspic_exp, pipe = raw.split('\|', 1)

        # Quote aspic args if necessary
        if ' ' in aspic_exp.strip(' '):
            cmd, args = aspic_exp.split(None, 1)
            if (cmd in self.session.commands
                    and not self.session.commands[cmd].frontend_conf['cmd2']
                ['multiline']):
                rewrite = "{0} '{1}'".format(cmd, args)
                if pipe:
                    rewrite = rewrite + '|' + pipe
                debug(rewrite, "ClApp.preparse return val")
                return rewrite
        return raw
Exemple #4
0
    def preparse(self, raw, **kwargs):
        """Overriding `cmd2.preparse` hook to single-quote arguments for the query
        command.

        This is necessary to prevent certain symbols to be recognized
        as built-in keywords by `cmd2.parser`

        """
        aspic_exp = raw
        pipe = ''

        # Split off part that should piped to OS shell, indicated by '\|''
        if raw.find('\|') != -1:
            aspic_exp, pipe = raw.split('\|', 1)

        # Quote aspic args if necessary
        if ' ' in aspic_exp.strip(' '):
            command, args = aspic_exp.split(' ', 1)
            if command.strip(' ') in CmdLineApp.custom_commands_quoted_args:
                rewrite = "{0} '{1}'".format(command, args)
                if pipe:
                    rewrite = rewrite + '|' + pipe
                debug(rewrite, "ClApp.preparse return val")
                return rewrite
        return raw
Exemple #5
0
 def apply(self, literal, *args, **kwargs):
     assumptions = self._session.state.assumptions
     ggfun_and_sign = self.parse_literal(literal)
     if ggfun_and_sign in assumptions:
         assumptions.remove(ggfun_and_sign)
     else:
         self.prnt("Literal {0} was not assumed!".format(literal))
     self._update_session_log("cancel", "literal", literal)
     debug(str(assumptions), "session.state.assumptions")
Exemple #6
0
 def __init__(self, t):
     self.label = str(t)
     debug("")
     debug("", "Next object")
     debug("Object " + type(self).__name__ + " " + str(self))
     debug("All sub-items")
     for item in t:
         debug(type(item),
               item.asList() if isinstance(item, pp.ParseResults) else item)
Exemple #7
0
 def apply(self, literal, *args, **kwargs):
     assumptions = self._session.state.assumptions
     ggfun_and_sign = self.parse_literal(literal)
     if ggfun_and_sign not in assumptions:
         assumptions.append(ggfun_and_sign)
     else:
         self.prnt("Literal {0} already assumed!".format(literal))
     self._update_session_log("assume", "literal", literal)
     debug(str(assumptions), "session.state.assumptions")
Exemple #8
0
 def _inject_external(self, rules, ext):
     """Adds external to rule bodies."""
     rewrite = ''
     for line in rules.splitlines():
         if line.find(':-') != -1:
             rewrite += line.replace('.', '; {0}.'.format(ext))
         else:
             rewrite += line.replace('.', ' :- {0}.'.format(ext))
     debug(rewrite, '_inject_external')
     return rewrite
Exemple #9
0
 def apply(self, atom, *args, **kwargs):
     prg = self._session.state.prg
     assertions = self._session.state.assertions
     if assertions.has_key(atom):
         ext_atom = self._session.state.assertions[atom][0]
         prg.assign_external(clingo.Function(ext_atom), False)
         assertions[atom][1] = 0
     else:
         print("Atom {0} not asserted!".format(atom))
     self._update_session_log("retract", "atom", atom)
     debug(str(self._session.state.assertions))
Exemple #10
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))
Exemple #11
0
 def __init__(self, t):
     global ResultTopObject
     super(PA_Literal, self).__init__(t)
     self.dneg = False
     if isinstance(t[0], str) and t[0] == 'not ':
         self.dneg = True
         self.ggfun = t[1].ggfun
     else:
         self.ggfun = t[0].ggfun
     ResultTopObject = self
     debug("ggfun " + type(self.ggfun).__name__ + " " + str(self.ggfun))
     if self.dneg:
         debug("has default neg!\n")
Exemple #12
0
 def apply(self, raw, *args, **kwargs):
     prg = self._session.state.prg
     debug(raw, "queryasp.auxops.Option, received args")
     re_models = re.compile(r'(--models|-n)\s*(\d+)')
     re_enum_mode = re.compile(r'(--enum-mode|-e)\s*(\w+)')
     re_opt_mode = re.compile(r'(--opt-mode)\s*(\w+)')
     if re_models.match(raw):
         prg.conf.solve.models = re_models.match(raw).group(2)
     elif re_enum_mode.match(raw):
         prg.conf.solve.enum_mode = re_enum_mode.match(raw).group(2)
     elif re_opt_mode.match(raw):
         prg.conf.solve.opt_mode = re_opt_mode.match(raw).group(2)
     else:
         self.prnt("Clingo command line option ({0}) not supported!".format(raw))
Exemple #13
0
    def reset_state(self, prg_files=None, solve_opts=None):
        #TODO: create explicit reset and load scops command referring to this
        # Probably whole session should never be reset, only state, i.e., solver; thus, rename to state_reset
        """Resets state by creating new clingo.Control object that optionally
        also takes a new ASP program(s) and solver options as input

        Arguments:
        prg_files     -- optional list of program file names to be used as initial rule set (default [])
        solve_options -- optional list of solve options for clingo (default [])

        """
        self._initial_prg_files = prg_files or self._initial_prg_files
        self._initial_solve_opts = solve_opts or self._initial_solve_opts
        self.state = self._create_initial_state()
        debug("State reset!")
Exemple #14
0
    def prnt(self, out_data=None, temp_mode=None):
        """Output printing with mode-dependent formatting.

        Only default method supported here.

        Arguments:
        out_data  -- data to be printed, expected type depending on printer and mode
        temp_mode -- optional different printing mode from self.smode to use for this print out
        """
        try:
            prnt = getattr(self, 'prnt_{0}'.format(temp_mode or self.mode)) # use temp_mode method if requested
        except AttributeError:
            print('CommandPrinter:prnt: Unknown print mode!')
        else:
            debug('Command {0} invokes print method {1} in next line:'.format(self.command, prnt))
            prnt(out_data)
Exemple #15
0
 def apply(self, atom, *args, **kwargs):
     assertions = self._session.state.assertions
     prg = self._session.state.prg
     ext_atom = "_ext_assert__{0}".format(atom)
     if not assertions.has_key(atom):
         enc_name = "assertion_" + atom
         prg.add(enc_name, [],
                 "{0} :- {1}. #external {1}.".format(atom, ext_atom))
         prg.ground([(enc_name, [])])
         assertions[atom] = [ext_atom, 1]
     elif assertions[atom][0] != ext_atom:
         raise Exception(
             "Bug: asserted atom exists in assertion list with different external!"
         )
     prg.assign_external(clingo.Function(ext_atom), True)
     self._update_session_log("assert", "atom", {atom: ext_atom})
     debug(str(self._session.state.assertions))
Exemple #16
0
    def _add_command(cmd_name, cmd_obj):
        """Adds front-end method with callback to command"""
        def do_cmd(self, raw, *args, **kwargs):
            cmd_obj.frontend_conf['cmd2']['callback'](
                Cmd2_CmdLineApp.cond_rm_quotes(cmd_obj, raw), *args, **kwargs)

        def help_cmd(self):
            print(cmd_obj.help)

        setattr(Cmd2_CmdLineApp, 'do_' + cmd_name,
                do_cmd)  # Add commmand and...
        setattr(Cmd2_CmdLineApp, 'help_' + cmd_name,
                help_cmd)  # its help func.
        debug(
            Cmd2Factory._add_command,
            "Added callback func of {1} as do_{0} method to Cmd2LineApp class."
            .format(cmd_name, cmd_obj))
Exemple #17
0
 def apply(self, raw, *args, **kwargs):
     """Application depending on the type of args."""
     opt_dat = self._data['opt_stmts']
     match_toggle = re.match(r'\s*(on|off)\s+([[0-9]+)\s*', raw)
     match_opt = re.match(r'\s*(min|max)\s+(.+)', raw)
     if match_toggle: # Turn ON/OFF previously defined dynamic program
         ext_tv = False
         if match_toggle.group(1) == 'on':
             ext_tv = True
         handle = match_toggle.group(2)
         ext_atom = ''
         try:
             ext_atom = opt_dat[int(handle)][1]
         except IndexError:
             self.prnt("Dynamic program with handle {0} does NOT exist!".format(handle))
             self._update_session_log("filter", match_toggle.group(1), handle)
             return
         ggfun = self.parse_literal(ext_atom)[0]
         debug(ggfun, "Assigning {0} to: ".format(str(ext_tv)))
         self._session.state.prg.assign_external(ggfun, ext_tv)
         if ext_tv:
             opt_dat[int(handle)][2] = 'on'
             self.prnt('Turned ON dynamic program with handle {0}.'.format(handle))
         else:
             opt_dat[int(handle)][2] = 'off'
             self.prnt('Turned OFF dynamic program with handle {0}.'.format(handle))
         self._update_session_log("filter", match_toggle.group(1), handle)
     elif match_opt:# Add optimization as filter
         self._add_opt(match_opt.group(1), match_opt.group(2))
     elif raw: # Add weak constraint (i.e. #minimize statement with a single <term tuple, body-literals>-pair ) as filter
         self._add_opt('min', raw)
     else: # Print out existing filter programs
         output = 'List of dynamically added optimization statements:\n'
         for i in range(len(opt_dat)):
             output += '\n**Filter-Program {0} ({2}):\n{1}\n'.format(str(i),
                                                                     opt_dat[i][0],
                                                                     opt_dat[i][2])
         self.prnt(output)
Exemple #18
0
    def flatten_head_atom(self, head, noVarArgs=False):
        """Aux method for `gen_head_atom` to make a head_atom a non-nested term

        Achieved by simply replacing
        - parenthesis with '_lpar_' and '_rpar_'.
        - commas and semicolons with _sepr_
        - whitespace occurring before/after arguments within parentheses stripped
        Additionally, all occurring variables are collected and added as arguments of a new body

        """
        head = head.replace("(", "_lpar_")
        head = head.replace(")", "_rpar_")
        head = head.replace(",", "_sepr_")
        head = head.replace(";", "_sepr_")
        head = head.replace(" ", "")

        matchlist = re.findall(r'(AND|OR|NOT)|([A-Z][a-zA-Z0-9]*)', head)
        varlist = list(set(m[1] for m in matchlist
                           if m[1] != ''))  # extract only vars and unify
        debug(varlist, 'varlist')
        if varlist and not noVarArgs:
            head = '{0}({1})'.format(head, ','.join(varlist))

        return head
Exemple #19
0
 def apply(self, atom, *args, **kwargs):
     #self.session.state.prg.assign_external(clingo.Function(atom), False)
     ggfun = self.parse_literal(atom)[0]
     self._session.state.prg.assign_external(ggfun, None)
     debug(ggfun, "Opening: ")
     self._update_session_log("open", "atom", atom)
Exemple #20
0
 def apply(self, atom, *args, **kwargs):
     #self.session.state.prg.assign_external(clingo.Function(atom), True)
     ggfun = self.parse_literal(atom)[0]
     self._session.state.prg.assign_external(ggfun, True)
     debug(ggfun, "Asserting: ")
     self._update_session_log("assert", "atom", atom)
Exemple #21
0
 def _inject_external(self, rule, ext):
     """Adds external to literal list bodies of terms."""
     rewrite = rule.replace(':', ':{0},'.format(ext))
     debug(rewrite, '_inject_external')
     return rewrite
Exemple #22
0
 def parse_literal(self, literal):
     """Parse literal to corrseponding `clingo.Function` object and Sign"""
     parse_result = litparse.LiteralParser.grammar().parseString(literal, True)
     debug(parse_result, "Parse Result: ")
     return litparse.ResultTopObject.ggfun, not litparse.ResultTopObject.dneg
Exemple #23
0
 def _update_session_log(self, op_type, input_type, input_args):
     """Update session log after operator application."""
     self._session.step += 1
     self._session.log.append((self._session.step, op_type, input_type, input_args))
     debug(str(self._session.log))
Exemple #24
0
 def __init__(self, t):
     super(PA_Num, self).__init__(t)
     self.ggfun = int(t[0])  #clingo.Function(t[0])
     debug("ggfun " + type(self.ggfun).__name__ + " " + str(self.ggfun))