Group Abstract Group Abstract

Message Boards Message Boards

[?] How to import multigraphs that have edge properties?

Posted 9 years ago
POSTED BY: Szabolcs Horvát

I found a solution and posted it over at StackExchange. A copy is below.


Graphlet (GML)

With the Graphlet format, we can do this:

{edgeRules, edgeAttr, vertexList, vertexAttr, directed} = 
   ImportString[
      file, 
      {"Graphlet", {"EdgeRules", "EdgeAttributes", "VertexList", "VertexAttributes", "DirectedEdges"}}
   ]

(*
{{1 -> 2, 1 -> 2, 2 -> 3, 3 -> 3}, 
 {{"value" -> 123}, {"value" -> 321}, {"value" -> 42}, {"value" -> 137}}, 
 {1, 2, 3}, 
 {{"label" -> "one"}, {"label" -> "two"}, {"label" -> "three"}}, 
 True}
*)

Of these, the "DirectedEdges" element is undocumented.

Now we can do the property combining:

edgeFinal = GroupBy[
    Transpose[{edgeRules, edgeAttr}],
    First -> Last,
    Merge[Identity]
    ] // Map[Normal] // KeyValueMap[Property]
(* {Property[1 -> 2, {"value" -> {123, 321}}], 
 Property[2 -> 3, {"value" -> {42}}], 
 Property[3 -> 3, {"value" -> {137}}]} *)

vertexFinal = MapThread[Property, {vertexList, vertexAttr}]
(* {Property[1, {"label" -> "one"}], 
 Property[2, {"label" -> "two"}], Property[3, {"label" -> "three"}]} *)

Now we can assemble the graph:

g = Graph[vertexFinal, edgeFinal, DirectedEdges -> directed]

Options[g]    
(* {Properties -> {1 \[DirectedEdge] 2 -> {"value" -> {123, 321}}, 
   2 -> {"label" -> "two"}, 1 -> {"label" -> "one"}, 
   3 -> {"label" -> "three"}, 
   3 \[DirectedEdge] 3 -> {"value" -> {137}}, 
   2 \[DirectedEdge] 3 -> {"value" -> {42}}}} *)

GraphML

The same method works with GraphML as well. The difference is that each of these import elements returns a list. This is because a GraphML file may contain more than one graph.

POSTED BY: Szabolcs Horvát
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard