Ejemplo n.º 1
0
def pb_solve2(comb, base):

    cnf = ""
    total = 0
    all_clauses = []

    con_ind = 0

    for con in base + [comb]:
        con_ind += 1
        rhs = -1
        all_eq = []
        all_str = ""
        for elem_ind in range(len(con)):
            elem = con[elem_ind]
            if elem != 0:
                for bit in range(1, 8):
                    all_eq.append(
                        pblib.WeightedLit(int("{}{}".format(elem_ind, bit)),
                                          2**(bit - 1) * elem))
                    if elem > 0:
                        all_str += "+ {} x{}".format(
                            2**(bit - 1) * elem,
                            int("{}{}".format(elem_ind, bit)))
                    else:
                        all_str += "{} x{}".format(
                            2**(bit - 1) * elem,
                            int("{}{}".format(elem_ind, bit)))

        all_str += " <= -1;"

        constr = pblib.PBConstraint(all_eq, pblib.LEQ, rhs)
        aux_var = pblib.AuxVarManager(10000 * con_ind)
        config = pblib.PBConfig()
        formula = pblib.VectorClauseDatabase(config)
        pb2cnf = pblib.Pb2cnf(config)
        pb2cnf.encode(constr, formula, aux_var)
        clauses = formula.get_clauses()
        all_clauses += clauses

    all_vars = set([])
    all_clauses_str = []
    for c in all_clauses:
        if not c:
            return
        clause_str = []
        for var in c:
            all_vars.add("x{}".format(var))
            clause_str.append("x{}".format(var))

        clause = "(" + " || ".join(clause_str) + ")"
        all_clauses_str.append(clause)

    cnf = " && ".join(all_clauses_str)

    cnf_string = "SatisfiableQ[{}, ".format(cnf) + "{" + " {} ".format(
        ",".join(all_vars)) + "}]"

    res = session.evaluate(wlexpr(cnf_string))
    print(res)
Ejemplo n.º 2
0
def is_compatible_pb(comb, base):
    cnf = ""
    total = 0
    all_clauses = []

    con_ind = 0

    for con in base + [comb]:
        con_ind += 1
        rhs = -1
        all_eq = []
        for elem_ind in range(len(con)):
            elem = con[elem_ind]
            if elem != 0:
                for bit in range(1, 8):
                    all_eq.append(
                        pblib.WeightedLit(int("{}{}".format(elem_ind, bit)),
                                          2**(bit - 1) * -elem))

        constr = pblib.PBConstraint(all_eq, pblib.LEQ, rhs)
        aux_var = pblib.AuxVarManager(10000 * con_ind)
        config = pblib.PBConfig()
        formula = pblib.VectorClauseDatabase(config)
        pb2cnf = pblib.Pb2cnf(config)
        pb2cnf.encode(constr, formula, aux_var)
        clauses = formula.get_clauses()
        all_clauses += clauses

    g = Glucose3()
    for c in all_clauses:
        g.add_clause(c)

    sol = g.solve()

    return sol
Ejemplo n.º 3
0
def pb_solve(comb, base):

    s = time.time()

    cnf = ""
    total = 0
    all_clauses = []

    con_ind = 0

    for con in base + [comb]:
        con_ind += 1
        rhs = -1
        all_eq = []
        for elem_ind in range(len(con)):
            elem = con[elem_ind]
            if elem != 0:
                for bit in range(1, 8):
                    all_eq.append(
                        pblib.WeightedLit(int("{}{}".format(elem_ind, bit)),
                                          2**(bit - 1) * elem))

        constr = pblib.PBConstraint(all_eq, pblib.LEQ, rhs)
        aux_var = pblib.AuxVarManager(10000 * con_ind)
        config = pblib.PBConfig()
        formula = pblib.VectorClauseDatabase(config)
        pb2cnf = pblib.Pb2cnf(config)
        pb2cnf.encode(constr, formula, aux_var)
        clauses = formula.get_clauses()
        all_clauses += clauses

    e = time.time()
    print("OPB to CNF time {}".format(e - s))
    """g = Glucose3()
	for c in all_clauses:
		g.add_clause(c)

	sol = g.solve()
	print(sol)"""

    s = time.time()

    l = Lingeling()
    for c in all_clauses:
        l.add_clause(c)

    sol = l.solve()
    print(sol)

    e = time.time()

    #print(pylgl.solve(all_clauses))

    print("CNF time {}".format(e - s))
Ejemplo n.º 4
0
    def _encode(cls, lits, weights=None, bound=1, top_id=None, vpool=None,
            encoding=EncType.best, comparator='<'):
        """
            This is the method that wraps the encoder of PyPBLib. Although the
            method can be invoked directly, a user is expected to call one of
            the following methods instead: :meth:`atmost`, :meth:`atleast`, or
            :meth:`equals`.

            The list of literals can contain either integers or pairs ``(l,
            w)``, where ``l`` is an integer literal and ``w`` is an integer
            weight. The latter can be done only if no ``weights`` are
            specified separately.

            :param lits: a list of literals in the sum.
            :param weights: a list of weights
            :param bound: the value of bound :math:`k`.
            :param top_id: top variable identifier used so far.
            :param vpool: variable pool for counting the number of variables.
            :param encoding: identifier of the encoding to use.
            :param comparator: identifier of the comparison operator

            :type lits: iterable(int)
            :type weights: iterable(int)
            :type bound: int
            :type top_id: integer or None
            :type vpool: :class:`.IDPool`
            :type encoding: integer
            :type comparator: str

            :rtype: :class:`pysat.formula.CNF`
        """

        assert pblib_present, 'Package \'pypblib\' is unavailable. Check your installation.'

        if encoding < 0 or encoding > 5:
            raise(NoSuchEncodingError(encoding))

        assert lits, 'No literals are provided.'

        assert not top_id or not vpool, \
                'Use either a top id or a pool of variables but not both.'

        # preparing weighted literals
        if weights:
            assert len(lits) == len(weights), 'Same number of literals and weights is expected.'
            wlits = [pblib.WeightedLit(l, w) for l, w in zip(lits, weights)]
        else:
            if all(map(lambda lw: (type(lw) in (list, tuple)) and len(lw) == 2, lits)):
                # literals are already weighted
                wlits = [pblib.WeightedLit(*wl) for wl in lits]
                lits = zip(*lits)[0]  # unweighted literals for getting top_id
            elif all(map(lambda l: type(l) is int, lits)):
                # no weights are provided => all weights are units
                wlits = [pblib.WeightedLit(l, 1) for l in lits]
            else:
                assert 0, 'Incorrect literals given.'

        # obtaining the top id from the variable pool
        if vpool:
            top_id = vpool.top

        if not top_id:
            top_id = max(map(lambda x: abs(x), lits))

        # pseudo-Boolean constraint and variable manager
        constr = pblib.PBConstraint(wlits, EncType._to_pbcmp[comparator], bound)
        varmgr = pblib.AuxVarManager(top_id + 1)

        # encoder configuration
        config = pblib.PBConfig()
        config.set_PB_Encoder(EncType._to_pbenc[encoding])

        # encoding
        result = pblib.VectorClauseDatabase(config)
        pb2cnf = pblib.Pb2cnf(config)
        pb2cnf.encode(constr, result, varmgr)

        # extracting clauses
        ret = CNF(from_clauses=result.get_clauses())

        # updating vpool if necessary
        if vpool:
            if vpool._occupied and vpool.top <= vpool._occupied[0][0] <= ret.nv:
                cls._update_vids(ret, vpool)
            else:
                vpool.top = ret.nv - 1
                vpool._next()

        return ret