本文整理汇总了Python中cnfformula.cnf.CNF.add_clause方法的典型用法代码示例。如果您正苦于以下问题:Python CNF.add_clause方法的具体用法?Python CNF.add_clause怎么用?Python CNF.add_clause使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类cnfformula.cnf.CNF
的用法示例。
在下文中一共展示了CNF.add_clause方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: TseitinFormula
# 需要导入模块: from cnfformula.cnf import CNF [as 别名]
# 或者: from cnfformula.cnf.CNF import add_clause [as 别名]
def TseitinFormula(graph,charges=None):
"""Build a Tseitin formula based on the input graph.
Odd charge is put on the first vertex by default, unless other
vertices are is specified in input.
Arguments:
- `graph`: input graph
- `charges': odd or even charge for each vertex
"""
V=enumerate_vertices(graph)
if charges==None:
charges=[1]+[0]*(len(V)-1) # odd charge on first vertex
else:
charges = [bool(c) for c in charges] # map to boolean
if len(charges)<len(V):
charges=charges+[0]*(len(V)-len(charges)) # pad with even charges
# init formula
tse=CNF()
for e in sorted(graph.edges(),key=sorted):
tse.add_variable(edgename(e))
# add constraints
for v,c in zip(V,charges):
# produce all clauses and save half of them
names = [ edgename((u,v)) for u in neighbors(graph,v) ]
for cls in parity_constraint(names,c):
tse.add_clause(list(cls),strict=True)
return tse
示例2: BinaryPigeonholePrinciple
# 需要导入模块: from cnfformula.cnf import CNF [as 别名]
# 或者: from cnfformula.cnf.CNF import add_clause [as 别名]
def BinaryPigeonholePrinciple(pigeons,holes):
"""Binary Pigeonhole Principle CNF formula
The pigeonhole principle claims that no M pigeons can sit in
N pigeonholes without collision if M>N. This formula encodes the
principle using binary strings to identify the holes.
Parameters
----------
pigeon : int
number of pigeons
holes : int
number of holes
"""
bphp=CNF()
bphp.header="Binary Pigeonhole Principle for {0} pigeons and {1} holes\n".format(pigeons,holes)\
+ bphp.header
bphpgen=bphp.binary_mapping(xrange(1,pigeons+1), xrange(1,holes+1), injective = True)
for v in bphpgen.variables():
bphp.add_variable(v)
for c in bphpgen.clauses():
bphp.add_clause(c,strict=True)
return bphp
示例3: CountingPrinciple
# 需要导入模块: from cnfformula.cnf import CNF [as 别名]
# 或者: from cnfformula.cnf.CNF import add_clause [as 别名]
def CountingPrinciple(M,p):
"""Generates the clauses for the counting matching principle.
The principle claims that there is a way to partition M in sets of
size p each.
Arguments:
- `M` : size of the domain
- `p` : size of each class
"""
cnf=CNF()
# Describe the formula
name="Counting Principle: {0} divided in parts of size {1}.".format(M,p)
cnf.header=name+"\n"+cnf.header
def var_name(tpl):
return "Y_{{"+",".join("{0}".format(v) for v in tpl)+"}}"
# Incidence lists
incidence=[[] for _ in range(M)]
for tpl in combinations(range(M),p):
for i in tpl:
incidence[i].append(tpl)
# Each element of the domain is in exactly one part.
for el in range(M):
edge_vars = [var_name(tpl) for tpl in incidence[el]]
for cls in CNF.equal_to_constraint(edge_vars,1):
cnf.add_clause(cls)
return cnf
示例4: RandomKCNF
# 需要导入模块: from cnfformula.cnf import CNF [as 别名]
# 或者: from cnfformula.cnf.CNF import add_clause [as 别名]
def RandomKCNF(k, n, m, seed=None, planted_assignments=[]):
"""Build a random k-CNF
Sample :math:`m` clauses over :math:`n` variables, each of width
:math:`k`, uniformly at random. The sampling is done without
repetition, meaning that whenever a randomly picked clause is
already in the CNF, it is sampled again.
Parameters
----------
k : int
width of each clause
n : int
number of variables to choose from. The resulting CNF object
will contain n variables even if some are not mentioned in the clauses.
m : int
number of clauses to generate
seed : hashable object
seed of the random generator
planted_assignments : iterable(dict), optional
a set of total/partial assigments such that all clauses in the formula
will be satisfied by all of them.
Returns
-------
a CNF object
Raises
------
ValueError
when some paramenter is negative, or when k>n.
"""
if seed:
random.seed(seed)
if n<0 or m<0 or k<0:
raise ValueError("Parameters must be non-negatives.")
if k>n:
raise ValueError("Clauses cannot have more {} literals.".format(n))
F = CNF()
F.header = "Random {}-CNF over {} variables and {} clauses\n".format(k,n,m) + F.header
indices = xrange(1,n+1)
for i in indices:
F.add_variable('x_{0}'.format(i))
try:
for clause in sample_clauses(k, indices, m, planted_assignments):
F.add_clause(list(clause), strict=True)
except ValueError:
raise ValueError("There are fewer clauses available than the number requested")
return F
示例5: PerfectMatchingPrinciple
# 需要导入模块: from cnfformula.cnf import CNF [as 别名]
# 或者: from cnfformula.cnf.CNF import add_clause [as 别名]
def PerfectMatchingPrinciple(graph):
"""Generates the clauses for the graph perfect matching principle.
The principle claims that there is a way to select edges to such
that all vertices have exactly one incident edge set to 1.
Arguments:
- `graph` : undirected graph
"""
cnf=CNF()
# Describe the formula
name="Perfect Matching Principle"
if hasattr(graph,'name'):
cnf.header=name+" of graph:\n"+graph.name+"\n"+cnf.header
else:
cnf.header=name+".\n"+cnf.header
def var_name(u,v):
if u<=v:
return 'x_{{{0},{1}}}'.format(u,v)
else:
return 'x_{{{0},{1}}}'.format(v,u)
# Each vertex has exactly one edge set to one.
for v in graph.nodes():
edge_vars = [var_name(u,v) for u in graph.adj[v]]
for cls in equal_to_constraint(edge_vars,1):
cnf.add_clause(cls)
return cnf
示例6: test_opposite_literals
# 需要导入模块: from cnfformula.cnf import CNF [as 别名]
# 或者: from cnfformula.cnf.CNF import add_clause [as 别名]
def test_opposite_literals(self):
F=CNF()
F.auto_add_variables = True
F.allow_opposite_literals = True
F.add_clause([(True,"S"),(False,"T"),(False,"S")])
F.allow_opposite_literals = False
self.assertRaises(ValueError, F.add_clause,
[(True,"T"),(True,"V"),(False,"T")])
示例7: test_one_clause
# 需要导入模块: from cnfformula.cnf import CNF [as 别名]
# 或者: from cnfformula.cnf.CNF import add_clause [as 别名]
def test_one_clause(self) :
opb="""\
* #variable= 4 #constraint= 1
*
+1 x1 +1 x2 -1 x3 -1 x4 >= -1;
"""
F=CNF()
F.add_clause([(True,"a"),(True,"b"),(False,"c"),(False,"d")])
self.assertCnfEqualsOPB(F,opb)
示例8: EvenColoringFormula
# 需要导入模块: from cnfformula.cnf import CNF [as 别名]
# 或者: from cnfformula.cnf.CNF import add_clause [as 别名]
def EvenColoringFormula(G):
"""Even coloring formula
The formula is defined on a graph :math:`G` and claims that it is
possible to split the edges of the graph in two parts, so that
each vertex has an equal number of incident edges in each part.
The formula is defined on graphs where all vertices have even
degree. The formula is satisfiable only on those graphs with an
even number of vertices in each connected component [1]_.
Arguments
---------
G : networkx.Graph
a simple undirected graph where all vertices have even degree
Raises
------
ValueError
if the graph in input has a vertex with odd degree
Returns
-------
CNF object
References
----------
.. [1] Locality and Hard SAT-instances, Klas Markstrom
Journal on Satisfiability, Boolean Modeling and Computation 2 (2006) 221-228
"""
F = CNF()
F.header = "Even coloring formula on graph " + G.name + "\n" + F.header
def var_name(u,v):
if u<=v:
return 'x_{{{0},{1}}}'.format(u,v)
else:
return 'x_{{{0},{1}}}'.format(v,u)
for (u, v) in enumerate_edges(G):
F.add_variable(var_name(u, v))
# Defined on both side
for v in enumerate_vertices(G):
if G.degree(v) % 2 == 1:
raise ValueError("Markstrom formulas requires all vertices to have even degree.")
edge_vars = [ var_name(u,v) for u in neighbors(G,v) ]
for cls in CNF.equal_to_constraint(edge_vars,
len(edge_vars)/2):
F.add_clause(cls,strict=True)
return F
示例9: test_strict_clause_insertion
# 需要导入模块: from cnfformula.cnf import CNF [as 别名]
# 或者: from cnfformula.cnf.CNF import add_clause [as 别名]
def test_strict_clause_insertion(self):
F=CNF()
F.mode_strict()
F.add_variable("S")
F.add_variable("T")
F.add_variable("U")
self.assertTrue(len(list(F.variables()))==3)
F.add_clause([(True,"S"),(False,"T")])
F.add_clause([(True,"T"),(False,"U")])
self.assertRaises(ValueError, F.add_clause,
[(True,"T"),(False,"V")])
示例10: test_auto_add_variables
# 需要导入模块: from cnfformula.cnf import CNF [as 别名]
# 或者: from cnfformula.cnf.CNF import add_clause [as 别名]
def test_auto_add_variables(self):
F=CNF()
F.auto_add_variables = True
F.add_variable("S")
F.add_variable("U")
self.assertTrue(len(list(F.variables()))==2)
F.add_clause([(True,"S"),(False,"T")])
self.assertTrue(len(list(F.variables()))==3)
F.auto_add_variables = False
F.add_clause([(True,"T"),(False,"U")])
self.assertRaises(ValueError, F.add_clause,
[(True,"T"),(False,"V")])
示例11: PythagoreanTriples
# 需要导入模块: from cnfformula.cnf import CNF [as 别名]
# 或者: from cnfformula.cnf.CNF import add_clause [as 别名]
def PythagoreanTriples(N):
"""There is a Pythagorean triples free coloring on N
The formula claims that it is possible to bicolor the numbers from
1 to :math:`N` so that there is no monochromatic triplet
:math:`(x,y,z)` so that :math:`x^2+y^2=z^2`.
Parameters
----------
N : int
size of the interval
Return
------
A CNF object
Raises
------
ValueError
Parameters are not positive integers
References
----------
.. [1] M. J. Heule, O. Kullmann, and V. W. Marek.
Solving and verifying the boolean pythagorean triples problem via cube-and-conquer.
arXiv preprint arXiv:1605.00723, 2016.
"""
ptn=CNF()
ptn.header=dedent("""
It is possible to bicolor the numbers from
1 to {} so that there is no monochromatic triplets
(x,y,z) such that x^2+y^2=z^2
""".format(N)) + ptn.header
def V(i):
return "x_{{{}}}".format(i)
# Variables represent the coloring of the number
for i in xrange(1,N+1):
ptn.add_variable(V(i))
for x,y in combinations(range(1,N+1),2):
z = int(sqrt(x**2 + y**2))
if z <=N and z**2 == x**2 + y**2:
ptn.add_clause([ (True, V(x)), (True, V(y)), (True, V(z))])
ptn.add_clause([ (False,V(x)), (False,V(y)), (False,V(z))])
return ptn
示例12: RamseyLowerBoundFormula
# 需要导入模块: from cnfformula.cnf import CNF [as 别名]
# 或者: from cnfformula.cnf.CNF import add_clause [as 别名]
def RamseyLowerBoundFormula(s,k,N):
"""Formula claiming that Ramsey number r(s,k) > N
Arguments:
- `s`: independent set size
- `k`: clique size
- `N`: vertices
"""
ram=CNF()
ram.mode_strict()
ram.header=dedent("""\
CNF encoding of the claim that there is a graph of %d vertices
with no independent set of size %d and no clique of size %d
""" % (N,s,k)) + ram.header
#
# One variable per edge (indices are ordered)
#
for edge in combinations(xrange(1,N+1),2):
ram.add_variable('e_{{{0},{1}}}'.format(*edge))
#
# No independent set of size s
#
for vertex_set in combinations(xrange(1,N+1),s):
clause=[]
for edge in combinations(vertex_set,2):
clause += [(True,'e_{{{0},{1}}}'.format(*edge))]
ram.add_clause(clause)
#
# No clique of size k
#
for vertex_set in combinations(xrange(1,N+1),k):
clause=[]
for edge in combinations(vertex_set,2):
clause+=[(False,'e_{{{0},{1}}}'.format(*edge))]
ram.add_clause(clause)
return ram
示例13: BinaryCliqueFormula
# 需要导入模块: from cnfformula.cnf import CNF [as 别名]
# 或者: from cnfformula.cnf.CNF import add_clause [as 别名]
def BinaryCliqueFormula(G,k):
"""Test whether a graph has a k-clique.
Given a graph :math:`G` and a non negative value :math:`k`, the
CNF formula claims that :math:`G` contains a :math:`k`-clique.
This formula uses the binary encoding, in the sense that the
clique elements are indexed by strings of bits.
Parameters
----------
G : networkx.Graph
a simple graph
k : a non negative integer
clique size
Returns
-------
a CNF object
"""
F=CNF()
F.header="Binary {0}-clique formula\n".format(k) + F.header
clauses_gen=F.binary_mapping(xrange(1,k+1), G.nodes(),
injective = True,
nondecreasing = True)
for v in clauses_gen.variables():
F.add_variable(v)
for c in clauses_gen.clauses():
F.add_clause(c,strict=True)
for (i1,i2),(v1,v2) in product(combinations(xrange(1,k+1),2),
combinations(G.nodes(),2)):
if not G.has_edge(v1,v2):
F.add_clause( clauses_gen.forbid_image(i1,v1) + clauses_gen.forbid_image(i2,v2),strict=True)
return F
示例14: PebblingFormula
# 需要导入模块: from cnfformula.cnf import CNF [as 别名]
# 或者: from cnfformula.cnf.CNF import add_clause [as 别名]
def PebblingFormula(digraph):
"""Pebbling formula
Build a pebbling formula from the directed graph. If the graph has
an `ordered_vertices` attribute, then it is used to enumerate the
vertices (and the corresponding variables).
Arguments:
- `digraph`: directed acyclic graph.
"""
if not is_dag(digraph):
raise ValueError("Pebbling formula is defined only for directed acyclic graphs")
peb=CNF()
peb.mode_unchecked()
if hasattr(digraph,'name'):
peb.header="Pebbling formula of: "+digraph.name+"\n\n"+peb.header
else:
peb.header="Pebbling formula\n\n"+peb.header
# add variables in the appropriate order
vertices=enumerate_vertices(digraph)
position=dict((v,i) for (i,v) in enumerate(vertices))
for v in vertices:
peb.add_variable(v,description="There is a pebble on vertex ${}$".format(v))
# add the clauses
for v in vertices:
# If predecessors are pebbled the vertex must be pebbled
pred=sorted(digraph.predecessors(v),key=lambda x:position[x])
peb.add_clause([(False,p) for p in pred]+[(True,v)])
if digraph.out_degree(v)==0: #the sink
peb.add_clause([(False,v)])
return peb
示例15: VertexCover
# 需要导入模块: from cnfformula.cnf import CNF [as 别名]
# 或者: from cnfformula.cnf.CNF import add_clause [as 别名]
def VertexCover(G,d):
F=CNF()
def D(v):
return "x_{{{0}}}".format(v)
def N(v):
return tuple(sorted([ e for e in G.edges(v) ]))
# Fix the vertex order
V=enumerate_vertices(G)
# Create variables
for v in V:
F.add_variable(D(v))
# Not too many true variables
F.add_less_or_equal([D(v) for v in V],d)
# Every edge must have a true D variable
for e in G.edges():
F.add_clause([ (True,D(v)) for v in e])
return F