def convert_region_to_loop(self, sub_region: Region):

        loop_condition = simplify(Bool('a') == Bool('a'))

        new_loop = MediumLevelILAstLoopNode(self, sub_region.header.block,
                                            loop_condition)
        new_loop._children = sub_region.nodes

        return new_loop
示例#2
0
    def add(self, f):
        clauses, dimacs, names_to_nums, num_to_name = get_cnf(f)
        if clauses is False:
            return False
        _names_to_nums = dict(names_to_nums)
        _names_to_nums.update({Not(Bool(k)): -v for (k, v) in names_to_nums.items()})
        _names_to_nums.update({(Bool(k)):  v for (k, v) in names_to_nums.items()})
        self._name_to_nums = _names_to_nums

        num_to_name.update({-k: v for (k, v) in num_to_name.items()})
        self._num_to_name = num_to_name
        self._solver.append_formula(clauses)
        return True
示例#3
0
    def _add_soft_constraints(self):
        self.s.push()
        for tid in range(self.agents):
            a = self.info.spawn[tid]
            for i, attr in enumerate(self.attrs[tid]):
                v = get_var(a.iface, i)
                fresh_bool = Bool(f"{v.store}_{tid}_{v.index}_%%soft%%")
                self.softs.add(fresh_bool)
                self.s.add(Implies(fresh_bool, attr == v.rnd_value(tid)))

        for i, env_var in enumerate(self.envs):
            v = get_var(self.info.e, i)
            fresh_bool = Bool(f"{v.store}_{v.index}_%%soft%%")
            self.softs.add(fresh_bool)
            self.s.add(Implies(fresh_bool, attr == v.rnd_value(tid)))
示例#4
0
    def __init__(self, owner, number, hw_config):
        self.owner = owner
        self.name = self.owner.name + "/r_" + str(number)
        self.hw_config = hw_config

        self.start = BitVec(self.name + "/start", 32)
        self.size = BitVec(self.name + "/size", 32)
        self.end = self.start + self.size
        subregion_size = self.size / hw_config.subregion_count
        self.subregions = []
        for i in range(hw_config.subregion_count):
            start = self.start + i * subregion_size
            self.subregions.append(
                Subregion(self, i, start, start + subregion_size))
        self.readable = Bool(self.name + "/can_read")
        self.writeable = Bool(self.name + "/can_write")
示例#5
0
文件: z3_utils.py 项目: galls2/OMG
    def concrete_transition_to_abstract(cls, nodes_from, abstract_witness):
        kripke = abstract_witness.get_kripke()
        tr = kripke.get_tr_formula()

        def sub_src(_tr, src_node):
            return _tr.assign_state(src_node.concrete_label)

        tr_from_concs = [sub_src(tr, node) for node in nodes_from]

        dst_vars = tr_from_concs[0].get_var_vectors()[0]
        in_tag = tr.get_input_vectors()[1]
        abs_formula = abstract_witness.get_descriptive_formula().substitute(
            dst_vars, 0).substitute_inputs(in_tag, 0)

        n_flags = len(tr_from_concs)
        flags = [Bool('f' + str(i)) for i in xrange(n_flags)]

        tr_flagged = [
            Or(Not(flags[i]), tr_from_concs[i].get_qbf().get_prop())
            for i in xrange(n_flags)
        ]
        all_tr_flagged = simplify(And(*tr_flagged))

        f_inner = simplify(
            And(all_tr_flagged,
                abs_formula.get_qbf().get_prop()))
        q_list = abs_formula.get_qbf().get_q_list()
        f_qbf = QBF(f_inner, q_list)
        f = FormulaWrapper(f_qbf, [dst_vars], tr.get_input_vectors())

        i, model = QbfSolverSelector.QbfSolverCtor().incremental_solve_flags(
            f, flags, sat)
        if i is False:
            return False
        return nodes_from[i], next(get_states(model, dst_vars, kripke))
