Esempio n. 1
0
def solveToken(eq):
    eq = eq.strip()

    # Request for a new token.
    token, eq = getToken(eq)
    if token is None: return None, eq

    # If the variable is a negation, Create a negated
    # variable. Return the relevant variable obj and the
    # remaining string
    if token[0] == '!':
        return (-Variable(token[1:].strip()), eq)

    # If no negation is present, return just the variable
    if re.match(r'^[\w]', token):
        return (Variable(token.strip()), eq)

    # If the token is a bracketed group, recursively
    # solve it
    if token[0] == '(':
        return (solve(token[1:-1]), eq)

    # This should ideally never be encountered
    print("I failed: ", token, eq)
    exit(0)
Esempio n. 2
0
    def fromstring(self, s):
        self.varname_dict = {}
        self.varobj_dict = {}

        lines = s.split("\n")
        # Throw away comments and empty lines
        new_lines = []
        for l in lines:
            l = l.strip()
            if l[0] != 'c' and l != "":
                new_lines.append(l)

        _, _, varz, clauses = new_lines[0].split(" ")
        varz, clauses = int(varz), int(clauses)

        c = Cnf()

        lines = new_lines[1:]
        c.dis = frozenset(
            frozenset(
                map(
                    lambda vn: Variable("v" + vn.strip(" \t\r\n-"), vn[0] ==
                                        '-'),
                    line.split(" ")[:-1])) for line in lines)

        for i in xrange(1, varz + 1):
            stri = str(i)
            vo = Variable('v' + stri)
            self.varname_dict[vo] = stri
            self.varobj_dict[stri] = vo

        return c
Esempio n. 3
0
def solve(eq):
    solution = Minisat().solve(eq)
    assert solution.success and not solution.error, 'ERR: Failed to solve'

    result = 1 << N - 1 if solution[Variable('0')] else 0
    for i in range(1, N):
        result |= 1 << i - 1 if (solution[Variable(str(i))]) else 0

    return result
Esempio n. 4
0
def reduce_AMO_sequential(items, _assign_id=[0]):
    """ At most one 'sequential' encoding (Sinz)

        Based on count-and-compare hardware.

        Example (where a-d are items; X1-X2 are extra variables):
        ~a | X1
        ~b | X2 & ~X1 | X2 & ~b | ~X1 (repeat)
        ~c | ~X2

        Setting a to True, forces X1 to be True. X1 as True X2 to true and b
        to false. Thus propagating as X2 to True forces c to False.

        items: A list of variables, or cnfs (must have two or more items)
        _assign_id: Internal counter, don't replace
    """
    nitems = [-i for i in items]
    extra_vars = []
    nextra_vars = []
    for _ in range(len(items)-1):
        v = Variable("SEQ" + str(_assign_id[0]))
        extra_vars.append(v)
        nextra_vars.append(-v)
        _assign_id[0] += 1
    cnf = (nitems[0] | extra_vars[0]) & (nitems[-1] | nextra_vars[-1])
    for i in range(1, len(items)-1):
        cnf &= ((nitems[i] | extra_vars[i]) &
                (nextra_vars[i-1] | extra_vars[i]) &
                (nitems[i] | nextra_vars[i-1]))
    return cnf
Esempio n. 5
0
 def get_variable(name):
     if name in variables:
         var = variables[name]
     else:
         var = Variable(name)
         variables[name] = var
     return var
Esempio n. 6
0
def genKey():
    # return random.getrandbits(k)

    # return 2**256-1 #since we want all 1s

    variables = [Variable(str(i)) for i in xrange(k)]  #all the 3sat variables
    return "1" * k, variables
Esempio n. 7
0
def reversedStep(x):
    variables = []
    for i in range(N):
        variables.append(Variable(str(i)))

    exp = Variable('None')

    for i in range(N):
        if (x >> i) & 1:
            exp &= (variables[i] & -variables[(i + 1) % N] & -variables[(i + 2) % N]) | (-variables[i] & variables[(i + 1) % N]) | (-variables[i] & variables[(i + 2) % N])
        else:
            exp &= (-variables[i] & -variables[(i + 1) % N] & -variables[(i + 2) % N]) | (variables[i] & variables[(i + 1) % N]) | (variables[i] & variables[(i + 2) % N])

    solver = Minisat()
    solution = solver.solve(exp)
    if solution.success:
        return arrayToInt(solution, variables)
