Reputation: 31
I don't know how to ask this question, actually. But I have a bunch of equations and constants and are all connected somehow. Let's say the following code in Matlab, for example:
R=8.314;
n=0.412;
a=4;
m=2;
S=10;
rho=1;
F=m*a;
P=F/S;
V=m/rho;
T=(P*V)/(n*R);
Is there a way that Matlab (or another language) returns you a diagram with the workflow, or something like that the figure?
Because I think any language needs to define each constant and equation in order, so I just want that order back
Upvotes: 1
Views: 186
Reputation: 269346
In R use the igraph package as shown. We assume that the input is the character string Lines
shown in the Note at the end.
Read the input using scan
(scan
can also read from a file but to keep things self contained we use a character string as input here), remove empty components and strip out whitespace.
Extract the lhs and rhs of each line.
Then for each element of rhs
get the variables in it giving list L. Replace names with character labels of the form variable = expression.
Convert to data frame and from that to an igraph object g
and plot.
library(igraph)
set.seed(123)
V1 <- scan(text = Lines, sep = ";", what = "", quiet = TRUE)
V1 <- gsub(" ", "", V1[V1 != ""])
lhs <- sub("=.*", "", V1)
rhs <- sub(".*=", "", V1)
L <- setNames(lapply(rhs, function(x) all.vars(parse(text = x))), V1)
L <- lapply(L, function(x) ifelse(x %in% lhs,
paste0(x, "=", rhs[match(x, lhs)]), x))
g <- graph.data.frame(stack(L))
plot(g, vertex.color = NA, vertex.frame.color = NA)
Another possible representation is as a heatmap. Get the adjacency matrix, optionally remove rows and columns which are all zero and plot.
m <- as.matrix(get.adjacency(g))
m <- m[apply(m > 0, 1, any), apply(m > 0, 2, any)] # rm 0 rows & cols
heatmap(m, Rowv = NA, Colv = NA, col = 2:3, scale = "none",
margins = c(7, 7), cexCol = 1, cexRow = 1)
Similar to the heat map we could draw a bubble plot:
library(ggplot2)
ggplot(stack(L), aes(ind, values)) + geom_point(cex = 10) + xlab("") + ylab("")
Another possibility is to just show the dependencies using text. Display just L
instead if you want to see components which have no dependencies as well.
L[lengths(L) > 0]
giving:
$`F=m*a`
[1] "m=2" "a=4"
$`P=F/S`
[1] "F=m*a" "S=10"
$`V=m/rho`
[1] "m=2" "rho=1"
$`T=(P*V)/(n*R)`
[1] "P=F/S" "V=m/rho" "n=0.412" "R=8.314"
and inverting the list:
lapply(split(stack(L), stack(L)$values), function(x) as.character(x$ind))
giving:
$`a=4`
[1] "F=m*a"
$`F=m*a`
[1] "P=F/S"
$`m=2`
[1] "F=m*a" "V=m/rho"
$`n=0.412`
[1] "T=(P*V)/(n*R)"
$`P=F/S`
[1] "T=(P*V)/(n*R)"
$`R=8.314`
[1] "T=(P*V)/(n*R)"
$`rho=1`
[1] "V=m/rho"
$`S=10`
[1] "P=F/S"
$`V=m/rho`
[1] "T=(P*V)/(n*R)"
Lines <- "
R=8.314;
n=0.412;
a=4;
m=2;
S=10;
rho=1;
F=m*a;
P=F/S;
V=m/rho;
T=(P*V)/(n*R);
"
Upvotes: 4