Python z3.And() Examples

The following are 20 code examples of z3.And(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module z3 , or try the search function .
Example #1
Source File: find_name_for_bits.py    From on-pwning with MIT License 8 votes vote down vote up
def find_name_for_bit_at_index(index, bit):
    solver = z3.Solver()

    NAME_LENGTH = 12  # arbitrary
    name = [z3.BitVec("c%d" % i, 32) for i in range(NAME_LENGTH)]
    for i in range(len(name)):
        solver.add(z3.And(name[i] > 0, name[i] <= 0xff))

    h1 = hash1(name)
    solver.add(h1 == index)

    h2 = hash2(name)
    solver.add(h2 == bit)

    h3 = hash3(name)
    solver.add(z3.Extract(15, 0, h3) == h2)  # for simplicity

    if solver.check() == z3.sat:
        return "".join(chr(solver.model()[c].as_long()) for c in name).encode("latin-1") 
Example #2
Source File: hoare_opt.py    From qiskit-terra with Apache License 2.0 6 votes vote down vote up
def _seq_as_one(self, sequence):
        """ use z3 solver to determine if the gates in the sequence are either
            all executed or none of them are executed, based on control qubits
            (consider sequences of length 2 for now)
        Args:
            sequence (list(DAGNode)): gate sequence to inspect
        Returns:
            bool: if gate sequence is only executed completely or not at all
        """
        assert len(sequence) == 2
        ctrlvar1 = self._seperate_ctrl_trgt(sequence[0])[1]
        ctrlvar2 = self._seperate_ctrl_trgt(sequence[1])[1]

        self.solver.push()
        self.solver.add(
            Or(
                And(And(*ctrlvar1), Not(And(*ctrlvar2))),
                And(Not(And(*ctrlvar1)), And(*ctrlvar2))
            )
        )
        res = self.solver.check() == unsat
        self.solver.pop()

        return res 
Example #3
Source File: mlil_ast.py    From f-ing-around-with-binaryninja with MIT License 6 votes vote down vote up
def _convert_to_while_loop(
        self, node: MediumLevelILAstLoopNode, while_condition
    ):
        log_debug(f"{node} is a while loop")
        node.loop_type = "while"
        node.condition = reduce(
            And, Tactic("ctx-solver-simplify")(Not(while_condition))[0]
        )

        break_cond = node.body.nodes[0]

        if break_cond[False] is not None:
            node.body._nodes[0] = break_cond[False]

        # Flatten condition nodes that have the same condition
        # as the loop condition
        for idx, child in enumerate(node.body.nodes):
            if (
                isinstance(child, MediumLevelILAstCondNode)
                and is_true(simplify(child.condition == node.condition))
                and child[False] is None
            ):
                node.body._nodes[idx] = child[True] 
Example #4
Source File: solver.py    From tea-lang with Apache License 2.0 6 votes vote down vote up
def construct_axioms(variables):  # List[StatVar]
    _axioms = []
    for var in variables:
        # A variable must be continuous or categorical, but not both.
        _axioms.append(z3.And(z3.Or(continuous(var).__z3__, categorical(var).__z3__),
                              z3.Not(z3.And(continuous(var).__z3__, categorical(var).__z3__))))

        # If a variable is an explanatory variable and all explanatory variables are categorical,
        # then the variable must be categorical.
        # It isn't clear how to reason about whether a variable is an explanatory or explained variable.
        # _axioms.append(z3.Implies(all_x_variables_categorical(var).__z3__, categorical(var).__z3__))

        # Not sure how to reason about test properties like one_x_variable and one_y_variable.
        # _axioms.append(z3.Not(z3.And(one_x_variable(var).__z3__, one_y_variable(var).__z3__)))

        # If a variable is normal, then it cannot be categorical.
        _axioms.append(z3.Implies(normal(var).__z3__, z3.Not(categorical(var).__z3__)))

        # If a variable is continuous or ordinal, it must be continuous.
        _axioms.append(z3.Implies(continuous_or_ordinal(var).__z3__, continuous(var).__z3__))

        # If a variable has two categories, then it must be categorical.
        # _axioms.append(z3.Implies(two_x_variable_categories(var).__z3__, categorical(var).__z3__))

    return _axioms 
Example #5
Source File: z3_common.py    From acsploit with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _generate_ascii_printable_string(base_name, size, solver):
    # establishes z3 variable names for bytes of the input string
    bytes = [z3.BitVec('%s%d' % (base_name, i), 8) for i in range(size)]
    # adds the constraint that the bytes are printable ascii
    solver.add(z3.And([_ascii_printable(byte) for byte in bytes]))
    return bytes 
Example #6
Source File: AST.py    From jeeves with MIT License 5 votes vote down vote up
def remapLabels(self, policy, writer):
		return And(
				self.left.remapLabels(policy, writer)
			, self.right.remapLabels(policy, writer)) 
Example #7
Source File: AST.py    From jeeves with MIT License 5 votes vote down vote up
def z3Node(self):
		return z3.And(self.left.z3Node(), self.right.z3Node()) 
Example #8
Source File: AST.py    From jeeves with MIT License 5 votes vote down vote up
def __rand__(r, l):
		return And(fexpr_cast(l), r)

	# The | operator 
Example #9
Source File: AST.py    From jeeves with MIT License 5 votes vote down vote up
def __and__(l, r):
		return And(l, fexpr_cast(r)) 
Example #10
Source File: solver.py    From cozy with Apache License 2.0 5 votes vote down vote up
def all(self, *conds): return self.bfold(conds, z3.And, True, False) 
Example #11
Source File: z3_common.py    From acsploit with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _ascii_printable(x):
    return z3.And(0x21 <= x, x <= 0x7e)  # enforces that byte is printable ascii 
Example #12
Source File: svm_utils.py    From ilf with Apache License 2.0 5 votes vote down vote up
def get_wstate_z3vars(wstate):
    r = get_z3vars(z3.simplify(z3.And(wstate.constraints)))
    for address, gstate in wstate.address_to_account.items():
        r.update(get_z3vars(z3.simplify(gstate.storage.storage)))
    return r 
Example #13
Source File: depgraph.py    From miasm with GNU General Public License v2.0 5 votes vote down vote up
def _gen_path_constraints(self, translator, expr, expected):
        """Generate path constraint from @expr. Handle special case with
        generated loc_keys
        """
        out = []
        expected = canonize_to_exprloc(self._ircfg.loc_db, expected)
        expected_is_loc_key = expected.is_loc()
        for consval in possible_values(expr):
            value = canonize_to_exprloc(self._ircfg.loc_db, consval.value)
            if expected_is_loc_key and value != expected:
                continue
            if not expected_is_loc_key and value.is_loc_key():
                continue

            conds = z3.And(*[translator.from_expr(cond.to_constraint())
                             for cond in consval.constraints])
            if expected != value:
                conds = z3.And(
                    conds,
                    translator.from_expr(
                        ExprAssign(value,
                                expected))
                )
            out.append(conds)

        if out:
            conds = z3.Or(*out)
        else:
            # Ex: expr: lblgen1, expected: 0x1234
            # -> Avoid inconsistent solution lblgen1 = 0x1234
            conds = translator.from_expr(self.unsat_expr)
        return conds 
Example #14
Source File: crosstalk_adaptive_schedule.py    From qiskit-terra with Apache License 2.0 5 votes vote down vote up
def scheduling_constraints(self):
        """
        DAG scheduling constraints optimization
        Sets overlap indicator variables
        """
        for gate in self.gate_start_time:
            for dep_gate in self.dag.successors(gate):
                if not dep_gate.type == 'op':
                    continue
                if isinstance(dep_gate.op, Measure):
                    continue
                if isinstance(dep_gate.op, Barrier):
                    continue
                fin_g = self.gate_start_time[gate] + self.gate_duration[gate]
                self.opt.add(self.gate_start_time[dep_gate] > fin_g)
        for g_1 in self.xtalk_overlap_set:
            for g_2 in self.xtalk_overlap_set[g_1]:
                if len(g_2.qargs) == 2 and self.gate_id[g_1] > self.gate_id[g_2]:
                    # Symmetry breaking: create only overlap variable for a pair
                    # of gates
                    continue
                s_1 = self.gate_start_time[g_1]
                f_1 = s_1 + self.gate_duration[g_1]
                s_2 = self.gate_start_time[g_2]
                f_2 = s_2 + self.gate_duration[g_2]
                # This constraint enforces full or zero overlap between two gates
                before = (f_1 < s_2)
                after = (f_2 < s_1)
                overlap1 = And(s_2 <= s_1, f_1 <= f_2)
                overlap2 = And(s_1 <= s_2, f_2 <= f_1)
                self.opt.add(Or(before, after, overlap1, overlap2))
                intervals_overlap = And(s_2 <= f_1, s_1 <= f_2)
                self.opt.add(self.overlap_indicator[g_1][g_2] == intervals_overlap) 
Example #15
Source File: hoare_opt.py    From qiskit-terra with Apache License 2.0 5 votes vote down vote up
def _traverse_dag(self, dag):
        """ traverse DAG in topological order
            for each gate check: if any control is 0, or
                                 if triviality conditions are satisfied
            if yes remove gate from dag
            apply postconditions of gate
        Args:
            dag (DAGCircuit): input DAG to optimize in place
        """
        for node in dag.topological_op_nodes():
            gate = node.op
            _, ctrlvar, trgtqb, trgtvar = self._seperate_ctrl_trgt(node)

            ctrl_ones = And(*ctrlvar)

            trivial = self._test_gate(gate, ctrl_ones, trgtvar)
            if trivial:
                dag.remove_op_node(node)
            elif self.size > 1:
                for qbt in node.qargs:
                    self.gatecache[qbt.index].append(node)
                    self.varnum[qbt.index][node] = self.gatenum[qbt.index]-1
                for qbt in node.qargs:
                    if len(self.gatecache[qbt.index]) >= self.size:
                        self._multigate_opt(dag, qbt.index)

            self._add_postconditions(gate, ctrl_ones, trgtqb, trgtvar) 
Example #16
Source File: hoare_opt.py    From qiskit-terra with Apache License 2.0 5 votes vote down vote up
def _test_gate(self, gate, ctrl_ones, trgtvar):
        """ use z3 sat solver to determine triviality of gate
        Args:
            gate (Gate): gate to inspect
            ctrl_ones (BoolRef): z3 condition asserting all control qubits to 1
            trgtvar (list(BoolRef)): z3 variables corresponding to latest state
                                     of target qubits
        Returns:
            bool: if gate is trivial
        """
        trivial = False
        self.solver.push()

        try:
            triv_cond = gate._trivial_if(*trgtvar)
        except AttributeError:
            self.solver.add(ctrl_ones)
            trivial = self.solver.check() == unsat
        else:
            if isinstance(triv_cond, bool):
                if triv_cond and len(trgtvar) == 1:
                    self.solver.add(And(ctrl_ones, Not(trgtvar[0])))
                    sol1 = self.solver.check() == unsat
                    self.solver.pop()
                    self.solver.push()
                    self.solver.add(And(ctrl_ones, trgtvar[0]))
                    sol2 = self.solver.check() == unsat
                    trivial = sol1 or sol2
            else:
                self.solver.add(And(ctrl_ones, Not(triv_cond)))
                trivial = self.solver.check() == unsat

        self.solver.pop()
        return trivial 
Example #17
Source File: mlil_ast.py    From f-ing-around-with-binaryninja with MIT License 4 votes vote down vote up
def generate_reaching_constraints(self):
        visitor = ConditionVisitor(self.view)

        for (
            (start, end),
            reaching_condition,
        ) in self.reaching_conditions.items():
            or_exprs = []

            for condition in reaching_condition:
                and_exprs = []

                for edge in condition:
                    if edge.type == BranchType.UnconditionalBranch:
                        continue

                    if edge.type == BranchType.TrueBranch:
                        condition = edge.source[-1].condition
                        if (
                            condition.operation
                            == MediumLevelILOperation.MLIL_VAR
                        ):
                            condition = self.function.get_ssa_var_definition(
                                edge.source[-1].ssa_form.condition.src
                            ).src
                        and_exprs.append(visitor.simplify(condition))

                    elif edge.type == BranchType.FalseBranch:
                        condition = edge.source[-1].condition
                        if (
                            condition.operation
                            == MediumLevelILOperation.MLIL_VAR
                        ):
                            condition = self.function.get_ssa_var_definition(
                                edge.source[-1].ssa_form.condition.src
                            ).src
                        and_exprs += Tactic("ctx-solver-simplify")(
                            Not(visitor.simplify(condition))
                        )[0]

                if and_exprs != []:
                    or_exprs.append(And(*and_exprs))

            if or_exprs:
                or_exprs = Tactic("ctx-solver-simplify")(Or(*or_exprs))[0]
                reaching_constraint = (
                    And(*or_exprs)
                    if len(or_exprs) > 1
                    else or_exprs[0]
                    if len(or_exprs)
                    else BoolVal(True)
                )
                self._reaching_constraints[(start, end)] = reaching_constraint 
Example #18
Source File: crosstalk_adaptive_schedule.py    From qiskit-terra with Apache License 2.0 4 votes vote down vote up
def fidelity_constraints(self):
        """
        Set gate fidelity based on gate overlap conditions
        """
        for gate in self.gate_start_time:
            q_0 = gate.qargs[0].index
            no_xtalk = False
            if gate not in self.xtalk_overlap_set:
                no_xtalk = True
            elif not self.xtalk_overlap_set[gate]:
                no_xtalk = True
            if no_xtalk:
                if isinstance(gate.op, U1Gate):
                    fid = math.log(1.0)
                elif isinstance(gate.op, U2Gate):
                    fid = math.log(1.0 - self.bp_u2_err[q_0])
                elif isinstance(gate.op, U3Gate):
                    fid = math.log(1.0 - self.bp_u3_err[q_0])
                elif isinstance(gate.op, CXGate):
                    fid = math.log(1.0 - self.bp_cx_err[self.cx_tuple(gate)])
                self.opt.add(self.gate_fidelity[gate] == round(fid, NUM_PREC))
            else:
                comb = list(self.powerset(self.xtalk_overlap_set[gate]))
                xtalk_set = set(self.xtalk_overlap_set[gate])
                for item in comb:
                    on_set = item
                    off_set = [i for i in xtalk_set if i not in on_set]
                    clauses = []
                    for tmpg in on_set:
                        clauses.append(self.overlap_indicator[gate][tmpg])
                    for tmpg in off_set:
                        clauses.append(Not(self.overlap_indicator[gate][tmpg]))
                    err = 0
                    if not on_set:
                        err = self.bp_cx_err[self.cx_tuple(gate)]
                    elif len(on_set) == 1:
                        on_gate = on_set[0]
                        err = self.crosstalk_prop[self.gate_tuple(gate)][self.gate_tuple(on_gate)]
                    else:
                        err_list = []
                        for on_gate in on_set:
                            tmp_prop = self.crosstalk_prop[self.gate_tuple(gate)]
                            err_list.append(tmp_prop[self.gate_tuple(on_gate)])
                        err = max(err_list)
                    if err == 1.0:
                        err = 0.999999
                    val = round(math.log(1.0 - err), NUM_PREC)
                    self.opt.add(Implies(And(*clauses), self.gate_fidelity[gate] == val)) 
Example #19
Source File: mlil_ast.py    From f-ing-around-with-binaryninja with MIT License 4 votes vote down vote up
def _convert_to_do_while_loop(
        self, node: MediumLevelILAstLoopNode, dowhile_condition
    ):
        log_debug(f"{node} is a do while loop")
        node.loop_type = "dowhile"
        node.condition = reduce(
            And, Tactic("ctx-solver-simplify")(Not(dowhile_condition))[0]
        )

        break_cond = node.body.nodes[-1]

        if break_cond[False] is not None:
            node.body._nodes[-1] = break_cond[False]
        else:
            node.body._nodes.pop()

        # Flatten condition nodes that have the same condition
        # as the loop condition
        for idx, child in enumerate(node.body.nodes):
            if (
                isinstance(child, MediumLevelILAstCondNode)
                and is_true(simplify(child.condition == node.condition))
                and child[False] is None
            ):
                node.body._nodes[idx] = child[True]

            log_debug(f"Checking {child} for break condition")
            if isinstance(child, MediumLevelILAstCondNode) and is_false(
                simplify(And(child.condition, node.condition))
            ):
                break_instr = child[True].nodes[-1].block[-1]

                child[True]._nodes.append(
                    MediumLevelILAstBreakNode(
                        self, break_instr.instr_index, break_instr.address
                    )
                )

                new_loop_condition = self._split_break_condition(
                    node.condition, child.condition
                )

                if new_loop_condition is not None:
                    log_debug(f"new_loop_condition is {new_loop_condition}")
                    node.condition = new_loop_condition 
Example #20
Source File: solver.py    From cozy with Apache License 2.0 4 votes vote down vote up
def visit_EBinOp(self, e, env):
        # optimization: x in (distinct y) --> x in y
        # ("distinct" is very expensive for the solver)
        if e.op == BOp.In and isinstance(e.e2, EUnaryOp) and e.e2.op == UOp.Distinct:
            return self.visit(EIn(e.e1, e.e2.e), env)

        # normal path
        v1 = self.visit(e.e1, env)
        v2 = self.visit(e.e2, env)
        if e.op == BOp.And:
            return self.all(v1, v2)
        elif e.op == BOp.Or:
            return self.any(v1, v2)
        elif e.op == "=>":
            return self.implies(v1, v2)
        elif e.op == "==":
            return self.eq(e.e1.type, v1, v2)
        elif e.op == "!=":
            return self.neg(self.eq(e.e1.type, v1, v2))
        elif e.op == "===":
            return self.eq(e.e1.type, v1, v2, deep=True)
        elif e.op == ">":
            return self.gt(e.e1.type, v1, v2, env)
        elif e.op == "<":
            return self.lt(e.e1.type, v1, v2, env)
        elif e.op == ">=":
            return v1 >= v2
        elif e.op == "<=":
            return v1 <= v2
        elif e.op == "*":
            return v1 * v2
        elif e.op == "+":
            if isinstance(e.type, TBag) or isinstance(e.type, TList):
                return (v1[0] + v2[0], v1[1] + v2[1])
            elif isinstance(e.type, TSet):
                return self.visit(EUnaryOp(UOp.Distinct, EBinOp(e.e1, "+", e.e2).with_type(TBag(e.type.elem_type))).with_type(TBag(e.type.elem_type)), env)
            elif is_numeric(e.type):
                return v1 + v2
            else:
                raise NotImplementedError(e.type)
        elif e.op == "-":
            if isinstance(e.type, TBag) or isinstance(e.type, TSet) or isinstance(e.type, TList):
                return self.remove_all(e.type, v1, v2, env)
            return v1 - v2
        elif e.op == BOp.In:
            return self.is_in(e.e1.type, v2, v1, env)
        else:
            raise NotImplementedError(e.op)