当前位置: 首页>>代码示例>>Python>>正文


Python pycosat.itersolve函数代码示例

本文整理汇总了Python中pycosat.itersolve函数的典型用法代码示例。如果您正苦于以下问题:Python itersolve函数的具体用法?Python itersolve怎么用?Python itersolve使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了itersolve函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: solve_SAT

def solve_SAT(expr, num_solutions=None):
    """
    Returns a iterator of {var: truth value} assignments which satisfy the given
    expression.

    Expressions should not include a variable named ``TRUE_``, since those
    are used in the internals of this function as stand-ins for truth literals.
    """
    expr = convert_to_conjunctive_normal_form(expr)
    Assignment = get_assignment_class(expr)

    # Hack to include a True literal (not directly supported by pycosat API).
    # We add a trivial constraint to the list of constraints, forcing this
    # variables to be True in any solutions. Note that this is still conjunctive
    # normal form, since T and F are literals.
    T = Var('TRUE_')
    expr = expr & T

    vars = list(get_free_variables(expr))

    # 1-index, since pycosat expects nonzero integers.
    var2pycosat_index = {v: i + 1 for i, v in enumerate(vars)}

    def get_pycosat_index(literal):
        # pycosat accepts input as a list of CNF subclauses (disjunctions of variables
        # or negated variables).
        if isinstance(literal, Not):
            return -get_pycosat_index(literal.children[0])
        elif isinstance(literal, Var):
            return var2pycosat_index[literal]
        elif isinstance(literal, ExpressionNode):  # pragma: no cover
            raise TypeError('Unhandled literal type %r' % literal)
        else:
            # Here we assume this is some other python object, so we consider it
            # a boolean.
            return var2pycosat_index[T] if literal else -var2pycosat_index[T]

    constraints = [
        map(get_pycosat_index,
            # Child is one of a literal or a disjunction of literals.
            (child.children if isinstance(child, Or) else [child]))
        for child in expr.children
    ]

    solutions = (
        pycosat.itersolve(constraints)
        if num_solutions is None else pycosat.itersolve(constraints, num_solutions))
    for solution in solutions:
        namespace = {}
        for i, var_assignment in enumerate(solution):
            # pycosat returns the solution as a list of positive or negative
            # 1-indexed variable numbers. Positive indices correspond to assignments
            # to True, and negative corresponds to False.
            as_bool = var_assignment > 0
            var = vars[i]
            if var == T:
                assert as_bool, 'Bug: Solution has an invalid solution to the T literal.'
            else:
                namespace[var.name] = as_bool
        yield Assignment(**namespace)
开发者ID:lucaswiman,项目名称:pyreasoner,代码行数:60,代码来源:expressions.py

示例2: main

def main():
    # A requires B
    r1 = [-1, 2]

    # A requires C
    r2 = [-1, 3]

    # B conflicts C
    r3 = [-2, -3]

    # A conflicts B
    r4 = [-1, -2]

    # (-A|B) & (-A|C) & (-B|-C)
    cnf1 = [r1, r2, r3]

    # (-A|B) & (-A|-B)
    cnf2 = [r1, r4]

    print("Case 1:")
    for sol in pycosat.itersolve(cnf1):
        interpret(sol)
        print("\t----")

    print("Case 2:")
    for sol in pycosat.itersolve(cnf2):
        interpret(sol)
        print("\t----")
开发者ID:lyshie,项目名称:py-misc-utils,代码行数:28,代码来源:sat.py

示例3: sat

def sat(clauses):
    """
    Calculate a SAT solution for `clauses`.

    Returned is the list of those solutions.  When the clauses are
    unsatisfiable, an empty list is returned.

    """
    try:
        import pycosat
    except ImportError:
        sys.exit('Error: could not import pycosat (required for dependency '
                 'resolving)')

    try:
        pycosat.itersolve({(1,)})
    except TypeError:
        # Old versions of pycosat require lists. This conversion can be very
        # slow, though, so only do it if we need to.
        clauses = list(map(list, clauses))

    solution = pycosat.solve(clauses)
    if solution == "UNSAT" or solution == "UNKNOWN": # wtf https://github.com/ContinuumIO/pycosat/issues/14
        return []
    # XXX: If solution == [] (i.e., clauses == []), the result will have
    # boolean value of False even though the clauses are not unsatisfiable)
    return solution
开发者ID:Bbouley,项目名称:conda,代码行数:27,代码来源:logic.py

示例4: test_shuffle_clauses

 def test_shuffle_clauses(self):
     ref_sols = set(tuple(sol) for sol in itersolve(clauses1))
     for _ in range(10):
         cnf = copy.deepcopy(clauses1)
         # shuffling the clauses does not change the solutions
         random.shuffle(cnf)
         self.assertEqual(set(tuple(sol) for sol in itersolve(cnf)),
                          ref_sols)
