Ejemplo n.º 1
0
    def test_get_model_unsat(self):
        varA = Symbol("A", BOOL)
        varB = Symbol("B", BOOL)
        f = And(varA, Not(varB))
        g = f.substitute({varB:varA})

        res = get_model(g, logic=QF_BOOL)
        self.assertIsNone(res, "Formula was expected to be UNSAT")

        for solver in get_env().factory.all_solvers(logic=QF_BOOL):
            res = get_model(g, solver_name=solver)
            self.assertIsNone(res, "Formula was expected to be UNSAT")
Ejemplo n.º 2
0
    def test_get_model_sat(self):
        varA = Symbol("A", BOOL)
        varX = Symbol("X", REAL)
        f = And(varA, Equals(varX, Real(8)))

        res = get_model(f, logic=QF_LRA)
        self.assertIsNotNone(res, "Formula was expected to be SAT")
        self.assertTrue(res.get_value(varA) == TRUE())
        self.assertTrue(res.get_value(varX) == Real(8))

        for solver in get_env().factory.all_solvers(logic=QF_LRA):
            res = get_model(f, solver_name=solver)
            self.assertIsNotNone(res, "Formula was expected to be SAT")
            self.assertTrue(res.get_value(varA) == TRUE())
            self.assertTrue(res.get_value(varX) == Real(8))
Ejemplo n.º 3
0
    def test_get_model_sat(self):
        varA = Symbol("A", BOOL)
        varX = Symbol("X", REAL)

        f = And(varA, Equals(varX, Real(8)))

        res = get_model(f, logic=QF_LRA)
        self.assertIsNotNone(res, "Formula was expected to be SAT")
        self.assertTrue(res.get_value(varA) == TRUE())
        self.assertTrue(res.get_value(varX) == Real(8))

        for solver in get_env().factory.all_solvers(logic=QF_LRA):
            res = get_model(f, solver_name=solver)
            self.assertIsNotNone(res, "Formula was expected to be SAT")
            self.assertTrue(res.get_value(varA) == TRUE())
            self.assertTrue(res.get_value(varX) == Real(8))
Ejemplo n.º 4
0
 def solve(self, simplify=False):
     formula = And(self.constraints)
     if simplify:
         formula = formula.simplify()
     model = get_model(formula)
     assert model is not None  # check for unsatisfiability
     return model
Ejemplo n.º 5
0
def process():
    varA = Symbol("A")
    varB = Symbol("B")
    f = And(varA, Not(varB))
    print(f)
    print(is_sat(f))

    hello = [Symbol(s, INT) for s in "hello"]
    world = [Symbol(s, INT) for s in "world"]

    letters = set(hello + world)

    domains = And(And(LE(Int(1), l),
                      GE(Int(10), l)) for l in letters)
    print(domains,'domain')
    sum_hello = Plus(hello)
    sum_world = Plus(world)

    problem = And(Equals(sum_hello, sum_world),
                  Equals(sum_hello, Int(36)))

    formula = And(domains, problem)

    print("Serialization of the formula:")
    print(formula)
    print(formula.serialize())
    print(is_sat(formula))
    print(get_model(formula))
Ejemplo n.º 6
0
    def test_z3_model_iteration(self):
        x, y = Symbol("x"), Symbol("y")
        m = get_model(And(x, y), solver_name="z3")
        self.assertIsNotNone(m)

        for _, v in m:
            self.assertEqual(v, TRUE())
Ejemplo n.º 7
0
    def test_z3_model_iteration(self):
        x, y = Symbol("x"), Symbol("y")
        m = get_model(And(x, y), solver_name="z3")
        self.assertIsNotNone(m)

        for _, v in m:
            self.assertEqual(v, TRUE())
Ejemplo n.º 8
0
def vertex_cover_solver(graph, k):
    vertexes, edges = graph

    # vertex in vertex cover 1 otherwise 0
    vertex_vars = [Symbol(v, INT) for v in vertexes]
    vertex_range = And(
        [And(GE(v, Int(0)), LE(v, Int(1))) for v in vertex_vars])

    # size of vertex cover <= k
    sum_vertex = Plus(vertex_vars)
    vertex_constraint = LE(sum_vertex, Int(k))

    # edge constraints
    # Plus(vi, vj) >= 1 for edge = (vi, vj)
    # cannot use Or(vi, vj), because variables are integers not boolean type
    edge_constraint = And([
        GE(Plus([vertex_vars[lv], vertex_vars[rv]]), Int(1))
        for (lv, rv) in edges
    ])

    # combined formula
    formula = And(vertex_range, vertex_constraint, edge_constraint)

    model = get_model(formula)
    size = get_formula_size(formula)
    cover = set()
    if model:
        for i, node in enumerate(vertexes):
            if model.get_py_value(vertex_vars[i]):
                cover.add(node)
        return cover, formula, size
    else:
        return None, formula, size
Ejemplo n.º 9
0
def efsmt(y, phi, logic=AUTO, maxloops=None,
          esolver_name=None, fsolver_name=None,
          verbose=False):
    """Solves exists x. forall y. phi(x, y)"""

    y = set(y)
    x = phi.get_free_variables() - y

    with Solver(logic=logic, name=esolver_name) as esolver:

        esolver.add_assertion(Bool(True))
        loops = 0
        while maxloops is None or loops <= maxloops:
            loops += 1

            eres = esolver.solve()
            if not eres:
                return False
            else:
                tau = {v: esolver.get_value(v) for v in x}
                sub_phi = phi.substitute(tau).simplify()
                if verbose: print("%d: Tau = %s" % (loops, tau))

                fmodel = get_model(Not(sub_phi),
                                   logic=logic, solver_name=fsolver_name)
                if fmodel is None:
                    return tau
                else:
                    sigma = {v: fmodel[v] for v in y}
                    sub_phi = phi.substitute(sigma).simplify()
                    if verbose: print("%d: Sigma = %s" % (loops, sigma))
                    esolver.add_assertion(sub_phi)

        raise SolverReturnedUnknownResultError
Ejemplo n.º 10
0
def encode_and_run(g, counter_examples=None):
    fs, store = encode_games(g, counter_examples)
    f = reduce(op.and_, fs, TRUE())
    model = get_model(f)

    if model is None:
        return Result(False, None, None, counter_examples)

    sol = {v: extract_ts(v, model, g, store) for v in fn.cat(g.model.vars)}
    return Result(True, 0, sol, counter_examples)
Ejemplo n.º 11
0
def check_in_language(tree_str, conf_file):
    cfg_f, cfg_r = read_features(conf_file)
    sent_t = Tree.parse(tree_str.strip(), trunc=False)
    symbols, all_constraints = get_sat_constraints(sent_t, cfg_f, cfg_r, {},
                                                   [])
    problem = And(all_constraints)
    model = get_model(problem)
    if model:
        return tree_to_str(sent_t)
    else:
        return None
Ejemplo n.º 12
0
def SMTSynthesizer():
    """
    Use SMT to solve the ordering of register loads based on call conventions
    """     

    print '> SMT synthesizer'
    
    # Use a SMT solver to figure out the order to pull register values from
    # user-space stack onto the kernel stack
    model = get_model(machine_desc)
    stack = sorted(regs.values(), key=lambda r: r.get_stack_index(model))
    return X86StackRegister.pushqs(stack)
Ejemplo n.º 13
0
def get_model_or_print_ucore(formula):
    m = s.get_model(formula)
    if not m:
        print('unsat')
        from pysmt.rewritings import conjunctive_partition
        conj = conjunctive_partition(s.And(formula))
        ucore = s.get_unsat_core(conj)
        print("UNSAT-Core size '%d'" % len(ucore))
        for f in ucore:
            print(f.serialize())
        return
    return m