Esempio n. 8
0
def encode(Sp, Sm, k):
    """Write NFA induction as SAT
  Input: examples, counter-examples, and an integer
  Output: boolean formula (Cnf), variables y and z"""
    idx = Idx(0)
    Sigma = alphabet(Sp | Sm)
    Q = range(k)
    P = prefixes(Sp | Sm)
    P.remove("")
    x = dict(((w, q), Variable(idx + 1)) for w in P for q in Q)
    y = dict(((a, p, q), Variable(idx + 1)) for a in Sigma for p in Q
             for q in Q)
    z = dict((q, Variable(idx + 1)) for q in Q)
    st = []  # subject to (i.e. constraints)

    # The empty word inclusion
    if "" in Sp: st.append(z[0])
    if "" in Sm: st.append(-z[0])

    # Acceptance of examples
    for w in Sp - {""}:
        st.append(reduce(or_, (x[w, q] & z[q] for q in Q)))

    # Rejection of counter-examples
    for w in Sm - {""}:
        for q in Q:
            st.append(-x[w, q] | -z[q])

    # Single-symbol prefixes inclusion
    for a in P & Sigma:
        for q in Q:
            st.append(-(x[a, q] ^ y[a, 0, q]))

    # Multi-symbol prefixes inclusion
    for w in P:
        if len(w) >= 2:
            v, a = w[:-1], w[-1]
            for q in Q:
                st.append(x[w, q] >> reduce(or_, (x[v, r] & y[a, r, q]
                                                  for r in Q)))
                for r in Q:
                    st.append((x[v, r] & y[a, r, q]) >> x[w, q])

    return (reduce(and_, st), y, z)
Esempio n. 9
0
    def build_model(self):

        nproc = self._instance.nproc
        nmach = self._instance.nmach
        nserv = self._instance.nserv
        nneigh = len(self._instance.N)
        nloc = len(self._instance.L)

        P = self._instance.P
        M = self._instance.M
        S = self._instance.S
        N = self._instance.N
        L = self._instance.L

        io = DimacsCnf()

        self.x = np.empty((nproc, nmach), dtype=object)
        for p in P:
            for m in M:
                self.x[p, m] = Variable('x[%d,%d]' % (p, m))

        # proc alloc
        all_proc_expr = Cnf()

        for p in P:
            p_expr1 = Cnf()
            p_expr2 = Cnf()
            p_expr3 = Cnf()

            for m1 in M:
                if any(self._instance.R[p] > self._instance.C[m1]):
                    p_expr1 &= -self.x[p, m1]
                else:
                    p_expr1 |= self.x[p, m1]

                    for m2 in range(m1 + 1, nmach):
                        p_expr2 &= self.x[p, m1] >> -self.x[p, m2]

            all_proc_expr &= p_expr1 & p_expr2 & p_expr3

        self.global_expr &= all_proc_expr

        # conflict
        all_conflict_expr = Cnf()

        for m in M:
            for s in S:
                if len(S[s]) == 1: continue
                conflict_expr = Cnf()
                for p1 in range(len(S[s])):
                    for p2 in range(p1 + 1, len(S[s])):
                        conflict_expr &= self.x[S[s][p1],
                                                m] >> -self.x[S[s][p2], m]
                all_conflict_expr &= conflict_expr

        self.global_expr &= all_conflict_expr
Esempio n. 10
0
    def __init__(self, roster = [], equipment = [], portfolio = {}):
        self.roster = {r: Variable(r) for r in roster}
        self.equipment = {e: Variable(e) for e in equipment}
        self.holdings = {a:
                [self.equipment[r] for r in portfolio[a]] for a in portfolio}
        list_diff = lambda xs,ys : list(set(xs).difference(set(ys)))
        self.neg_holdings = {a:
             list_diff(self.equipment.keys(), portfolio[a]) for a in self.holdings}
        self.neg_holdings = {a: [self.equipment[r] for r in self.neg_holdings[a]] for a in self.neg_holdings}
        self.roster_expression = reduce(lambda a,b: a|b, self.roster.values())
        self.equip_expression = reduce(lambda a,b: a|b, self.equipment.values())

        zs = []
        for a in self.neg_holdings:
            xs = reduce(lambda a,b:a|b,self.neg_holdings[a])
            xs = self.roster[a] >> -xs
            zs = zs + [xs]
        self.res_expression =  reduce(lambda a,b:a&b, zs)
        self.expression = self.roster_expression & self.res_expression & self.equip_expression
