Beispiel #1
0
def execute_script_fname(smtfile, logic, expected_result):
    """Read and call a Solver to solve the instance"""

    reset_env()
    Solver = get_env().factory.Solver
    parser = SmtLibParser()
    script = parser.get_script_fname(smtfile)
    try:
        log = script.evaluate(
            Solver(logic=logic, incremental=False, generate_models=False))
    except NoSolverAvailableError:
        raise SkipTest("No solver for logic %s." % logic)
    except SolverReturnedUnknownResultError:
        if not logic.quantifier_free:
            warnings.warn(
                "Test (%s, %s) could not be solver due to quantifiers." %
                (logic, smtfile))
            return
        raise

    res = check_sat_filter(log)
    if res:
        assert expected_result == "sat"
    else:
        assert expected_result == "unsat"
Beispiel #2
0
 def parse(self, file_id):
     fname = SMTLIB_FILE_PATTERN % file_id
     reset_env()
     parser = SmtLibParser()
     script = parser.get_script_fname(fname)
     self.assertIsNotNone(script)
     return script
Beispiel #3
0
 def parse(self, file_id):
     fname = SMTLIB_FILE_PATTERN % file_id
     reset_env()
     parser = SmtLibParser()
     script = parser.get_script_fname(fname)
     self.assertIsNotNone(script)
     return script
Beispiel #4
0
def execute_script_fname(smtfile, logic, expected_result):
    """Read and call a Solver to solve the instance"""

    reset_env()
    Solver = get_env().factory.Solver
    parser = SmtLibParser()
    script = parser.get_script_fname(smtfile)
    try:
        solver = Solver(logic=logic, incremental=False, generate_models=False)
        if logic == QF_UF and type(solver).__name__ == 'CVC4Solver':
            warnings.warn(
                "Test (%s, %s) skipped because CVC4 can't handle QF_UF." %
                (logic, smtfile))
            return
        if logic == QF_UF and type(solver).__name__ == 'BoolectorSolver':
            warnings.warn(
                "Test (%s, %s) skipped because Boolector can't handle QF_UF." %
                (logic, smtfile))
            return
        log = script.evaluate(solver)
    except NoSolverAvailableError:
        raise SkipTest("No solver for logic %s." % logic)
    except SolverReturnedUnknownResultError:
        if not logic.quantifier_free:
            warnings.warn(
                "Test (%s, %s) could not be solved due to quantifiers." %
                (logic, smtfile))
            return
        raise

    res = check_sat_filter(log)
    assert expected_result == res
Beispiel #5
0
def main(path):
    parser = SmtLibParser()
    script = parser.get_script_fname(path)
    formula = script.get_last_formula()
    h = SegmentsHeuristics(formula, 'z3')
    l = h.try_to_unsatisfy()
    print(l)
Beispiel #6
0
def remove_quant_and_define_funs(path):
    parser = SmtLibParser()
    script = parser.get_script_fname(path)
    formula = script.get_last_formula()
    prenex_normalizer = PrenexNormalizer()
    quantifications, matrix = prenex_normalizer.walk(formula)
    quantifier, variables = quantifications[0]
    assert (len(quantifications) == 1)
    env = get_env()
    mgr = env.formula_manager
    subs = dict((x, mgr.FreshSymbol(x.symbol_type())) for x in variables)
    substitued_matrix = matrix.substitute(subs)

    declarations = []
    declarations.extend(script.filter_by_command_name("declare-sort"))
    declarations.extend(script.filter_by_command_name("declare-fun"))
    declarations.extend(script.filter_by_command_name("declare-const"))
    new_script = SmtLibScript()
    new_script.add(SET_LOGIC, [QF_NRA])
    for key in subs.keys():
        new = subs[key]
        new_script.add("declare-fun", [new])
    for declaration in declarations:
        new_script.add_command(declaration)
    new_script.add("assert", [substitued_matrix])
    new_script.add("check-sat", [])
    buf = cStringIO()
    new_script.serialize(buf, False)
    smtlib = buf.getvalue()
    print(smtlib)
Beispiel #7
0
    def read_properties(self, path: str) -> dict:
        """
        This method reads the SMT property file and
        creates a property for each node.

        Parameters
        ----------
        path : str
            The SMT-LIB file path.

        Returns
        -------
        dict
            The dictionary of properties

        """

        parser = SmtLibParser()
        try:
            script = parser.get_script_fname(path)
        except PysmtException:
            dialog = MessageDialog("Failed to parse SMT property.",
                                   MessageType.ERROR)
            dialog.exec()
            return dict()

        declarations = script.filter_by_command_name(
            ['declare-fun', 'declare-const'])
        assertions = script.filter_by_command_name('assert')
        var_set = []
        var_list = []
        properties = dict()

        for d in declarations:
            var_list.append(str(d.args[0]).replace('\'', ''))
            varname = str(d.args[0]).split('_')[0].replace(
                '\'', '')  # Variable format is <v_name>_<idx>
            if varname not in var_set:
                var_set.append(varname)

        counter = 0

        for a in assertions:
            line = str(a.args[0]).replace('\'', '')
            for v in var_set:
                if f" {v}" in line or f"({v}" in line:  # Either '(v ...' or '... v)'
                    if v not in properties.keys():
                        properties[v] = PropertyBlock(f"{counter}Pr",
                                                      "Generic SMT")
                        properties[v].smt_string = ''
                        properties[v].variables = list(
                            filter(lambda x: v in x, var_list))
                        counter += 1
                    conv = ExpressionTreeConverter()
                    wrap = conv.build_from_infix(line).as_prefix()
                    properties[v].smt_string += f"(assert {wrap})\n"
                    break

        return properties
