How can I re-create the original Graph object from Graphics object into which that Graph was converted previously?
We can convert a Graph into Graphics very easily like it is shown in this answer. My question is: how to convert a Graphics object into the original Graph from which it was created? Like the g1,g2 and g3 in the following:
SeedRandom[1]
g1 = Show[RandomGraph[{6, 10}]]
Head[g1]
Graphics
g2 = GraphPlot3D[{1 -> 2, 1 -> 3, 1 -> 4, 1 -> 5, 2 -> 3, 2 -> 4,
2 -> 5, 3 -> 4, 3 -> 5, 4 -> 5}]
g3 = GraphPlot[{1 -> 2, 2 -> 1, 3 -> 1, 3 -> 2, 4 -> 1, 4 -> 2,
4 -> 4}, VertexLabeling -> True, DirectedEdges -> True]
Answer
WOW! I made it!
Code first~
Graphics2Graph[g_] :=
Module[{cd =
If[FreeQ[g, Line],
DirectedEdge @@@ (Extract[g, Position[g, Arrow[___]]] /.
Arrow[x_, ___] :> {First@x, Last@x}),
UndirectedEdge @@@ Extract[g, Position[g, Line[_]]][[1, 1]]]},
Graph[cd,
VertexCoordinates ->
Extract[Extract[g, Position[g, GraphicsComplex[___]]][[1, 1]],
List /@ VertexList@Graph[cd]], VertexLabels -> "Name"]]
Graphics2Graph /@ {g1, g2, g3}
Well, the method of doing this is quite simple. After analyzed several Graph's FullForm, I realized that all the Graphics created are in the form of GraphicsComplex and all the useful information are stored in the form of either a great Line or several Arrow. The storage, fortunately, are in regular forms:
(*Line Form*)
Line[{{1, 2}, {1, 3}, {1, 4}, {1, 5}, {2, 3}, {2, 4}, {2, 5}, {3, 4}, {3, 5}, {4, 5}}]
(*Arrow Form*)
Arrow[{2,1}]
Arrow[{2,3,4,5,1}]
Arrow[{1,2},0.2]
Also, I found out that in one graph, only one form will be presented. So either a graph is totally presented by Line Form or totally presented by Arrow Form.
So the only thing I'll have to do is to find out all the Line Expression or Arrow Expression and properly convert them into styled forms. The code simply do this job with Position and Extract.
Seemingly this version do is wide-range supportive~ I've tried a few examples in Graph's documentation and it seems that this function works fine. Also the speed is quite high too~



Comments
Post a Comment