示例#6
0
def GenerateConstraintForExample(spec, specConn, circuits, psiConn, newExample,
                                 iteration):
    substList = []

    for circuit in circuits:
        substList.append(
            (circuit.outputPort.var,
             circuit.outputPort.GenVarCopyForIteration(iteration)))
        substList.extend([(circuitInputPort.var,
                           circuitInputPort.GenVarCopyForIteration(iteration))
                          for circuitInputPort in circuit.inputPorts])

        for comp in circuit.components:
            substList.append(
                (comp.outputPort.var,
                 comp.outputPort.GenVarCopyForIteration(iteration)))
            substList.extend([(inputPort.var,
                               inputPort.GenVarCopyForIteration(iteration))
                              for inputPort in comp.inputPorts])

    substList.extend((port.var, val) for (port, val) in newExample.iteritems())

    constraints = [Bool(True)]

    constraints.append(substitute(psiConn, substList))
    constraints.append(substitute(specConn, substList))
    constraints.append(substitute(spec, substList))

    return And(constraints)
示例#7
0
    def setup_vars(self):
        for x, y in self.coords():
            if self.cell[x, y] == ".":
                self[cell(x, y)] = Int(cell(x, y))

        for w in self.words:
            self[placed(w)] = Bool(placed(w))
示例#8
0
def mk_var(name, vsort):
    """
    Create a variable of type vsort.

    Examples:

    >>> from z3 import *
    >>> v = mk_var('real_v', Real('x').sort())
    >>> print v
    real_v

    """
    if vsort.kind() == Z3_INT_SORT:
        v = Int(name)
    elif vsort.kind() == Z3_REAL_SORT:
        v = Real(name)
    elif vsort.kind() == Z3_BOOL_SORT:
        v = Bool(name)
    elif vsort.kind() == Z3_DATATYPE_SORT:
        v = Const(name, vsort)

    else:
        raise AssertionError,\
            'Cannot handle this sort (s: {}, {})'\
            .format(vsort, vsort.kind())

    return v
示例#9
0
def get_mus(constraints):
    '''
    Returns a single MUS
    '''
    seed = set(range(len(constraints)))
    idx2indicator = {i:Bool(str(i)) for i in seed}
    indicator2idx = {b.get_id():i for (i,b) in idx2indicator.items()}

    s = Solver()
    for i, b in idx2indicator.items():
        s.add(Implies(b, constraints[i]))

    def check_subset(current_seed):
        assumptions = [idx2indicator[i] for i in current_seed]
        return (s.check(assumptions) == sat)

    current = set(seed)
    for i in seed:
        if i not in current:
            continue
        current.remove(i)
        if not check_subset(current):
            core = s.unsat_core()
            # FIXME: do constraints never show up in the core? Seems like we could get a key error
            current = set(indicator2idx[ind.get_id()] for ind in core)
        else:
            current.add(i)
    assert not check_subset(current), "Expecting unsat at end of get_mus"
    return [constraints[i] for i in current]
示例#10
0
 def gen_var_list(cls):
     """Generate var_list by alphabet and k."""
     cls.var_list.append(BoolVal(True))
     number = cls.get_number()
     number = number * number + 1
     for i in range(1, number):
         v_name = "A_{}".format(i)
         cls.var_list.append(Bool(v_name))
     cls.var_list.append(BoolVal(False))
示例#11
0
def get_z3obj_type(d_type, name):
    from z3 import Bool, Int, Real

    if d_type.is_bool:
        return Bool(name)
    elif d_type.is_integer:
        return Int(name)
    else:
        return Real(name)
