aboutsummaryrefslogtreecommitdiff
path: root/wqflask/wqflask
diff options
context:
space:
mode:
authorBonfaceKilz2020-10-09 15:47:43 +0300
committerGitHub2020-10-09 15:47:43 +0300
commit58c3815571f83db0296dc099f1e4c6ff69619f64 (patch)
tree2f1841afed3281c8eb179aa2c695caf650a4e1cf /wqflask/wqflask
parent7db8f7da013eefdf518ccf024477d0abf4324c03 (diff)
parenteae4f1e6fad57a77063a637f0b03c171b6437565 (diff)
downloadgenenetwork2-58c3815571f83db0296dc099f1e4c6ff69619f64.tar.gz
Merge pull request #458 from BonfaceKilz/tests/add-extra-tests-for-collections
Tests/add extra tests for collections
Diffstat (limited to 'wqflask/wqflask')
-rw-r--r--wqflask/wqflask/collect.py37
-rw-r--r--wqflask/wqflask/wgcna/wgcna_analysis.py181
2 files changed, 121 insertions, 97 deletions
diff --git a/wqflask/wqflask/collect.py b/wqflask/wqflask/collect.py
index 42a09fed..4c558bfe 100644
--- a/wqflask/wqflask/collect.py
+++ b/wqflask/wqflask/collect.py
@@ -1,41 +1,30 @@
from __future__ import print_function, division, absolute_import
-
-import os
-import hashlib
import datetime
-import time
-
-import uuid
-import hashlib
-import base64
-
-import urlparse
-
import simplejson as json
-from flask import (Flask, g, render_template, url_for, request, make_response,
- redirect, flash, jsonify)
+from flask import g
+from flask import render_template
+from flask import url_for
+from flask import request
+from flask import redirect
+from flask import flash
from wqflask import app
-
-from pprint import pformat as pf
-
-from wqflask.database import db_session
-
-from wqflask import model
-
-from utility import Bunch, Struct, hmac
+from utility import hmac
from utility.formatting import numify
from utility.redis_tools import get_redis_conn
-Redis = get_redis_conn()
-from base.trait import create_trait, retrieve_trait_info, jsonable
+from base.trait import create_trait
+from base.trait import retrieve_trait_info
+from base.trait import jsonable
from base.data_set import create_dataset
-import logging
from utility.logger import getLogger
+
logger = getLogger(__name__)
+Redis = get_redis_conn()
+
def process_traits(unprocessed_traits):
if isinstance(unprocessed_traits, basestring):
diff --git a/wqflask/wqflask/wgcna/wgcna_analysis.py b/wqflask/wqflask/wgcna/wgcna_analysis.py
index 880a1cb2..70077703 100644
--- a/wqflask/wqflask/wgcna/wgcna_analysis.py
+++ b/wqflask/wqflask/wgcna/wgcna_analysis.py
@@ -1,5 +1,8 @@
-# WGCNA analysis for GN2
-# Author / Maintainer: Danny Arends <Danny.Arends@gmail.com>
+"""
+WGCNA analysis for GN2
+
+Author / Maintainer: Danny Arends <Danny.Arends@gmail.com>
+"""
import sys
from numpy import *
import scipy as sp # SciPy
@@ -17,106 +20,138 @@ from utility import helper_functions
from rpy2.robjects.packages import importr
utils = importr("utils")
-## Get pointers to some common R functions
-r_library = ro.r["library"] # Map the library function
-r_options = ro.r["options"] # Map the options function
-r_read_csv = ro.r["read.csv"] # Map the read.csv function
-r_dim = ro.r["dim"] # Map the dim function
-r_c = ro.r["c"] # Map the c function
-r_cat = ro.r["cat"] # Map the cat function
-r_paste = ro.r["paste"] # Map the paste function
-r_unlist = ro.r["unlist"] # Map the unlist function
-r_unique = ro.r["unique"] # Map the unique function
-r_length = ro.r["length"] # Map the length function
-r_unlist = ro.r["unlist"] # Map the unlist function
-r_list = ro.r.list # Map the list function
-r_matrix = ro.r.matrix # Map the matrix function
-r_seq = ro.r["seq"] # Map the seq function
-r_table = ro.r["table"] # Map the table function
-r_names = ro.r["names"] # Map the names function
-r_sink = ro.r["sink"] # Map the sink function
-r_is_NA = ro.r["is.na"] # Map the is.na function
-r_file = ro.r["file"] # Map the file function
-r_png = ro.r["png"] # Map the png function for plotting
-r_dev_off = ro.r["dev.off"] # Map the dev.off function
+# Get pointers to some common R functions
+r_library = ro.r["library"] # Map the library function
+r_options = ro.r["options"] # Map the options function
+r_read_csv = ro.r["read.csv"] # Map the read.csv function
+r_dim = ro.r["dim"] # Map the dim function
+r_c = ro.r["c"] # Map the c function
+r_cat = ro.r["cat"] # Map the cat function
+r_paste = ro.r["paste"] # Map the paste function
+r_unlist = ro.r["unlist"] # Map the unlist function
+r_unique = ro.r["unique"] # Map the unique function
+r_length = ro.r["length"] # Map the length function
+r_unlist = ro.r["unlist"] # Map the unlist function
+r_list = ro.r.list # Map the list function
+r_matrix = ro.r.matrix # Map the matrix function
+r_seq = ro.r["seq"] # Map the seq function
+r_table = ro.r["table"] # Map the table function
+r_names = ro.r["names"] # Map the names function
+r_sink = ro.r["sink"] # Map the sink function
+r_is_NA = ro.r["is.na"] # Map the is.na function
+r_file = ro.r["file"] # Map the file function
+r_png = ro.r["png"] # Map the png function for plotting
+r_dev_off = ro.r["dev.off"] # Map the dev.off function
+
class WGCNA(object):
def __init__(self):
+ # To log output from stdout/stderr to a file add `r_sink(log)`
print("Initialization of WGCNA")
- #log = r_file("/tmp/genenetwork_wcgna.log", open = "wt")
- #r_sink(log) # Uncomment the r_sink() commands to log output from stdout/stderr to a file
- #r_sink(log, type = "message")
- r_library("WGCNA") # Load WGCNA - Should only be done once, since it is quite expensive
- r_options(stringsAsFactors = False)
+
+ # Load WGCNA - Should only be done once, since it is quite expensive
+ r_library("WGCNA")
+ r_options(stringsAsFactors=False)
print("Initialization of WGCNA done, package loaded in R session")
- self.r_enableWGCNAThreads = ro.r["enableWGCNAThreads"] # Map the enableWGCNAThreads function
- self.r_pickSoftThreshold = ro.r["pickSoftThreshold"] # Map the pickSoftThreshold function
- self.r_blockwiseModules = ro.r["blockwiseModules"] # Map the blockwiseModules function
- self.r_labels2colors = ro.r["labels2colors"] # Map the labels2colors function
- self.r_plotDendroAndColors = ro.r["plotDendroAndColors"] # Map the plotDendroAndColors function
+ # Map the enableWGCNAThreads function
+ self.r_enableWGCNAThreads = ro.r["enableWGCNAThreads"]
+ # Map the pickSoftThreshold function
+ self.r_pickSoftThreshold = ro.r["pickSoftThreshold"]
+ # Map the blockwiseModules function
+ self.r_blockwiseModules = ro.r["blockwiseModules"]
+ # Map the labels2colors function
+ self.r_labels2colors = ro.r["labels2colors"]
+ # Map the plotDendroAndColors function
+ self.r_plotDendroAndColors = ro.r["plotDendroAndColors"]
print("Obtained pointers to WGCNA functions")
def run_analysis(self, requestform):
print("Starting WGCNA analysis on dataset")
- self.r_enableWGCNAThreads() # Enable multi threading
- self.trait_db_list = [trait.strip() for trait in requestform['trait_list'].split(',')]
- print("Retrieved phenotype data from database", requestform['trait_list'])
+ # Enable multi threading
+ self.r_enableWGCNAThreads()
+ self.trait_db_list = [trait.strip()
+ for trait in requestform['trait_list'].split(',')]
+ print("Retrieved phenotype data from database",
+ requestform['trait_list'])
helper_functions.get_trait_db_obs(self, self.trait_db_list)
- self.input = {} # self.input contains the phenotype values we need to send to R
- strains = [] # All the strains we have data for (contains duplicates)
- traits = [] # All the traits we have data for (should not contain duplicates)
+ # self.input contains the phenotype values we need to send to R
+ self.input = {}
+ # All the strains we have data for (contains duplicates)
+ strains = []
+ # All the traits we have data for (should not contain duplicates)
+ traits = []
for trait in self.trait_list:
traits.append(trait[0].name)
self.input[trait[0].name] = {}
for strain in trait[0].data:
strains.append(strain)
- self.input[trait[0].name][strain] = trait[0].data[strain].value
+ self.input[trait[0].name][strain] = trait[0].data[strain].value
# Transfer the load data from python to R
- uStrainsR = r_unique(ro.Vector(strains)) # Unique strains in R vector
+ # Unique strains in R vector
+ uStrainsR = r_unique(ro.Vector(strains))
uTraitsR = r_unique(ro.Vector(traits)) # Unique traits in R vector
r_cat("The number of unique strains:", r_length(uStrainsR), "\n")
r_cat("The number of unique traits:", r_length(uTraitsR), "\n")
- # rM is the datamatrix holding all the data in R /rows = strains columns = traits
- rM = ro.r.matrix(ri.NA_Real, nrow=r_length(uStrainsR), ncol=r_length(uTraitsR), dimnames = r_list(uStrainsR, uTraitsR))
+ # rM is the datamatrix holding all the data in
+ # R /rows = strains columns = traits
+ rM = ro.r.matrix(ri.NA_Real, nrow=r_length(uStrainsR), ncol=r_length(
+ uTraitsR), dimnames=r_list(uStrainsR, uTraitsR))
for t in uTraitsR:
- trait = t[0] # R uses vectors every single element is a vector
+ # R uses vectors every single element is a vector
+ trait = t[0]
for s in uStrainsR:
- strain = s[0] # R uses vectors every single element is a vector
- #DEBUG: print(trait, strain, " in python: ", self.input[trait].get(strain), "in R:", rM.rx(strain,trait)[0])
- rM.rx[strain, trait] = self.input[trait].get(strain) # Update the matrix location
+ # R uses vectors every single element is a vector
+ strain = s[0]
+ rM.rx[strain, trait] = self.input[trait].get(
+ strain) # Update the matrix location
sys.stdout.flush()
self.results = {}
- self.results['nphe'] = r_length(uTraitsR)[0] # Number of phenotypes/traits
- self.results['nstr'] = r_length(uStrainsR)[0] # Number of strains
+ # Number of phenotypes/traits
+ self.results['nphe'] = r_length(uTraitsR)[0]
+ self.results['nstr'] = r_length(
+ uStrainsR)[0] # Number of strains
self.results['phenotypes'] = uTraitsR # Traits used
- self.results['strains'] = uStrainsR # Strains used in the analysis
- self.results['requestform'] = requestform # Store the user specified parameters for the output page
+ # Strains used in the analysis
+ self.results['strains'] = uStrainsR
+ # Store the user specified parameters for the output page
+ self.results['requestform'] = requestform
- # Calculate soft threshold if the user specified the SoftThreshold variable
+ # Calculate soft threshold if the user specified the
+ # SoftThreshold variable
if requestform.get('SoftThresholds') is not None:
- powers = [int(threshold.strip()) for threshold in requestform['SoftThresholds'].rstrip().split(",")]
- rpow = r_unlist(r_c(powers))
- print "SoftThresholds: {} == {}".format(powers, rpow)
- self.sft = self.r_pickSoftThreshold(rM, powerVector = rpow, verbose = 5)
-
- print "PowerEstimate: {}".format(self.sft[0])
- self.results['PowerEstimate'] = self.sft[0]
- if self.sft[0][0] is ri.NA_Integer:
- print "No power is suitable for the analysis, just use 1"
- self.results['Power'] = 1 # No power could be estimated
- else:
- self.results['Power'] = self.sft[0][0] # Use the estimated power
+ powers = [int(threshold.strip())
+ for threshold in requestform['SoftThresholds'].rstrip().split(",")]
+ rpow = r_unlist(r_c(powers))
+ print("SoftThresholds: {} == {}".format(powers, rpow))
+ self.sft = self.r_pickSoftThreshold(
+ rM, powerVector=rpow, verbose=5)
+
+ print("PowerEstimate: {}".format(self.sft[0]))
+ self.results['PowerEstimate'] = self.sft[0]
+ if self.sft[0][0] is ri.NA_Integer:
+ print "No power is suitable for the analysis, just use 1"
+ # No power could be estimated
+ self.results['Power'] = 1
+ else:
+ # Use the estimated power
+ self.results['Power'] = self.sft[0][0]
else:
- # The user clicked a button, so no soft threshold selection
- self.results['Power'] = requestform.get('Power') # Use the power value the user gives
+ # The user clicked a button, so no soft threshold selection
+ # Use the power value the user gives
+ self.results['Power'] = requestform.get('Power')
# Create the block wise modules using WGCNA
- network = self.r_blockwiseModules(rM, power = self.results['Power'], TOMType = requestform['TOMtype'], minModuleSize = requestform['MinModuleSize'], verbose = 3)
+ network = self.r_blockwiseModules(
+ rM,
+ power=self.results['Power'],
+ TOMType=requestform['TOMtype'],
+ minModuleSize=requestform['MinModuleSize'],
+ verbose=3)
# Save the network for the GUI
self.results['network'] = network
@@ -130,7 +165,9 @@ class WGCNA(object):
self.results['imgloc'] = GENERATED_IMAGE_DIR + self.results['imgurl']
r_png(self.results['imgloc'], width=1000, height=600, type='cairo-png')
mergedColors = self.r_labels2colors(network[1])
- self.r_plotDendroAndColors(network[5][0], mergedColors, "Module colors", dendroLabels = False, hang = 0.03, addGuide = True, guideHang = 0.05)
+ self.r_plotDendroAndColors(network[5][0], mergedColors,
+ "Module colors", dendroLabels=False,
+ hang=0.03, addGuide=True, guideHang=0.05)
r_dev_off()
sys.stdout.flush()
@@ -146,11 +183,9 @@ class WGCNA(object):
print("Processing WGCNA output")
template_vars = {}
template_vars["input"] = self.input
- template_vars["powers"] = self.sft[1:] # Results from the soft threshold analysis
+ # Results from the soft threshold analysis
+ template_vars["powers"] = self.sft[1:]
template_vars["results"] = self.results
self.render_image(results)
sys.stdout.flush()
- #r_sink(type = "message") # This restores R output to the stdout/stderr
- #r_sink() # We should end the Rpy session more or less
return(dict(template_vars))
-