Ejemplo n.º 14
0
def graph_color_ass_smt(G, h):
    n = len(G.nodes)
    x = [Symbol(f"x_{i}", INT) for i in range(n)]
    f = And(
        *(0 < v for v in x),
        *(v <= h for v in x),
        *(NotEquals(x[u],x[v]) for u, v in G.edges)
    )
    model = get_model(f)
    if model:
        print(model)
    else:
        print("No solution found")
Ejemplo n.º 15
0
    def solve(self, solver_name=None, get_assignment=False):
        """Solve the SMT problem.

        Return whether the decision problem is satisfiable. If get_assignment
        is set to True, solve() returns an assignment of the variables
        that makes the SMT problem satisfiable (if the problem is
        unsatisfiable, None is returned).

        This assignment is returned as a dictionary with the following entries:

        - differences: an ordered dictionary containing the sequence of
          differences.
        - weight: the weight of the characteristic.
        - op_weights: the weights of each operation with non-deterministic
          propagation.

            >>> from arxpy.bitvector.function import Function
            >>> from arxpy.diffcrypt.difference import XorDiff, DiffVar
            >>> from arxpy.diffcrypt.characteristic import Characteristic
            >>> from arxpy.diffcrypt.smt import SmtProblem
            >>> class MyFunction(Function):
            ...     input_widths = [8, 8, 8]
            ...     output_widths = [8, 8]
            ...     @classmethod
            ...     def eval(cls, x, y, k):
            ...         return (y + k, (y + k) ^ x)
            >>> x, y, k = DiffVar("x", 8), DiffVar("y", 8), DiffVar("k", 8)
            >>> ch = Characteristic(MyFunction, XorDiff, [x, y, k])
            >>> smt_problem = SmtProblem(ch, 0)
            >>> smt_problem.solve()
            True
            >>> smt_problem.solve(get_assignment=True)  # doctest:+NORMALIZE_WHITESPACE
            {'differences': OrderedDict([(x, 0x80), (y, 0x00), (k, 0x80),
            (d0, 0x80), (d1, 0x00)]), 'weight': 0,
            'op_weights': OrderedDict([(w_ky_d0, 0)])}

        """
        sc.reset_env()
        pysmt_formula = sc.And(*[bv2pysmt(a) for a in self.assertions])

        if not get_assignment:
            return sc.is_sat(pysmt_formula, solver_name, logic=logics.QF_BV)
        else:
            model = sc.get_model(pysmt_formula,
                                 solver_name,
                                 logic=logics.QF_BV)

            if model is None:
                return None
            else:
                return self._get_assignment(model)
Ejemplo n.º 16
0
        def get_def_model(formula, vars_list, val):
            model_sat = get_model(formula)

            assert model_sat is not None

            model = {}
            for v in vars_list:
                if v not in model_sat:
                    model[v] = val
                else:
                    if model_sat.get_value(v) == TRUE():
                        model[v] = True
                    else:
                        model[v] = False

            return model
Ejemplo n.º 17
0
def decide_epidemic(source, size, m, p, limit, target, timesteps, p_infect):
    if source == 'generate':
        contact_network = networkx.watts_strogatz_graph(size, m, p)
    else:
        contact_network = networkx.read_adjlist(source)
    spread_graph = grow_connections_in_time(contact_network, timesteps,
                                            p_infect)

    formula, _, _ = construct_spread_formula_from_graph(
        spread_graph, limit, target)
    model = get_model(formula)

    if model:
        return True, model
    else:
        return False, None
Ejemplo n.º 18
0
def solveDecisionProblem(filename):
	global robots_info
	global task_info
	global task_utilities
	global k
	robots_info = {}
	task_info = {}
	task_utilities = {}
	k=0

	file = open(filename, "r")
	mode = 0
	for line in file:
		if line=='\n':
			mode+=1
		elif mode==0:
			k = int(line.strip())
		elif mode==1:
			task_line = line.split()
			task_info[task_line[0]] = [int(resource) for resource in task_line[2:]]
			task_utilities[task_line[0]] = int(task_line[1])
		elif mode == 2:
			robot_line = line.split()
			robots_info[robot_line[0]] = [int(resource) for resource in robot_line[1:]]
	file.close()
		

	# Each robot may be assigned to at most one task
	# runs in time |Robots||Tasks||Tasks|
	oneTask = And([Symbol(robot+taskAssigned).Implies(Not(Symbol(robot+task))) for robot in robots_info.keys() for taskAssigned in task_info.keys() for task in task_info.keys() if (taskAssigned != task)])

	# A task is satisfied if and only if all of its resource requirements are met
	# runs in time |Robots||Tasks||ResourceTypes|
	tasksSatisfied = And([Iff(Symbol(task +"Sat"), And([GE(Plus([Times(Ite(Symbol(robot+task),Int(1), Int(0)), Int(robots_info[robot][i])) for robot in robots_info.keys()]), Int(task_info[task][i])) for i in range(len(task_info[task]))])) for task in task_info.keys()])

	# Is the decision problem satisfied
	# runs in time |Tasks|
	decisionProb = GE(Plus([Times(Ite(Symbol(task+"Sat"), Int(1), Int(0)), Int(task_utilities[task])) for task in task_info.keys()]), Int(k))

	prob = And(oneTask, tasksSatisfied, decisionProb)
	model = get_model(prob)
	return model
Ejemplo n.º 19
0
def solve(problem):
    from pysmt.shortcuts import AllDifferent, And, Symbol, get_model
    from pysmt.typing import INT
    tree = parser.parse(problem)
    letters = sorted(get_letters(tree))
    first_letters = get_first_letters(tree)
    symbols = {}
    for letter in letters:
        symbol = Symbol(letter, INT)
        symbols[letter] = symbol
    formula = make_formula(tree, symbols)
    clauses = []
    for letter in letters:
        symbol = symbols[letter]
        if letter in first_letters:
            clauses.append(1 <= symbol)
            clauses.append(symbol < 10)
        else:
            clauses.append(0 <= symbol)
            clauses.append(symbol < 10)
    clauses.append(AllDifferent(*symbols.values()))
    clauses.append(formula)
    cp = And(clauses)
    return get_model(cp)
Ejemplo n.º 20
0
def scheduler(chip_power):
    total_power = 0
    mem = [Symbol(M, INT) for M in mem_list]
    # print(mem_power_list.get(str(mem[0])))
    domain = And([And(GE(l, Int(0)), LT(l, Int(2))) for l in mem])
    # print(domain)
    sum_power = Plus([l * mem_power_list.get(str(l)) for l in mem])
    # print(sum_power)
    problem = Equals(sum_power, Int(chip_power))
    formula = And(domain, problem)
    # print(formula)
    model = get_model(formula)
    # print(model)
    if model != None:
        for l in mem:
            mem_test_time_list[str(l)] = mem_test_time_list[str(l)] - int(
                model.get_value(l).constant_value())
            if int(model.get_value(l).constant_value()) == 1:
                print(str(l))
                total_power = total_power + mem_power_list[str(l)]
        print("total power:", total_power)
        return True
    else:
        return False
Ejemplo n.º 21
0
    def solve(self, solver_name=None, get_assignment=False):
        """Solve the pair of SMT problems simultaneously.

        Return whether the pair of decision problems are satisfiable.
        If get_assignment is set to True, solve() returns an assignment of
        the variables that makes the pair of SMT problems satisfiable
        (if one of the problems is unsatisfiable, None is returned).

        This assignment is returned as a pair of dictionaries, where
        the first dictionary is the assignment of the inner SMT problem
        and the second dictionary is the assignment of the outer SMT problem.

            >>> from arxpy.bitvector.operation import RotateLeft
            >>> from arxpy.bitvector.function import Function, CompositeFunction
            >>> from arxpy.diffcrypt.difference import XorDiff, DiffVar
            >>> from arxpy.diffcrypt.characteristic import Characteristic, CompositeCh
            >>> class MyInner(Function):
            ...     input_widths = [8]
            ...     output_widths = [8, 8]
            ...     @classmethod
            ...     def eval(cls, k):
            ...         return (k, RotateLeft(k, 1))
            >>> class MyOuter(Function):
            ...     input_widths = [8, 8, 8, 8]
            ...     output_widths = [8, 8]
            ...     @classmethod
            ...     def eval(cls, x, y, k0, k1):
            ...         for ki in [k0, k1]:
            ...             x, y = y + ki, (y + ki) ^ x
            ...         return x, y
            >>> class MyComposite(CompositeFunction):
            ...     input_widths = [8, 8, 8]
            ...     output_widths = [8, 8]
            ...     inner_func = MyInner
            ...     outer_func = MyOuter
            >>> x, y, k = DiffVar("x", 8), DiffVar("y", 8), DiffVar("k", 8)
            >>> ch = CompositeCh(MyComposite, XorDiff, [x, y, k])
            >>> smt_problem = CompositeSmtProblem(ch, [1, 1])
            >>> smt_problem.solve()
            True
            >>> inner_assig, outer_assig = smt_problem.solve(get_assignment=True)
            >>> inner_assig  # doctest:+NORMALIZE_WHITESPACE
            {'differences': OrderedDict([(k, 0x40), (i0, 0x80)]),
            'weight': 0, 'op_weights': OrderedDict()}
            >>> outer_assig  # doctest:+NORMALIZE_WHITESPACE
            {'differences': OrderedDict([(x, 0x40), (y, 0x00), (k, 0x40),
            (i0, 0x80), (o0, 0x40), (o1, 0x00), (o2, 0x80), (o3, 0xc0)]),
            'weight': 1, 'op_weights': OrderedDict([(w_ky_o0, 1),
            (w_i0o1_o2, 0)])}

        """
        sc.reset_env()
        i_f = sc.And(*[bv2pysmt(a) for a in self.inner_problem.assertions])
        o_f = sc.And(*[bv2pysmt(a) for a in self.outer_problem.assertions])
        pysmt_formula = sc.And(i_f, o_f)

        if not get_assignment:
            return sc.is_sat(pysmt_formula, solver_name, logic=logics.QF_BV)
        else:
            model = sc.get_model(pysmt_formula,
                                 solver_name,
                                 logic=logics.QF_BV)

            if model is None:
                return None
            else:
                inner_assig = self.inner_problem._get_assignment(model)
                outer_assig = self.outer_problem._get_assignment(model)
                return inner_assig, outer_assig
Ejemplo n.º 22
0
def generate_model(formula):
    """
           This function will invoke PySMT APIs to solve the provided formula and return the byte list of the model
           Arguments:
               formula: smtlib formatted formula
    """
    emitter.debug("extracting z3 model")
    model = get_model(formula)
    if model is None:
        return None
    path_script = "/tmp/z3_script_model"
    write_smtlib(formula, path_script)
    with open(path_script, "r") as script_file:
        script_lines = script_file.readlines()
    script = "".join(script_lines)
    var_list = set(re.findall("\(declare-fun (.+?) \(\)", script))
    sym_var_list = dict()
    for var_name in var_list:
        # sym_var_list[var_name] = dict()
        if "const_" in var_name and not "const_arr" in var_name:
            sym_def = Symbol(var_name, BV32)
            if sym_def not in model:
                continue
            x = model[sym_def]
            byte_list = dict()
            default_value = x.bv_signed_value()
            byte_list[0] = default_value
        else:
            sym_def = Symbol(var_name, ArrayType(BV32, BV8))
            if sym_def not in model:
                continue
            x = model[sym_def].simplify()
            byte_list = dict()
            value_array_map = x.array_value_assigned_values_map()
            default_value = int(str(x.array_value_default()).split("_")[0])
            if not value_array_map:
                byte_list[0] = default_value
            else:
                for idx, val in value_array_map.items():
                    index = int(str(idx).split("_")[0])
                    value = int(str(val).split("_")[0])
                    byte_list[index] = value

                max_index = max(list(byte_list.keys()))
                if var_name in values.LIST_BIT_LENGTH:
                    array_size = values.LIST_BIT_LENGTH[var_name] - 1
                    if var_name in ["A-data"]:
                        array_size = max_index

                else:
                    array_size = max_index + 1  # TODO: this could be wrong calculation

                if max_index == 0:
                    array_size = 2

                if var_name not in ["A-data"]:
                    for i in range(0, array_size):
                        if i not in byte_list:
                            byte_list[i] = default_value

                if var_name not in ["A-data", "A-data-stat"]:
                    for i in range(array_size - 1, -1, -1):
                        if byte_list[i] == 0:
                            byte_list.pop(i)
                        else:
                            break
        sym_var_list[var_name] = byte_list
    emitter.data("model var list", sym_var_list)
    return sym_var_list
Ejemplo n.º 23
0
# We create a map from BitVectors to Reals, so that each bitvector
# value (interpreted as unary number) is equal to the Real
# value.
#
# The map is represented by an Array of type BV8 -> Real
map_type = ArrayType(BV8, REAL)
my_map = Symbol("my_map", map_type)

# Fill-up the map, by defining all 256 values:
for i in range(0, 255):
    my_map = my_map.Store(BV(i, 8), Real(i))

# We want to find find a value for which our relation does not work.
# In other words, we ask if there is a value for the bitvector
# s.t. the corresponding value in the array is different from the
# unary interpretation of the bitvector.
bv_var = Symbol("bv", BV8)
int_var = Symbol("int", INT)
real_var = Symbol("real", REAL)

f = And(
    # Convert the BV into INT
    int_var.Equals(BVToNatural(bv_var)),
    # Convert the INT into REAL
    real_var.Equals(ToReal(int_var)),
    # Compare the value stored in the map with the REAL value
    my_map.Select(bv_var).NotEquals(real_var)
    )

