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


Python CNF.header方法代码示例

本文整理汇总了Python中cnfformula.cnf.CNF.header方法的典型用法代码示例。如果您正苦于以下问题:Python CNF.header方法的具体用法?Python CNF.header怎么用?Python CNF.header使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在cnfformula.cnf.CNF的用法示例。


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

示例1: PerfectMatchingPrinciple

# 需要导入模块: from cnfformula.cnf import CNF [as 别名]
# 或者: from cnfformula.cnf.CNF import header [as 别名]
def PerfectMatchingPrinciple(G):
    """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.

    Parameters
    ----------
    G : undirected graph

    """
    cnf=CNF()

    # Describe the formula
    name="Perfect Matching Principle"
    
    if hasattr(G,'name'):
        cnf.header=name+" of graph:\n"+G.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 enumerate_vertices(G):

        edge_vars = [var_name(u,v) for u in neighbors(G,v)]
        cnf.add_equal_to(edge_vars,1)

    return cnf
开发者ID:marcvinyals,项目名称:cnfgen,代码行数:36,代码来源:counting.py

示例2: PerfectMatchingPrinciple

# 需要导入模块: from cnfformula.cnf import CNF [as 别名]
# 或者: from cnfformula.cnf.CNF import header [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
开发者ID:chansonyhu,项目名称:cnfgen,代码行数:37,代码来源:counting.py

示例3: CountingPrinciple

# 需要导入模块: from cnfformula.cnf import CNF [as 别名]
# 或者: from cnfformula.cnf.CNF import header [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]]
        cnf.add_equal_to(edge_vars,1)

    return cnf
开发者ID:marcvinyals,项目名称:cnfgen,代码行数:34,代码来源:counting.py

示例4: RandomKCNF

# 需要导入模块: from cnfformula.cnf import CNF [as 别名]
# 或者: from cnfformula.cnf.CNF import header [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
开发者ID:MassimoLauria,项目名称:cnfgen,代码行数:62,代码来源:randomformulas.py

示例5: BinaryPigeonholePrinciple

# 需要导入模块: from cnfformula.cnf import CNF [as 别名]
# 或者: from cnfformula.cnf.CNF import header [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
    
    mapping=binary_mapping(xrange(1,pigeons+1),
                           xrange(1,holes+1), injective = True)
    bphp.mode_unchecked()
    mapping.load_variables_to_formula(bphp)
    mapping.load_clauses_to_formula(bphp)
    bphp.mode_default()

    return bphp
开发者ID:marcvinyals,项目名称:cnfgen,代码行数:29,代码来源:pigeonhole.py

示例6: BinaryPigeonholePrinciple

# 需要导入模块: from cnfformula.cnf import CNF [as 别名]
# 或者: from cnfformula.cnf.CNF import header [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
开发者ID:,项目名称:,代码行数:30,代码来源:

示例7: GraphIsomorphism

# 需要导入模块: from cnfformula.cnf import CNF [as 别名]
# 或者: from cnfformula.cnf.CNF import header [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
开发者ID:marcvinyals,项目名称:cnfgen,代码行数:60,代码来源:graphisomorphism.py

示例8: EvenColoringFormula

# 需要导入模块: from cnfformula.cnf import CNF [as 别名]
# 或者: from cnfformula.cnf.CNF import header [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
开发者ID:MassimoLauria,项目名称:cnfgen,代码行数:58,代码来源:coloring.py

示例9: build_cnf

# 需要导入模块: from cnfformula.cnf import CNF [as 别名]
# 或者: from cnfformula.cnf.CNF import header [as 别名]
    def build_cnf(args):
        """Build a conjunction

        Arguments:
        - `args`: command line options
        """
        clauses = [ [(True,"x_{}".format(i))] for i in range(args.P) ] + \
                  [ [(False,"y_{}".format(i))] for i in range(args.N) ]
        andcnf =  CNF(clauses)
        andcnf.header = "Singleton clauses: {} positive and {} negative\n\n""".format(args.P,args.N) +\
                        andcnf.header
        return andcnf
开发者ID:MassimoLauria,项目名称:cnfgen,代码行数:14,代码来源:simple.py

示例10: PythagoreanTriples

# 需要导入模块: from cnfformula.cnf import CNF [as 别名]
# 或者: from cnfformula.cnf.CNF import header [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
开发者ID:marcvinyals,项目名称:cnfgen,代码行数:54,代码来源:ramsey.py