示例#12
0
    def __init__(
        self,
        list_of_tasks,
        nb_tasks_to_schedule,
        list_of_time_intervals,
        kind: Optional[str] = "exact",
        optional: Optional[bool] = False,
    ) -> None:
        super().__init__(optional)

        problem_function = {"min": PbGe, "max": PbLe, "exact": PbEq}

        # first check that all tasks from the list_of_optional_tasks are
        # actually optional
        if not isinstance(list_of_tasks, list):
            raise TypeError("list_of_task must be a list")

        if not isinstance(list_of_time_intervals, list):
            raise TypeError("list_of_time_intervals must be a list of list")

        # count the number of tasks that re scheduled in this time interval
        all_bools = []
        for task in list_of_tasks:
            # for this task, the logic expression is that any of its start or end must be
            # between two consecutive intervals
            bools_for_this_task = []
            for time_interval in list_of_time_intervals:
                task_in_time_interval = Bool(
                    "InTimeIntervalTask_%s_%i" % (task.name, uuid.uuid4().int)
                )
                lower_bound, upper_bound = time_interval
                cstrs = [
                    task.start >= lower_bound,
                    task.end <= upper_bound,
                    Not(
                        And(task.start < lower_bound, task.end > lower_bound)
                    ),  # overlap at start
                    Not(
                        And(task.start < upper_bound, task.end > upper_bound)
                    ),  # overlap at end
                    Not(And(task.start < lower_bound, task.end > upper_bound)),
                ]  # full overlap
                asst = Implies(task_in_time_interval, And(cstrs))
                self.set_z3_assertions(asst)
                bools_for_this_task.append(task_in_time_interval)
            # only one maximum bool to True from the previous possibilities
            asst_tsk = PbLe([(scheduled, True) for scheduled in bools_for_this_task], 1)
            self.set_z3_assertions(asst_tsk)
            all_bools.extend(bools_for_this_task)

        # we also have to exclude all the other cases, where start or end can be between two intervals
        # then set the constraint for the number of tasks to schedule
        asst_pb = problem_function[kind](
            [(scheduled, True) for scheduled in all_bools], nb_tasks_to_schedule
        )
        self.set_z3_assertions(asst_pb)
示例#13
0
    def prop_at(self, prop, t):
        st = ""
        for term in prop:
            st += str(term) + "_"
        key = st + str(t)
        if key not in self.props:
            p = Bool(key)
            self.props[key] = p

        return self.props[key]
示例#14
0
    def GenerateAcycConstraints(self):
        constraints = [Bool(True)]

        for comp in self.components:
            for inputPort in comp.inputPorts:
                constraints.append(
                    Int(self.PN2LNMap[inputPort.name]) < Int(self.PN2LNMap[
                        comp.outputPort.name]))

        return And(constraints)
示例#15
0
def make_variable(var: Variable):
    if var.name == "":
        if var.source_type == VariableSourceType.RegisterVariableSourceType:
            var.name = var.function.arch.get_reg_by_index(var.storage)
        else:
            var.name = f'var_{abs(var.storage):x}'
    if var.type.width == 1:
        return Bool(var.name)
    else:
        return BitVec(var.name, var.type.width * 8)
示例#16
0
def create_bitmap(bitvecs):
    bitmap = {}
    constraints = []
    for bv in bitvecs:
        for i in range(bv.size()):
            var = Bool(str(bv) + '_bit' + str(i))
            bitmap[(bv, i)] = var
            mask = BitVecVal(2**i, bv.size())
            constraints.append(var == ((bv & mask) == mask))
    return bitmap, And(constraints)
示例#17
0
    def GenerateDistinctOutputLabelConstraints(self):
        constraints = [Bool(True)]

        for i in range(len(self.components)):
            for j in range(i + 1, len(self.components)):
                dist_ij = (Int(
                    self.PN2LNMap[self.components[i].outputPort.name]) != Int(
                        self.PN2LNMap[self.components[j].outputPort.name]))
                constraints.append(dist_ij)

        return And(constraints)
示例#18
0
 def set_assertions(self, list_of_z3_assertions: List[BoolRef]) -> None:
     """Take a list of constraint to satisfy. If the constraint is optional then
     the list of z3 assertions apply under the condition that the applied flag
     is set to True.
     """
     if self.optional:
         self.applied = Bool("constraint_%s_applied" % self.uid)
         self.add_assertion(Implies(self.applied, list_of_z3_assertions))
     else:
         self.applied = True
         self.add_assertion(list_of_z3_assertions)
