示例#1
0
    def get_last_formula(self, mgr=None):
        """Returns the last formula of the execution of the Script.

        This coincides with the conjunction of the assertions that are
        left on the assertion stack at the end of the SMTLibScript.
        """
        stack = []
        backtrack = []
        _And = mgr.And if mgr else get_env().formula_manager.And

        for cmd in self.commands:
            if cmd.name == smtcmd.ASSERT:
                stack.append(cmd.args[0])
            if cmd.name == smtcmd.RESET_ASSERTIONS:
                stack = []
                backtrack = []
            elif cmd.name == smtcmd.PUSH:
                for _ in xrange(cmd.args[0]):
                    backtrack.append(len(stack))
            elif cmd.name == smtcmd.POP:
                for _ in xrange(cmd.args[0]):
                    l = backtrack.pop()
                    stack = stack[:l]

        return _And(stack)
示例#2
0
 def __init__(self, assignment, environment=None):
     if environment is None:
         environment = get_env()
     Model.__init__(self, environment)
     self.environment = environment
     self.assignment = dict(assignment)
     # Create a copy of the assignments to memoize completions
     self.completed_assignment = dict(self.assignment)
示例#3
0
def check_installed(required_solvers, install_dir, bindings_dir, mirror_link):
    """Checks which solvers are visible to pySMT."""

    # Check which solvers are accessible from the Factory
    pypath_solvers = get_env().factory.all_solvers()

    global_solvers_status = []
    print("Installed Solvers:")
    for i in INSTALLERS:
        installer_ = i.InstallerClass(install_dir=install_dir,
                                      bindings_dir=bindings_dir,
                                      solver_version=i.version,
                                      mirror_link=mirror_link,
                                      **i.extra_params)
        solver = installer_.SOLVER
        version = installer_.get_installed_version()
        is_installed = (version is not None)
        global_solvers_status.append((solver, is_installed, version))
        del installer_

    for solver in required_solvers:
        if solver not in pypath_solvers:
            raise PyomtException("Was expecting to find %s installed" % solver)

    #
    # Output information
    #
    for (solver, is_installed, version) in global_solvers_status:
        msg = "  %s%s " % (solver.ljust(10), is_installed)
        msg += ("(%s)" % version).ljust(20)
        if solver not in pypath_solvers:
            msg += "Not in Python's path!"
        print(msg)
    print("")


    print("Solvers: %s" % ", ".join(name for name in pypath_solvers))
    qes = get_env().factory.all_quantifier_eliminators()
    print("Quantifier Eliminators: %s" % ", ".join(name for name in qes))

    ucs = get_env().factory.all_unsat_core_solvers()
    print("UNSAT-Cores: %s" % ", ".join(name for name in ucs))

    interps = get_env().factory.all_interpolators()
    print("Interpolators: %s" % ", ".join(name for name in interps))
示例#4
0
 def __init__(self, stream, template=".def_%d"):
     DagWalker.__init__(self, invalidate_memoization=True)
     self.stream = stream
     self.write = self.stream.write
     self.openings = 0
     self.name_seed = 0
     self.template = template
     self.names = None
     self.mgr = get_env().formula_manager
示例#5
0
    def __init__(self, env=None):
        if env is None:
            env = get_env()
        self.env = env
        self.mgr = env.formula_manager
        self.get_type = env.stc.get_type

        self.rules = []
        self.scanner = None
        self.eoi = EndOfInput()
示例#6
0
    def __init__(self, LexerClass, env=None):
        if env is None:
            env = get_env()

        self.env = env
        self.mgr = env.formula_manager
        self.get_type = env.stc.get_type
        self.lexer = LexerClass(env)

        self.token = None
        self.tokenizer = None
示例#7
0
def _run_solver(idx, solver, options, formula, signaling_queue, ctrl_pipe):
    """Function used by the child Process to handle Portfolio requests.

    solver  : name of the solver
    options : options for the solver
    formula : formula to assert
    signaling_queue: queue in which to write to indicate completion of solve
    ctrl_pipe: Pipe to communicate with parent process *after* solve
    """
    from pyomt.environment import get_env

    Solver = get_env().factory.Solver
    with Solver(name=solver, **options) as s:
        s.add_assertion(formula)
        try:
            local_res = s.solve()
        except Exception as ex:
            signaling_queue.put((solver, ex))
            return

        signaling_queue.put((idx, local_res))
        _exit = False
        while not _exit:
            try:
                cmd = ctrl_pipe.recv()
            except EOFError:
                break
            if type(cmd) == tuple:
                cmd, args = cmd
            if cmd == "exit":
                _exit = True
            elif cmd == "get_model":
                # MG: Can we pickle the EagerModel directly?
                # Note: contextualization happens on the receiver side
                model = list(s.get_model())
                ctrl_pipe.send(model)
            elif cmd == "get_value":
                args = get_env().formula_manager.normalize(args)
                ctrl_pipe.send(s.get_value(args))
            else:
                raise ValueError("Unknown command '%s'" % cmd)