Esempio n. 11
0
    def createVariables(self):
        """
        Allocate 2 dictionaries:
        - boolean variables
        - action variable
        """

        self.boolean_variables = defaultdict(dict)
        for step in range(self.horizon + 1):
            for fluent in self.boolean_fluents:
                var_name = utils.makeName(fluent, step)
                self.boolean_variables.update({var_name: Variable(var_name)})

        self.action_variables = defaultdict(dict)
        for step in range(self.horizon):
            for a in self.actions:
                action_name = utils.makeName(a.name, step)
                self.action_variables.update(
                    {action_name: Variable(action_name)})
Esempio n. 12
0
def reduce_AMO_product(items, _assign_id=[0]):
    """ At most one 'product' encoding (Chen)

        Which I believe to be the best, once a large number is involved >25

        Assign each var to a point in a p*q grid, (Pi, Qj).
        Forcing that value of Pi and Qi to be True. Each point will differ
        by either P or Q (or both).
        As such this can be applied recursively, by allowing at most one
        of the P's and one of the Q's to be set. Once the number of P or Q is
        small, another encoding can be used.

        items: A list of variables, or cnfs (must have two or more items)
        _assign_id: Internal counter, don't replace
    """
    # Find two numbers p, q such that p*q >= len(items)
    p = int(math.ceil(math.sqrt(len(items))))
    if p * (p-1) >= len(items):
        q = p-1
    else:
        q = p
    assert p*q >= len(items)
    # Allocate variables for q and p
    qs = []
    ps = []
    nitems = [-i for i in items]
    for _ in range(q):
        qs.append(Variable("PRD" + str(_assign_id[0])))
        _assign_id[0] += 1
    for _ in range(p):
        ps.append(Variable("PRD" + str(_assign_id[0])))
        _assign_id[0] += 1

    cnf = Cnf()
    i = 0  # Iterate item counter
    for vp in ps:
        for vq in qs:
            if i >= len(items):
                break
            cnf &= (nitems[i] | vp) & (nitems[i] | vq)
            i += 1
    return reduce_AMO(ps) & reduce_AMO(qs) & cnf
Esempio n. 13
0
    def test_sat_lib(self):
        """Sanity check: (x1 v -x2), (-x2), (-x1), (x3 v x1 x x2)"""
        cnf = Cnf()
        x1 = Variable('x1')
        x2 = Variable('x2')
        x3 = Variable('x3')

        solver = Minisat()
        solution = solver.solve(cnf)

        if not solution.success:
            self.fail("Something seriously wrong with this library.")

        true_literals = [x3]
        false_literals = [x1, x2]

        for lit in true_literals:
            self.assertTrue(solution[lit])
        for lit in false_literals:
            self.assertFalse(solution[lit])
Esempio n. 14
0
	def __init__(self, i,j):
        	self.i = i
		self.j = j
		self.p = []
		self.f = Cnf()	
		self.s = Cnf()	
		for d in range(9):
			temp = 'p' + str(i) + str(j) + str(d+1)
			#print temp
			self.p.append(Variable(temp))
			#create first case -- it must be filled
			self.f |= self.p[d]
Esempio n. 15
0
def solve(eq):
    eq = eq.strip()
    if eq == '': return Cnf()

    op = re.findall(r'^(\^\^|\|\||\?\?)', eq)
    if op:
        op = op[0]
        if op == '||':
            var, eq = getToken(eq[2:])
            assert var[0] == '(' and var[-1] == ')'
            result = all_or(var)
        elif op == '^^':
            var, eq = getToken(eq[2:])
            assert var[0] == '(' and var[-1] == ')'
            result = all_xor(var)
        elif op == '??':
            var, eq = getToken(eq[2:])
            assert var[0] == '(' and var[-1] == ')'
            result = at_most(var)
        return result & solve(eq)

    op = re.findall(r'^[\w]+\s*\?', eq)
    if op:
        op = op[0]
        eq = eq[len(op):]
        var1 = Variable(op[:-1].strip())
        var2, eq = solveToken(eq)
        return (var1 >> var2) & solve(eq)

    op = re.findall(r'^[\w]+', eq)
    if op:
        op = op[0]
        eq = eq[len(op):]
        var = Variable(op.strip())
        return var & solve(eq)

        # This should ideally never be encountered
    print("I failed", eq)
    exit(1)
