diff options
author | zsloan | 2021-07-09 16:49:42 -0500 |
---|---|---|
committer | GitHub | 2021-07-09 16:49:42 -0500 |
commit | bce7aaab7d65309dc0e755a74bf8339a721f2cd9 (patch) | |
tree | 9819308f9ae2a56b2810001720c0c44aa49d8558 | |
parent | bc2869179f2483d9ad5995d3abb0c9dbc1024acd (diff) | |
parent | 9f823f4e07be834d5c9e918902f7cf626b85dcba (diff) | |
download | genenetwork2-bce7aaab7d65309dc0e755a74bf8339a721f2cd9.tar.gz |
Merge pull request #587 from zsloan/feature/use_gn3_for_correlations
Feature/use gn3 for correlations
-rw-r--r-- | wqflask/base/data_set.py | 12 | ||||
-rw-r--r-- | wqflask/base/trait.py | 17 | ||||
-rw-r--r-- | wqflask/wqflask/correlation/correlation_gn3_api.py | 27 | ||||
-rw-r--r-- | wqflask/wqflask/correlation/show_corr_results.py | 605 | ||||
-rw-r--r-- | wqflask/wqflask/templates/correlation_page.html | 16 | ||||
-rw-r--r-- | wqflask/wqflask/templates/show_trait_calculate_correlations.html | 2 | ||||
-rw-r--r-- | wqflask/wqflask/views.py | 14 |
7 files changed, 196 insertions, 497 deletions
diff --git a/wqflask/base/data_set.py b/wqflask/base/data_set.py index 6dc44829..4cb82665 100644 --- a/wqflask/base/data_set.py +++ b/wqflask/base/data_set.py @@ -557,6 +557,7 @@ class DataSet: self.fullname = None self.type = None self.data_scale = None # ZS: For example log2 + self.accession_id = None self.setup() @@ -573,6 +574,17 @@ class DataSet: self.group.get_samplelist() self.species = species.TheSpecies(self) + def as_dict(self): + return { + 'name': self.name, + 'shortname': self.shortname, + 'fullname': self.fullname, + 'type': self.type, + 'data_scale': self.data_scale, + 'group': self.group.name, + 'accession_id': self.accession_id + } + def get_accession_id(self): if self.type == "Publish": results = g.db.execute("""select InfoFiles.GN_AccesionId from InfoFiles, PublishFreeze, InbredSet where diff --git a/wqflask/base/trait.py b/wqflask/base/trait.py index d09cfd40..10851e00 100644 --- a/wqflask/base/trait.py +++ b/wqflask/base/trait.py @@ -284,17 +284,19 @@ def get_sample_data(): return None -def jsonable(trait): +def jsonable(trait, dataset=None): """Return a dict suitable for using as json Actual turning into json doesn't happen here though""" - dataset = create_dataset(dataset_name=trait.dataset.name, - dataset_type=trait.dataset.type, - group_name=trait.dataset.group.name) + if not dataset: + dataset = create_dataset(dataset_name=trait.dataset.name, + dataset_type=trait.dataset.type, + group_name=trait.dataset.group.name) if dataset.type == "ProbeSet": return dict(name=trait.name, + view=trait.view, symbol=trait.symbol, dataset=dataset.name, dataset_name=dataset.shortname, @@ -308,37 +310,44 @@ def jsonable(trait): elif dataset.type == "Publish": if trait.pubmed_id: return dict(name=trait.name, + view=trait.view, dataset=dataset.name, dataset_name=dataset.shortname, description=trait.description_display, abbreviation=trait.abbreviation, authors=trait.authors, + pubmed_id=trait.pubmed_id, pubmed_text=trait.pubmed_text, pubmed_link=trait.pubmed_link, + mean=trait.mean, lrs_score=trait.LRS_score_repr, lrs_location=trait.LRS_location_repr, additive=trait.additive ) else: return dict(name=trait.name, + view=trait.view, dataset=dataset.name, dataset_name=dataset.shortname, description=trait.description_display, abbreviation=trait.abbreviation, authors=trait.authors, pubmed_text=trait.pubmed_text, + mean=trait.mean, lrs_score=trait.LRS_score_repr, lrs_location=trait.LRS_location_repr, additive=trait.additive ) elif dataset.type == "Geno": return dict(name=trait.name, + view=trait.view, dataset=dataset.name, dataset_name=dataset.shortname, location=trait.location_repr ) elif dataset.name == "Temp": return dict(name=trait.name, + view=trait.view, dataset="Temp", dataset_name="Temp") else: diff --git a/wqflask/wqflask/correlation/correlation_gn3_api.py b/wqflask/wqflask/correlation/correlation_gn3_api.py index 30c05f03..aea91220 100644 --- a/wqflask/wqflask/correlation/correlation_gn3_api.py +++ b/wqflask/wqflask/correlation/correlation_gn3_api.py @@ -165,8 +165,14 @@ def fetch_sample_data(start_vars, this_trait, this_dataset, target_dataset): return (this_trait_data, results) -def compute_correlation(start_vars, method="pearson"): - """compute correlation for to call gn3 api""" +def compute_correlation(start_vars, method="pearson", compute_all=False): + """Compute correlations using GN3 API + + Keyword arguments: + start_vars -- All input from form; includes things like the trait/dataset names + method -- Correlation method to be used (pearson, spearman, or bicor) + compute_all -- Include sample, tissue, and literature correlations (when applicable) + """ # pylint: disable-msg=too-many-locals corr_type = start_vars['corr_type'] @@ -220,11 +226,9 @@ def compute_correlation(start_vars, method="pearson"): correlation_results = correlation_results[0:corr_return_results] - compute_all = True # later to be passed as argument - if (compute_all): - - correlation_results = compute_corr_for_top_results(correlation_results, + correlation_results = compute_corr_for_top_results(start_vars, + correlation_results, this_trait, this_dataset, target_dataset, @@ -238,7 +242,8 @@ def compute_correlation(start_vars, method="pearson"): return correlation_data -def compute_corr_for_top_results(correlation_results, +def compute_corr_for_top_results(start_vars, + correlation_results, this_trait, this_dataset, target_dataset, @@ -261,8 +266,12 @@ def compute_corr_for_top_results(correlation_results, correlation_results = merge_correlation_results( correlation_results, lit_result) - if corr_type != "sample": - pass + if corr_type != "sample" and this_dataset.type == "ProbeSet" and target_dataset.type == "ProbeSet": + sample_result = sample_for_trait_lists( + correlation_results, target_dataset, this_trait, this_dataset, start_vars) + if sample_result: + correlation_results = merge_correlation_results( + correlation_results, sample_result) return correlation_results diff --git a/wqflask/wqflask/correlation/show_corr_results.py b/wqflask/wqflask/correlation/show_corr_results.py index f1cf3733..bebef9e7 100644 --- a/wqflask/wqflask/correlation/show_corr_results.py +++ b/wqflask/wqflask/correlation/show_corr_results.py @@ -18,491 +18,145 @@ # # This module is used by GeneNetwork project (www.genenetwork.org) -import collections import json -import scipy -import numpy -import rpy2.robjects as ro # R Objects -import utility.logger -import utility.webqtlUtil -from base.trait import create_trait +from base.trait import create_trait, jsonable +from base.data_set import create_dataset -from base import data_set -from utility import helper_functions -from utility import corr_result_helpers from utility import hmac -from wqflask.correlation import correlation_functions -from utility.benchmark import Bench +def set_template_vars(start_vars, correlation_data): + corr_type = start_vars['corr_type'] + corr_method = start_vars['corr_sample_method'] -from utility.type_checking import is_str -from utility.type_checking import get_float -from utility.type_checking import get_int -from utility.type_checking import get_string -from utility.db_tools import escape + this_dataset_ob = create_dataset(dataset_name=start_vars['dataset']) + this_trait = create_trait(dataset=this_dataset_ob, + name=start_vars['trait_id']) -from flask import g + correlation_data['this_trait'] = jsonable(this_trait, this_dataset_ob) + correlation_data['this_dataset'] = this_dataset_ob.as_dict() -logger = utility.logger.getLogger(__name__) + target_dataset_ob = create_dataset(correlation_data['target_dataset']) + correlation_data['target_dataset'] = target_dataset_ob.as_dict() -METHOD_LIT = "3" -METHOD_TISSUE_PEARSON = "4" -METHOD_TISSUE_RANK = "5" + table_json = correlation_json_for_table(correlation_data, + correlation_data['this_trait'], + correlation_data['this_dataset'], + target_dataset_ob) -TISSUE_METHODS = [METHOD_TISSUE_PEARSON, METHOD_TISSUE_RANK] + correlation_data['table_json'] = table_json -TISSUE_MOUSE_DB = 1 - - -class CorrelationResults: - def __init__(self, start_vars): - # get trait list from db (database name) - # calculate correlation with Base vector and targets - - # Check parameters - assert('corr_type' in start_vars) - assert(is_str(start_vars['corr_type'])) - assert('dataset' in start_vars) - # assert('group' in start_vars) permitted to be empty? - assert('corr_sample_method' in start_vars) - assert('corr_samples_group' in start_vars) - assert('corr_dataset' in start_vars) - assert('corr_return_results' in start_vars) - if 'loc_chr' in start_vars: - assert('min_loc_mb' in start_vars) - assert('max_loc_mb' in start_vars) - - with Bench("Doing correlations"): - if start_vars['dataset'] == "Temp": - self.dataset = data_set.create_dataset( - dataset_name="Temp", dataset_type="Temp", group_name=start_vars['group']) - self.trait_id = start_vars['trait_id'] - self.this_trait = create_trait(dataset=self.dataset, - name=self.trait_id, - cellid=None) - else: - helper_functions.get_species_dataset_trait(self, start_vars) - - corr_samples_group = start_vars['corr_samples_group'] - - self.sample_data = {} - self.corr_type = start_vars['corr_type'] - self.corr_method = start_vars['corr_sample_method'] - self.min_expr = get_float(start_vars, 'min_expr') - self.p_range_lower = get_float(start_vars, 'p_range_lower', -1.0) - self.p_range_upper = get_float(start_vars, 'p_range_upper', 1.0) - - - if ('loc_chr' in start_vars - and 'min_loc_mb' in start_vars - and 'max_loc_mb' in start_vars): - - self.location_type = get_string(start_vars, 'location_type') - self.location_chr = get_string(start_vars, 'loc_chr') - self.min_location_mb = get_int(start_vars, 'min_loc_mb') - self.max_location_mb = get_int(start_vars, 'max_loc_mb') - else: - self.location_type = self.location_chr = self.min_location_mb = self.max_location_mb = None - - self.get_formatted_corr_type() - self.return_number = int(start_vars['corr_return_results']) - - # The two if statements below append samples to the sample list based upon whether the user - # rselected Primary Samples Only, Other Samples Only, or All Samples - - primary_samples = self.dataset.group.samplelist - if self.dataset.group.parlist != None: - primary_samples += self.dataset.group.parlist - if self.dataset.group.f1list != None: - primary_samples += self.dataset.group.f1list - - # If either BXD/whatever Only or All Samples, append all of that group's samplelist - if corr_samples_group != 'samples_other': - self.process_samples(start_vars, primary_samples) - - # If either Non-BXD/whatever or All Samples, get all samples from this_trait.data and - # exclude the primary samples (because they would have been added in the previous - # if statement if the user selected All Samples) - if corr_samples_group != 'samples_primary': - if corr_samples_group == 'samples_other': - primary_samples = [x for x in primary_samples if x not in ( - self.dataset.group.parlist + self.dataset.group.f1list)] - self.process_samples(start_vars, list( - self.this_trait.data.keys()), primary_samples) - - self.target_dataset = data_set.create_dataset( - start_vars['corr_dataset']) - self.target_dataset.get_trait_data(list(self.sample_data.keys())) - - self.header_fields = get_header_fields( - self.target_dataset.type, self.corr_method) - - if self.target_dataset.type == "ProbeSet": - self.filter_cols = [7, 6] - elif self.target_dataset.type == "Publish": - self.filter_cols = [6, 0] - else: - self.filter_cols = [4, 0] - - self.correlation_results = [] - - self.correlation_data = {} - - if self.corr_type == "tissue": - self.trait_symbol_dict = self.dataset.retrieve_genes("Symbol") - - tissue_corr_data = self.do_tissue_correlation_for_all_traits() - if tissue_corr_data != None: - for trait in list(tissue_corr_data.keys())[:self.return_number]: - self.get_sample_r_and_p_values( - trait, self.target_dataset.trait_data[trait]) - else: - for trait, values in list(self.target_dataset.trait_data.items()): - self.get_sample_r_and_p_values(trait, values) - - elif self.corr_type == "lit": - self.trait_geneid_dict = self.dataset.retrieve_genes("GeneId") - lit_corr_data = self.do_lit_correlation_for_all_traits() - - for trait in list(lit_corr_data.keys())[:self.return_number]: - self.get_sample_r_and_p_values( - trait, self.target_dataset.trait_data[trait]) - - elif self.corr_type == "sample": - for trait, values in list(self.target_dataset.trait_data.items()): - self.get_sample_r_and_p_values(trait, values) - - self.correlation_data = collections.OrderedDict(sorted(list(self.correlation_data.items()), - key=lambda t: -abs(t[1][0]))) - - # ZS: Convert min/max chromosome to an int for the location range option - range_chr_as_int = None - for order_id, chr_info in list(self.dataset.species.chromosomes.chromosomes.items()): - if 'loc_chr' in start_vars: - if chr_info.name == self.location_chr: - range_chr_as_int = order_id - - for _trait_counter, trait in enumerate(list(self.correlation_data.keys())[:self.return_number]): - trait_object = create_trait( - dataset=self.target_dataset, name=trait, get_qtl_info=True, get_sample_info=False) - if not trait_object: - continue - - chr_as_int = 0 - for order_id, chr_info in list(self.dataset.species.chromosomes.chromosomes.items()): - if self.location_type == "highest_lod": - if chr_info.name == trait_object.locus_chr: - chr_as_int = order_id - else: - if chr_info.name == trait_object.chr: - chr_as_int = order_id - - - if (float(self.correlation_data[trait][0]) >= self.p_range_lower - and float(self.correlation_data[trait][0]) <= self.p_range_upper): - - if (self.target_dataset.type == "ProbeSet" or self.target_dataset.type == "Publish") and bool(trait_object.mean): - if (self.min_expr != None) and (float(trait_object.mean) < self.min_expr): - continue - - if range_chr_as_int != None and (chr_as_int != range_chr_as_int): - continue - if self.location_type == "highest_lod": - if (self.min_location_mb != None) and (float(trait_object.locus_mb) < float(self.min_location_mb)): - continue - if (self.max_location_mb != None) and (float(trait_object.locus_mb) > float(self.max_location_mb)): - continue - else: - if (self.min_location_mb != None) and (float(trait_object.mb) < float(self.min_location_mb)): - continue - if (self.max_location_mb != None) and (float(trait_object.mb) > float(self.max_location_mb)): - continue - - (trait_object.sample_r, - trait_object.sample_p, - trait_object.num_overlap) = self.correlation_data[trait] - - # Set some sane defaults - trait_object.tissue_corr = 0 - trait_object.tissue_pvalue = 0 - trait_object.lit_corr = 0 - if self.corr_type == "tissue" and tissue_corr_data != None: - trait_object.tissue_corr = tissue_corr_data[trait][1] - trait_object.tissue_pvalue = tissue_corr_data[trait][2] - elif self.corr_type == "lit": - trait_object.lit_corr = lit_corr_data[trait][1] - - self.correlation_results.append(trait_object) - - if self.corr_type != "lit" and self.dataset.type == "ProbeSet" and self.target_dataset.type == "ProbeSet": - self.do_lit_correlation_for_trait_list() - - if self.corr_type != "tissue" and self.dataset.type == "ProbeSet" and self.target_dataset.type == "ProbeSet": - self.do_tissue_correlation_for_trait_list() - - self.json_results = generate_corr_json( - self.correlation_results, self.this_trait, self.dataset, self.target_dataset) - -############################################################################################################################################ - - def get_formatted_corr_type(self): - self.formatted_corr_type = "" - if self.corr_type == "lit": - self.formatted_corr_type += "Literature Correlation " - elif self.corr_type == "tissue": - self.formatted_corr_type += "Tissue Correlation " - elif self.corr_type == "sample": - self.formatted_corr_type += "Genetic Correlation " - - if self.corr_method == "pearson": - self.formatted_corr_type += "(Pearson's r)" - elif self.corr_method == "spearman": - self.formatted_corr_type += "(Spearman's rho)" - elif self.corr_method == "bicor": - self.formatted_corr_type += "(Biweight r)" - - def do_tissue_correlation_for_trait_list(self, tissue_dataset_id=1): - """Given a list of correlation results (self.correlation_results), gets the tissue correlation value for each""" - - # Gets tissue expression values for the primary trait - primary_trait_tissue_vals_dict = correlation_functions.get_trait_symbol_and_tissue_values( - symbol_list=[self.this_trait.symbol]) - - if self.this_trait.symbol.lower() in primary_trait_tissue_vals_dict: - primary_trait_tissue_values = primary_trait_tissue_vals_dict[self.this_trait.symbol.lower( - )] - gene_symbol_list = [ - trait.symbol for trait in self.correlation_results if trait.symbol] - - corr_result_tissue_vals_dict = correlation_functions.get_trait_symbol_and_tissue_values( - symbol_list=gene_symbol_list) - - for trait in self.correlation_results: - if trait.symbol and trait.symbol.lower() in corr_result_tissue_vals_dict: - this_trait_tissue_values = corr_result_tissue_vals_dict[trait.symbol.lower( - )] - - result = correlation_functions.cal_zero_order_corr_for_tiss(primary_trait_tissue_values, - this_trait_tissue_values, - self.corr_method) - - trait.tissue_corr = result[0] - trait.tissue_pvalue = result[2] - - def do_tissue_correlation_for_all_traits(self, tissue_dataset_id=1): - # Gets tissue expression values for the primary trait - primary_trait_tissue_vals_dict = correlation_functions.get_trait_symbol_and_tissue_values( - symbol_list=[self.this_trait.symbol]) - - if self.this_trait.symbol.lower() in primary_trait_tissue_vals_dict: - primary_trait_tissue_values = primary_trait_tissue_vals_dict[self.this_trait.symbol.lower( - )] - - #print("trait_gene_symbols: ", pf(trait_gene_symbols.values())) - corr_result_tissue_vals_dict = correlation_functions.get_trait_symbol_and_tissue_values( - symbol_list=list(self.trait_symbol_dict.values())) - - #print("corr_result_tissue_vals: ", pf(corr_result_tissue_vals_dict)) - - #print("trait_gene_symbols: ", pf(trait_gene_symbols)) - - tissue_corr_data = {} - for trait, symbol in list(self.trait_symbol_dict.items()): - if symbol and symbol.lower() in corr_result_tissue_vals_dict: - this_trait_tissue_values = corr_result_tissue_vals_dict[symbol.lower( - )] - - result = correlation_functions.cal_zero_order_corr_for_tiss(primary_trait_tissue_values, - this_trait_tissue_values, - self.corr_method) - - tissue_corr_data[trait] = [symbol, result[0], result[2]] - - tissue_corr_data = collections.OrderedDict(sorted(list(tissue_corr_data.items()), - key=lambda t: -abs(t[1][1]))) - - return tissue_corr_data - - def do_lit_correlation_for_trait_list(self): - - input_trait_mouse_gene_id = self.convert_to_mouse_gene_id( - self.dataset.group.species.lower(), self.this_trait.geneid) - - for trait in self.correlation_results: - - if trait.geneid: - trait.mouse_gene_id = self.convert_to_mouse_gene_id( - self.dataset.group.species.lower(), trait.geneid) - else: - trait.mouse_gene_id = None + if target_dataset_ob.type == "ProbeSet": + filter_cols = [7, 6] + elif target_dataset_ob.type == "Publish": + filter_cols = [6, 0] + else: + filter_cols = [4, 0] - if trait.mouse_gene_id and str(trait.mouse_gene_id).find(";") == -1: - result = g.db.execute( - """SELECT value - FROM LCorrRamin3 - WHERE GeneId1='%s' and - GeneId2='%s' - """ % (escape(str(trait.mouse_gene_id)), escape(str(input_trait_mouse_gene_id))) - ).fetchone() - if not result: - result = g.db.execute("""SELECT value - FROM LCorrRamin3 - WHERE GeneId2='%s' and - GeneId1='%s' - """ % (escape(str(trait.mouse_gene_id)), escape(str(input_trait_mouse_gene_id))) - ).fetchone() + correlation_data['corr_method'] = corr_method + correlation_data['filter_cols'] = filter_cols + correlation_data['header_fields'] = get_header_fields(target_dataset_ob.type, correlation_data['corr_method']) + correlation_data['formatted_corr_type'] = get_formatted_corr_type(corr_type, corr_method) - if result: - lit_corr = result.value - trait.lit_corr = lit_corr - else: - trait.lit_corr = 0 - else: - trait.lit_corr = 0 + return correlation_data - def do_lit_correlation_for_all_traits(self): - input_trait_mouse_gene_id = self.convert_to_mouse_gene_id( - self.dataset.group.species.lower(), self.this_trait.geneid) +def correlation_json_for_table(correlation_data, this_trait, this_dataset, target_dataset_ob): + """Return JSON data for use with the DataTable in the correlation result page - lit_corr_data = {} - for trait, gene_id in list(self.trait_geneid_dict.items()): - mouse_gene_id = self.convert_to_mouse_gene_id( - self.dataset.group.species.lower(), gene_id) + Keyword arguments: + correlation_data -- Correlation results + this_trait -- Trait being correlated against a dataset, as a dict + this_dataset -- Dataset of this_trait, as a dict + target_dataset_ob - Target dataset, as a Dataset ob + """ + this_trait = correlation_data['this_trait'] + this_dataset = correlation_data['this_dataset'] + target_dataset = target_dataset_ob.as_dict() - if mouse_gene_id and str(mouse_gene_id).find(";") == -1: - #print("gene_symbols:", input_trait_mouse_gene_id + " / " + mouse_gene_id) - result = g.db.execute( - """SELECT value - FROM LCorrRamin3 - WHERE GeneId1='%s' and - GeneId2='%s' - """ % (escape(mouse_gene_id), escape(input_trait_mouse_gene_id)) - ).fetchone() - if not result: - result = g.db.execute("""SELECT value - FROM LCorrRamin3 - WHERE GeneId2='%s' and - GeneId1='%s' - """ % (escape(mouse_gene_id), escape(input_trait_mouse_gene_id)) - ).fetchone() - if result: - #print("result:", result) - lit_corr = result.value - lit_corr_data[trait] = [gene_id, lit_corr] + corr_results = correlation_data['correlation_results'] + results_list = [] + for i, trait_dict in enumerate(corr_results): + trait_name = list(trait_dict.keys())[0] + trait = trait_dict[trait_name] + target_trait_ob = create_trait(dataset=target_dataset_ob, + name=trait_name, + get_qtl_info=True) + target_trait = jsonable(target_trait_ob, target_dataset_ob) + if target_trait['view'] == False: + continue + results_dict = {} + results_dict['index'] = i + 1 + results_dict['trait_id'] = target_trait['name'] + results_dict['dataset'] = target_dataset['name'] + results_dict['hmac'] = hmac.data_hmac( + '{}:{}'.format(target_trait['name'], target_dataset['name'])) + results_dict['sample_r'] = f"{float(trait['corr_coeffient']):.3f}" + results_dict['num_overlap'] = trait['num_overlap'] + results_dict['sample_p'] = f"{float(trait['p_value']):.3e}" + if target_dataset['type'] == "ProbeSet": + results_dict['symbol'] = target_trait['symbol'] + results_dict['description'] = "N/A" + results_dict['location'] = target_trait['location'] + results_dict['mean'] = "N/A" + results_dict['additive'] = "N/A" + if bool(target_trait['description']): + results_dict['description'] = target_trait['description'] + if bool(target_trait['mean']): + results_dict['mean'] = f"{float(target_trait['mean']):.3f}" + try: + results_dict['lod_score'] = f"{float(target_trait['lrs_score']) / 4.61:.1f}" + except: + results_dict['lod_score'] = "N/A" + results_dict['lrs_location'] = target_trait['lrs_location'] + if bool(target_trait['additive']): + results_dict['additive'] = f"{float(target_trait['additive']):.3f}" + results_dict['lit_corr'] = "--" + results_dict['tissue_corr'] = "--" + results_dict['tissue_pvalue'] = "--" + if this_dataset['type'] == "ProbeSet": + if 'lit_corr' in trait: + results_dict['lit_corr'] = f"{float(trait['lit_corr']):.3f}" + if 'tissue_corr' in trait: + results_dict['tissue_corr'] = f"{float(trait['tissue_corr']):.3f}" + results_dict['tissue_pvalue'] = f"{float(trait['tissue_p_val']):.3e}" + elif target_dataset['type'] == "Publish": + results_dict['abbreviation_display'] = "N/A" + results_dict['description'] = "N/A" + results_dict['mean'] = "N/A" + results_dict['authors_display'] = "N/A" + results_dict['additive'] = "N/A" + results_dict['pubmed_link'] = "N/A" + results_dict['pubmed_text'] = "N/A" + + if bool(target_trait['abbreviation']): + results_dict['abbreviation_display'] = target_trait['abbreviation'] + if bool(target_trait['description']): + results_dict['description'] = target_trait['description'] + if bool(target_trait['mean']): + results_dict['mean'] = f"{float(target_trait['mean']):.3f}" + if bool(target_trait['authors']): + authors_list = target_trait['authors'].split(',') + if len(authors_list) > 6: + results_dict['authors_display'] = ", ".join( + authors_list[:6]) + ", et al." else: - lit_corr_data[trait] = [gene_id, 0] - else: - lit_corr_data[trait] = [gene_id, 0] - - lit_corr_data = collections.OrderedDict(sorted(list(lit_corr_data.items()), - key=lambda t: -abs(t[1][1]))) - - return lit_corr_data - - def convert_to_mouse_gene_id(self, species=None, gene_id=None): - """If the species is rat or human, translate the gene_id to the mouse geneid - - If there is no input gene_id or there's no corresponding mouse gene_id, return None - - """ - if not gene_id: - return None - - mouse_gene_id = None - - if species == 'mouse': - mouse_gene_id = gene_id - - elif species == 'rat': - - query = """SELECT mouse - FROM GeneIDXRef - WHERE rat='%s'""" % escape(gene_id) - - result = g.db.execute(query).fetchone() - if result != None: - mouse_gene_id = result.mouse - - elif species == 'human': - - query = """SELECT mouse - FROM GeneIDXRef - WHERE human='%s'""" % escape(gene_id) - - result = g.db.execute(query).fetchone() - if result != None: - mouse_gene_id = result.mouse - - return mouse_gene_id - - def get_sample_r_and_p_values(self, trait, target_samples): - """Calculates the sample r (or rho) and p-value - - Given a primary trait and a target trait's sample values, - calculates either the pearson r or spearman rho and the p-value - using the corresponding scipy functions. - - """ - - self.this_trait_vals = [] - target_vals = [] - for index, sample in enumerate(self.target_dataset.samplelist): - if sample in self.sample_data: - sample_value = self.sample_data[sample] - target_sample_value = target_samples[index] - self.this_trait_vals.append(sample_value) - target_vals.append(target_sample_value) - - self.this_trait_vals, target_vals, num_overlap = corr_result_helpers.normalize_values( - self.this_trait_vals, target_vals) - - if num_overlap > 5: - # ZS: 2015 could add biweight correlation, see http://www.ncbi.nlm.nih.gov/pmc/articles/PMC3465711/ - if self.corr_method == 'bicor': - sample_r, sample_p = do_bicor( - self.this_trait_vals, target_vals) - if self.corr_method == 'pearson': - sample_r, sample_p = scipy.stats.pearsonr( - self.this_trait_vals, target_vals) - else: - sample_r, sample_p = scipy.stats.spearmanr( - self.this_trait_vals, target_vals) - - if numpy.isnan(sample_r): - pass - else: - self.correlation_data[trait] = [ - sample_r, sample_p, num_overlap] - - def process_samples(self, start_vars, sample_names, excluded_samples=None): - if not excluded_samples: - excluded_samples = () - - sample_val_dict = json.loads(start_vars['sample_vals']) - for sample in sample_names: - if sample not in excluded_samples: - value = sample_val_dict[sample] - if not value.strip().lower() == 'x': - self.sample_data[str(sample)] = float(value) - - -def do_bicor(this_trait_vals, target_trait_vals): - r_library = ro.r["library"] # Map the library function - r_options = ro.r["options"] # Map the options function - - r_library("WGCNA") - r_bicor = ro.r["bicorAndPvalue"] # Map the bicorAndPvalue function - - r_options(stringsAsFactors=False) - - this_vals = ro.FloatVector(this_trait_vals) - target_vals = ro.FloatVector(target_trait_vals) + results_dict['authors_display'] = target_trait['authors'] + if 'pubmed_id' in target_trait: + results_dict['pubmed_link'] = target_trait['pubmed_link'] + results_dict['pubmed_text'] = target_trait['pubmed_text'] + try: + results_dict['lod_score'] = f"{float(target_trait['lrs_score']) / 4.61:.1f}" + except: + results_dict['lod_score'] = "N/A" + results_dict['lrs_location'] = target_trait['lrs_location'] + if bool(target_trait['additive']): + results_dict['additive'] = f"{float(target_trait['additive']):.3f}" + else: + results_dict['location'] = target_trait['location'] - the_r, the_p, _fisher_transform, _the_t, _n_obs = [ - numpy.asarray(x) for x in r_bicor(x=this_vals, y=target_vals)] + results_list.append(results_dict) - return the_r, the_p + return json.dumps(results_list) def generate_corr_json(corr_results, this_trait, dataset, target_dataset, for_api=False): @@ -598,6 +252,25 @@ def generate_corr_json(corr_results, this_trait, dataset, target_dataset, for_ap return json.dumps(results_list) +def get_formatted_corr_type(corr_type, corr_method): + formatted_corr_type = "" + if corr_type == "lit": + formatted_corr_type += "Literature Correlation " + elif corr_type == "tissue": + formatted_corr_type += "Tissue Correlation " + elif corr_type == "sample": + formatted_corr_type += "Genetic Correlation " + + if corr_method == "pearson": + formatted_corr_type += "(Pearson's r)" + elif corr_method == "spearman": + formatted_corr_type += "(Spearman's rho)" + elif corr_method == "bicor": + formatted_corr_type += "(Biweight r)" + + return formatted_corr_type + + def get_header_fields(data_type, corr_method): if data_type == "ProbeSet": if corr_method == "spearman": diff --git a/wqflask/wqflask/templates/correlation_page.html b/wqflask/wqflask/templates/correlation_page.html index 4cad2749..f66eb4bd 100644 --- a/wqflask/wqflask/templates/correlation_page.html +++ b/wqflask/wqflask/templates/correlation_page.html @@ -17,9 +17,9 @@ <hr style="height: 1px; background-color: #A9A9A9;"> </div> <div style="max-width: 100%;"> - <p>Values of record {{ this_trait.name }} in the <a href="http://genenetwork.org/webqtl/main.py?FormID=sharinginfo&{% if dataset.accession_id != 'None' %}GN_AccessionId={{ dataset.accession_id }}{% else %}InfoPageName={{ dataset.name }}{% endif %}">{{ dataset.fullname }}</a> + <p>Values of record {{ this_trait.name }} in the <a href="http://genenetwork.org/webqtl/main.py?FormID=sharinginfo&{% if this_dataset.accession_id != 'None' %}GN_AccessionId={{ this_dataset.accession_id }}{% else %}InfoPageName={{ this_dataset.name }}{% endif %}">{{ this_dataset.fullname }}</a> dataset were compared to all records in the <a href="http://genenetwork.org/webqtl/main.py?FormID=sharinginfo&{% if target_dataset.accession_id != 'None' %}GN_AccessionId={{ target_dataset.accession_id }}{% else %}InfoPageName={{ target_dataset.name }}{% endif %}">{{ target_dataset.fullname }}</a> - dataset. The top {{ return_number }} correlations ranked by the {{ formatted_corr_type }} are displayed. + dataset. The top {{ return_results }} correlations ranked by the {{ formatted_corr_type }} are displayed. You can resort this list by clicking the headers. Select the Record ID to open the trait data and analysis page. </p> @@ -30,7 +30,7 @@ <input type="hidden" name="form_url" value="" /> <input type="hidden" name="trait_list" id="trait_list" value= " {% for this_trait in trait_list %} - {{ this_trait.name }}:{{ this_trait.dataset }}, + {{ this_trait }}:{{ this_dataset.name }}, {% endfor %}" > {% include 'tool_buttons.html' %} </form> @@ -43,7 +43,7 @@ <button class="btn btn-success" id="add" type="button" disabled><span class="glyphicon glyphicon-plus-sign"></span> Add</button> <input type="hidden" name="database_name" id="database_name" value="None"> <input type="hidden" name="export_data" id="export_data" value=""> - <input type="hidden" name="file_name" id="file_name" value="{{ this_trait.name }}_{{ dataset.name }}_correlation"> + <input type="hidden" name="file_name" id="file_name" value="{{ this_trait.name }}_{{ this_dataset.name }}_correlation"> <input type="text" id="searchbox" class="form-control" style="width: 200px; display: inline;" placeholder="Search Table For ..."> <input type="text" id="select_top" class="form-control" style="width: 200px; display: inline;" placeholder="Select Top ..."> <button class="btn btn-default" id="deselect_all" type="button"><span class="glyphicon glyphicon-remove"></span> Deselect</button> @@ -146,7 +146,7 @@ <script type="text/javascript" charset="utf-8"> - var table_json = {{ json_results | safe }} + var table_json = {{ table_json | safe }} </script> <script type="text/javascript" charset="utf-8"> @@ -313,7 +313,7 @@ 'orderSequence': [ "desc", "asc"], 'render': function(data, type, row, meta) { if (data.sample_r != "N/A") { - return "<a target\"_blank\" href=\"corr_scatter_plot?method={% if corr_method == 'spearman' %}spearman{% else %}pearson{% endif %}&dataset_1={% if dataset.name == 'Temp' %}Temp_{{ dataset.group.name }}{% else %}{{ dataset.name }}{% endif %}&dataset_2=" + data.dataset + "&trait_1={{ this_trait.name }}&trait_2=" + data.trait_id + "\">" + data.sample_r + "</a>" + return "<a target\"_blank\" href=\"corr_scatter_plot?method={% if corr_method == 'spearman' %}spearman{% else %}pearson{% endif %}&dataset_1={% if this_dataset.name == 'Temp' %}Temp_{{ this_dataset.group }}{% else %}{{ this_dataset.name }}{% endif %}&dataset_2=" + data.dataset + "&trait_1={{ this_trait.name }}&trait_2=" + data.trait_id + "\">" + data.sample_r + "</a>" } else { return data.sample_r } @@ -441,7 +441,7 @@ 'orderSequence': [ "desc", "asc"], 'render': function(data, type, row, meta) { if (data.sample_r != "N/A") { - return "<a target\"_blank\" href=\"corr_scatter_plot?method={% if corr_method == 'spearman' %}spearman{% else %}pearson{% endif %}&dataset_1={% if dataset.name == 'Temp' %}Temp_{{ dataset.group.name }}{% else %}{{ dataset.name }}{% endif %}&dataset_2=" + data.dataset + "&trait_1={{ this_trait.name }}&trait_2=" + data.trait_id + "\">" + data.sample_r + "</a>" + return "<a target\"_blank\" href=\"corr_scatter_plot?method={% if corr_method == 'spearman' %}spearman{% else %}pearson{% endif %}&dataset_1={% if this_dataset.name== 'Temp' %}Temp_{{ this_dataset.group }}{% else %}{{ this_dataset.name }}{% endif %}&dataset_2=" + data.dataset + "&trait_1={{ this_trait.name }}&trait_2=" + data.trait_id + "\">" + data.sample_r + "</a>" } else { return data.sample_r } @@ -495,7 +495,7 @@ 'orderSequence': [ "desc", "asc"], 'render': function(data, type, row, meta) { if (data.sample_r != "N/A") { - return "<a target\"_blank\" href=\"corr_scatter_plot?method={% if corr_method == 'spearman' %}spearman{% else %}pearson{% endif %}&dataset_1={% if dataset.name == 'Temp' %}Temp_{{ dataset.group.name }}{% else %}{{ dataset.name }}{% endif %}&dataset_2=" + data.dataset + "&trait_1={{ this_trait.name }}&trait_2=" + data.trait_id + "\">" + data.sample_r + "</a>" + return "<a target\"_blank\" href=\"corr_scatter_plot?method={% if corr_method == 'spearman' %}spearman{% else %}pearson{% endif %}&dataset_1={% if this_dataset.name == 'Temp' %}Temp_{{ this_dataset.group }}{% else %}{{ this_dataset.name }}{% endif %}&dataset_2=" + data.dataset + "&trait_1={{ this_trait.name }}&trait_2=" + data.trait_id + "\">" + data.sample_r + "</a>" } else { return data.sample_r } diff --git a/wqflask/wqflask/templates/show_trait_calculate_correlations.html b/wqflask/wqflask/templates/show_trait_calculate_correlations.html index 59f9b47c..16a819fa 100644 --- a/wqflask/wqflask/templates/show_trait_calculate_correlations.html +++ b/wqflask/wqflask/templates/show_trait_calculate_correlations.html @@ -7,8 +7,10 @@ <div class="col-xs-3 controls"> <select name="corr_type" class="form-control"> <option value="sample">Sample r</option> + {% if dataset.type == 'ProbeSet' %} <option value="lit">Literature r</option> <option value="tissue">Tissue r</option> + {% endif %} </select> </div> </div> diff --git a/wqflask/wqflask/views.py b/wqflask/wqflask/views.py index b9181368..da427bfe 100644 --- a/wqflask/wqflask/views.py +++ b/wqflask/wqflask/views.py @@ -65,7 +65,7 @@ from wqflask.comparison_bar_chart import comparison_bar_chart from wqflask.marker_regression import run_mapping from wqflask.marker_regression import display_mapping_results from wqflask.network_graph import network_graph -from wqflask.correlation import show_corr_results +from wqflask.correlation.show_corr_results import set_template_vars from wqflask.correlation.correlation_gn3_api import compute_correlation from wqflask.correlation_matrix import show_corr_matrix from wqflask.correlation import corr_scatter_plot @@ -1082,15 +1082,9 @@ def network_graph_page(): @app.route("/corr_compute", methods=('POST',)) def corr_compute_page(): - logger.info("In corr_compute, request.form is:", pf(request.form)) - logger.info(request.url) - template_vars = show_corr_results.CorrelationResults(request.form) - return render_template("correlation_page.html", **template_vars.__dict__) - - # to test/disable the new correlation api uncomment these lines - - # correlation_results = compute_correlation(request.form) - # return render_template("test_correlation_page.html", correlation_results=correlation_results) + correlation_results = compute_correlation(request.form, compute_all=True) + correlation_results = set_template_vars(request.form, correlation_results) + return render_template("correlation_page.html", **correlation_results) @app.route("/test_corr_compute", methods=["POST"]) |