R/plotEmap.R

Defines functions plotEmap

Documented in plotEmap

#' Create EnrichmentMap in Cytoscape to visualize predictive pathways
#' 
#' @description Create a network where nodes are predictive pathways passing
#' certain cutoff and edges indicate similarity in gene-sets. Pathways are 
#' then clustered to identify themes of predictive pathways. Generates one 
#' such network for each patient label.
#' @param gmtFile (character) file path to GMT file 
#' (generated by getEMapInput()).
#' NOTE: This needs to be the absolute path name
#' @param nodeAttrFile (list) file path to nodeAttr.txt file (generated by
#' getEMapInput())
#' @param netName (character) name for network in Cytoscape. Using the patient
#' class name is a good idea. (e.g. SURVIVE_YES and SURVIVE_NO).
#' @param scoreCol (character) column of nodeAttrFile with the node score
#' @param minScore (integer) minimum score of node to show
#' @param maxScore (integer) maximum score of node to show
#' @param nodeFillStops (integer) vector of length 2. Contains score values
#' that indicate "good signal" and "best signal". Nodes with values
#' above "good signal" are coloured orange, and those with "best signal"
#' are coloured red.
#' @param colorScheme (character) colour scheme for nodes. 'cont_heatmap' 
#' sets a discrete map ranging from yellow to red for increasing scores. 
#' 'netDx_ms' is the colour scheme used in the netDx methods paper.
#' This map is (<=6: white; 7-9: orange; 10: red)
#' @param imageFormat (character) one of PNG, PDF, SVG, or JPEG
#' @param verbose (logical) print messages
#' @param createStyle (logical) if generating more than one EMap, set to 
#' TRUE for first one and to FALSE for subsequent. Due to limitation in 
#' current version of RCy3
#' @param groupClusters (logical) if TRUE, redraws network with thematic
#' clusters lined up in rows. This setting is useful if setting this flag to
#' FALSE results in a cluttered network. However, applying this layout will
#' organize nodes in each cluster into circles, which loses the c
#' topology.
#' @param hideNodeLabels (logical) if TRUE hides the node label in the EnrichmentMap.
#' Cluster labels remain visible.
#' 
#' @importFrom grDevices colorRampPalette
#' @examples
#' #refer to getEMapInput_many.R for working getEMapInput_many() example
#' data(featScores)
#' pathwayList <- readPathways(fetchPathwayDefinitions("October",2020))
#' pathwayList <- pathwayList[seq_len(5)]
#' netInfoFile <- system.file("extdata",
#' 	paste("example_output","inputNets.txt",sep=getFileSep()),
#'		package="netDx")
#' netTypes <- read.delim(netInfoFile,sep='\t',header=FALSE,as.is=TRUE)
#' outDir <- paste(tempdir(),'plots',sep=getFileSep())
#' if (!file.exists(outDir)) dir.create(outDir)
#' EMap_input <- getEMapInput_many(featScores,pathwayList,
#'      netTypes,outDir=outDir)
#' outDir <- paste(getwd(),'plots',sep=getFileSep())
#' if (!file.exists(outDir)) dir.create(outDir)
#' gmtFile <- EMap_input[[1]][1]
#' nodeAttrFile <- EMap_input[[1]][2]
#' 
#' # not run because requires Cytoscape to be installed and open
#' # plotEmap(gmtFile = gmtFile, nodeAttrFile = nodeAttrFile, 
#' #\t\tnetName='HighRisk')
#' @return No value. Side effect of plotting the EnrichmentMap in an open 
#' session of Cytoscape.
#' @export
plotEmap <- function(gmtFile, nodeAttrFile, netName = "generic", 
	  scoreCol="maxScore",
		minScore = 1, maxScore = 10, nodeFillStops=c(7,9),
    colorScheme = "cont_heatmap", imageFormat = "png", verbose = FALSE, 
		createStyle = TRUE, 
    groupClusters = FALSE, hideNodeLabels=FALSE) {

  if (!requireNamespace("RCy3",quietly=TRUE)) {
		stop("Package \"RCy3\" needed for plotEmap() to work. Please install it and then make your call.",
		call.=FALSE)
	}
    
    validColSchemes <- c("cont_heatmap", "netDx_ms")
    if (!colorScheme %in% validColSchemes) {
        stop(sprintf("colorScheme should be one of { %s }\n", 
					paste(validColSchemes, 
            collapse = ",")))
    }
    
    ####################################### create EM using given parameters
    if (netName %in% getNetworkList()) {
        RCy3::deleteNetwork(netName)
    }
    em_command <- paste("enrichmentmap build analysisType=\"generic\"", 
				"gmtFile=", gmtFile, "pvalue=", 1, "qvalue=", 1, 
				"similaritycutoff=", 0.05, "coefficients=", "JACCARD")
    response <- RCy3::commandsGET(em_command)
    renameNetwork(netName, getNetworkSuid())
    
    ### #annotate the network using AutoAnnotate app
    aa_command <- paste("autoannotate annotate-clusterBoosted", 
				"clusterAlgorithm=MCL", 
        "labelColumn=name", "maxWords=3", "network=", netName)
    print(aa_command)
    response <- RCy3::commandsGET(aa_command)
    
    message("* Importing node attributes\n")
    table_command <- sprintf(paste("table import file file=%s ", 
				"keyColumnIndex=1 ", 
        "firstRowAsColumnNames=true startLoadRow=1 TargetNetworkList=%s ", 
				"WhereImportTable=To%%20selected%%20networks%%20only", 
        sep = " "), nodeAttrFile, netName)
    response <- RCy3::commandsGET(table_command)
    
    # apply style
    message("* Creating or applying style\n")
    all_unique_scores_int <- sort(unique(read.delim(nodeAttrFile)[, 2]))
    all_unique_scores <- unlist(lapply(all_unique_scores_int, toString))
    styleName <- "EMapStyle"
    
    # define colourmap
    scoreVals <- minScore:maxScore
    style_cols <- ""
    if (colorScheme == "cont_heatmap") {
        colfunc <- colorRampPalette(c("yellow", "red"))
        gradient_cols <- colfunc(length(scoreVals))
        style_cols <- colfunc(length(scoreVals))
    } else if (colorScheme == "netDx_ms") {
        style_cols <- rep("white", length(scoreVals))
        style_cols[which(scoreVals >= nodeFillStops[1])] <- "orange"
        style_cols[which(scoreVals >= nodeFillStops[2])] <- "red"
    }
    nodeLabels <- RCy3::mapVisualProperty("node label", "name", "p")
    nodeFills <- RCy3::mapVisualProperty("node fill color", scoreCol, "d", 
				scoreVals, style_cols)
    defaults <- list(NODE_SHAPE = "ellipse", NODE_SIZE = 30, 
				EDGE_TRANSPARENCY = 200, 
        NODE_TRANSPARENCY = 255, EDGE_STROKE_UNSELECTED_PAINT = "#999999")
    if (createStyle) {
        message("Making style\n")
        RCy3::createVisualStyle(styleName, defaults, list(nodeLabels, nodeFills))
    }
    RCy3::setVisualStyle(styleName)
    if (groupClusters) {
        RCy3::layoutNetwork("attributes-layout NodeAttribute=__mclCLuster")
        redraw_command <- sprintf("autoannotate redraw network=%s", 
					RCy3::getNetworkSuid())
        response <- RCy3::commandsGET(redraw_command)
        RCy3::fitContent()
        
        redraw_command <- sprintf("autoannotate redraw network=%s", 
					RCy3::getNetworkSuid())
        response <- RCy3::commandsGET(redraw_command)
        RCy3::fitContent()
    }

		if (hideNodeLabels) {
			RCy3::setNodeFontSizeDefault(0,styleName)
	}
}
BaderLab/netDx documentation built on Sept. 26, 2021, 9:13 a.m.