print(get_model(f)) # Indeed our range only gets up to 254!!!
Ejemplo n.º 24
0
    def test_bv(self):
        mgr = get_env().formula_manager
        BV = mgr.BV

        # Constants
        one = BV(1, 32)
        zero = BV(0, 32)
        big = BV(127, 128)
        binary = BV("111")
        binary2 = BV("#b111")
        binary3 = BV(0b111, 3)  # In this case we need to explicit the width

        self.assertEqual(binary, binary2)
        self.assertEqual(binary2, binary3)
        self.assertEqual(one, mgr.BVOne(32))
        self.assertEqual(zero, mgr.BVZero(32))

        # Type Equality
        self.assertTrue(BV32 != BV128)
        self.assertFalse(BV32 != BV32)
        self.assertFalse(BV32 == BV128)
        self.assertTrue(BV32 == BV32)

        with self.assertRaises(ValueError):
            # Negative numbers are not supported
            BV(-1, 10)
        with self.assertRaises(ValueError):
            # Number should fit in the width
            BV(10, 2)

        # Variables
        b128 = Symbol("b", BV128)  # BV1, BV8 etc. are defined in pysmt.typing
        b32 = Symbol("b32", BV32)
        hexample = BV(0x10, 32)
        #s_one = BV(-1, 32)
        bcustom = Symbol("bc", BVType(42))

        self.assertIsNotNone(hexample)
        self.assertIsNotNone(bcustom)
        #self.assertIsNotNone(s_one)
        self.assertEqual(bcustom.bv_width(), 42)
        self.assertEqual(hexample.constant_value(), 16)
        #self.assertEqual(str(s_one), "-1_32")

        not_zero32 = mgr.BVNot(zero)
        not_b128 = mgr.BVNot(b128)

        f1 = Equals(not_zero32, b32)
        f2 = Equals(not_b128, big)

        #print(f1)
        #print(f2)

        self.assertTrue(is_sat(f1, logic=QF_BV))
        self.assertTrue(is_sat(f2, logic=QF_BV))

        zero_and_one = mgr.BVAnd(zero, one)
        zero_or_one = mgr.BVOr(zero, one)
        zero_xor_one = mgr.BVXor(zero, one)

        zero_xor_one.simplify()
        self.assertTrue(zero_xor_one.is_bv_op())
        # print(zero_and_one)
        # print(zero_or_one)
        # print(zero_xor_one)

        f1 = Equals(zero_and_one, b32)
        f2 = Equals(zero_or_one, b32)
        f3 = Equals(zero_xor_one, b32)
        f4 = Equals(zero_xor_one, one)

        self.assertTrue(is_sat(f1, logic=QF_BV), f1)
        self.assertTrue(is_sat(f2, logic=QF_BV), f2)
        self.assertTrue(is_sat(f3, logic=QF_BV), f3)
        self.assertTrue(is_valid(f4, logic=QF_BV), f4)

        with self.assertRaises(TypeError):
            mgr.BVAnd(b128, zero)

        f = mgr.BVAnd(b32, zero)
        f = mgr.BVOr(f, b32)
        f = mgr.BVXor(f, b32)
        f = Equals(f, zero)

        self.assertTrue(is_sat(f, logic=QF_BV), f)

        zero_one_64 = mgr.BVConcat(zero, one)
        one_zero_64 = mgr.BVConcat(one, zero)
        one_one_64 = mgr.BVConcat(one, one)

        self.assertTrue(zero_one_64.bv_width() == 64)
        f1 = Equals(mgr.BVXor(one_zero_64, zero_one_64), one_one_64)

        self.assertTrue(is_sat(f1, logic=QF_BV), f1)

        # MG: BV indexes grow to the left.
        # This is confusing and we should address this.
        extraction = mgr.BVExtract(zero_one_64, 32, 63)
        self.assertTrue(is_valid(Equals(extraction, zero)))
        #print(extraction)

        ult = mgr.BVULT(zero, one)
        neg = mgr.BVNeg(one)
        self.assertTrue(is_valid(ult, logic=QF_BV), ult)
        test_eq = Equals(neg, one)
        self.assertTrue(is_unsat(test_eq, logic=QF_BV))

        # print(ult)
        # print(neg)

        f = zero
        addition = mgr.BVAdd(f, one)
        multiplication = mgr.BVMul(f, one)
        udiv = mgr.BVUDiv(f, one)

        self.assertTrue(is_valid(Equals(addition, one), logic=QF_BV), addition)
        self.assertTrue(is_valid(Equals(multiplication, zero), logic=QF_BV),
                        multiplication)
        self.assertTrue(is_valid(Equals(udiv, zero), logic=QF_BV), udiv)

        # print(addition)
        # print(multiplication)
        # print(udiv)

        three = mgr.BV(3, 32)
        two = mgr.BV(2, 32)

        reminder = mgr.BVURem(three, two)
        shift_l_a = mgr.BVLShl(one, one)
        shift_l_b = mgr.BVLShl(one, 1)

        self.assertTrue(is_valid(Equals(reminder, one)), reminder)
        self.assertEqual(shift_l_a, shift_l_b)
        self.assertTrue(is_valid(Equals(shift_l_a, two)))
        # print(reminder)
        # print(shift_l_a)
        # print(shift_l_b)

        shift_r_a = mgr.BVLShr(one, one)
        shift_r_b = mgr.BVLShr(one, 1)
        self.assertEqual(shift_r_a, shift_r_b)
        self.assertTrue(is_valid(Equals(shift_r_a, zero)))

        rotate_l = mgr.BVRol(one, 3)
        rotate_r = mgr.BVRor(rotate_l, 3)
        self.assertTrue(is_valid(Equals(one, rotate_r)))

        # print(rotate_l)
        # print(rotate_r)

        zero_ext = mgr.BVZExt(one, 64)
        signed_ext = mgr.BVSExt(one, 64)
        signed_ext2 = mgr.BVSExt(mgr.BVNeg(one), 64)

        self.assertNotEqual(signed_ext2, signed_ext)
        self.assertTrue(is_valid(Equals(zero_ext, signed_ext), logic=QF_BV))

        # print(zero_ext)
        # print(signed_ext)

        x = Symbol("x")
        g = And(x, mgr.BVULT(zero, one))

        res = is_sat(g, logic=QF_BV)
        self.assertTrue(res)

        model = get_model(g, logic=QF_BV)
        self.assertTrue(model[x] == TRUE())

        gt_1 = mgr.BVUGT(zero, one)
        gt_2 = mgr.BVULT(one, zero)
        self.assertEqual(gt_1, gt_2)

        gte_1 = mgr.BVULE(zero, one)
        gte_2 = mgr.BVUGE(one, zero)
        self.assertEqual(gte_1, gte_2)

        self.assertTrue(is_valid(gte_2, logic=QF_BV))

        ide = Equals(mgr.BVNeg(BV(10, 32)), mgr.SBV(-10, 32))
        self.assertValid(ide, logic=QF_BV)

        # These should work without exceptions
        mgr.SBV(-2, 2)
        mgr.SBV(-1, 2)
        mgr.SBV(0, 2)
        mgr.SBV(1, 2)

        # Overflow and Underflow
        with self.assertRaises(ValueError):
            mgr.SBV(2, 2)
        with self.assertRaises(ValueError):
            mgr.SBV(-3, 2)

        # These should work without exceptions
        mgr.BV(0, 2)
        mgr.BV(1, 2)
        mgr.BV(2, 2)
        mgr.BV(3, 2)
        # Overflow
        with self.assertRaises(ValueError):
            mgr.BV(4, 2)
        # No negative number allowed
        with self.assertRaises(ValueError):
            mgr.BV(-1, 2)

        # SBV should behave as BV for positive numbers
        self.assertEqual(mgr.SBV(10, 16), mgr.BV(10, 16))

        return
