Python z3.Not() Examples

The following are 23 code examples of z3.Not(). 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: 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 #2
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 #3
Source File: svm_utils.py    From ilf with Apache License 2.0 6 votes vote down vote up
def generate_contract_objects(contract_to_build_data, hash_to_func_name):
    contract_name_to_contract = {}
    lib_name_to_address = {}
    # filename = combined_json_data['sourceList'][0]
    # assert len(combined_json_data['sourceList']) == 1, 'Not a flat file!'
    utils.get_next_lib_address()
    for contract_name, contract_json_data in contract_to_build_data.items():
        src_code = contract_json_data['source']
        runtime_bytecode = contract_json_data['deployedBytecode']
        bytecode = contract_json_data['bytecode']
        for lib_name in find_library_names(bytecode) | find_library_names(runtime_bytecode):
            lib_name_to_address.setdefault(lib_name, utils.get_next_lib_address())
        # runtime_bytecode = link_libraries(filename, lib_name_to_address, runtime_bytecode)
        # bytecode = link_libraries(filename, lib_name_to_address, bytecode)
        abi = contract_json_data['abi']
        runtime_src_map = contract_json_data['deployedSourceMap']
        src_map = contract_json_data['sourceMap']
        contract = SolidityContract(contract_name, abi, bytecode,
                                    runtime_bytecode, src_map,
                                    runtime_src_map, src_code, hash_to_func_name)
        contract_name_to_contract[contract_name] = contract
    return contract_name_to_contract, lib_name_to_address 
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: mlil_ast.py    From f-ing-around-with-binaryninja with MIT License 6 votes vote down vote up
def try_make_simple_if_else(
        self, node1, node2, nodes_to_check, nodes_to_remove
    ):

        log_debug("try_make_simple_if_else")

        cond1 = node1.condition
        cond2 = node2.condition

        if is_true(simplify(cond1 == Not(cond2))):
            log_debug(f"found a simple if/else match")
            if cond1.decl().name() == "not":
                node2[False] = node1[True]
                nodes_to_check.remove(node2)
                nodes_to_remove.append(node1)
            else:
                node1[False] = node2[True]
                nodes_to_remove.append(node2)

            return True

        return False 
Example #6
Source File: z3_extra_util.py    From teether with Apache License 2.0 5 votes vote down vote up
def is_true(cond):
    # NOTE: This differs from `not is_false(cond)`, which corresponds to "may be true"
    return is_false(z3.Not(cond)) 
Example #7
Source File: AST.py    From jeeves with MIT License 5 votes vote down vote up
def __ne__(self, other):
		try:
			f = getattr(self.v, '__ne__')
		except AttributeError:
			return Not(Eq(self, fexpr_cast(other)))
		return f(other) 
Example #8
Source File: AST.py    From jeeves with MIT License 5 votes vote down vote up
def remapLabels(self, policy, writer):
		return Not(self.sub.remapLabels(policy, writer)) 
Example #9
Source File: AST.py    From jeeves with MIT License 5 votes vote down vote up
def z3Node(self):
		return z3.Not(self.sub.z3Node()) 
Example #10
Source File: AST.py    From jeeves with MIT License 5 votes vote down vote up
def remapLabels(self, policy, writer):
		return Mod(
				self.left.remapLabels(policy, writer)
			, self.right.remapLabels(policy, writer))

# Not sure if bitwise operations are supported by Z3? 
Example #11
Source File: AST.py    From jeeves with MIT License 5 votes vote down vote up
def __ne__(self, other):
		other = fexpr_cast(other)
		if self.type == object or other.type == object:
			return JeevesLib.jif(self.cond, lambda : self.thn != other,
																									 lambda : self.els != other)
		else:
			return Not(Eq(self, other)) 
Example #12
Source File: AST.py    From jeeves with MIT License 5 votes vote down vote up
def __ne__(l, r):
		return Not(Eq(l, fexpr_cast(r)))
		
	# The & operator 
Example #13
Source File: deflatten.py    From ollvm-breaker with MIT License 5 votes vote down vote up
def compute_reaching_states(bv, mlil, from_bb, to_bb, states):
    visitor = ConditionVisitor(bv)
    path = next(dfs_paths_backward(from_bb, to_bb))
    reaching_conditions = []
    cond = None
    for edge in path:
        terminator = edge.source[-1]
        # assert terminator.operation == MediumLevelILOperation.MLIL_IF
        if terminator.operation == MediumLevelILOperation.MLIL_IF:
            cond = terminator.condition
            if cond.operation == MediumLevelILOperation.MLIL_VAR:
                cond = mlil.get_var_definitions(cond.src)[0].src
            condition = visitor.visit(cond)
            if edge.type == BranchType.TrueBranch:
                reaching_conditions.append(condition)
            else:
                reaching_conditions.append(z3.Not(condition))

    solver = z3.Solver()
    for condition in reaching_conditions:
        solver.add(condition)

    reaching_states = set()
    if cond.operation == MediumLevelILOperation.MLIL_VAR:
        cond = mlil.get_var_definitions(cond.src)[0].src
    symbolic_state = make_variable(cond.left.src)
    for state in states:
        solver.push()
        solver.add(symbolic_state == state)
        if solver.check() == z3.sat:
            reaching_states.add(state)
        solver.pop()
    return list(reaching_states) 
Example #14
Source File: solver.py    From cozy with Apache License 2.0 5 votes vote down vote up
def neg(self, cond):
        b = to_bool(cond)
        if b is True:  return self.false
        if b is False: return self.true
        return z3.Not(cond, self.ctx) 