Esempio n. 16
0
def touch_variable(name, map):
    """
    Find variable map[name] if it exists else create one and map it.
    :param name: key to mapper
    :param map: mapping of name to Variable
    :return: variable found or created
    """
    if name in map:
        var = map[name]
    else:
        var = Variable(name)
        map[name] = var
    return var
Esempio n. 17
0
def main():
    all_origin_number = {}

    for i in range(9):
        while True:
            row_input = input('please input ' + str(i + 1) + ' row: ')
            if valid_input(row_input):
                break
        for j in range(9):
            if row_input[j] != 'n':
                all_origin_number[(i, j)] = int(row_input[j]) - 1

    all_variable = [[[
        Variable('v' + str(i) + str(j) + str(k)) for k in range(9)
    ] for j in range(9)] for i in range(9)]
    true_var = Variable('v_true')

    exp = true_var
    exp = exp & all_element(all_variable, true_var)
    exp = exp & valid_all(all_variable, true_var)

    for keys in all_origin_number.keys():
        exp = exp & all_variable[keys[0]][keys[1]][all_origin_number[keys]]

    solver = Minisat()
    solution = solver.solve(exp)
    if solution.success:
        for i in range(9):
            print('row' + str(i + 1) + ': ', end='')
            for j in range(9):
                for index, var in enumerate(all_variable[i][j]):
                    if solution[var]:
                        print(index + 1, end='')
                        break
            print('\n', end='')
    else:
        print('no solution')
Esempio n. 18
0
    def __init__(self, numVariables, numClauses):
        self.numVariables = numVariables
        self.numLiterals = 2 * numVariables
        self.numClauses = numClauses

        # satispy Variables
        self.variables = [Variable(str(i)) for i in range(numVariables)]

        # Array of arrays (clauses)
        # Literal 2n represents variable n, whereas literal (2n + 1) represents variable -n
        self.formula = []

        # Total number of variables actually used in formula
        self.variablesInFormula = []
        self.solution = []
Esempio n. 19
0
def generate(numVariables, k, numClauses):
    # TODO: assert numVariables < k * numClauses?
    # Total number of possible literals
    numLiterals = 2 * numVariables

    # Literal 2n represents variable n, whereas literal (2n + 1) represents variable -n
    formula = [sample(range(numLiterals), k) for _ in range(numClauses)]

    # Get total number of variables actually used in formula
    variablesInFormula = set([literal / 2 for clause in formula for literal in clause])

    variables = [Variable(str(i)) for i in range(numVariables)]

    # Build CNF
    cnf = Cnf()
    for clause in formula:

        # Build DNF
        dnf = Cnf()
        for literal in clause:

            # Get variable using literal index
            variable = variables[literal / 2]

            # Again, negate variable as described above
            dnf |= variable if literal % 2 == 0 else -variable

        # Append DNF clause
        cnf &= dnf

    solver = Minisat()
    solution = solver.solve(cnf)
    for dis in cnf.dis:
        for var in dis:
            print var.name
            print var.inverted

    # TODO: consider external representation for 'formula'
    if solution.success:
        return (formula, [solution[variables[i]] for i in variablesInFormula])
    else:
        return (formula, None)
Esempio n. 20
0
def reduce_AMO_binary(items, _assign_id=[0]):
    """ At most one 'binary' encoding (Prestwich) aka. 'bitwise'

        Example (where a-d are items; X1-X2 are extra variables):
        -a|-X1   -b| X1   -c|-X1   d|X1
        -a|-X2   -b|-X2   -c| X1   d|X1

        As soon a var is set True ~var becomes False so the X clause must
        become True. This forces all X's to a value of either True of False.
        In the case of a this is b1=False b2=False which can be shortened to
        00, b set true becomes 01, c 10, d 11. I.e. increasing binary
        numbers, which are unique; therefore will conflict if two vars are
        set to True.

        Clauses: n * log2(n)
        Extra Vars: log2(n)
        Only sees a win over naive with 8+ vars. 7 is equal.

        items: A list of variables, or cnfs (must have two or more items)
        assign_id: Internal counter, don't replace

        NOTE: This method is less efficient than sequential and product.
              However in-case something matters in the future.
    """
    mask = 1
    nitems = [-i for i in items]
    cnf = Cnf()
    # 8 items mask
    while (mask << 1) < len(items):
        v = Variable("BIN" + str(_assign_id[0]))
        _assign_id[0] += 1
        nv = -v
        for i in range(len(items)):
            if i & mask:
                cnf &= nitems[i] | v
            else:
                cnf &= nitems[i] | nv
        mask <<= 1
    return cnf