Ejemplo n.º 25
0
    def test_bv(self):
        mgr = self.env.formula_manager
        BV = mgr.BV

        # Constants
        one = BV(1, 32)
        zero = BV(0, 32)
        big = BV(127, 128)
        binary = BV("111")
        binary2 = BV("#b111")
        binary3 = BV(0b111, 3) # In this case we need to explicit the width

        self.assertEqual(binary, binary2)
        self.assertEqual(binary2, binary3)
        self.assertEqual(one, mgr.BVOne(32))
        self.assertEqual(zero, mgr.BVZero(32))

        # Type Equality
        self.assertTrue(BV32 != BV128)
        self.assertFalse(BV32 != BV32)
        self.assertFalse(BV32 == BV128)
        self.assertTrue(BV32 == BV32)

        with self.assertRaises(PysmtValueError):
            # Negative numbers are not supported
            BV(-1, 10)
        with self.assertRaises(PysmtValueError):
            # Number should fit in the width
            BV(10, 2)

        # Variables
        b128 = Symbol("b", BV128) # BV1, BV8 etc. are defined in pysmt.typing
        b32 = Symbol("b32", BV32)
        hexample = BV(0x10, 32)
        bcustom = Symbol("bc", BVType(42))

        self.assertIsNotNone(hexample)
        self.assertIsNotNone(bcustom)
        self.assertEqual(bcustom.bv_width(), 42)
        self.assertEqual(hexample.constant_value(), 16)

        not_zero32 = mgr.BVNot(zero)
        not_b128 = mgr.BVNot(b128)
        self.assertTrue(not_b128.is_bv_not())

        f1 = Equals(not_zero32, b32)
        f2 = Equals(not_b128, big)
        self.assertTrue(is_sat(f1, logic=QF_BV))
        self.assertTrue(is_sat(f2, logic=QF_BV))

        zero_and_one = mgr.BVAnd(zero, one)
        self.assertTrue(zero_and_one.is_bv_and())
        zero_or_one = mgr.BVOr(zero, one)
        self.assertTrue(zero_or_one.is_bv_or())
        zero_xor_one = mgr.BVXor(zero, one)
        self.assertTrue(zero_xor_one.is_bv_xor())

        zero_xor_one.simplify()
        self.assertTrue(zero_xor_one.is_bv_op())

        f1 = Equals(zero_and_one, b32)
        f2 = Equals(zero_or_one, b32)
        f3 = Equals(zero_xor_one, b32)
        f4 = Equals(zero_xor_one, one)

        self.assertTrue(is_sat(f1, logic=QF_BV), f1)
        self.assertTrue(is_sat(f2, logic=QF_BV), f2)
        self.assertTrue(is_sat(f3, logic=QF_BV), f3)
        self.assertTrue(is_valid(f4, logic=QF_BV), f4)

        with self.assertRaises(PysmtTypeError):
            mgr.BVAnd(b128, zero)

        f = mgr.BVAnd(b32, zero)
        f = mgr.BVOr(f, b32)
        f = mgr.BVXor(f, b32)
        f = Equals(f, zero)

        self.assertTrue(is_sat(f, logic=QF_BV), f)

        zero_one_64 = mgr.BVConcat(zero, one)
        one_zero_64 = mgr.BVConcat(one, zero)
        one_one_64  = mgr.BVConcat(one, one)
        self.assertTrue(one_one_64.is_bv_concat())
        self.assertFalse(one_one_64.is_bv_and())

        self.assertTrue(zero_one_64.bv_width() == 64)
        f1 = Equals(mgr.BVXor(one_zero_64, zero_one_64),
                    one_one_64)

        self.assertTrue(is_sat(f1, logic=QF_BV), f1)

        # MG: BV indexes grow to the left.
        # This is confusing and we should address this.
        extraction = mgr.BVExtract(zero_one_64, 32, 63)
        self.assertTrue(is_valid(Equals(extraction, zero)))

        ult = mgr.BVULT(zero, one)
        self.assertTrue(ult.is_bv_ult())
        neg = mgr.BVNeg(one)
        self.assertTrue(neg.is_bv_neg())
        self.assertTrue(is_valid(ult, logic=QF_BV), ult)
        test_eq = Equals(neg, one)
        self.assertTrue(is_unsat(test_eq, logic=QF_BV))

        f = zero
        addition = mgr.BVAdd(f, one)
        self.assertTrue(addition.is_bv_add())
        multiplication = mgr.BVMul(f, one)
        self.assertTrue(multiplication.is_bv_mul())
        udiv = mgr.BVUDiv(f, one)
        self.assertTrue(udiv.is_bv_udiv())

        self.assertTrue(is_valid(Equals(addition, one), logic=QF_BV), addition)
        self.assertTrue(is_valid(Equals(multiplication, zero), logic=QF_BV), multiplication)
        self.assertTrue(is_valid(Equals(udiv, zero), logic=QF_BV), udiv)

        three = mgr.BV(3, 32)
        two = mgr.BV(2, 32)
        self.assertEqual(3, three.bv2nat())

        reminder = mgr.BVURem(three, two)
        self.assertTrue(reminder.is_bv_urem())
        shift_l_a = mgr.BVLShl(one, one)
        self.assertTrue(shift_l_a.is_bv_lshl())
        shift_l_b = mgr.BVLShl(one, 1)

        self.assertTrue(is_valid(Equals(reminder, one)), reminder)
        self.assertEqual(shift_l_a, shift_l_b)
        self.assertTrue(is_valid(Equals(shift_l_a, two)))

        shift_r_a = mgr.BVLShr(one, one)
        self.assertTrue(shift_r_a.is_bv_lshr())
        shift_r_b = mgr.BVLShr(one, 1)
        self.assertEqual(shift_r_a, shift_r_b)
        self.assertTrue(is_valid(Equals(shift_r_a, zero)))

        ashift_r_a = mgr.BVAShr(one, one)
        ashift_r_b = mgr.BVAShr(one, 1)
        self.assertEqual(ashift_r_a, ashift_r_b)
        self.assertTrue(ashift_r_a.is_bv_ashr())

        rotate_l = mgr.BVRol(one, 3)
        self.assertTrue(rotate_l.is_bv_rol())
        rotate_r = mgr.BVRor(rotate_l, 3)
        self.assertTrue(rotate_r.is_bv_ror())
        self.assertTrue(is_valid(Equals(one, rotate_r)))

        zero_ext = mgr.BVZExt(one, 64)
        self.assertTrue(zero_ext.is_bv_zext())
        signed_ext = mgr.BVSExt(one, 64)
        self.assertTrue(signed_ext.is_bv_sext())
        signed_ext2 = mgr.BVSExt(mgr.BVNeg(one), 64)

        self.assertNotEqual(signed_ext2, signed_ext)
        self.assertTrue(is_valid(Equals(zero_ext, signed_ext), logic=QF_BV))

        x = Symbol("x")
        g = And(x, mgr.BVULT(zero, one))

        res = is_sat(g, logic=QF_BV)
        self.assertTrue(res)

        model = get_model(g, logic=QF_BV)
        self.assertTrue(model[x] == TRUE())

        gt_1 = mgr.BVUGT(zero, one)
        gt_2 = mgr.BVULT(one, zero)
        self.assertEqual(gt_1, gt_2)

        gte_1 = mgr.BVULE(zero, one)
        gte_2 = mgr.BVUGE(one, zero)
        self.assertEqual(gte_1, gte_2)

        self.assertTrue(is_valid(gte_2, logic=QF_BV))

        ide = Equals(mgr.BVNeg(BV(10, 32)), mgr.SBV(-10, 32))
        self.assertValid(ide, logic=QF_BV)

        # These should work without exceptions
        mgr.SBV(-2, 2)
        mgr.SBV(-1, 2)
        mgr.SBV(0, 2)
        mgr.SBV(1, 2)

        # Overflow and Underflow
        with self.assertRaises(PysmtValueError):
            mgr.SBV(2, 2)
        with self.assertRaises(PysmtValueError):
            mgr.SBV(-3, 2)

        # These should work without exceptions
        mgr.BV(0, 2)
        mgr.BV(1, 2)
        mgr.BV(2, 2)
        mgr.BV(3, 2)
        # Overflow
        with self.assertRaises(PysmtValueError):
            mgr.BV(4, 2)
        # No negative number allowed
        with self.assertRaises(PysmtValueError):
            mgr.BV(-1, 2)

        # SBV should behave as BV for positive numbers
        self.assertEqual(mgr.SBV(10, 16), mgr.BV(10, 16))

        # Additional is_bv_* tests
        f = mgr.BVSub(one, one)
        self.assertTrue(f.is_bv_sub())

        f = mgr.BVSLT(one, one)
        self.assertTrue(f.is_bv_slt())
        f = mgr.BVSLE(one, one)
        self.assertTrue(f.is_bv_sle())
        f = mgr.BVComp(one, one)
        self.assertTrue(f.is_bv_comp())
        f = mgr.BVSDiv(one, one)
        self.assertTrue(f.is_bv_sdiv())
        f = mgr.BVSRem(one, one)
        self.assertTrue(f.is_bv_srem())
        f = mgr.BVULE(one, one)
        self.assertTrue(f.is_bv_ule())
Ejemplo n.º 26
0
from pysmt.shortcuts import And, Symbol, LE, GE, Int, Equals, Plus, Times, is_sat, get_model
from pysmt.typing import INT


hello = [Symbol(s, INT) for s in "hello"]
world = [Symbol(s, INT) for s in "world"]