开发者ID:ContinuumIO,项目名称:pycosat,代码行数:8,代码来源:test_pycosat.py

示例5: test_cnf1

    def test_cnf1(self):
        for sol in itersolve(clauses1, nvars1):
            #sys.stderr.write('%r\n' % repr(sol))
            self.assertTrue(evaluate(clauses1, sol))

        sols = list(itersolve(clauses1, vars=nvars1))
        self.assertEqual(len(sols), 18)
        # ensure solutions are unique
        self.assertEqual(len(set(tuple(sol) for sol in sols)), 18)
开发者ID:ContinuumIO,项目名称:pycosat,代码行数:9,代码来源:test_pycosat.py

示例6: min_sat

def min_sat(clauses, max_n=1000, N=None, alg='iterate'):
    """
    Calculate the SAT solutions for the `clauses` for which the number of true
    literals from 1 to N is minimal.  Returned is the list of those solutions.
    When the clauses are unsatisfiable, an empty list is returned.

    alg can be any algorithm supported by generate_constraints, or 'iterate",
    which iterates all solutions and finds the smallest.

    """
    log.debug("min_sat using alg: %s" % alg)
    try:
        import pycosat
    except ImportError:
        sys.exit('Error: could not import pycosat (required for dependency '
                 'resolving)')

    if not clauses:
        return []
    m = max(map(abs, chain(*clauses)))
    if not N:
        N = m
    if alg == 'iterate':
        min_tl, solutions = sys.maxsize, []
        try:
            pycosat.itersolve({(1,)})
        except TypeError:
            # Old versions of pycosat require lists. This conversion can be
            # very slow, though, so only do it if we need to.
            clauses = list(map(list, clauses))
        for sol in islice(pycosat.itersolve(clauses), max_n):
            tl = sum(lit > 0 for lit in sol[:N]) # number of true literals
            if tl < min_tl:
                min_tl, solutions = tl, [sol]
            elif tl == min_tl:
                solutions.append(sol)
        return solutions
    else:
        solution = sat(clauses)
        if not solution:
            return []
        eq = [(1, i) for i in range(1, N+1)]
        def func(lo, hi):
            return list(generate_constraints(eq, m,
                [lo, hi], alg=alg))
        evaluate_func = partial(evaluate_eq, eq)
        # Since we have a solution, might as well make use of that fact
        max_val = evaluate_func(solution)
        log.debug("Using max_val %s. N=%s" % (max_val, N))
        constraints = bisect_constraints(0, min(max_val, N), clauses, func,
            evaluate_func=evaluate_func, increment=1000)
        return min_sat(list(chain(clauses, constraints)), max_n=max_n, N=N, alg='iterate')
开发者ID:Trentonoliphant,项目名称:conda,代码行数:52,代码来源:logic.py

示例7: solve

def solve(n):
	y =[]
	#rows
	for i in range (1,(n*n)+1,n):
		y += vertical(range(i,i+n,1),True)

	#columns
	for i in range (1,n+1):
		y+= vertical(range(i,(n*n)-n+1+i,n),True)
		
	#diagonals 
	y+=diagonal(1,n)
	
	#results
	result = []
	for sol in pycosat.itersolve(y):
		result.append(sol)

	#replace numbers with something more meaningful
	result = changeFormat(result,n)
	#return a boolean list indicating which solutions are unique 
	isValid = returnWithoutRotations(result)
	#figure out how many unique solutions there are
	NValidSol = 0
	for i in range(0,len(result)): 
		if isValid[i] :
			NValidSol += 1
	#print out all the unique solutions
	for i in range(0,len(result)):
		if(isValid[i]):
			printSol(result[i])

	print("There are " , NValidSol ,  " unique solutions with rotations and reflections")
开发者ID:nellsel,项目名称:NQueens,代码行数:33,代码来源:n_queens2.py

示例8: solve

 def solve(self):
     """
     Produces an iterator for schedule possibilities that have no conflicts.
     
     Solves the constraints using a SAT solving algorithm and processes the results.
     """
     return ([self.index_mapping[y] for y in x if y > 0] for x in pycosat.itersolve(self.constraints))
开发者ID:ldfaiztt,项目名称:COURSERATOR3000,代码行数:7,代码来源:scheduler.py

示例9: min_sat

def min_sat(clauses, max_n=1000):
    """
    Calculate the SAT solutions for the `clauses` for which the number of
    true literals is minimal.  Returned is the list of those solutions.
    When the clauses are unsatisfiable, an empty list is returned.

    This function could be implemented using a Pseudo-Boolean SAT solver,
    which would avoid looping over the SAT solutions, and would therefore
    be much more efficient.  However, for our purpose the current
    implementation is good enough.
    """
    try:
        import pycosat
    except ImportError:
        sys.exit('Error: could not import pycosat (required for dependency '
                 'resolving)')

    min_tl, solutions = sys.maxsize, []
    for sol in islice(pycosat.itersolve(clauses), max_n):
        tl = sum(lit > 0 for lit in sol) # number of true literals
        if tl < min_tl:
            min_tl, solutions = tl, [sol]
        elif tl == min_tl:
            solutions.append(sol)

    return solutions
