2
$\begingroup$

I have graphs in DIMACS format, with vertex colors specified. The vertex colors are denoted by lines n u c, where u is the vertex number and c an integer representing its color.

Here's an example of a triangle colored with 2 colors:

p edge 3 3
e 1 2
e 2 3
e 3 1
n 1 1
n 2 1
n 3 2

Using Import, I can nicely import the graph, but not the vertex colors. Is there a way to read them in with Import, or am I forced to write my own reader that manually sets the vertex colors?

$\endgroup$
2
$\begingroup$

There doesn't be to be a way to Import the colours. The only available information are the following:

{#, Import["~/test.col", #]} & /@ Import["~/test.col", "Elements"]

Mathematica graphics

Thus you indeed need to Import your Graph from the .col file and add the colours afterwards:

g = Import@"~/test.col";
data = Import["~/test.col", "List"];
vclist = ToExpression /@ ((StringReplace[#, " " -> ","] & /@ 
           StringTrim /@ (StringCases[data, "n" ~~ x__ :> x] /. {} :> Sequence[])) /. 
             List[x_String] :> "{" ~~ x ~~ "}");
col = Module[{}, SeedRandom@(#^2); RGBColor@RandomReal[{}, {3}]] &;
vc = (Rule @@@ ({#, col@#2} & @@@ vclist))
{1 -> RGBColor[{0.817389, 0.11142, 0.789526}], 
 2 -> RGBColor[{0.817389, 0.11142, 0.789526}], 
 3 -> RGBColor[{0.311376, 0.566004, 0.627155}]}

Now one can recreate the Graph g with coloured vertices:

Graph[EdgeList@g, VertexCoordinates -> AbsoluteOptions[g, VertexCoordinates], 
  VertexStyle -> vc, VertexLabels -> "Name", ImagePadding -> 10]

Mathematica graphics

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.