letters = set(hello+world)

domains = And([And( LE(Int(1), l),
                    GE(Int(10), l) ) for l in letters])


sum_hello = Plus(hello)
sum_world = Plus(world)


problem = And(Equals(sum_hello, sum_world),
              Equals(sum_hello, Int(25)))

formula = And(domains, problem)

print("Printing model:")
print(get_model(formula))
Ejemplo n.º 27
0
    And(ExactlyOne(color(i, c) for i in Houses) for c in Color),
    And(ExactlyOne(nat(i, c) for i in Houses) for c in Nat),
    And(ExactlyOne(pet(i, c) for i in Houses) for c in Pet),
    And(ExactlyOne(drink(i, c) for i in Houses) for c in Drink),
    And(ExactlyOne(smoke(i, c) for i in Houses) for c in Smoke),
    #
    And(ExactlyOne(color(i, c) for c in Color) for i in Houses),
    And(ExactlyOne(nat(i, c) for c in Nat) for i in Houses),
    And(ExactlyOne(pet(i, c) for c in Pet) for i in Houses),
    And(ExactlyOne(drink(i, c) for c in Drink) for i in Houses),
    And(ExactlyOne(smoke(i, c) for c in Smoke) for i in Houses),
    )

problem = And(domain, facts)

model = get_model(problem)

if model is None:
    print("UNSAT")
    # We first check whether the constraints on the domain and problem
    # are satisfiable in isolation.
    assert is_sat(facts)
    assert is_sat(domain)
    assert is_unsat(problem)

    # In isolation they are both fine, rules from both are probably
    # interacting.
    #
    # The problem is given by a nesting of And().
    # conjunctive_partition can be used to obtain a "flat"
    # structure, i.e., a list of conjuncts.
Ejemplo n.º 28
0
            # Otherwise IntToStr returns the empty string
            randint >= 0)
    return s, f

# Create a strong passowrd from the initial one
new_password, constr = strengthen_password(password_in)

# If the input password is strong, if not, use the strengthen_password
check = And(password_out.Equals(Ite(is_good_password(password_in),
                                    password_in,
                                    new_password)),
            constr)

# Run the example by providing an example password to be checked
import sys
if len(sys.argv) >= 2:
    user_pass = sys.argv[1]
else:
    print("Usage %s <password>" % sys.argv[0])
    user_pass = "******"

m1 = get_model(And(password_in.Equals(String(user_pass)),
                  check))
print(m1[password_out])

# Is our 'strengthen' procedure always yielding a strong password?
# Can you think of an input that would not be properly sanitized?
m2 = get_model(And(check,
                   Not(is_good_password(password_out))))
print(m2[password_in])
Ejemplo n.º 29
0
def app(args):
    # sample data from the corners of the unit HyperCube
    n_layers = 1
    n_data = [10, 100, 1000, 10000, 100000]
    n_weight = [2, 4, 8, 16, 32]
    data_dimension = [2, 4, 8, 16, 32]#, 3, 4]#, 8, 16, 32, 64, 128, 256, 512, 1024]
    for n_weights, dim in zip(n_weight, data_dimension):
        for n_samples in n_data:
            data, labels = generate_iid_samples(dim, n_samples)
            if args.verbose:
                print ('generated data for dim={}: {}'.format(dim, list(zip(data, labels))))
            
            training_symbols = []
            label_symbols = []
            # Create symbolic representation of data
            training_symbols = [Symbol('input_{}'.format(i), BOOL) for i in range(len(data))]
            label_symbols = [Symbol('label_{}'.format(i), REAL) for i in range(len(labels))]
            
            bin_x = np.array([np.binary_repr(sample, width=dim) for sample in data])
            layers = []
            layer_input = bin_x
            weights = []
            for layer in range(n_layers):
                
                weight_symbols = [Symbol('weight_{}'.format(i), REAL) for i in range(n_weights)]
                weights.extend(weight_symbols)
                bias_symbol = Symbol('bias_{}'.format(layer), REAL)
                
                layer_domains = []
                for i in range(len(layer_input)):  # loop over data
                    # \sum <w_ji,  x_i> + b_i
                    weight_input_i = Plus([Times(w_j, Real(int(x_j))) for w_j, x_j in zip(weight_symbols, layer_input[i])])
                    prod_bias_i = Plus(weight_input_i, bias_symbol)

                    layer_domain = Equals(prod_bias_i, Real(labels[i]))

                    layer_domains.append(layer_domain)
                layer = And(x for x in layer_domains)
                layers.append(layer)
            
            network_domain = And([x for x in layers])  
            dnn_problem = network_domain
            if args.verbose:
                print ('DNN [Boolean expression]: ', dnn_problem)
            print ('DNN [Satisfiable?]: ', is_sat(dnn_problem))
            if is_sat(dnn_problem):
                model = get_model(dnn_problem)
                print (model)
            else:
                print ('[DNN] not satisfiable')
                break

            with Solver(name='msat') as solver:
                solver.add_assertion(dnn_problem)
                if solver.solve():
                    # extract_values
                    weights = [float(solver.get_py_value(w)) for w in weights]
                    bias = float(solver.get_py_value(bias_symbol))
                
                # evaluate model on generated weights
                eval_smt_dnn(x=bin_x, w=weights, b=bias, y=labels)
Ejemplo n.º 30
0
#                 # could get 'dump', 'value', 'xf_index'
#               #  print thecell.value,
#                 xfx = sheet.cell_xf_index(row, col)
#                 xf = book.xf_list[xfx]
#                 bgx = xf.background.pattern_colour_index
#               #  print bgx
#                 color_set.add(bgx)
#     print(color_set)
#     return color_set
#
#

if __name__ == "__main__":
    workers, jobs = load_data()

    k = IntervalTree()
    # for w in workers:
    #     k = k|w.availability
    #
    # print(k)
    #
    # exit(0)

    print(workers)
    const = get_constraints(jobs, workers)
    formula = And(const)
    model = get_model(formula)
    if model:
        print(model)
    else:
        print("No solution found")
Ejemplo n.º 31
0
 def timed_get_model(*args, **kwargs):
     return get_model(*args, **kwargs)
Ejemplo n.º 32
0
    And(ExactlyOne(color(i, c) for i in Houses) for c in Color),
    And(ExactlyOne(nat(i, c) for i in Houses) for c in Nat),
    And(ExactlyOne(pet(i, c) for i in Houses) for c in Pet),
    And(ExactlyOne(drink(i, c) for i in Houses) for c in Drink),
    And(ExactlyOne(smoke(i, c) for i in Houses) for c in Smoke),
    #
    And(ExactlyOne(color(i, c) for c in Color) for i in Houses),
    And(ExactlyOne(nat(i, c) for c in Nat) for i in Houses),
    And(ExactlyOne(pet(i, c) for c in Pet) for i in Houses),
    And(ExactlyOne(drink(i, c) for c in Drink) for i in Houses),
    And(ExactlyOne(smoke(i, c) for c in Smoke) for i in Houses),
)

problem = And(domain, facts)

model = get_model(problem)

if model is None:
    print("UNSAT")
    # We first check whether the constraints on the domain and problem
    # are satisfiable in isolation.
    assert is_sat(facts)
    assert is_sat(domain)
    assert is_unsat(problem)

    # In isolation they are both fine, rules from both are probably
    # interacting.
    #
    # The problem is given by a nesting of And().
    # conjunctive_partition can be used to obtain a "flat"
    # structure, i.e., a list of conjuncts.
