python - How to restrict the number of zeros in constraint programming -


for given n , m iterate on n m partial circulant matrices entries either 0 or 1. want find if there matrix such there no 2 subsets of columns have same sum. here when add columns elementwise. current code uses constraint programming via ortools. here code.

from scipy.linalg import circulant import numpy np import itertools ortools.constraint_solver import pywrapcp cs  n = 4 m = 6  def isdetecting(matrix):     solver = cs.solver("scip")     x = np.array([solver.intvar(values) in range(matrix.shape[1])])     x1 = x.tolist()     row in matrix:         x = x[row].tolist()         solver.add(solver.sum(x) == 0)     db = solver.phase(x1, solver.choose_first_unbound, solver.assign_center_value)     solver.newsearch(db)     count = 0 #find 1 non-zero solution if there 1     while (solver.nextsolution() , count < 2):         solution = [x.value() x in x1]         count += 1     solver.endsearch()     if (count == 1):         return true  values = [-1,0,1] nosols = 0 row in itertools.product([0,1],repeat = m):     m = np.array(circulant(row)[0:n], dtype=bool)     if isdetecting(m):         nosols += 1         print m.astype(int) 

the line values = [-1,0,1] allows number of zeros in solutions. how can specify exact number of zeros permitted in solution instead?

in or-tools/python there global constraint solver.count() might used. example:

 the_count = 1 # number of 0's allowed  solver.add(solver.count(x1, 0,the_count)) 

where "the_count" number of 0's allow in (flat) array "x1". the_count can either constant or decision variable (so can constrain value further constraints, or letting domains work of constraining count, e.g. domain 1..4 constrain count between 1 , 4 occurrences).

"x1" array of decision variables checked. second parameter, "0", value count in x.

an example of usage of solver.count(): http://hakank.org/or-tools/young_tableaux.py .

there generalization of solver.count(), namely solver.distribute (a.k.a. global cardinality count, gcc) can count/constrain more 1 value @ same time. see debruijn sequence model example how it's used: http://hakank.org/or-tools/debruijn_binary.py .


Comments

Popular posts from this blog

Android layout hidden on keyboard show -

google app engine - 403 Forbidden POST - Flask WTForms -

c - Why would PK11_GenerateRandom() return an error -8023? -