示例#8
0
    def get_strict_formula(self, mgr=None):
        if self.contains_command(smtcmd.PUSH) or \
           self.contains_command(smtcmd.POP):
            raise PyomtValueError("Was not expecting push-pop commands")
        if self.count_command_occurrences(smtcmd.CHECK_SAT) != 1:
            raise PyomtValueError(
                "Was expecting exactly one check-sat command")
        _And = mgr.And if mgr else get_env().formula_manager.And

        assertions = [
            cmd.args[0] for cmd in self.filter_by_command_name([smtcmd.ASSERT])
        ]
        return _And(assertions)
示例#9
0
def smtlibscript_from_formula(formula, logic=None):
    script = SmtLibScript()

    if logic is None:
        # Get the simplest SmtLib logic that contains the formula
        f_logic = get_logic(formula)

        smt_logic = None
        try:
            smt_logic = get_closer_smtlib_logic(f_logic)
        except NoLogicAvailableError:
            warnings.warn("The logic %s is not reducible to any SMTLib2 " \
                          "standard logic. Proceeding with non-standard " \
                          "logic '%s'" % (f_logic, f_logic),
                          stacklevel=3)
            smt_logic = f_logic
    elif not (isinstance(logic, Logic) or isinstance(logic, str)):
        raise UndefinedLogicError(str(logic))
    else:
        if logic not in SMTLIB2_LOGICS:
            warnings.warn("The logic %s is not reducible to any SMTLib2 " \
                          "standard logic. Proceeding with non-standard " \
                          "logic '%s'" % (logic, logic),
                          stacklevel=3)
        smt_logic = logic

    script.add(name=smtcmd.SET_LOGIC, args=[smt_logic])

    # Declare all types
    types = get_env().typeso.get_types(formula, custom_only=True)
    for type_ in types:
        script.add(name=smtcmd.DECLARE_SORT, args=[type_.decl])

    deps = formula.get_free_variables()
    # Declare all variables
    for symbol in deps:
        assert symbol.is_symbol()
        script.add(name=smtcmd.DECLARE_FUN, args=[symbol])

    # Assert formula
    script.add_command(SmtLibCommand(name=smtcmd.ASSERT, args=[formula]))
    # check-sat
    script.add_command(SmtLibCommand(name=smtcmd.CHECK_SAT, args=[]))
    return script
示例#10
0
    def write_assertions(self,asserts_list,file_out,var_dict):
        '''
            Write the list of assertion

        '''
        if self.flag_bigand==True: #necessary bigand
            mgr = get_env()._formula_manager
            bigAnd=asserts_list[0][0]
            tmp_ris=None
            for ind in xrange(1,len(asserts_list)):
                if type(asserts_list[ind]) is list:
                    tmp=asserts_list[ind][0]
                else:
                    tmp=asserts_list[ind]
                tmp_ris=mgr.And(bigAnd,tmp)
                bigAnd=tmp_ris
            self.serializer.serialize(bigAnd,output_file=file_out)
        else:
            for el in asserts_list:
                if type(el) is list:
                    el=el[0]
                self.serializer.serialize(el,output_file=file_out)
示例#11
0
    def modify_type_assert_soft_var(self,asserts_soft_list,var_dict):
        '''
            For each group of assert_soft understand the type of the id variable (Reals,Int)
        '''
        dict_type={}
        mgr = get_env()._formula_manager
        for assert_exp in asserts_soft_list:
            if assert_exp[1]==1:
                current_type=mgr.Int(1).get_type()
            else:
                current_type=assert_exp[1].get_type()
            if assert_exp[2] not in dict_type:
                dict_type[assert_exp[2]]=[]
                dict_type[assert_exp[2]].append(current_type)
            else:
                dict_type[assert_exp[2]].append(current_type)
        for k in dict_type:
            if len(set(dict_type[k]))==1:
                var_dict[k]=[dict_type[k][0]]
            else:
                if "Real" in str(dict_type[k]) and "Int" in str(dict_type[k]):   #TODO: add the other cases
                    var_dict[k]=[tp._RealType()]

        return var_dict