示例11: PebblingFormula

# 需要导入模块: from cnfformula.cnf import CNF [as 别名]
# 或者: from cnfformula.cnf.CNF import header [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
开发者ID:marcvinyals,项目名称:cnfgen,代码行数:41,代码来源:pebbling.py

示例12: RamseyLowerBoundFormula

# 需要导入模块: from cnfformula.cnf import CNF [as 别名]
# 或者: from cnfformula.cnf.CNF import header [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
开发者ID:marcvinyals,项目名称:cnfgen,代码行数:44,代码来源:ramsey.py

示例13: BinaryCliqueFormula

# 需要导入模块: from cnfformula.cnf import CNF [as 别名]
# 或者: from cnfformula.cnf.CNF import header [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
开发者ID:,项目名称:,代码行数:42,代码来源:

示例14: GraphColoringFormula

# 需要导入模块: from cnfformula.cnf import CNF [as 别名]
# 或者: from cnfformula.cnf.CNF import header [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
开发者ID:marcvinyals,项目名称:cnfgen,代码行数:70,代码来源:coloring.py

示例15: DominatingSet

# 需要导入模块: from cnfformula.cnf import CNF [as 别名]
# 或者: from cnfformula.cnf.CNF import header [as 别名]
def DominatingSet(G,d, alternative = False):
    r"""Generates the clauses for a dominating set for G of size <= d

    The formula encodes the fact that the graph :math:`G` has
    a dominating set of size :math:`d`. This means that it is possible
    to pick at most :math:`d` vertices in :math:`V(G)` so that all remaining
    vertices have distance at most one from the selected ones.

    Parameters
    ----------
    G : networkx.Graph
        a simple undirected graph
    d : a positive int
        the size limit for the dominating set
    alternative : bool
        use an alternative construction that 
        is provably hard from resolution proofs.

    Returns
    -------
    CNF
       the CNF encoding for dominating of size :math:`\leq d` for graph :math:`G`

    """
    F=CNF()

    if not isinstance(d,int) or d<1:
        ValueError("Parameter \"d\" is expected to be a positive integer")
    
    # Describe the formula
    name="{}-dominating set".format(d)
    
    if hasattr(G,'name'):
        F.header=name+" of graph:\n"+G.name+".\n\n"+F.header
    else:
        F.header=name+".\n\n"+F.header

    # Fix the vertex order
    V=enumerate_vertices(G)
    

    def D(v):
        return "x_{{{0}}}".format(v)

    def M(v,i):
        return "g_{{{0},{1}}}".format(v,i)

    def N(v):
        return tuple(sorted([ v ] + [ u for u in G.neighbors(v) ]))
    
    # Create variables
    for v in V:
        F.add_variable(D(v))
    for i,v in product(range(1,d+1),V):
        F.add_variable(M(v,i))
    
    # No two (active) vertices map to the same index
    if alternative:
        for u,v in combinations(V,2):
            for i in range(1,d+1):
                F.add_clause( [ (False,D(u)),(False,D(v)), (False,M(u,i)), (False,M(v,i))    ])
    else:
        for i in range(1,d+1):
            for c in CNF.less_or_equal_constraint([M(v,i) for v in V],1):
                F.add_clause(c)
                
    # (Active) Vertices in the sequence are not repeated
    if alternative:
        for v in V:
            for i,j in combinations(range(1,d+1),2):
                F.add_clause([(False,D(v)),(False,M(v,i)),(False,M(v,j))])
    else:
        for i,j in combinations_with_replacement(range(1,d+1),2):
            i,j = min(i,j),max(i,j)
            for u,v in combinations(V,2):
                u,v = max(u,v),min(u,v)
                F.add_clause([(False,M(u,i)),(False,M(v,j))])

    # D(v) = M(v,1) or M(v,2) or ... or M(v,d)        
    if not alternative:
        for i,v in product(range(1,d+1),V):
            F.add_clause([(False,M(v,i)),(True,D(v))])
    for v in V:
        F.add_clause([(False,D(v))] + [(True,M(v,i)) for i in range(1,d+1)])
    
        
    # Every neighborhood must have a true D variable
    neighborhoods = sorted( set(N(v) for v in V) )
    for N in neighborhoods:
        F.add_clause([ (True,D(v)) for v in N])
        
    return F
开发者ID:MassimoLauria,项目名称:cnfgen,代码行数:94,代码来源:dominatingset.py


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