Convert from graph6 to DIMACS (bliss) graph format

graph theorymath-software

I know there is a tool to convert from graph6 file format to DIMACS (bliss) file format for graphs, but I am not able to find it now.

Somebody can help me?

Best Answer

I am not aware of an existing converter and I suppose that you have already done all the necessary research. Since the DIMACS format is pretty simple, I have decided to just implement a converter myself.

I choose SageMath since it already parses graph6 to an internal SageMath graph object which makes it pretty simple to achieve what we desire.

Here is the code.

def convert(graph6String):
    G=Graph(graph6String)
    dimacsString = "p edge {} {}\n".format(G.order(), G.size())
    template = "e {} {}\n"
    for e in G.edges():
        dimacsString += template.format(e[0], e[1])
    return dimacsString

def convertWithDescription(graph6String, description):
    dimacsString = "c " + description + '\n'
    dimacsString += convert(graph6String)
    return dimacsString

Let "DrK" be a graph6 string (this is the house graph) which looks as follows.

enter image description here

We can convert it to DIMACS as follows

result=convert("DrK")
print(result)

which yields to

p edge 5 6
e 0 1
e 0 2
e 1 3
e 2 3
e 2 4
e 3 4

If we want to provide a description (the 'c' line), we can achieve this as follows.

result=convert("DrK", "This is an optional description")
print(result)

which yields to

c This is an optional description
p edge 5 6
e 0 1
e 0 2
e 1 3
e 2 3
e 2 4
e 3 4

I have added a convenient function in order to convert a given graph6 file directly to a DIMACS file. The code looks as follows.

def convertGraph6FileToDimacsFile(pathToGraph6, pathToDimacs):
    graph6=open(pathToGraph6, 'r')
    dimacs=open(pathToDimacs, 'a')
    dimacs.write(convert(graph6.read()))
    graph6.close()
    dimacs.close()

Assume that we have a graph6 file named "house.g6" whose content looks as follows.

DrK

Then, we can convert the file directly using the above function as follows.

convertGraph6FileToDimacsFile("pathToGraph6File", "pathToDimacsFile")

The output is a DIAMCS file containing the content given above. If you have a huge g6 file with multiple graphs, then you can easily read this file line by line and convert each graph using the above functions. Notice that I have not added the possibility to add the optional description here as well, but this is very simple to implement.

Notice that the above does not work if the optional graph6 header >>graph6<< is provided. If that is the case, then we need to do some preprocessing first (which is not very complicated; just go through the file first and remove it).

I have published this little tool on my GitHub under the MIT license.