Example #15
Source File: svm_utils.py    From ilf with Apache License 2.0 5 votes vote down vote up
def get_library_names(combined_json_data):
    lib_names = []
    filename = combined_json_data['sourceList'][0]
    assert len(combined_json_data['sourceList']) == 1, 'Not a flat file!'
    pattern = re.compile('(' + filename + ':)([a-zA-Z0-9]+)(_+)')
    hash_pattern = re.compile('__\$([a-f0-9]{34})\$__')
    hash_to_contract_name = { ethereum.utils.sha3(c).hex()[:34]: c for c in combined_json_data['contracts'].keys() }
    for contract_name, contract_data in combined_json_data['contracts'].items():
        lib_names.extend([lib_name for (_, lib_name, _) in re.findall(pattern, contract_data['bin-runtime'])])
        hash_matches = re.findall(hash_pattern, contract_data['bin-runtime'])
        for hash_match in hash_matches:
            lib_full_name = hash_to_contract_name[hash_match]
            lib_names.append(lib_full_name.split(':')[-1])
    return set(lib_names) 
Example #16
Source File: z3_ir.py    From miasm with GNU General Public License v2.0 5 votes vote down vote up
def equiv(z3_expr1, z3_expr2):
    s = z3.Solver()
    s.add(z3.Not(z3_expr1 == z3_expr2))
    return s.check() == z3.unsat 
Example #17
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 #18
Source File: hoare_opt.py    From qiskit-terra with Apache License 2.0 5 votes vote down vote up
def _add_postconditions(self, gate, ctrl_ones, trgtqb, trgtvar):
        """ create boolean variables for each qubit the gate is applied to
            and apply the relevant post conditions.
            a gate rotating out of the z-basis will not have any valid
            post-conditions, in which case the qubit state is unknown
        Args:
            gate (Gate): gate to inspect
            ctrl_ones (BoolRef): z3 condition asserting all control qubits to 1
            trgtqb (list((QuantumRegister, int))): list of target qubits
            trgtvar (list(BoolRef)): z3 variables corresponding to latest state
                                     of target qubits
        """
        new_vars = []
        for qbt in trgtqb:
            new_vars.append(self._gen_variable(qbt.index))

        try:
            self.solver.add(
                Implies(ctrl_ones, gate._postconditions(*(trgtvar + new_vars)))
            )
        except AttributeError:
            pass

        for i, tvar in enumerate(trgtvar):
            self.solver.add(
                Implies(Not(ctrl_ones), new_vars[i] == tvar)
            ) 
Example #19
Source File: hoare_opt.py    From qiskit-terra with Apache License 2.0 5 votes vote down vote up
def _initialize(self, dag):
        """ create boolean variables for each qubit and apply qb == 0 condition
        Args:
            dag (DAGCircuit): input DAG to get qubits from
        """
        for qbt in dag.qubits:
            self.gatenum[qbt.index] = 0
            self.variables[qbt.index] = []
            self.gatecache[qbt.index] = []
            self.varnum[qbt.index] = dict()
            x = self._gen_variable(qbt.index)
            self.solver.add(Not(x)) 
Example #20
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 #21
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 #22
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 #23
Source File: solver.py    From cozy with Apache License 2.0 4 votes vote down vote up
def visit_EUnaryOp(self, e, env):
        if e.op == UOp.Not:
            return self.neg(self.visit(e.e, env))
        elif e.op == UOp.Sum:
            bag = self.visit(e.e, env)
            bag_mask, bag_elems = bag
            sum = self.int_zero
            for i in range(len(bag_elems)):
                sum = ite(INT, bag_mask[i], bag_elems[i], self.int_zero) + sum
            return sum
        elif e.op == UOp.Length:
            v = EVar("v").with_type(e.e.type.elem_type)
            return self.visit(EUnaryOp(UOp.Sum, EMap(e.e, ELambda(v, ONE)).with_type(TBag(INT))).with_type(e.type), env)
        elif e.op == UOp.AreUnique:
            def is_unique(bag):
                bag_mask, bag_elems = bag
                rest = (bag_mask[1:], bag_elems[1:])
                if bag_elems:
                    return self.all(
                        self.implies(bag_mask[0], self.neg(self.is_in(e.e.type.elem_type, rest, bag_elems[0], env))),
                        is_unique(rest))
                else:
                    return self.true
            return is_unique(self.visit(e.e, env))
        elif e.op == UOp.Empty:
            mask, elems = self.visit(e.e, env)
            return self.neg(self.any(*mask))
        elif e.op == UOp.Exists:
            mask, elems = self.visit(e.e, env)
            return self.any(*mask)
        elif e.op == UOp.All:
            mask, elems = self.visit(e.e, env)
            return self.all(*[self.implies(m, e) for (m, e) in zip(mask, elems)])
        elif e.op == UOp.Any:
            mask, elems = self.visit(e.e, env)
            return self.any(*[self.all(m, e) for (m, e) in zip(mask, elems)])
        elif e.op == UOp.Distinct:
            elem_type = e.type.elem_type
            return self.distinct_bag_elems(self.visit(e.e, env), elem_type)
        elif e.op == UOp.Length:
            return self.len_of(self.visit(e.e, env))
        elif e.op == UOp.The:
            t = e.type
            bag = self.visit(e.e, env)
            mask, elems = bag
            exists = self.any(*mask)
            elem = self.mkval(t)
            for (m, e) in reversed(list(zip(mask, elems))):
                elem = ite(t, m, e, elem)
            return elem
        elif e.op == UOp.Reversed:
            mask, elems = self.visit(e.e, env)
            return (list(reversed(mask)), list(reversed(elems)))
        elif e.op == "-":
            return -self.visit(e.e, env)
        else:
            raise NotImplementedError(e.op)