开发者ID:hajs,项目名称:conda,代码行数:26,代码来源:resolve.py

示例10: solve

def solve():
    clauses = queens_clauses()
    # solve the SAT problem
    for sol in pycosat.itersolve(clauses):
        sol = set(sol)
        for i in range(N):
            print(''.join('Q' if v(i, j) in sol else '.' for j in range(N)))
        print('')
开发者ID:ContinuumIO,项目名称:pycosat,代码行数:8,代码来源:8queens.py

示例11: solutions

    def solutions(self):
        """
        Yield each solution to the current set of constraints.
        """
        solution_found = False
        for solution in pycosat.itersolve(self.clauses):
            yield self.remap_solution(solution)
            solution_found = True

        if not solution_found:
            # Only present to raise a descriptive exception.
            self.solution
开发者ID:ericpruitt,项目名称:a9bsp,代码行数:12,代码来源:a9bsp.py

示例12: minimal_solutions

    def minimal_solutions(self):
        # this is a bit of a strawman.  the idea is, we need to enumerate all of the SAT
        # solutions to know which is the smallest!  the containment thing in the old version (below)
        # seems sketchy to me, due to nonmonotonicity.  return to this later.
        solns = []
        for soln in pycosat.itersolve(self.satformula):
            solns.append(frozenset(map(self.vars.lookupNum, filter(lambda x: x > 0, soln))))

        def getKey(item):
            return len(item)

        for soln in sorted(solns, key=getKey):
            yield soln
开发者ID:palvaro,项目名称:ldfi-py,代码行数:13,代码来源:psat.py

示例13: Nminimal_solutions

    def Nminimal_solutions(self):
        solns = []        
        done = []
        for soln in pycosat.itersolve(self.satformula):
            solns.append(frozenset(map(self.vars.lookupNum, filter(lambda x: x > 0, soln))))
        
        def getKey(item):
            return len(item)

        for soln in sorted(solns, key=getKey):
            #if not done.has_key(soln):
            #    yield soln
            if self.contained_in_none(done, soln):
                yield soln
            done.append(soln)
开发者ID:palvaro,项目名称:ldfi-py,代码行数:15,代码来源:psat.py

示例14: main

def main(req_use):
    if req_use.strip() == '':
        return [[]]
    # REQUIRED_USE variable value for which the combinations
    # are being generated

    # If flags aren't provided, match words from REQUIRED_USE
    flags = re.findall(r'\w+', req_use)

    # Remove duplicates
    flags = list(set(flags))
    # sort reverse to length (so that they can be replaced in
    # this order by numbers later)
    flags = sorted(flags, key=len)
    flags.reverse()

    i = 1
    dict = {}
    rev_dict = {}
    # Assign a number to each keyword (to send to pycosat as
    # it accepts cnf in form of numbers )
    for k in flags:
        dict[k] = i
        rev_dict[i] = k
        i += 1

    # Generate the needed boolean expression
    cnf_out = solve(req_use)

    # str(object) gives a string in CNF form
    cnf_str = str(cnf_out)

    # Replace all flags with numerical equivalent
    for key in flags:
        cnf_str = cnf_str.replace(key, str(dict[key]))

    # Convert to form needed by pycosat
    cnf_str = cnf_str[1:-1]
    cnf_lst = cnf_str.split(') & (')
    for i in range(len(cnf_lst)):
        cnf_lst[i] = [int(k) for k in cnf_lst[i].split(' | ')]

    # Generate all possible solutions to the equation
    k = (list(pycosat.itersolve(cnf_lst)))
    for soln in k:
        for i in range(0, len(soln)):
            soln[i] = ( "-" if soln[i] < 0 else "" ) + rev_dict[abs(soln[i])]
    return k
开发者ID:pallavagarwal07,项目名称:SummerOfCode16,代码行数:48,代码来源:solver.py

示例15: process_cnf_file

def process_cnf_file(path):
    sys.stdout.write('%30s:  ' % basename(path))
    sys.stdout.flush()

    clauses, n_vars = read_cnf(path)
    sys.stdout.write('vars: %6d   cls: %6d   ' % (n_vars, len(clauses)))
    sys.stdout.flush()
    n_sol = 0
    for sol in itersolve(clauses, n_vars):
        sys.stdout.write('.')
        sys.stdout.flush()
        assert evaluate(clauses, sol)
        n_sol += 1
    sys.stdout.write("%d\n" % n_sol)
    sys.stdout.flush()
    return n_sol
开发者ID:ContinuumIO,项目名称:pycosat,代码行数:16,代码来源:test_pycosat.py


注:本文中的pycosat.itersolve函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。