Thursday, February 9, 2017

From R igraph to Java BioFabric in one easy .sif!

If you are working in an R environment (e.g. in RStudio) with igraph to build your networks, then you can always use my RBioFabric package to get simple static visualizations:

https://github.com/wjrl/RBioFabric

There is also a short posting over on StackOverflow that shows RBioFabric in action:

http://stackoverflow.com/questions/22453273/how-to-visualize-a-large-network-in-r
 
But you get the most bang for the buck by being able to use the interactive features of the Java version of BioFabric, which can import a network definition using the .sif input format. I've tossed together some R code that can be used to build that file, including the listing of singleton nodes (i.e. degree = 0). I'm a very newbie R coder, so I don't suggest this is the best way to do things, but it should get you started.

Note that the method requires that the igraph nodes have name attributes defined. If not, you will need to do that step first. The code snippet below has a utility function you can use to do this.

In addition to the listing below, this code is also available on GitHub as a Gist.

# if you need to install igraph:
#install.packages("igraph")

library(igraph)

#
# We only work with graphs that have node name attributes!
# If graph does not already have them, apply this function to it!
#

autoNameForGraph <- function(inGraph) {
  vlabels <- get.vertex.attribute(inGraph, "name")
  if (is.null(vlabels)) {
    vlabels <- get.vertex.attribute(inGraph, "label")
    if (is.null(vlabels)) {
      vlabels <- paste("BF", 1:vcount(inGraph), sep="")
    }
    outGraph <- set.vertex.attribute(inGraph, "name", value=vlabels);
  } else {
    outGraph <- inGraph
  }
  return (outGraph)
}

#
# Hand this function the graph, the name of the output file, and an edge label.
#

igraphToSif <- function(inGraph, outfile="output.sif", edgeLabel="label") {
 
  sink(outfile)
  singletons <- as.list(get.vertex.attribute(bfGraph, "name"))
  edgeList <- get.edgelist(bfGraph, names=FALSE)
  nodeNames <- get.vertex.attribute(bfGraph, "name")
  numE <- ecount(bfGraph)
  for (i in 1:numE) {
    node1 <- edgeList[i,1]
    node2 <- edgeList[i,2]
    singletons <- singletons[which(singletons != nodeNames[node1])]
    singletons <- singletons[which(singletons != nodeNames[node2])]
    cat(nodeNames[node1], "\t", edgeLabel, "\t", nodeNames[node2], "\n")
  } 
  for (single in singletons) {
    cat(single, "\n")
  }
  sink()
}

#
# Test snippet
#
set.seed(123)
bfGraph <- erdos.renyi.game(1000, 2000, "gnm")
bfGraph <- autoNameForGraph(bfGraph)
igraphToSif(bfGraph, "myGraph.sif", "mylabel")