示例#19
0
 def __init__(self, prism_variable):
     self._prism_variable = prism_variable
     self.name = prism_variable.name
     self.bounds = None
     self.lower_bound = None
     self.upper_bound = None
     if isinstance(prism_variable, PrismBooleanVariable):
         self.variable = Bool(prism_variable.name)
     elif isinstance(prism_variable, PrismIntegerVariable):
         self.variable = INT_CTOR(prism_variable.name)
     else:
         raise NotImplementedError()
示例#20
0
    def __init__(
        self,
        list_of_workers: List[Resource],
        nb_workers_to_select: Optional[int] = 1,
        kind: Optional[str] = "exact",
    ):
        """create an instance of the SelectWorkers class."""
        super().__init__("")

        problem_function = {"min": PbGe, "max": PbLe, "exact": PbEq}

        if kind not in problem_function:
            raise ValueError("kind must be either 'exact', 'min' or 'max'")
        self.kind = kind

        if not is_strict_positive_integer(nb_workers_to_select):
            raise TypeError("nb_workers must be an integer > 0")
        if nb_workers_to_select > len(list_of_workers):
            raise ValueError(
                "nb_workers must be <= the number of workers provided in list_of_workers."
            )
        self.nb_workers_to_select = nb_workers_to_select

        # build the list of workers that will be the base of the selection
        # instances from this list mght either be Workers or CumulativeWorkers. If
        # this is a cumulative, then we add the list of all workers from the cumulative
        # into this list.
        self.list_of_workers = []
        for worker in list_of_workers:
            if isinstance(worker, CumulativeWorker):
                self.list_of_workers.extend(worker.cumulative_workers)
            else:
                self.list_of_workers.append(worker)

        # a dict that maps workers and selected boolean
        self.selection_dict = {}

        # create as many booleans as resources in the list
        for worker in self.list_of_workers:
            worker_is_selected = Bool("Selected_%s_%i" %
                                      (worker.name, self.uid))
            self.selection_dict[worker] = worker_is_selected

        # create the assertion : exactly n boolean flags are allowed to be True,
        # the others must be False
        # see https://github.com/Z3Prover/z3/issues/694
        # and https://stackoverflow.com/questions/43081929/k-out-of-n-constraint-in-z3py
        selection_list = list(self.selection_dict.values())
        self.selection_assertion = problem_function[kind](
            [(selected, True) for selected in selection_list],
            nb_workers_to_select)
        ps_context.main_context.add_resource_select_workers(self)