示例#12
0
    def write_stack_box(self,var_dict,asserts_list,asserts_soft_list,commands_list,out_file):
        '''
            For each function to maximize or to minize create a new file,
            keep the assignement to the optimization variables on all the files but not the upper
            and lower constraints
        '''
        i=0
        common_lines=[]
        unique_lower=[]
        unique_upper=[]
        mgr = get_env()._formula_manager
        signed = -1
        for (name,args) in commands_list: #argslist [cost_function,[parameter]]
            upper=None
            lower=None
            args_inner=args[1]
            index=args_inner.index(":id")
            opt_var=args_inner[index+1] #temp variable (d'appoggio) to maximize or minimize
            objective_arg = args[0] #FNODE type -> parsed with get_expression
            try:
                signed=args_inner.index(":signed")
            except ValueError:
                signed=-1
            #writing the maximize and the minimize
            if ":upper" in args_inner:
                index=args_inner.index(":upper")
                upper=args_inner[index+1]
            if ":lower" in args_inner:
                index=args_inner.index(":lower")
                lower=args_inner[index+1]
            if objective_arg.size() == 1: #name of a variable
                objective_arg=mgr._create_symbol(str(args[0]),typename=var_dict[str(args[0])][0])
            opt_symbol = mgr._create_symbol(opt_var,var_dict[opt_var][0])
            assignment = mgr.Equals(opt_symbol,objective_arg)
            common_lines.append("constraint ("+self.serializer.serialize(assignment,daggify=False)+");\n")
            #opt_Var and opt_symbol are the same
            if upper is not None:
                if "BV" in str(upper.get_type()):
                    if signed>=0:
                        less_than = mgr.BVSLE(opt_symbol,upper)
                    else:
                        less_than = mgr.BVULE(opt_symbol,upper)
                    unique_upper.append("constraint ("+self.serializer.serialize(less_than)+");\n")
                else:
                    less_than = mgr.LE(opt_symbol,upper)
                    unique_upper.append("constraint ("+self.serializer.serialize(less_than,daggify=False)+");\n")
            else:
                unique_upper.append(" ")
            if lower is not None:
                if "BV" in str(lower.get_type()):
                    if signed>=0:
                        less_than = mgr.BVSLE(lower,opt_symbol)
                    else:
                        less_than = mgr.BVULE(lower,opt_symbol)
                    unique_lower.append("constraint ("+self.serializer.serialize(less_than)+");\n")
                else:
                    less_than = mgr.LE(lower,opt_symbol)
                    unique_lower.append("constraint ("+self.serializer.serialize(less_than,daggify=False)+");\n")
            else:
                unique_lower.append(" ")
        for (name,args) in commands_list:
            i+=1
            file_out=open(out_file.replace(".mzn","_b"+str(i))+".mzn","w")
            print("writing variables")
            self.write_list_variables(var_dict,file_out)
            print("writing assertions")
            self.write_assertions(asserts_list,file_out,var_dict)
            print("writing soft")
            self.write_assertions_soft(asserts_soft_list,file_out)
            print("writing maximize/minimize")
            for line in common_lines:
                file_out.write(line)
            file_out.write(unique_lower[i-1]) #same list as command_list
            file_out.write(unique_upper[i-1]) #same list as command_list
            args_inner=args[1]
            index=args_inner.index(":id")
            opt_var=args_inner[index+1]
            opt_symbol = mgr._create_symbol(opt_var,var_dict[opt_var][0])
            try:
                signed=args_inner.index(":signed")
            except ValueError:
                signed=-1
            if name=='maximize': #qui si puo decidere facilmente se con segno o no, basta vedere se signed
                if "BV" in str(var_dict[opt_var][0]):
                    file_out.write("constraint(%s >= %s /\ %s <= %s);\n"%(opt_symbol,0,opt_symbol,pow(2,opt_symbol.bv_width())-1))
                    if signed!=-1:
                        file_out.write("solve maximize (-%s*((%s div %s) mod 2))+sum([pow(2,i)*((%s div pow(2,i)) mod 2)| i in 0..%s-1]);\n"
                                                        %(pow(2,opt_symbol.bv_width()-1),opt_symbol,pow(2,opt_symbol.bv_width()-1),opt_symbol,opt_symbol.bv_width()-1))
                    else:
                        #bound = mgr.And(mgr.BVULE(opt_symbol,mgr.BV(pow(2,opt_symbol.bv_width())-1,width=opt_symbol.bv_width())),mgr.BVUGE(opt_symbol,mgr.BV(0,width=opt_symbol.bv_width())))
                        #file_out.write("constraint ("+self.serializer.serialize(bound)+");\n")
                        file_out.write("solve maximize "+opt_var+";\n")
                else:
                    file_out.write("solve maximize "+opt_var+";\n")
            else:
                if "BV" in str(var_dict[opt_var][0]):
                    file_out.write("constraint(%s >= %s /\ %s <= %s);\n"%(opt_symbol,0,opt_symbol,pow(2,opt_symbol.bv_width())-1))
                    if signed!=-1:
                        file_out.write("solve minimize (-%s*((%s div %s) mod 2))+sum([pow(2,i)*((%s div pow(2,i)) mod 2)| i in 0..%s-1]);\n"
                                                        %(pow(2,opt_symbol.bv_width()-1),opt_symbol,pow(2,opt_symbol.bv_width()-1),opt_symbol,opt_symbol.bv_width()-1))
                    else:
                        #bound = mgr.And(mgr.BVULE(opt_symbol,mgr.BV(pow(2,opt_symbol.bv_width())-1,width=opt_symbol.bv_width())),mgr.BVUGE(opt_symbol,mgr.BV(0,width=opt_symbol.bv_width())))
                        #file_out.write("constraint ("+self.serializer.serialize(bound)+");\n")

                        file_out.write("solve minimize "+opt_var+";\n")
                else:
                    file_out.write("solve minimize "+opt_var+";\n")

            file_out.write("output [ \"opt_var = \",show("+opt_var+")]")
            file_out.close()
