3

Mathematica being a CAS, I would have thought what I'm trying to do a natural task. But I have not been able to find any information on this in the Internet.

Basically, I have a large collection of equations that describe relationships between a large set of variables. Can I use the symbol manipulation functions of Mathematica to extract this structure and plot the results as a directed network graph?

For example,

Y = a + b X
Z = 1/X + Y

would give a graph that has the following edges:

a -> Y
b -> Y
X -> Y
X -> Z
Y -> Z
m_goldberg
  • 107,779
  • 16
  • 103
  • 257
Ming K
  • 133
  • 6
  • 4
    Can you give a small example illustrating what you're expecting to get? – J. M.'s missing motivation Apr 01 '16 at 02:17
  • To avoid having to make multiple future updates to any answers, can you set down the form of your equations precisely (e.g. does the LHS always have a single variable? are the equations always polynomial in form?) and give an example in valid Mathematica syntax that is representative of all your actual systems? Please use code blocks to format the Mathematica code you post. – Szabolcs Apr 01 '16 at 08:06
  • Generally, the procedure is to separate RHS from LHS (see Everything is an Expression for a starting point; this is an easy task once you know the basics of Mathematica), then extract variables (Variables for polynomial, or non-Head non-NumericQ symbols extracted with Cases otherwise) and build the graph. – Szabolcs Apr 01 '16 at 08:13

2 Answers2

7

As it was mentioned in the question and in the comments this is fairly easy to program.

eqs = {Y == a + b X, Z == 1/X + Y};

edges = Flatten@
  Map[Outer[Rule, 
     Cases[{#[[2]]}, s_Symbol /; Not@NumericQ[s], \[Infinity]], 
     Cases[{#[[1]]}, s_Symbol /; Not@NumericQ[s], \[Infinity]]] &, 
   eqs]

(* {a -> Y, b -> Y, X -> Y, X -> Z, Y -> Z} *)

The code above assumes that the equations are properly defined. Let us plot the graph with the obtained edges:

Graph[edges, VertexLabels -> "Name"]

enter image description here

A more complicated example for plotting dependencies between symbols can be found in this answer of the question What's the analogue of UML in Mathematica land?.

Anton Antonov
  • 37,787
  • 3
  • 100
  • 178
6
eqsToGraph = Block[{Equal = Rule @@@ Tuples[{Variables@#2, Variables@#1}] &}, 
    Graph[Join @@ #, VertexShapeFunction -> "Name"]] &;

Example:

eqsToGraph@{Y == a + b X, Z == 1/X + Y}

Mathematica graphics

eqsToGraph@{Y == a + b X, Z + W == 1/X + Y}

Mathematica graphics

kglr
  • 394,356
  • 18
  • 477
  • 896