Beispiel #8
0
def main(path, solver_name):
    solver = Solver(solver_name)
    parser = SmtLibParser()
    script = parser.get_script_fname(path)
    formula = script.get_last_formula()
    solver.add_assertion(formula)
    result = solver.solve()
    print(result)
Beispiel #9
0
def get_value():
    solver = Solver('z3')
    parser = SmtLibParser()
    script = parser.get_script_fname("get_value.smt2")
    #result = script.evaluate(Solver('z3'))
    exprs = []
    for get_val_cmd in script.filter_by_command_name("get-value"):
        exprs.extend(get_val_cmd.args)
    formula = script.get_last_formula()
    solver.add_assertion(formula)
    result1 = solver.solve()
    result2 = solver.get_values(exprs)
Beispiel #10
0
    def __as_script(self):
        """
        This method makes use of pysmt for extracting the commands.

        Returns
        ----------
        SmtLibScript
            The list of SMTLIB commands contained in the file.

        """

        parser = SmtLibParser()
        return parser.get_script_fname(self.smtlib_property.smtlib_path)
Beispiel #11
0
def process_file(input_file, no_ann_file):
    inputNoAnn = removeAnnotations(input_file)
    inputNoAnnFile = open(no_ann_file, 'w')
    inputNoAnnFile.write(inputNoAnn)
    inputNoAnnFile.close()
    strip_file(no_ann_file)

    parser = SmtLibParser()
    script = parser.get_script_fname(no_ann_file)

    formula = script.get_last_formula()

    formulas = get_all_conjuncts(formula)
    portfolio_solver = PortfolioSolver(formulas)
    satunsat = portfolio_solver.solve()
    print(satunsat)
Beispiel #12
0
def execute_script_fname(smtfile, logic, expected_result):
    """Read and call a Solver to solve the instance"""

    reset_env()
    assert os.path.exists(smtfile), smtfile
    parser = SmtLibParser()
    script = parser.get_script_fname(smtfile)
    try:
        log = script.evaluate(Solver(logic=logic))
    except NoSolverAvailableError:
        raise unittest.SkipTest("No solver for logic %s." % logic)

    res = check_sat_filter(log)
    if res:
        assert expected_result == "sat"
    else:
        assert expected_result == "unsat"
Beispiel #13
0
def execute_script_fname(smtfile):
    """Read and call a Solver to solve the instance"""
    print(smtfile)
    reset_env()
    assert os.path.exists(smtfile)
    parser = SmtLibParser()
    solver = NoopSolver(get_env())

    start = time.clock()
    script = parser.get_script_fname(smtfile)
    end = time.clock()

    script.evaluate(solver)
    res = solver.get_asserted_formula()
    assert res is not None

    return (smtfile, (end - start))
Beispiel #14
0
def execute_script_fname(smtfile, logic, expected_result):
    """Read and call a Solver to solve the instance"""

    reset_env()
    assert os.path.exists(smtfile), smtfile
    parser = SmtLibParser()
    script = parser.get_script_fname(smtfile)
    try:
        log = script.evaluate(Solver(logic=logic))
    except NoSolverAvailableError:
        raise SkipTest("No solver for logic %s." % logic)

    res = check_sat_filter(log)
    if res:
        assert expected_result == "sat"
    else:
        assert expected_result == "unsat"
