# A program printing a SAT expression in CNF for the graph coloring
# problem. The output follows the DIMACS format for CNF.
#
# The program reads a graph specification from a file. The first line
# in the file contains just the number n of vertices. Each line in the
# rest of the file contains two integers between 1 and n (i.e., we use
# 1-indexing). Such a line specifies an (unordered) edge. Each edge
# only needs to be present once (not twice). The program also reads an
# integer given on the command line, which specifies the number of
# colors to model by the SAT program.
#
# The SAT expression produced is satisfiable if and only if the graph
# can be colored with the specified number of colors.
#
# Usage:
#
# python coloring.py numberOfColors graphSpecificationFile.txt
#

import sys

noOfColors = int(sys.argv[1]) # We index colors by ints from 1 to noOfColors
graphFileName = sys.argv[2]

with open(graphFileName, "r") as file:
    lines = file.readlines()

# Parse the graph specification file, store the edges as tuples in a
# list
n = int(lines[0].strip())
edges = []
for l in lines[1:]:
    edges.append(tuple(map(int,l.split())))

# In the SAT model, there will be one Boolean variable for each pair
# of a node and a color. The variable for a pair (i,k) models whether
# node i is assigned the color k (the variable is true iff this is the
# case). This is the key aspect of the SAT modeling.
numberOfVars = n * noOfColors

# Convert index pairs (i,k) to a single positive int index, as needed
# for the DIMACS format.  Here, i is a node index and k is a color
# index. To illustrate the conversion, here it is for the case of four
# nodes (rows) and three colors (columns):
#
#    1  2  3
# 1  1  2  3
# 2  4  5  6
# 3  7  8  9
# 4 10 11 12
#
def pair2int(i,k):
    return noOfColors*(i-1) + k

# Functions for generating clauses. A clause is a list of ints. Each
# function returns a list of clauses (hence, a list of lists of ints).

def atLeastOneIsSet(varList):
    return [varList]

def atMostOneIsSet(varList):
    return [[-varList[i],-varList[j]] for i in range(len(varList)) for
            j in range(i+1,len(varList))]
            
def exactlyOneIsSet(varList):
    return atLeastOneIsSet(varList) + (atMostOneIsSet(varList))

clauses = []
# Modeling part A (each node has exactly one color):
for i in range(1,n+1):
    clauses.extend(exactlyOneIsSet([pair2int(i,k) for k in range(1,noOfColors+1)]))
# Modeling part B (endpoints of edges have different colors):
clauses.extend([[-pair2int(i,k),-pair2int(j,k)] for (i,j) in edges for k in range(1,noOfColors+1)])

# Print output
print("p cnf", numberOfVars, len(clauses))
for clause in clauses:
    clause.append(0)
    print(*clause) # The use of * during a call unpacks a list, i.e.,
                   # its elements become arguments of the call to
                   # print (exploiting that print can work with any
                   # number of arguments).