Ejemplo n.º 33
0
def processor(config_file_name):
    var_str = []
    coefficients = []
    constrnt_mins = []
    constrnt_maxes = []
    constraint_terms = []
    num_vars = []
    num_expr = []
    terms = []
    eqn_mins = []
    eqn_maxes = []

    readfile(config_file_name, var_str, coefficients, constrnt_mins,
             constrnt_maxes, constraint_terms, num_vars, num_expr, eqn_mins,
             eqn_maxes)
    nvars = num_vars[0]
    nexpr = num_expr[0]
    symbols = [Symbol(X, REAL) for X in sorted(var_str)]
    symbols.append(Symbol("c", REAL))

    for x in itertools.combinations_with_replacement(symbols, 2):
        terms.append(x)
    for i in range(0, len(terms), 1):
        terms[i] = list(terms[i])
    for i in range(0, len(terms), 1):
        if (Symbol("c", REAL) in terms[i]):
            terms[i].remove(Symbol("c", REAL))
    # [('x1', 'x1'), ('x1', 'x2'), ('x1', 'c'), ('x2', 'x2'), ('x2', 'c'), ('c', 'c')]
    sorted(terms, key=lambda elem: elem[0])
    #print(terms)
    variables = set(symbols)
    d = []
    j = 0
    for CONSTRAINT in constraint_terms:
        C = []
        for i in range(0, len(CONSTRAINT), 1):
            if (symbols[i] == Symbol("c", REAL)):
                C.append(Real(CONSTRAINT[i]))
            else:
                C.append(Times(Real(CONSTRAINT[i]), symbols[i]))
        C = Plus(C)
        d.append(
            And(GE(C, Real(constrnt_mins[j])), LT(C, Real(constrnt_maxes[j]))))
        j = j + 1

    domains = And(d)
    eqns = []
    i = 0
    for expr in coefficients:
        cur = []
        j = 0
        for term in expr:
            if (len(terms[j]) == 2):
                cur.append(Times(Real(float(term)), Times(terms[j])))
            elif (Symbol("c", REAL) in terms[j]):
                cur.append(Real(float(term)))
            else:
                cur.append(Times(Real(float(term)), terms[j][0]))
            j = j + 1
        cur = Plus(cur)
        eqns.append(cur)
        i = i + 1
    formulas = []
    models = []
    satisfiable = bool(True)
    i = 0
    for eqn in eqns:
        p0 = And(domains, GE(Min(eqn), Real(float(eqn_mins[i]))))
        p1 = And(domains, LT(Max(eqn), Real(float(eqn_maxes[i]))))
        formulas.append(p0)
        formulas.append(p1)
        models.append(get_model(p0))
        models.append(get_model(p1))
        i = i + 1
    out_str = ""
    i = 0
    j = 0
    postfix = ["min satisfiability", "max satisfiability"]
    pat = re.compile(r'\d+/\d+')
    for model in models:
        print("\tModel {} {}: ".format(str(i), postfix[j % 2]))
        #formula_str = model.print#str(formulas[i].serialize())
        cur_str = pysmt.shortcuts.simplify(formulas[j]).serialize().replace(
            "&", "\n\t\t\t&")
        cur_str = re.sub(
            pat, lambda match: "{0}".format(
                str(
                    float(str(match.group()).split("/")[0]) / float(
                        str(match.group()).split("/")[1]))), cur_str)

        if model:
            print("\t\tSerialization of the formula:")

            print("\t\t\t" + cur_str)

            #temp_strs = formula_str.split("&")
            #for k in range(1,len(temp_strs)):
            #  temp_strs[k] = "& " + temp_strs[k]
            #formula_strs = []
            #for s in temp_strs:
            #  t = s.split(" + ")
            #  ts = []
            #  ts.append(t[0])
            #  for k in range(1,len(t)):
            #    ts.append(" + " + t[k])
            #  new_t = [a+b+c+d for a,b,c,d in zip(*[iter(ts)]*4)]
            #  final = ""
            #  for k in range(len(ts) - (len(ts) % 4), len(ts),1):
            #    final = final + ts[k]
            #  new_t.append(final)
            #  formula_strs.append(new_t)

            #for s in formula_strs:
            #  print("\t\t\t%s" % s)
            print("\t\tSolution: ")
            model_str = str(model)
            model_str = model_str.replace("\n", "\n\t\t\t")
            print("\t\t\t%s" % model_str)
        else:
            print("\t\tSerialization of the formula: ")
            print("\t\t\t%s" % cur_str)
            print("\t\tNo solution found")
            satisfiable = False
        if j % 2 == 1:
            i = i + 1
        j = j + 1
    print("\tResult: ")
    if (satisfiable):
        print("\t\tThe problem is satisfiable using the solutions given.")
    else:
        print("\t\tThe problem is not satisfiable")

    return satisfiable
Ejemplo n.º 34
0
    all_classes,

    #prereqs_init,
    prereqs_only,
    coreqs_only,
    already_taken_courses,
    not_yet_taken_courses,
    electives_courses,
    restrict_electives,
    csm101,
    fall_courses,
    spring_courses,
    other_courses)

print("Generate model")
model = get_model(facts_domain, solver_name=args.solver)

#print model
if model is None:
    print("UNSAT")
    print("Please verify that the student fields are correct.")
    # In isolation they are both fine, rules from both are probably
    # interacting.
    #
    # The problem is given by a nesting of And().
    # conjunctive_partition can be used to obtain a "flat"
    # structure, i.e., a list of conjuncts.
    #
    from pysmt.rewritings import conjunctive_partition
    conj = conjunctive_partition(facts_domain)
    ucore = get_unsat_core(conj)
Ejemplo n.º 35
0
    prefixes_f, prefixes_r, suffixes_f, suffixes_r = enumerate_fixes(train)
    G  = build_distinguishability_graph(train, prefixes_r, suffixes_r)

    clique = dfa_clique_approx(G, train, prefixes_r)
    states = len(clique)
    state_limit = 13
    total_time = 0

    while True:
        print(f'Building problem for {states} states')
        x, y, z, model_c = min_dfa_setup_model(train, prefixes_f, prefixes_r, G, sigma, states)
        symmetry_c = break_dfa_symmetry_bfs(x, y, sigma, prefixes_r, states)
        # symmetry_c = break_dfa_symmetry_clique(x, clique)
        start_time = time.perf_counter()
        print(f'Starting solver: {len(model_c) + len(symmetry_c)} constraints')
        model = get_model(And(*model_c, *symmetry_c).simplify(), 'z3')
        end_time = time.perf_counter()
        solve_time = end_time - start_time
        total_time += solve_time
        print(f"Took {solve_time:.4f} seconds")

        if model: break

        states += 1
        if states > state_limit: break

    print(f'Found solution with {states} states!')
    print(f'Took {total_time:.4f} seconds')

    dfa = extract_dfa(model, x, y, z, sigma, prefixes_r, states)