Beispiel #15
0
def execute_script_fname(smtfile, logic, expected_result):
    """Read and call a Solver to solve the instance"""

    reset_env()
    Solver = get_env().factory.Solver
    parser = SmtLibParser()
    script = parser.get_script_fname(smtfile)
    try:
        log = script.evaluate(Solver(logic=logic, incremental=False,
                                     generate_models=False))
    except NoSolverAvailableError:
        raise SkipTest("No solver for logic %s." % logic)
    except SolverReturnedUnknownResultError:
        if not logic.quantifier_free:
            warnings.warn("Test (%s, %s) could not be solver due to quantifiers." % (logic, smtfile))
            return
        raise

    res = check_sat_filter(log)
    assert expected_result == res
    def test_vmt(self):
        parser = SmtLibParser()
        fname = os.path.join(SMTLIB_DIR, "small_set/vmt/c432_0f.vmt")
        script = parser.get_script_fname(fname)

        ann = script.annotations

        self.assertIn("A_1__AT0 ->", str(ann))

        a1 = Symbol("A_1__AT0")

        self.assertIn(a1, ann)
        self.assertTrue(ann.has_annotation(a1, "next"))
        self.assertFalse(ann.has_annotation(a1, "non-existent"))
        self.assertTrue(ann.has_annotation(a1, "next", "A_1__AT1"))
        self.assertFalse(ann.has_annotation(a1, "next", "non-existent"))

        self.assertIn("A_1__AT1", ann.annotations(a1)["next"])
        self.assertIn("A_1__AT1", ann[a1]["next"])

        curr_a1 = ann.all_annotated_formulae("next", "A_1__AT1")
        self.assertEqual(curr_a1, set([a1]))
Beispiel #17
0
    def test_vmt(self):
        parser = SmtLibParser()
        fname = os.path.join(SMTLIB_DIR, "small_set/vmt/c432_0f.vmt")
        script = parser.get_script_fname(fname)

        ann = script.annotations

        self.assertIn("A_1__AT0 ->", str(ann))

        a1 = Symbol("A_1__AT0")

        self.assertIn(a1, ann)
        self.assertTrue(ann.has_annotation(a1, "next"))
        self.assertFalse(ann.has_annotation(a1, "non-existent"))
        self.assertTrue(ann.has_annotation(a1, "next", "A_1__AT1"))
        self.assertFalse(ann.has_annotation(a1, "next", "non-existent"))

        self.assertIn("A_1__AT1", ann.annotations(a1)["next"])
        self.assertIn("A_1__AT1", ann[a1]["next"])

        curr_a1 = ann.all_annotated_formulae("next", "A_1__AT1")
        self.assertEqual(curr_a1, set([a1]))
Beispiel #18
0
def parse_input_formula(path):
    with open(path, "r") as f:
        script_str = f.read()
    parser = SmtLibParser()
    script = parser.get_script_fname(path)
    smtlib_formula = script.get_strict_formula()

    #verify that the input formula is in cnf
    assert (smtlib_formula.is_and())
    for clause in smtlib_formula.args():
        assert (clause.is_or())
        for l in clause.args():
            assert (l.is_literal())

    #transform the input formula to a set of sets of literals
    cnf_formula = [
        list(set(clause.args())) for clause in smtlib_formula.args()
    ]

    #obtain all the boolean variables of the input formula
    free_vars = smtlib_formula.get_free_variables()

    return cnf_formula, free_vars
Beispiel #19
0
 def parse(self, fname):
     reset_env()
     parser = SmtLibParser()
     script = parser.get_script_fname(fname)
     self.assertIsNotNone(script)
 def test_truncated_file2(self):
     d = os.path.dirname(os.path.realpath(__file__))
     smtfile = d + "/small_set/negative/wrong3.smt2.bz2"
     parser = SmtLibParser()
     with self.assertRaises(PysmtSyntaxError):
         parser.get_script_fname(smtfile)
 def test_wrong(self):
     d = os.path.dirname(os.path.realpath(__file__))
     smtfile = d + "/small_set/negative/wrong1.smt2.bz2"
     parser = SmtLibParser()
     with self.assertRaises(TypeError):
         parser.get_script_fname(smtfile)
 def test_wrong(self):
     d = os.path.dirname(os.path.realpath(__file__))
     smtfile = d + "/small_set/negative/wrong1.smt2"
     parser = SmtLibParser()
     with self.assertRaises(TypeError):
         parser.get_script_fname(smtfile)
Beispiel #23
0
 def parse(self, fname):
     reset_env()
     parser = SmtLibParser()
     script = parser.get_script_fname(fname)
     self.assertIsNotNone(script)
     return script
Beispiel #24
0
        new_script.add("declare-fun", [new])
    for declaration in declarations:
        new_script.add_command(declaration)
    new_script.add("assert", [substitued_matrix])
    new_script.add("check-sat", [])
    buf = cStringIO()
    new_script.serialize(buf, False)
    smtlib = buf.getvalue()
    print(smtlib)


DREAL_NAME = "dreal"
DREAL_PATH = "/home/yoniz/git/dreal/bin/dReal"
DREAL_ARGS = "--in"
DREAL_LOGICS = [QF_NRA, QF_NIRA]
def solve_with_dreal(formula):
        env = get_env()
        env.factory.add_generic_solver(DREAL_NAME, [DREAL_PATH, DREAL_ARGS], DREAL_LOGICS)
        solver = Solver('dreal')
        solver.add_assertion(formula)
        solver.solve()



if __name__ == "__main__":
    path = argv[1]
    parser = SmtLibParser()
    script = parser.get_script_fname(path)
    formula = script.get_last_formula()
    solve_with_dreal(formula)