示例#13
0
    def write_commands_lex(self,commands_list,var_dict,file_out):
        var_list=[]
        var_list_type=set() #if just one type rescued from the maximize,otherwise use to2float
        mgr = get_env()._formula_manager

        for (name,args) in commands_list: #only maximize or minimize -> manage the lower and the upper
            args_inner=args[1]
            index=args_inner.index(":id") #taking the id value -> equal to the variable
            opt_var=args_inner[index+1]
            var_list_type.add(var_dict[opt_var][0])

        if len(var_list_type)==1:
            final_type=var_list_type.pop()
            if "BV" in str(final_type):
                final_type="int"
            elif "Real" == str(final_type):
                final_type="float"
            elif "Int" == str(final_type):
                final_type="int"
        else:
            raise MultiTypeLexErr("MultiType Lexicographic optimization is not supported")

        for (name,args) in commands_list: #only maximize or minimize -> manage the lower and the upper
            upper=None
            lower=None
            args_inner=args[1]
            index=args_inner.index(":id") #taking the id value -> equal to the variable
            opt_var=args_inner[index+1] #temp variable (d'appoggio) to maximize or minimize
            objective_arg = args[0] #FNODE type -> parsed with get_expression

            if ":upper" in args_inner:
                index=args_inner.index(":upper")
                upper=args_inner[index+1] #Fnode
            if ":lower" in args_inner:
                index=args_inner.index(":lower")
                lower=args_inner[index+1] #Fnode
            try:
                signed=args_inner.index(":signed")
            except ValueError:
                signed=-1
            if objective_arg.size() == 1: #name of a variable
                objective_arg=mgr._create_symbol(str(args[0]),typename=var_dict[str(args[0])][0])

            opt_symbol = mgr._create_symbol(opt_var,var_dict[opt_var][0])
            assignment = mgr.Equals(opt_symbol,objective_arg)
            file_out.write("constraint ("+self.serializer.serialize(assignment,daggify=False)+");\n")

            opt_symbol_lex = mgr._create_symbol(opt_var+"_lex",var_dict[opt_var][0])
            lex_type = "int" if "BV" in str(var_dict[opt_var][0]) else str(var_dict[opt_var][0]).lower()
            file_out.write("var %s:%s;\n "%(lex_type,opt_symbol_lex))
            if name=="maximize" and "BV" not in str(var_dict[opt_var][0]):
                opt_symbol_tmp = mgr.Minus(mgr.Int(0),opt_symbol)
                assignment = mgr.Equals(opt_symbol_lex,opt_symbol_tmp)
                file_out.write("constraint ("+self.serializer.serialize(assignment,daggify=False)+");\n")
            elif name=="maximize" and "BV" in str(var_dict[opt_var][0]) and signed==-1: #maximization BV8 unisgned -> max value is 255 -> minimize 255-opt_symbol
                file_out.write("constraint( %s = %s - %s );\n"%(opt_symbol_lex,pow(2,opt_symbol.bv_width())-1,opt_symbol))
            elif name=="maximize" and "BV" in str(var_dict[opt_var][0]) and signed>-1: #maximization BV8 signed -> maxvalue is 127 -> minimize 127-opt_symbol
                file_out.write("constraint( %s = %s - (-%s*((%s div %s) mod 2))+sum([pow(2,i)*((%s div pow(2,i)) mod 2)| i in 0..%s-1] ));\n"
                               %(opt_symbol_lex,pow(2,opt_symbol.bv_width()-1)-1,pow(2,opt_symbol.bv_width()-1),opt_symbol,pow(2,opt_symbol.bv_width()-1),opt_symbol,opt_symbol.bv_width()-1))
            elif name=="minimize" and "BV" in str(var_dict[opt_var][0]) and signed>-1: #maximization BV8 signed -> maxvalue is 127 -> minimize 127-opt_symbol
                file_out.write("constraint( %s = (-%s*((%s div %s) mod 2))+sum([pow(2,i)*((%s div pow(2,i)) mod 2)| i in 0..%s-1] ));\n"
                               %(opt_symbol_lex,pow(2,opt_symbol.bv_width()-1),opt_symbol,pow(2,opt_symbol.bv_width()-1),opt_symbol,opt_symbol.bv_width()-1))
            else:
                assignment = mgr.Equals(opt_symbol,opt_symbol_lex)
                file_out.write("constraint ("+self.serializer.serialize(assignment,daggify=False)+");\n")
            if upper is not None:
                if "BV" in str(upper.get_type()):
                    file_out.write("constraint(%s >= %s /\ %s <= %s);\n"%(opt_symbol,0,opt_symbol,pow(2,opt_symbol.bv_width())-1))
                    if signed>=0:
                        less_than = mgr.BVSLE(opt_symbol,upper)
                    else:
                        less_than = mgr.BVULE(opt_symbol,upper)
                    file_out.write("constraint ("+self.serializer.serialize(less_than)+");\n")
                else:
                    less_than = mgr.LE(opt_symbol,upper)
                    file_out.write("constraint ("+self.serializer.serialize(less_than,daggify=False)+");\n")
            if lower is not None:
                if "BV" in str(lower.get_type()):
                    file_out.write("constraint(%s >= %s /\ %s <= %s);\n"%(opt_symbol,0,opt_symbol,pow(2,opt_symbol.bv_width())-1))
                    if signed>=0:
                        less_than = mgr.BVSLE(lower,opt_symbol)
                    else:
                        less_than = mgr.BVULE(lower,opt_symbol)
                    file_out.write("constraint ("+self.serializer.serialize(less_than)+");\n")
                else:
                    less_than = mgr.LE(lower,opt_symbol)
                    file_out.write("constraint ("+self.serializer.serialize(less_than,daggify=False)+");\n")
            var_list.append(opt_symbol_lex)
        file_out.write("array[int] of var "+str(final_type)+": obj_array;\n")
        file_out.write("obj_array=[")
        file_out.write(str(var_list[0]))
        for el in var_list[1:]:
            file_out.write(","+str(el))
        file_out.write("];\n")
        file_out.write("%using minisearch\n")
        file_out.write("solve search minimize_lex_pers(obj_array);\n")



        ##Minisearch Paper Implementation
        file_out.write("""\n
    function ann : minimize_lex_pers(array[int] of var """+str(final_type)+""" : objs) =
        next() /\ commit() /\ print() /\\
        repeat( scope(
            post(lex_less(objs, [sol(objs[i]) | i in index_set(objs)])) /\\
            if next() then commit() /\ print() else break endif ) );
    """)
示例#14
0
 def __init__(self, stream):
     TreeWalker.__init__(self)
     self.stream = stream
     self.write = self.stream.write
     self.mgr = get_env().formula_manager
示例#15
0
 def assert_infix_enabled_wrap(*args, **kwargs):
     from pyomt.environment import get_env
     if not get_env().enable_infix_notation:
         raise PyomtModeError(INFIX_ERROR_MSG)
     return f(*args, **kwargs)