Esempio n. 21
0
    def tostring(self, cnf):
        """Convert Cnf object ot Dimacs cnf string
        
        cnf: Cnf object
        
        In the converted Cnf there will be only numbers for
        variable names. The conversion guarantees that the
        variables will be numbered alphabetically.
        """
        self.varname_dict = {}
        self.varobj_dict = {}

        varis = set()
        for d in cnf.dis:
            for v in d:
                varis.add(v.name)

        ret = "p cnf %d %d" % (len(varis), len(cnf.dis))

        varis = dict(
            list(
                zip(sorted(list(varis)),
                    list(map(str, list(range(1,
                                             len(varis) + 1)))))))

        for v in varis:
            vo = Variable(v)
            self.varname_dict[vo] = varis[v]
            self.varobj_dict[varis[v]] = vo

        for d in cnf.dis:
            ret += "\n"
            vnamelist = []
            for v in d:
                vnamelist.append(("-" if v.inverted else "") + varis[v.name])
            ret += " ".join(vnamelist) + " 0"

        return ret
    def solve(self, expr):
        """Takes a list of dependent and conflicting packages
        and returns whether the current configuration is satisfiable."""

        dependent = [p for p in expr if '-' not in p]
        conflicting = [p[1:] for p in expr if '-' in p]

        # Generate set of unique package variables.
        variables = {}
        for var in set(dependent + conflicting):
            variables[var] = Variable(var)

        # Generate 'CNF' logical expression from dependencies
        # and conflicts.
        expr = Cnf()

        for con in dependent:
            v = variables[con]
            expr = expr & v

        for con in conflicting:
            v = variables[con]
            expr = expr & -v

        # Calculate the satisfiability of the input variables.
        valid, param = self._check_satisfiability(variables, expr)

        if valid:
            logging.debug(
                "Logical expression, {}, is satisfiable with parameters, {}.".
                format(expr, param))
        else:
            logging.debug(
                "Logical expression, {} , is unsatisfiable.".format(expr))

        return valid, param
Esempio n. 23
0
def solve(num_wizards, num_constraints, wizards, constraints, constraintDiction):
    """
    Write your algorithm here.
    Input:
        num_wizards: Number of wizards
        num_constraints: Number of constraints
        wizards: An array of wizard names, in no particular order
        constraints: A 2D-array of constraints, 
                     where constraints[0] may take the form ['A', 'B', 'C']i

    Output:
        An array of wizard names in the ordering your algorithm returns
    """
    maxVal = 0
    maxRet = wizards

    #constraintDict = {}

    iteration = 0
    while True:
        constraintToVariable = dict()
        exp = None

        g1 = Graph(num_wizards)
        g2 = Graph(num_wizards)
        for constraint in constraints:
            wiz1 = constraint[0]
            wiz2 = constraint[1]
            wiz3 = constraint[2]

            clause1 = wiz3 + " " + wiz1
            clause2 = wiz3 + " " + wiz2
            clause3 = wiz1 + " " + wiz3
            clause4 = wiz2 + " " + wiz3

            g1.addEdge(wiz3, wiz1)
            g1.addEdge(wiz3, wiz2)
            g2.addEdge(wiz1, wiz3)
            g2.addEdge(wiz2, wiz3)

            if clause1 in constraintToVariable:
                v1 = constraintToVariable[clause1]
            else:
                constraintToVariable[clause1] = Variable(clause1)
                v1 = constraintToVariable[clause1]

            if clause2 in constraintToVariable:
                v2 = constraintToVariable[clause2]
            else:
                constraintToVariable[clause2] = Variable(clause2)
                v2 = constraintToVariable[clause2]

            if clause3 in constraintToVariable:
                v3 = constraintToVariable[clause3]
            else:
                constraintToVariable[clause3] = Variable(clause3)
                v3 = constraintToVariable[clause3]

            if clause4 in constraintToVariable:
                v4 = constraintToVariable[clause4]
            else:
                constraintToVariable[clause4] = Variable(clause4)
                v4 = constraintToVariable[clause4]

            literal = ((v1 & v2 & -v3 & -v4) ^ (v3 & v4 & -v1 & -v2))
            if exp is None:
                exp = literal
            else:
                exp = exp & literal

        solver = Minisat()
        solution = solver.solve(exp)
        if solution.success:
            graph = dict()
            g = Graph(num_wizards)
            for wizard in wizards:
                graph[wizard] = set()
            for constraint in constraintToVariable:
                v = constraintToVariable[constraint]
                if solution[v] == True:
                    # print(v)
                    w = str(v).split()
                    vertexU = w[0]
                    vertexV = w[1]
                    graph[vertexU].add(vertexV)
                    g.addEdge(vertexU, vertexV)

                    cycle = False
                    try: topological(graph)
                    except ValueError: cycle = True
                    if cycle:
                        graph[vertexU].remove(vertexV)
                        graph[vertexV].add(vertexU)
            cycle = False
            try: topSortGraph = topological(graph)
            except ValueError: cycle = True
        graph = {}
        if not cycle:
            ans = list(topSortGraph)
            comp = checkConstraintsWithList(constraints, ans)
            if comp > maxVal:
                maxVal = comp
                maxRet = ans
            if iteration > 100:
                return az(maxRet,constraintDiction) #maxRet
            # print(comp)
        iteration += 1
        shuffle(wizards)
        shuffle(constraints)
