# Required package:
# Graph
# In addition, you should install Graphviz from http://www.graphviz.org/.

# Set the working dicrectory to the one containning the file "PCC.txt",
# by issuing the command "setwd("&&&&")", replacing &&&& with the name of the actual directory.
# Or you can set the directory in the "file" manu -> "Change dir".


# 
# !!! NOTE: AFTER SETTING THE RIGHT DIRECTORY, YOU CAN JUST COPY AND PASTE THIS SCRIPT INTO THE R CONSOLE. !!! 
#

# Loading the significant edges into the data frame "SigEdges".
SigEdges <- read.table("PCC.txt")


# Define the function "mkgraph", which will generate the a graph object.
mkgraph <-
function (grd){
        V <- c(as.character(grd[,1]),as.character(grd[,2]))
        V <- unique(V)
        require (graph)
        gR<-new("graphNEL",nodes = V)
        gX <- addEdge(as.character(grd[,1]),as.character(grd[,2]),gR,round(grd[,3],digits = 2))
        return (gX)
}

# Genereate the "MainGraph" from the data frame "SigEdges".
MainGraph <- mkgraph(SigEdges)
MainGraph

# Define the function "adjnodes". "gr", the input graph. "seeds", the cetered node(s). "steps", the connections removed from the seeds. 
adjnodes <-
function (gr, seeds, steps){
        library(graph)
        start_nodes = seeds
        for( i in 1:steps){
                nodes_list = adj(gr, start_nodes)
                end_nodes = start_nodes
                for ( j in 1:length(nodes_list)){
                        end_nodes = c(end_nodes, nodes_list[[j]])
                }
                end_nodes = unique (end_nodes)
                start_nodes = end_nodes
        }
        return (end_nodes)
}

# Define the function "subnet", which is used to extract sub-graph from the 'MainGraph'
subnet <-
function(seeds,steps, gr = MainGraph ){
	subnodes <- adjnodes(gr, seeds, steps)
	sg <- subGraph(subnodes, gr)
	cat("A graphNEL graph with undirected edges\nNumber of Nodes = ",numNodes(sg),"\nNumber of Edges = ", numEdges(sg),"\n",sep="")
	if (numEdges(sg) > 100)
		cat("\nWARNING: This is a graph with more than 100 edges. \nWARNING: Plotting this graph may take a lot of time, \nWARNING: and possbily CRASHES your program.\n")
	return(sg)
}


# Defind the function "gr2dot". This function generates the 'dot' file used by the program graphviz. This function is modified from the function "ggm.make.dot" in GeneNet 1.2.2 (Schafer, J., R. Opgen-Rhein, and K. Strimmer. 2006. Reverse engineering genetic networks using the GeneNet package. R News 6/5: 50-53; http://cran.r-project.org/doc/Rnews ).
gr2dot <-
function( gr , filename = "graph.dot"){

	require (graph)

	f <- file(filename, "w")
	e <- eWV (gr, edgeMatrix(gr), sep = "\" -- \"", useNNames = T)
	cutoff <- quantile(abs(e), c(0.2, 0.8))

	cat("Graph G {\n", file=f)
	cat("\tgraph [bgcolor=\"transparent\", fontcolor=\"black\", ratio=\"fill\", splines=TRUE, rank=\"same\", overlap=\" \", size = \"6.49,4.99\", center = TRUE];\n", file=f)
	cat("\tnode[shape=\"ellipse\", fixedsize=FALSE, fontsize=14, height=0.5, width=0.75];\n", file=f)

	for(i in 1:length(e))
	{
		cat ( "\t\"",names(e[i]),"\"", "[weight=", abs(e[i]), ", ", sep = "", file=f)
		
		if( abs(e[i]) < cutoff[1]) # lower 20% quantile
		{
			if(e[i] <0)
				cat("color=grey, style=\"dashed,setlinewidth(1)\"", file=f)
			else
				cat("color=grey, style=\"solid,setlinewidth(1)\"", file=f)
		}
		else if (abs(e[i]) < cutoff[2]) # 20% - 80%
		{
			if(e[i] < 0)
				cat("color=black, style=\"dashed,setlinewidth(1)\"", file=f)
			else
				cat("color=black, sytle=\"solid,setlinewidth(1)\"", file=f)
		}
		else	# higher 20%
		{
			if(e[i] < 0)
				cat("color=black, style=\"dahsed,setlinewidth(2)\"", file=f)
			else
				cat("color=black, style=\"solid,setlinewidth(2)\"", file=f)
		}

		cat("];\n", file=f)
	}
	cat("}\n", file=f)
	close(f)
}
