本文整理汇总了Python中cnfformula.cnf.CNF.mode_strict方法的典型用法代码示例。如果您正苦于以下问题:Python CNF.mode_strict方法的具体用法?Python CNF.mode_strict怎么用?Python CNF.mode_strict使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类cnfformula.cnf.CNF
的用法示例。
在下文中一共展示了CNF.mode_strict方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: GraphIsomorphism
# 需要导入模块: from cnfformula.cnf import CNF [as 别名]
# 或者: from cnfformula.cnf.CNF import mode_strict [as 别名]
def GraphIsomorphism(G1, G2):
"""Graph Isomorphism formula
The formula is the CNF encoding of the statement that two simple
graphs G1 and G2 are isomorphic.
Parameters
----------
G1 : networkx.Graph
an undirected graph object
G2 : networkx.Graph
an undirected graph object
Returns
-------
A CNF formula which is satiafiable if and only if graphs G1 and G2
are isomorphic.
"""
F = CNF()
F.header = "Graph Isomorphism problem between graphs " +\
G1.name + " and " + G2.name + "\n" + F.header
F.mode_strict()
U=enumerate_vertices(G1)
V=enumerate_vertices(G2)
var = _graph_isomorphism_var
for (u, v) in product(U,V):
F.add_variable(var(u, v))
# Defined on both side
for u in U:
F.add_clause([(True, var(u, v)) for v in V])
for v in V:
F.add_clause([(True, var(u, v)) for u in U])
# Injective on both sides
for u in U:
for v1, v2 in combinations(V, 2):
F.add_clause([(False, var(u, v1)),
(False, var(u, v2))])
for v in V:
for u1, u2 in combinations(U, 2):
F.add_clause([(False, var(u1, v)),
(False, var(u2, v))])
# Edge consistency
for u1, u2 in combinations(U, 2):
for v1, v2 in combinations(V, 2):
if G1.has_edge(u1, u2) != G2.has_edge(v1, v2):
F.add_clause([(False, var(u1, v1)),
(False, var(u2, v2))])
F.add_clause([(False, var(u1, v2)),
(False, var(u2, v1))])
return F
示例2: EvenColoringFormula
# 需要导入模块: from cnfformula.cnf import CNF [as 别名]
# 或者: from cnfformula.cnf.CNF import mode_strict [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.mode_strict()
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) ]
F.add_exactly_half_ceil(edge_vars) # F.add_exactly_half_floor would work the same
return F
示例3: test_strict_clause_insertion
# 需要导入模块: from cnfformula.cnf import CNF [as 别名]
# 或者: from cnfformula.cnf.CNF import mode_strict [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")])
示例4: RamseyLowerBoundFormula
# 需要导入模块: from cnfformula.cnf import CNF [as 别名]
# 或者: from cnfformula.cnf.CNF import mode_strict [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
示例5: TseitinFormula
# 需要导入模块: from cnfformula.cnf import CNF [as 别名]
# 或者: from cnfformula.cnf.CNF import mode_strict [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()
edgename = { }
for (u,v) in sorted(graph.edges(),key=sorted):
edgename[(u,v)] = "E_{{{0},{1}}}".format(u,v)
edgename[(v,u)] = "E_{{{0},{1}}}".format(u,v)
tse.add_variable(edgename[(u,v)])
tse.mode_strict()
# add constraints
for v,charge in zip(V,charges):
# produce all clauses and save half of them
names = [ edgename[(u,v)] for u in neighbors(graph,v) ]
tse.add_parity(names,charge)
return tse
示例6: GraphColoringFormula
# 需要导入模块: from cnfformula.cnf import CNF [as 别名]
# 或者: from cnfformula.cnf.CNF import mode_strict [as 别名]
def GraphColoringFormula(G,colors,functional=True):
"""Generates the clauses for colorability formula
The formula encodes the fact that the graph :math:`G` has a coloring
with color set ``colors``. This means that it is possible to
assign one among the elements in ``colors``to that each vertex of
the graph such that no two adjacent vertices get the same color.
Parameters
----------
G : networkx.Graph
a simple undirected graph
colors : list or positive int
a list of colors or a number of colors
Returns
-------
CNF
the CNF encoding of the coloring problem on graph ``G``
"""
col=CNF()
col.mode_strict()
if isinstance(colors,int) and colors>=0:
colors = range(1,colors+1)
if not isinstance(list, collections.Iterable):
ValueError("Parameter \"colors\" is expected to be a iterable")
# Describe the formula
name="graph colorability"
if hasattr(G,'name'):
col.header=name+" of graph:\n"+G.name+".\n\n"+col.header
else:
col.header=name+".\n\n"+col.header
# Fix the vertex order
V=enumerate_vertices(G)
# Create the variables
for vertex in V:
for color in colors:
col.add_variable('x_{{{0},{1}}}'.format(vertex,color))
# Each vertex has a color
for vertex in V:
clause = []
for color in colors:
clause += [(True,'x_{{{0},{1}}}'.format(vertex,color))]
col.add_clause(clause)
# unique color per vertex
if functional:
for (c1,c2) in combinations(colors,2):
col.add_clause([
(False,'x_{{{0},{1}}}'.format(vertex,c1)),
(False,'x_{{{0},{1}}}'.format(vertex,c2))])
# This is a legal coloring
for (v1,v2) in enumerate_edges(G):
for c in colors:
col.add_clause([
(False,'x_{{{0},{1}}}'.format(v1,c)),
(False,'x_{{{0},{1}}}'.format(v2,c))])
return col
示例7: RandomKCNF
# 需要导入模块: from cnfformula.cnf import CNF [as 别名]
# 或者: from cnfformula.cnf.CNF import mode_strict [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
F.mode_strict()
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))
except ValueError:
raise ValueError("There are fewer clauses available than the number requested")
return F
示例8: GraphOrderingPrinciple
# 需要导入模块: from cnfformula.cnf import CNF [as 别名]
# 或者: from cnfformula.cnf.CNF import mode_strict [as 别名]
def GraphOrderingPrinciple(graph,total=False,smart=False,plant=False,knuth=0):
"""Generates the clauses for graph ordering principle
Arguments:
- `graph` : undirected graph
- `total` : add totality axioms (i.e. "x < y" or "x > y")
- `smart` : "x < y" and "x > y" are represented by a single variable (implies `total`)
- `plant` : allow last element to be minimum (and could make the formula SAT)
- `knuth` : Don Knuth variants 2 or 3 of the formula (anything else suppress it)
"""
gop = CNF()
gop.mode_strict()
# Describe the formula
if total or smart:
name = "Total graph ordering principle"
else:
name = "Ordering principle"
if smart:
name = name + "(compact representation)"
if hasattr(graph, 'name'):
gop.header = name+"\n on graph "+graph.name+".\n\n"+gop.header
else:
gop.header = name+".\n\n"+gop.header
# Fix the vertex order
V = enumerate_vertices(graph)
# Add variables
iterator = combinations if smart else permutations
for v1,v2 in iterator(V,2):
gop.add_variable(varname(v1,v2))
#
# Non minimality axioms
#
# Clause is generated in such a way that if totality is enforces,
# every pair occurs with a specific orientation.
# Allow minimum on last vertex if 'plant' options.
for med in xrange(len(V) - (plant and 1)):
clause = []
for lo in xrange(med):
if graph.has_edge(V[med], V[lo]):
clause += [(True, varname(V[lo], V[med]))]
for hi in xrange(med+1, len(V)):
if not graph.has_edge(V[med], V[hi]):
continue
elif smart:
clause += [(False, varname(V[med], V[hi]))]
else:
clause += [(True, varname(V[hi], V[med]))]
gop.add_clause(clause)
#
# Transitivity axiom
#
if len(V) >= 3:
if smart:
# Optimized version if smart representation of totality is used
for (v1, v2, v3) in combinations(V, 3):
gop.add_clause([(True, varname(v1, v2)),
(True, varname(v2, v3)),
(False, varname(v1, v3))])
gop.add_clause([(False, varname(v1, v2)),
(False, varname(v2, v3)),
(True, varname(v1, v3))])
elif total:
# With totality we still need just two axiom per triangle
for (v1, v2, v3) in combinations(V, 3):
gop.add_clause([(False, varname(v1, v2)),
(False, varname(v2, v3)),
(False, varname(v3, v1))])
gop.add_clause([(False, varname(v1, v3)),
(False, varname(v3, v2)),
(False, varname(v2, v1))])
else:
for (v1, v2, v3) in permutations(V, 3):
# knuth variants will reduce the number of
# transitivity axioms
if knuth == 2 and ((v2 < v1) or (v2 < v3)):
continue
if knuth == 3 and ((v3 < v1) or (v3 < v2)):
continue
gop.add_clause([(False, varname(v1, v2)),
(False, varname(v2, v3)),
(True, varname(v1, v3))])
#.........这里部分代码省略.........
示例9: CliqueColoring
# 需要导入模块: from cnfformula.cnf import CNF [as 别名]
# 或者: from cnfformula.cnf.CNF import mode_strict [as 别名]
def CliqueColoring(n,k,c):
r"""Clique-coloring CNF formula
The formula claims that a graph :math:`G` with :math:`n` vertices
simultaneously contains a clique of size :math:`k` and a coloring
of size :math:`c`.
If :math:`k = c + 1` then the formula is clearly unsatisfiable,
and it is the only known example of a formula hard for cutting
planes proof system. [1]_
Variables :math:`e_{u,v}` to encode the edges of the graph.
Variables :math:`q_{i,v}` encode a function from :math:`[k]` to
:math:`[n]` that represents a clique.
Variables :math:`r_{v,\ell}` encode a function from :math:`[n]` to
:math:`[c]` that represents a coloring.
Parameters
----------
n : number of vertices in the graph
k : size of the clique
c : size of the coloring
Returns
-------
A CNF object
References
----------
.. [1] Pavel Pudlak.
Lower bounds for resolution and cutting plane proofs and
monotone computations.
Journal of Symbolic Logic (1997)
"""
def E(u,v):
"Name of an edge variable"
return 'e_{{{0},{1}}}'.format(min(u,v),max(u,v))
def Q(i,v):
"Name of an edge variable"
return 'q_{{{0},{1}}}'.format(i,v)
def R(v,ell):
"Name of an coloring variable"
return 'r_{{{0},{1}}}'.format(v,ell)
formula=CNF()
formula.mode_strict()
formula.header="There is a graph of {0} vertices with a {1}-clique".format(n,k)+\
" and a {0}-coloring\n\n".format(c)\
+ formula.header
# Edge variables
for u in range(1,n+1):
for v in range(u+1,n+1):
formula.add_variable(E(u,v))
# Clique encoding variables
for i in range(1,k+1):
for v in range(1,n+1):
formula.add_variable(Q(i,v))
# Coloring encoding variables
for v in range(1,n+1):
for ell in range(1,c+1):
formula.add_variable(R(v,ell))
# some vertex is i'th member of clique
formula.mode_strict()
for k in range(1,k+1):
formula.add_equal_to([Q(k,v) for v in range(1,n+1)], 1)
# clique members are connected by edges
for v in range(1,n+1):
for i,j in combinations(range(1,k+1),2):
formula.add_clause([(False, Q(i,v)), (False, Q(j,v))])
for u,v in combinations(range(1,n+1),2):
for i,j in permutations(range(1,k+1),2):
formula.add_clause([(True, E(u,v)), (False, Q(i,u)), (False, Q(j,v))])
# every vertex v has exactly one colour
for v in range(1,n+1):
formula.add_equal_to([R(v,ell) for ell in range(1,c+1)], 1)
# neighbours have distinct colours
for u,v in combinations(range(1,n+1),2):
for ell in range(1,c+1):
formula.add_clause([(False, E(u,v)), (False, R(u,ell)), (False, R(v,ell))])
return formula
示例10: SubgraphFormula
# 需要导入模块: from cnfformula.cnf import CNF [as 别名]
# 或者: from cnfformula.cnf.CNF import mode_strict [as 别名]
def SubgraphFormula(graph,templates, symmetric=False):
"""Test whether a graph contains one of the templates.
Given a graph :math:`G` and a sequence of template graphs
:math:`H_1`, :math:`H_2`, ..., :math:`H_t`, the CNF formula claims
that :math:`G` contains an isomorphic copy of at least one of the
template graphs.
E.g. when :math:`H_1` is the complete graph of :math:`k` vertices
and it is the only template, the formula claims that :math:`G`
contains a :math:`k`-clique.
Parameters
----------
graph : networkx.Graph
a simple graph
templates : list-like object
a sequence of graphs.
symmetric:
all template graphs are symmetric wrt permutations of
vertices. This allows some optimization in the search space of
the assignments.
induce:
force the subgraph to be induced (i.e. no additional edges are allowed)
Returns
-------
a CNF object
"""
F=CNF()
F.mode_strict()
# One of the templates is chosen to be the subgraph
if len(templates)==0:
return F
elif len(templates)==1:
selectors=[]
elif len(templates)==2:
selectors=['c']
else:
selectors=['c_{{{}}}'.format(i) for i in range(len(templates))]
for s in selectors:
F.add_variable(s)
if len(selectors)>1:
for cls in F.equal_to_constraint(selectors,1):
F.add_clause( cls )
# comment the formula accordingly
if len(selectors)>1:
F.header=dedent("""\
CNF encoding of the claim that a graph contains one among
a family of {0} possible subgraphs.
""".format(len(templates))) + F.header
else:
F.header=dedent("""\
CNF encoding of the claim that a graph contains an induced
copy of a subgraph.
""".format(len(templates))) + F.header
# A subgraph is chosen
N=graph.order()
k=max([s.order() for s in templates])
var_name = lambda i,j: "S_{{{0},{1}}}".format(i,j)
if symmetric:
mapping = unary_mapping(range(k),range(N),var_name=var_name,
functional=True,injective=True,
nondecreasing=True)
else:
mapping = unary_mapping(range(k),range(N),var_name=var_name,
functional=True,injective=True,
nondecreasing=False)
mapping.load_variables_to_formula(F)
mapping.load_clauses_to_formula(F)
# The selectors choose a template subgraph. A mapping must map
# edges to edges and non-edges to non-edges for the active
# template.
if len(templates)==1:
activation_prefixes = [[]]
elif len(templates)==2:
activation_prefixes = [[(True,selectors[0])],[(False,selectors[0])]]
else:
activation_prefixes = [[(True,v)] for v in selectors]
#.........这里部分代码省略.........