Ejemplo n.º 36
0
def iterate_to_find_satisfiable_solution(features, feature_implimentation_time,
                                         dependencies, sequential, developers,
                                         feature_developer, parallel_tasks,
                                         end_time):

    feature_time_map = {}
    i = 1
    for fe in features:
        feature_time_map[fe] = {
            'EndTime': Symbol('E' + str(i), INT),
            'StartTime': Symbol('S' + str(i), INT),
            'Duration': Int(feature_implimentation_time[i - 1])
        }
        i += 1

    b_greater = And(
        And(GE(feature_time_map[fe]['EndTime'], Int(0)),
            GE(feature_time_map[fe]['StartTime'], Int(0))) for fe in features)

    b_impli_time = And(
        Equals(
            Minus(feature_time_map[l]['EndTime'], feature_time_map[l]
                  ['StartTime']), feature_time_map[l]['Duration'])
        for l in features)

    b_dependencies = And(
        GE(feature_time_map[depe[1]]['StartTime'], feature_time_map[depe[0]]
           ['EndTime']) for depe in dependencies)

    b_sequential = And(
        Or(
            GE(feature_time_map[seq[1]]['StartTime'], feature_time_map[seq[0]]
               ['EndTime']),
            GE(feature_time_map[seq[0]]['StartTime'], feature_time_map[seq[1]]
               ['EndTime'])) for seq in sequential)

    developer_feature_imp = {}
    for fet_dev in feature_developer:
        developer_feature_imp.setdefault(fet_dev[1], []).append(fet_dev[0])

    and_relation = []
    for val in developer_feature_imp.values():
        if len(val) > 1:
            for comb in combinations(val, 2):
                and_relation.append(
                    Or(
                        GE(feature_time_map[comb[1]]['StartTime'],
                           feature_time_map[comb[0]]['EndTime']),
                        GE(feature_time_map[comb[0]]['StartTime'],
                           feature_time_map[comb[1]]['EndTime'])))
    b_dev_pararale = And(and_relation)
    and_parallel = []
    for val in parallel_tasks:
        and_parallel.append(
            And(
                LE(feature_time_map[val[0]]['StartTime'],
                   feature_time_map[val[1]]['StartTime']),
                GE(feature_time_map[val[0]]['EndTime'],
                   feature_time_map[val[1]]['StartTime'])))

    b_parallel = And(and_parallel)

    print('++++++++++++++Conditions++++++++++++++++')
    print('Start and End times should be grater than zero : ', b_greater)
    print('Difference between end and start times : ', b_impli_time)
    print('Some features should be implimented first : ', b_dependencies)
    print('Some features can not be executed parallelly : ', b_sequential)
    print('Some features need specific developers : ', b_dev_pararale)
    print('Some features need to be started before ending some features : ',
          b_parallel)

    print('++++++++++++++Release Dates++++++++++++++++')
    end_time = 1
    max_end_time = sum(feature_implimentation_time)
    sloved = False
    for end in tqdm(range(max_end_time),
                    'running binary search to find shortest release date'):

        b_end_time = And(
            LE(fe['EndTime'], Int(end_time))
            for fe in feature_time_map.values())
        formula = And(b_greater, b_impli_time, b_dependencies, b_sequential,
                      b_dev_pararale, b_end_time, b_parallel)

        if is_sat(formula):
            print('\n' + 'You have to spend at least', end_time,
                  'days to finish your next release')
            print('Therefore, the closest release date is :',
                  (datetime.today() +
                   timedelta(end_time)).strftime('%d/%m/%Y'))
            for key, val in feature_time_map.items():
                print(
                    'Feature', key, ', Start Date :',
                    (datetime.today() + timedelta(
                        get_model(formula)[val['StartTime']].constant_value())
                     ).strftime('%d/%m/%Y'), '-> End Date : ',
                    (datetime.today() + timedelta(
                        get_model(formula)[val['EndTime']].constant_value())
                     ).strftime('%d/%m/%Y'))
            sloved = True
            break
        end_time += 1
    if sloved == False:
        print("This problem is not solvable")

    # print(b_devlopers)
    # print(is_sat(b_devlopers))

    return len(formula.serialize()), 'S' if is_sat(formula) else 'U'
Ejemplo n.º 37
0
from pysmt.shortcuts import Symbol, And, GE, LT, Plus, Equals, Int, get_model
from pysmt.typing import INT

hello = [Symbol(s, INT) for s in "hello"]
world = [Symbol(s, INT) for s in "world"]
letters = set(hello + world)
domains = And([And(GE(l, Int(1)), LT(l, Int(10))) for l in letters])
print domains

sum_hello = Plus(hello)  # n-ary operators can take lists
sum_world = Plus(world)  # as arguments
problem = And(Equals(sum_hello, sum_world), Equals(sum_hello, Int(25)))
formula = And(domains, problem)

print("Serialization of the formula:")
print(formula)

model = get_model(formula)
if model:
    print(model)
else:
    print("No solution found")
Ejemplo n.º 38
0
        StrLength(s) >= 10,
        # And that randint is a natural number
        # Otherwise IntToStr returns the empty string
        randint >= 0)
    return s, f


# Create a strong passowrd from the initial one
new_password, constr = strengthen_password(password_in)

# If the input password is strong, if not, use the strengthen_password
check = And(
    password_out.Equals(
        Ite(is_good_password(password_in), password_in, new_password)), constr)

# Run the example by providing an example password to be checked
import sys
if len(sys.argv) >= 2:
    user_pass = sys.argv[1]
else:
    print("Usage %s <password>" % sys.argv[0])
    user_pass = "******"

m1 = get_model(And(password_in.Equals(String(user_pass)), check))
print(m1[password_out])

# Is our 'strengthen' procedure always yielding a strong password?
# Can you think of an input that would not be properly sanitized?
m2 = get_model(And(check, Not(is_good_password(password_out))))
print(m2[password_in])
Ejemplo n.º 39
0
    def test_sample(self, sample):
        """
            Check whether or not the encoding "predicts" the same class
            as the classifier given an input sample.
        """

        # first, compute the scores for all classes as would be
        # predicted by the classifier

        # score arrays computed for each class
        csum = [[] for c in range(self.nofcl)]

        if self.optns.verb:
            print('testing sample:', list(sample))

        sample_internal = list(self.xgb.transform(sample)[0])

        # traversing all trees
        for i, tree in enumerate(self.ensemble.trees):
            # getting class id
            clid = i % self.nofcl

            # a score computed by the current tree
            score = scores_tree(tree, sample_internal)

            # this tree contributes to class with clid
            csum[clid].append(score)

        # final scores for each class
        cscores = [sum(scores) for scores in csum]

        # second, get the scores computed with the use of the encoding

        # asserting the sample
        hypos = []

        if not self.intvs:
            for i, fval in enumerate(sample_internal):
                feat, vid = self.xgb.transform_inverse_by_index(i)
                fid = self.feats[feat]

                if vid == None:
                    fvar = Symbol('f{0}'.format(fid), typename=REAL)
                    hypos.append(Equals(fvar, Real(float(fval))))
                else:
                    fvar = Symbol('f{0}_{1}'.format(fid, vid), typename=BOOL)
                    if int(fval) == 1:
                        hypos.append(fvar)
                    else:
                        hypos.append(Not(fvar))
        else:
            for i, fval in enumerate(sample_internal):
                feat, _ = self.xgb.transform_inverse_by_index(i)
                feat = 'f{0}'.format(self.feats[feat])

                # determining the right interval and the corresponding variable
                for ub, fvar in zip(self.intvs[feat], self.ivars[feat]):
                    if ub == '+' or fval < ub:
                        hypos.append(fvar)
                        break
                else:
                    assert 0, 'No proper interval found for {0}'.format(feat)

        # now, getting the model
        escores = []
        model = get_model(And(self.enc, *hypos), solver_name=self.optns.solver)
        for c in range(self.nofcl):
            v = Symbol('class{0}_score'.format(c), typename=REAL)
            escores.append(float(model.get_py_value(v)))

        assert all(map(lambda c, e: abs(c - e) <= 0.001, cscores, escores)), \
                'wrong prediction: {0} vs {1}'.format(cscores, escores)

        if self.optns.verb:
            print('xgb scores:', cscores)
            print('enc scores:', escores)
Ejemplo n.º 40
0
from pysmt.shortcuts import And, Symbol, LE, GE, Int, Equals, Plus, Times, is_sat, get_model
from pysmt.typing import INT

hello = [Symbol(s, INT) for s in "hello"]
world = [Symbol(s, INT) for s in "world"]

letters = set(hello + world)

domains = And([And(LE(Int(1), l), GE(Int(10), l)) for l in letters])

sum_hello = Plus(hello)
sum_world = Plus(world)

problem = And(Equals(sum_hello, sum_world), Equals(sum_hello, Int(25)))

formula = And(domains, problem)

print("Printing model:")
print(get_model(formula))