def build_problem():
    num_inputs = 16

    component_operators = [And, Nor]

    pins = [Bool('dip_%d' % i) for i in range(num_inputs)]

    operator_queue = random.sample(component_operators *
                                   (num_inputs // len(component_operators)),
                                   k=num_inputs)
    pin_queue = random.sample(pins * 2, k=num_inputs * 2)

    return (pins, And(*enlarge_problem(pin_queue, operator_queue, [])))
示例#22
0
def findConfig(ships, observations, dimensions=(10, 10)):
    (M, N) = dimensions
    NS = len(ships)
    s = Solver()
    W = map(lambda (w, h): w, ships)
    H = map(lambda (w, h): h, ships)
    (xs, ys, ds) = ([], [], [])
    for k in range(NS):
        xs.append(Int('x_%d' % k))
        ys.append(Int('y_%d' % k))
        ds.append(Bool('d_%d' % k))
        #assert that x,y are in the dimensions' range
        s.add(xs[k] < M, xs[k] >= 0, ys[k] < N, ys[k] >= 0)

    occupied = dict()
    observe = dict()

    for i in range(M):
        occupied[i] = dict()
        observe[i] = dict()
        for j in range(N):
            occupied[i][j] = dict()
            observe[i][j] = False
            for k in range(NS):
                rect1 = rect(xs[k], ys[k], W[k], H[k], i, j)
                rect2 = rect(xs[k], ys[k], H[k], W[k], i, j)
                occupied[i][j][k] = Or(And(ds[k], rect1),
                                       And(Not(ds[k]), rect2))
                observe[i][j] = Or(occupied[i][j][k], observe[i][j])
    sumvar = 0
    for ((i, j), hit) in observations:
        if hit:
            s.add(observe[i][j])
        else:
            s.add(Not(observe[i][j]))

    for i in range(M):
        for j in range(N):
            sumvar = If(observe[i][j], 1, 0) + sumvar

    s.add(sumvar == getAreaCount(ships))
    if s.check() == sat:
        model = s.model()
        output = []
        for k in range(NS):
            output.append((model[xs[k]].as_long(), model[ys[k]].as_long(),
                           is_true(model[ds[k]])))
        return output
    else:
        #print "UNSAT!"
        return "UNSAT"
示例#23
0
def GenerateVerificationConstraint(spec, specConn, circuits, psiConn,
                                   circuitModel):
    constraints = [Bool(True)]

    substList = []
    for circuit in circuits:
        substList.extend([(Int(labelName),
                           circuitModel.eval(Int(labelName), True))
                          for (_, labelName) in circuit.labels.iteritems()])

    constraints.append(substitute(psiConn, substList))
    constraints.append(specConn)
    constraints.append(Not(spec))
    return And(constraints)
示例#24
0
 def _gen_variable(self, qubit):
     """After each gate generate a new unique variable name for each of the
         qubits, using scheme: 'q[id]_[gatenum]', e.g. q1_0 -> q1_1 -> q1_2,
                                                       q2_0 -> q2_1
     Args:
         qubit (Qubit): qubit to generate new variable for
     Returns:
         BoolRef: z3 variable of qubit state
     """
     varname = "q" + str(qubit) + "_" + str(self.gatenum[qubit])
     var = Bool(varname)
     self.gatenum[qubit] += 1
     self.variables[qubit].append(var)
     return var
示例#25
0
    def GenerateConnectionConstraints(self):
        constraints = [Bool(True)]
        numInputPorts = len(self.inputPorts)
        numComponents = len(self.components)

        for i in range(numInputPorts):
            for comp in self.components:
                for inputPort in comp.inputPorts:
                    if inputPort.breed == self.inputPorts[i].breed:
                        antecedent = (Int(self.PN2LNMap[inputPort.name]) == i)
                        consequent = (inputPort.var == self.inputPorts[i].var)
                        constraints.append(Implies(antecedent, consequent))
                    else:
                        constraints.append(
                            Int(self.PN2LNMap[inputPort.name]) != i)

        numLabels = len(self.labels)

        for i in range(numLabels):
            for j in range(i + 1, numLabels):
                labelX = self.labels[i]
                labelY = self.labels[j]

                portX = self.LN2PMap[labelX]
                portY = self.LN2PMap[labelY]

                if portX.breed == portY.breed:
                    antecedent = Int(labelX) == Int(labelY)
                    consequent = (portX.var == portY.var)
                    constraints.append(Implies(antecedent, consequent))
                else:
                    constraints.append(Int(labelX) != Int(labelY))

        for comp in self.components:
            if comp.outputPort.breed == self.outputPort.breed:
                antecedent = (Int(
                    self.PN2LNMap[comp.outputPort.name]) == numInputPorts +
                              numComponents - 1)
                consequent = (self.outputPort.var == comp.outputPort.var)
                constraints.append(Implies(antecedent, consequent))
            else:
                constraints.append(
                    Int(self.PN2LNMap[comp.outputPort.name]) != numInputPorts +
                    numComponents - 1)

        constraints.extend([comp.spec for comp in self.components])

        return And(constraints)
示例#26
0
def translate(ctx: Dict[str, str], lt: LiquidTerm):
    if isinstance(lt, LiquidVar):
        if ctx[lt.name] == "bool":
            return Bool(lt.name)  # There might be a bug here!
        elif ctx[lt.name] == "int":
            return Int(lt.name)  # There might be a bug here!
        else:
            assert False

    elif isinstance(lt, LiquidLiteralInt) or isinstance(lt, LiquidLiteralBool):
        return lt.value
    elif isinstance(lt, LiquidApp):
        f = builtin_functions[lt.name]
        nargs = [translate(ctx, a) for a in lt.arguments]
        return f(*nargs)
    assert False
示例#27
0
    def __init__(self, optional):
        super().__init__("")

        self.optional = optional

        # by default, we dont know if the constraint is created from
        # an assertion
        self.created_from_assertion = False

        # by default, this constraint has to be applied
        if self.optional:
            self.applied = Bool("constraint_%s_applied" % self.uid)
        else:
            self.applied = True

        # store this constraint into the current context
        ps_context.main_context.add_constraint(self)
示例#28
0
def get_lit(litstr: str) -> BoolRef:
    sign = litstr[0] == '-'
    if sign:
        litstr = litstr[1:]
    try:
        l = varmap[litstr]
        if sign:
            l = Not(l)
        return l
    except:
        v = Bool('l' + litstr)
        varmap[litstr] = v
        if sign:
            l = Not(v)
        else:
            l = v
        return l
示例#29
0
    def insert(cls,
               name,
               typeinfo,
               is_input=False,
               init_value=None,
               min_max=None):
        if (name in cls.vartable):
            return cls.vartable[name]
        var = Var(name, typeinfo, is_input, init_value, min_max)
        cls.vartable[name] = var

        if (typeinfo == "bool"):
            Z3VarTable.z3table[var] = Bool(name)
        else:
            Z3VarTable.z3table[var] = Int(name)

        return var
    def create_z3_vars(self):
        """
        Setup the variables required for Z3 optimization
        """
        for gate in self.dag.gate_nodes():
            t_var_name = 't_' + str(self.gate_id[gate])
            d_var_name = 'd_' + str(self.gate_id[gate])
            f_var_name = 'f_' + str(self.gate_id[gate])
            self.gate_start_time[gate] = Real(t_var_name)
            self.gate_duration[gate] = Real(d_var_name)
            self.gate_fidelity[gate] = Real(f_var_name)
        for gate in self.xtalk_overlap_set:
            self.overlap_indicator[gate] = {}
            self.overlap_amounts[gate] = {}
        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 g_1 in self.overlap_indicator[g_2]:
                    self.overlap_indicator[g_1][g_2] = self.overlap_indicator[
                        g_2][g_1]
                    self.overlap_amounts[g_1][g_2] = self.overlap_amounts[g_2][
                        g_1]
                else:
                    # Indicator variable for overlap of g_1 and g_2
                    var_name1 = 'olp_ind_' + str(
                        self.gate_id[g_1]) + '_' + str(self.gate_id[g_2])
                    self.overlap_indicator[g_1][g_2] = Bool(var_name1)
                    var_name2 = 'olp_amnt_' + str(
                        self.gate_id[g_1]) + '_' + str(self.gate_id[g_2])
                    self.overlap_amounts[g_1][g_2] = Real(var_name2)
        active_qubits_list = []
        for gate in self.dag.gate_nodes():
            for q in gate.qargs:
                active_qubits_list.append(q.index)
        for active_qubit in list(set(active_qubits_list)):
            q_var_name = 'l_' + str(active_qubit)
            self.qubit_lifetime[active_qubit] = Real(q_var_name)

        meas_q = []
        for node in self.dag.op_nodes():
            if isinstance(node.op, Measure):
                meas_q.append(node.qargs[0].index)

        self.measured_qubits = list(
            set(self.input_measured_qubits).union(set(meas_q)))
        self.measure_start = Real('meas_start')