1

I have an undirected graph $G$. How would I randomly assign directions to some fraction $p$ of the edges? How might I do this efficiently / quickly provided I have a large graph structure?

For example, to assign a graph random edge weights, I might write:

GraphWithRandomWeights = Graph[EdgeList[G], EdgeWeight -> Table[RandomReal[{-1, 1}], {abc, 1, Length[EdgeList[G]]}]];
Peter
  • 227
  • 1
  • 5

1 Answers1

8

There is a built-in function DirectedGraph[ (*your undirected graph*) , "Random"] for this job:

myGraph = RandomGraph[{10, 13},
  VertexLabels -> Table[v -> Style[v, 20], {v, 10}],
  ImagePadding -> 20, VertexSize -> Medium]

myGraph

DirectedGraph[myGraph, "Random"]

myDirectGraph

(Note the layout may not be the same as myGraph.)

Edit:

As OP asked in a comment, if you only want a fraction of the total edges to be directed, then the best way might be to manipulate the adjacency matrix:

myAdj = AdjacencyMatrix[myGraph]

myAdj

Suppose the edges we want to become directed are those between vertices $2\sim 4$, $1\sim 9$, $1\sim 10$, $5\sim 7$:

directEdgeSet = {{2, 4}, {1, 9}, {1, 10}, {5, 7}};

So a randomly constructed directed adjacency matrix would be:

myDirectAdj = ReplacePart[myAdj,
      Thread[RandomSample /@ directEdgeSet -> 0]
     ]

myDirectAdj

The corresponding graph is

AdjacencyGraph[myDirectAdj,
 DirectedEdges -> True,
 VertexLabels -> Table[v -> Style[v, 20], {v, 10}],
 ImagePadding -> 20, VertexSize -> Medium]

my partial directed graph

J. M.'s missing motivation
  • 124,525
  • 11
  • 401
  • 574
Silvia
  • 27,556
  • 3
  • 84
  • 164
  • @Sylvia is it possible for me to only direct a fraction of the total edges? – Peter Apr 21 '13 at 19:10
  • 1
    @Peter Directed edges and undirected edges can not coexist in a same graph by definition. Please compare the difference of AdjacencyGraph[{{0, 1}, {1, 0}}, DirectedEdges -> True] and AdjacencyGraph[{{0, 1}, {1, 0}}]. – Silvia Apr 21 '13 at 19:32
  • Got it, thanks! – Peter Apr 21 '13 at 19:45
  • @Peter You're welcome. – Silvia Apr 21 '13 at 19:53
  • How do i work with the function DirectedGraph[myGraph, "Random"] ? Is there in networkx package? – Peyman Arebi Mar 17 '21 at 11:08
  • @PeymanArebi Sorry I never used or heard of networkx package. Regarding DirectedGraph, please refer to the official documentation: http://reference.wolfram.com/language/ref/DirectedGraph.html . – Silvia Mar 22 '21 at 02:35