Esempio n. 24
0
from satispy import Variable, Cnf
from satispy.solver import Minisat

solver = Minisat()

file = open('testes.txt')

x = [[[0 for k in range(4)] for j in range(4)] for i in range(4)] 

for i in range(4):
    for j in range(4):
        for k in range(4):
            x[i][j][k] = Variable('x_'+str(i)+str(j)+'_'+str(k))

sudoku = file.readline()

n = 1

while sudoku != '':

########################################################################################
########################################################################################
## Escreva aqui o código gerador da formula CNF que representa o Sudoku codificado na ##
## variavel 'sudoku'. Nao se esqueca que o codigo deve estar no escopo do 'while'     ##
## acima e deve guardar a formula CNF na variavel 'cnf'.                              ##
########################################################################################
########################################################################################

    cnf = Cnf()   
    
    #Configurando o sudoku como uma matriz dos números passados
Esempio n. 25
0
def r_sat_step(x):
    eq = Variable('eq')
    for i in range(0, N):
        eq &= get_formula(get_bit(x, i), i % N, (i + 1) % N, (i + 2) % N)

    return solve(eq)
Esempio n. 26
0
def get_formula(bit, c, b, a):
    a, b, c = Variable(str(a)), Variable(str(b)), Variable(str(c))
    if bit:
        return (-a & -b & c) | (b & -c) | (a & -c)
    else:
        return (-a & -b & -c) | (b & c) | (a & c)
Esempio n. 27
0
            graph.append(nums)

    graph_file.close()
    return graph


graph = readGraphFile()

exp = Cnf()
c1 = dict()
c2 = dict()
c3 = dict()

# one of the three colors for a vertex
for vertex in range(VERTICES):
    c1[vertex] = Variable('edge%dhasColor1' % vertex)
    c2[vertex] = Variable('edge%dhasColor2' % vertex)
    c3[vertex] = Variable('edge%dhasColor3' % vertex)

    # one of three
    exp &= c1[vertex] | c2[vertex] | c3[vertex]
    exp &= c1[vertex] | -c2[vertex] | -c3[vertex]
    exp &= -c1[vertex] | c2[vertex] | -c3[vertex]
    exp &= -c1[vertex] | -c2[vertex] | c3[vertex]

# not same color on one edge
for edge in graph:
    begin = edge[0]
    end = edge[1]
    exp &= -c1[begin] | -c1[end]
    exp &= -c2[begin] | -c2[end]
team= n
week =n-1
period=int(n/2)

exp = Cnf()


sol={}
#Creation des variables :
for w in range(week):
    sol[w]={}
    for p in range(period):
        sol[w][p]=[]

        for length_team in range(team):
            v0 = Variable(str(w)+str(p)+str(length_team))
            sol[w][p].append(v0)




#C1 Une équipe joue contre une autre
for w in range(week):
    for p in range(period):
        c = Cnf()
        for t in range(team):

            for t2 in range(t+1, team):
                c |= (sol[w][p][t]&sol[w][p][t2]) #C1-3 Au moins deux équipe
                for t3 in range(t2+1, team):
                    exp &= ( (sol[w][p][t] & sol[w][p][t2] )>> -sol[w][p][t3]) #Pas plus de deux équipes
Esempio n. 29
0
from satispy import Variable
from satispy.solver import Minisat

v1 = Variable('v1')
v2 = Variable('v2')
v3 = Variable('v3')

exp = v1 & v2 | v3

solver = Minisat()

solution = solver.solve(exp)

if solution.error != False:
    print "Error:"
    print solution.error
elif solution.success:
    print "Found a solution:"
    print v1, solution[v1]
    print v2, solution[v2]
    print v3, solution[v3]
else:
    print "The expression cannot be satisfied"
Esempio n. 30
0
def sat(instance):
    expr = Cnf()

    nproc = instance.nproc
    nmach = instance.nmach
    nserv = instance.nserv
    nneigh = len(instance.N)
    nloc = len(instance.L)

    P = instance.P
    M = instance.M
    S = instance.S
    N = instance.N
    L = instance.L

    print(" %10.3f creating vars - x" % (time() - all_start))
    x = np.empty((nproc, nmach), dtype=object)
    for p in P:
        for m in M:
            x[p, m] = Variable('x[%d,%d]' % (p, m))

    print(" %10.3f creating vars - h" % (time() - all_start))
    h = np.empty((nserv, nneigh), dtype=object)
    for s in S:
        for n in N:
            h[s, n] = Variable('h[%d,%d]' % (s, n))

    print(" %10.3f creating vars - o" % (time() - all_start))
    o = np.empty((nserv, nloc), dtype=object)
    for s in S:
        for l in L:
            o[s, l] = Variable('o[%d,%d]' % (s, l))

    print(" %10.3f H[s,n]" % (time() - all_start))
    for s in S:
        #print(" %10.3f H[%6d,n]" %( time() - all_start,s))
        for n in N:
            pres_expr = Cnf()
            for p in S[s]:
                for m in N[n]:
                    pres_expr |= x[p, m]

            expr &= h[s, n] >> pres_expr
            expr &= pres_expr >> h[s, n]
            for sd in instance.sdep[s]:
                expr &= h[s, n] >> h[sd, n]

    print(" %10.3f O[s,l]" % (time() - all_start))
    for s in S:
        #print(" %10.3f O[%6d,l]" %( time() - all_start,s))
        if instance.delta[s] == 1: continue
        for l in L:
            pres_expr = Cnf()
            for p in S[s]:
                for m in L[l]:
                    pres_expr |= x[p, m]

            expr &= o[s, l] >> pres_expr
            expr &= pres_expr >> o[s, l]

    print(" %10.3f X[p,m]" % (time() - all_start))

    for p in P:
        #print(" %10.3f X[%6d, m]" %( time() - all_start, p))
        p_constr1 = Cnf()
        p_constr2 = Cnf()
        for m in M:
            p_constr1 |= x[p, m]

            for m2 in range(m + 1, nmach):
                p_constr2 &= x[p, m] >> -x[p, m2]
        expr &= p_constr1 & p_constr2

    print(" %10.3f X[p,m] - conflito" % (time() - all_start))

    for m in M:
        for s in S:
            conf_constr = Cnf()
            if len(S[s]) == 1: continue
            for i1 in range(len(S[s])):
                for i2 in range(i1 + 1, len(S[s])):
                    conf_constr &= x[S[s][i1], m] >> -x[S[s][i2], m]
            expr &= conf_constr

    print(" %10.3f solving" % (time() - all_start))

    io = DimacsCnf()
    #s = io.tostring(expr)
    #print(s)
    solver = Minisat('minisat %s %s')

    solution = solver.solve(expr)
    print(" %10.3f done" % (time() - all_start))

    if not solution.success:
        print(" %10.3f sem solucao" % (time() - all_start))
        exit(0)

    print(" %10.3f solucao" % (time() - all_start))

    xsol = np.empty((nproc, nmach), dtype=np.int32)
    for p in P:
        for m in M:
            #print(p,m,solution[x[p,m]])
            #print(io.varname(x[p,m]))
            xsol[p, m] = solution[x[p, m]]

    print(xsol)
    print(np.all(xsol.sum(axis=1) == 1))
    for m in M:
        print(instance.mach_validate(m, xsol[:, m]))