From fbdbf4b7410185e2a978ecc8e120ae56ff6da0ce Mon Sep 17 00:00:00 2001 From: Zachary Sloan Date: Wed, 9 Jul 2014 18:39:52 +0000 Subject: Updated coffeescript, svg export working fine, interval mapping zoom working --- wqflask/base/data_set.py | 5 +- wqflask/other_config/nginx_conf/penguin.conf | 2 + .../wqflask/interval_mapping/interval_mapping.py | 16 +- .../wqflask/marker_regression/marker_regression.py | 1184 ++++---- wqflask/wqflask/my_pylmm/data/genofile_parser.py | 7 +- .../wqflask/static/new/css/.corr_matrix.css.swp | Bin 12288 -> 0 bytes .../wqflask/static/new/css/interval_mapping.css | 16 +- .../wqflask/static/new/css/marker_regression.css | 12 +- wqflask/wqflask/static/new/javascript/bar_chart.js | 680 +++-- wqflask/wqflask/static/new/javascript/box_plot.js | 103 +- .../static/new/javascript/chr_interval_map.coffee | 293 ++ .../static/new/javascript/chr_interval_map.js | 224 ++ .../new/javascript/chr_manhattan_plot.coffee | 17 +- .../static/new/javascript/chr_manhattan_plot.js | 423 +-- .../new/javascript/compare_traits_scatterplot.js | 225 +- .../wqflask/static/new/javascript/corr_matrix.js | 295 +- .../static/new/javascript/create_corr_matrix.js | 81 +- .../new/javascript/create_interval_map.coffee | 91 + .../static/new/javascript/create_interval_map.js | 53 + .../new/javascript/create_manhattan_plot.coffee | 57 + .../static/new/javascript/create_manhattan_plot.js | 53 + .../static/new/javascript/dataset_select_menu.js | 255 +- .../static/new/javascript/draw_corr_scatterplot.js | 67 +- .../new/javascript/get_traits_from_collection.js | 355 ++- wqflask/wqflask/static/new/javascript/histogram.js | 222 +- .../static/new/javascript/interval_map_new.coffee | 86 +- .../static/new/javascript/interval_map_new.js | 39 +- .../static/new/javascript/interval_mapping.js | 434 +-- .../wqflask/static/new/javascript/lod_chart.coffee | 108 +- wqflask/wqflask/static/new/javascript/lod_chart.js | 1076 +++---- wqflask/wqflask/static/new/javascript/login.js | 86 +- .../static/new/javascript/manhattan_plot.coffee | 534 ++++ .../static/new/javascript/manhattan_plot.js | 475 +++ .../static/new/javascript/marker_regression.coffee | 37 +- .../static/new/javascript/marker_regression.js | 662 +++-- .../static/new/javascript/marker_regression_old.js | 396 ++- .../node_modules/coffee-script/.npmignore | 11 - .../javascript/node_modules/coffee-script/CNAME | 1 - .../node_modules/coffee-script/CONTRIBUTING.md | 9 - .../javascript/node_modules/coffee-script/LICENSE | 22 - .../javascript/node_modules/coffee-script/README | 51 - .../javascript/node_modules/coffee-script/Rakefile | 79 - .../javascript/node_modules/coffee-script/bin/cake | 7 - .../node_modules/coffee-script/bin/coffee | 7 - .../node_modules/coffee-script/extras/jsl.conf | 44 - .../coffee-script/lib/coffee-script/browser.js | 101 - .../coffee-script/lib/coffee-script/cake.js | 113 - .../lib/coffee-script/coffee-script.js | 218 -- .../coffee-script/lib/coffee-script/command.js | 506 ---- .../coffee-script/lib/coffee-script/grammar.js | 623 ---- .../coffee-script/lib/coffee-script/helpers.js | 150 - .../coffee-script/lib/coffee-script/index.js | 11 - .../coffee-script/lib/coffee-script/lexer.js | 905 ------ .../coffee-script/lib/coffee-script/nodes.js | 3088 -------------------- .../coffee-script/lib/coffee-script/optparse.js | 138 - .../coffee-script/lib/coffee-script/parser.js | 608 ---- .../coffee-script/lib/coffee-script/repl.js | 104 - .../coffee-script/lib/coffee-script/rewriter.js | 478 --- .../coffee-script/lib/coffee-script/scope.js | 147 - .../coffee-script/lib/coffee-script/sourcemap.js | 237 -- .../node_modules/coffee-script/package.json | 57 - .../static/new/javascript/password_strength.js | 76 +- .../wqflask/static/new/javascript/scatterplot.js | 777 +++-- .../static/new/javascript/search_results.js | 200 +- .../wqflask/static/new/javascript/show_trait.js | 826 +++--- .../new/javascript/show_trait_mapping_tools.js | 163 +- wqflask/wqflask/static/new/javascript/stats.js | 210 +- wqflask/wqflask/static/new/javascript/thank_you.js | 16 +- .../wqflask/static/new/javascript/validation.js | 92 +- wqflask/wqflask/templates/interval_mapping.html | 23 +- wqflask/wqflask/templates/marker_regression.html | 225 +- wqflask/wqflask/templates/show_trait.html | 1 - .../templates/show_trait_mapping_tools.html | 16 +- wqflask/wqflask/user_manager.py | 1 - wqflask/wqflask/views.py | 10 + 75 files changed, 6654 insertions(+), 12366 deletions(-) delete mode 100755 wqflask/wqflask/static/new/css/.corr_matrix.css.swp create mode 100644 wqflask/wqflask/static/new/javascript/chr_interval_map.coffee create mode 100644 wqflask/wqflask/static/new/javascript/chr_interval_map.js create mode 100644 wqflask/wqflask/static/new/javascript/create_interval_map.coffee create mode 100644 wqflask/wqflask/static/new/javascript/create_interval_map.js create mode 100644 wqflask/wqflask/static/new/javascript/create_manhattan_plot.coffee create mode 100644 wqflask/wqflask/static/new/javascript/create_manhattan_plot.js create mode 100644 wqflask/wqflask/static/new/javascript/manhattan_plot.coffee create mode 100644 wqflask/wqflask/static/new/javascript/manhattan_plot.js delete mode 100755 wqflask/wqflask/static/new/javascript/node_modules/coffee-script/.npmignore delete mode 100755 wqflask/wqflask/static/new/javascript/node_modules/coffee-script/CNAME delete mode 100755 wqflask/wqflask/static/new/javascript/node_modules/coffee-script/CONTRIBUTING.md delete mode 100755 wqflask/wqflask/static/new/javascript/node_modules/coffee-script/LICENSE delete mode 100755 wqflask/wqflask/static/new/javascript/node_modules/coffee-script/README delete mode 100755 wqflask/wqflask/static/new/javascript/node_modules/coffee-script/Rakefile delete mode 100755 wqflask/wqflask/static/new/javascript/node_modules/coffee-script/bin/cake delete mode 100755 wqflask/wqflask/static/new/javascript/node_modules/coffee-script/bin/coffee delete mode 100755 wqflask/wqflask/static/new/javascript/node_modules/coffee-script/extras/jsl.conf delete mode 100755 wqflask/wqflask/static/new/javascript/node_modules/coffee-script/lib/coffee-script/browser.js delete mode 100755 wqflask/wqflask/static/new/javascript/node_modules/coffee-script/lib/coffee-script/cake.js delete mode 100755 wqflask/wqflask/static/new/javascript/node_modules/coffee-script/lib/coffee-script/coffee-script.js delete mode 100755 wqflask/wqflask/static/new/javascript/node_modules/coffee-script/lib/coffee-script/command.js delete mode 100755 wqflask/wqflask/static/new/javascript/node_modules/coffee-script/lib/coffee-script/grammar.js delete mode 100755 wqflask/wqflask/static/new/javascript/node_modules/coffee-script/lib/coffee-script/helpers.js delete mode 100755 wqflask/wqflask/static/new/javascript/node_modules/coffee-script/lib/coffee-script/index.js delete mode 100755 wqflask/wqflask/static/new/javascript/node_modules/coffee-script/lib/coffee-script/lexer.js delete mode 100755 wqflask/wqflask/static/new/javascript/node_modules/coffee-script/lib/coffee-script/nodes.js delete mode 100755 wqflask/wqflask/static/new/javascript/node_modules/coffee-script/lib/coffee-script/optparse.js delete mode 100755 wqflask/wqflask/static/new/javascript/node_modules/coffee-script/lib/coffee-script/parser.js delete mode 100755 wqflask/wqflask/static/new/javascript/node_modules/coffee-script/lib/coffee-script/repl.js delete mode 100755 wqflask/wqflask/static/new/javascript/node_modules/coffee-script/lib/coffee-script/rewriter.js delete mode 100755 wqflask/wqflask/static/new/javascript/node_modules/coffee-script/lib/coffee-script/scope.js delete mode 100755 wqflask/wqflask/static/new/javascript/node_modules/coffee-script/lib/coffee-script/sourcemap.js delete mode 100755 wqflask/wqflask/static/new/javascript/node_modules/coffee-script/package.json (limited to 'wqflask') diff --git a/wqflask/base/data_set.py b/wqflask/base/data_set.py index 843862aa..2a79dc9c 100755 --- a/wqflask/base/data_set.py +++ b/wqflask/base/data_set.py @@ -162,14 +162,15 @@ class Markers(object): for marker in markers: if (marker['chr'] != "X") and (marker['chr'] != "Y"): marker['chr'] = int(marker['chr']) - else: - marker['chr'] = 19 + #else: + # marker['chr'] = 20 print("Mb:", marker['Mb']) marker['Mb'] = float(marker['Mb']) self.markers = markers #print("self.markers:", self.markers) + def add_pvalues(self, p_values): print("length of self.markers:", len(self.markers)) print("length of p_values:", len(p_values)) diff --git a/wqflask/other_config/nginx_conf/penguin.conf b/wqflask/other_config/nginx_conf/penguin.conf index 5c380da8..0a89072e 100755 --- a/wqflask/other_config/nginx_conf/penguin.conf +++ b/wqflask/other_config/nginx_conf/penguin.conf @@ -1,5 +1,7 @@ server { # Modeled after http://flask.pocoo.org/docs/deploying/wsgi-standalone/ + + client_max_body_size 20M; listen 80; server_name gn2python.genenetwork.org; diff --git a/wqflask/wqflask/interval_mapping/interval_mapping.py b/wqflask/wqflask/interval_mapping/interval_mapping.py index a81a62b4..4ac7bde2 100755 --- a/wqflask/wqflask/interval_mapping/interval_mapping.py +++ b/wqflask/wqflask/interval_mapping/interval_mapping.py @@ -58,18 +58,18 @@ class IntervalMapping(object): self.json_data = {} - if self.method == "qtl_reaper": - self.json_data['lodnames'] = ['lod.hk'] - self.gen_reaper_results(tempdata) - else: - self.gen_pylmm_results(tempdata) + #if self.method == "qtl_reaper": + self.json_data['lodnames'] = ['lod.hk'] + self.gen_reaper_results(tempdata) + #else: + # self.gen_pylmm_results(tempdata) #self.gen_qtl_results(tempdata) #Get chromosome lengths for drawing the interval map plot chromosome_mb_lengths = {} self.json_data['chrnames'] = [] for key in self.species.chromosomes.chromosomes.keys(): - self.json_data['chrnames'].append(self.species.chromosomes.chromosomes[key].name) + self.json_data['chrnames'].append([self.species.chromosomes.chromosomes[key].name, self.species.chromosomes.chromosomes[key].mb_length]) chromosome_mb_lengths[key] = self.species.chromosomes.chromosomes[key].mb_length @@ -94,10 +94,10 @@ class IntervalMapping(object): #self.plot_scale = start_vars['scale'] #if self.plotScale == 'physic' and not fd.genotype.Mbmap: # self.plotScale = 'morgan' - self.method = start_vars['mapping_method'] + #self.method = start_vars['mapping_method'] self.num_permutations = int(start_vars['num_permutations']) #self.do_bootstrap = start_vars['do_bootstrap'] - self.selected_chr = start_vars['chromosome'] + #self.selected_chr = start_vars['chromosome'] if start_vars['display_additive'] == "yes": self.additive = True else: diff --git a/wqflask/wqflask/marker_regression/marker_regression.py b/wqflask/wqflask/marker_regression/marker_regression.py index d43fe37c..30c6453c 100755 --- a/wqflask/wqflask/marker_regression/marker_regression.py +++ b/wqflask/wqflask/marker_regression/marker_regression.py @@ -1,585 +1,599 @@ -from __future__ import absolute_import, print_function, division - -from base.trait import GeneralTrait -from base import data_set #import create_dataset - -from pprint import pformat as pf - -import string -import sys -import datetime -import os -import collections -import uuid - -import numpy as np -from scipy import linalg - -import cPickle as pickle - -import simplejson as json - -from redis import Redis -Redis = Redis() - -from flask import Flask, g - -from base.trait import GeneralTrait -from base import data_set -from base import species -from base import webqtlConfig -from utility import webqtlUtil -from wqflask.my_pylmm.data import prep_data -from wqflask.my_pylmm.pyLMM import lmm -from wqflask.my_pylmm.pyLMM import input -from utility import helper_functions -from utility import Plot, Bunch -from utility import temp_data - -from utility.benchmark import Bench - - -class MarkerRegression(object): - - def __init__(self, start_vars, temp_uuid): - - helper_functions.get_species_dataset_trait(self, start_vars) - - #tempdata = temp_data.TempData(temp_uuid) - - self.samples = [] # Want only ones with values - self.vals = [] - - for sample in self.dataset.group.samplelist: - value = start_vars['value:' + sample] - self.samples.append(str(sample)) - self.vals.append(value) - - self.mapping_method = start_vars['method'] - self.maf = start_vars['maf'] # Minor allele frequency - print("self.maf:", self.maf) - - if self.mapping_method == "gemma": - qtl_results = self.run_gemma() - elif self.mapping_method == "plink": - qtl_results = self.run_plink() - #print("qtl_results:", pf(qtl_results)) - elif self.mapping_method == "pylmm": - print("RUNNING PYLMM") - #self.qtl_results = self.gen_data(tempdata) - qtl_results = self.gen_data(str(temp_uuid)) - else: - print("RUNNING NOTHING") - - self.lod_cutoff = 2 - self.filtered_markers = [] - for marker in qtl_results: - if marker['chr'] > 0: - self.filtered_markers.append(marker) - #if marker['lod_score'] > self.lod_cutoff: - - - #print("filtered_markers:", self.filtered_markers) - - #Get chromosome lengths for drawing the manhattan plot - chromosome_mb_lengths = {} - for key in self.species.chromosomes.chromosomes.keys(): - chromosome_mb_lengths[key] = self.species.chromosomes.chromosomes[key].mb_length - - self.js_data = dict( - this_trait = self.this_trait.name, - data_set = self.dataset.name, - maf = self.maf, - chromosomes = chromosome_mb_lengths, - qtl_results = self.filtered_markers, - ) - - def run_gemma(self): - """Generates p-values for each marker using GEMMA""" - - self.dataset.group.get_markers() - - #filename = webqtlUtil.genRandStr("{}_{}_".format(self.dataset.group.name, self.this_trait.name)) - self.gen_pheno_txt_file() - - os.chdir("/home/zas1024/gene/web/gemma") - - gemma_command = './gemma -bfile %s -k output_%s.cXX.txt -lmm 1 -o %s_output' % ( - self.dataset.group.name, - self.dataset.group.name, - self.dataset.group.name) - print("gemma_command:" + gemma_command) - - os.system(gemma_command) - - included_markers, p_values = self.parse_gemma_output() - - self.dataset.group.get_specified_markers(markers = included_markers) - - #for marker in self.dataset.group.markers.markers: - # if marker['name'] not in included_markers: - # print("marker:", marker) - # self.dataset.group.markers.markers.remove(marker) - # #del self.dataset.group.markers.markers[marker] - - self.dataset.group.markers.add_pvalues(p_values) - - return self.dataset.group.markers.markers - - - def parse_gemma_output(self): - included_markers = [] - p_values = [] - with open("/home/zas1024/gene/web/gemma/output/{}_output.assoc.txt".format(self.dataset.group.name)) as output_file: - for line in output_file: - if line.startswith("chr"): - continue - else: - included_markers.append(line.split("\t")[1]) - p_values.append(float(line.split("\t")[10])) - #p_values[line.split("\t")[1]] = float(line.split("\t")[10]) - print("p_values: ", p_values) - return included_markers, p_values - - def gen_pheno_txt_file(self): - """Generates phenotype file for GEMMA""" - - #with open("/home/zas1024/gene/web/gemma/tmp_pheno/{}.txt".format(filename), "w") as outfile: - # for sample, i in enumerate(self.samples): - # print("sample:" + str(i)) - # print("self.vals[i]:" + str(self.vals[sample])) - # outfile.write(str(i) + "\t" + str(self.vals[sample]) + "\n") - - with open("/home/zas1024/gene/web/gemma/{}.fam".format(self.dataset.group.name), "w") as outfile: - for i, sample in enumerate(self.samples): - outfile.write(str(sample) + " " + str(sample) + " 0 0 0 " + str(self.vals[i]) + "\n") - - #def gen_plink_for_gemma(self, filename): - # - # make_bed = "/home/zas1024/plink/plink --file /home/zas1024/plink/%s --noweb --no-fid --no-parents --no-sex --no-pheno --pheno %s%s.txt --out %s%s --make-bed" % (webqtlConfig.HTMLPATH, - # webqtlConfig.HTMLPATH, - # self.dataset.group.name, - # webqtlConfig.TMPDIR, - # filename, - # webqtlConfig.TMPDIR, - # filename) - # - # - - def run_plink(self): - - os.chdir("/home/zas1024/plink") - - self.dataset.group.get_markers() - - plink_output_filename = webqtlUtil.genRandStr("%s_%s_"%(self.dataset.group.name, self.this_trait.name)) - - self.gen_pheno_txt_file_plink(pheno_filename = plink_output_filename) - - plink_command = './plink --noweb --ped %s.ped --no-fid --no-parents --no-sex --no-pheno --map %s.map --pheno %s/%s.txt --pheno-name %s --maf %s --missing-phenotype -9999 --out %s%s --assoc ' % (self.dataset.group.name, self.dataset.group.name, webqtlConfig.TMPDIR, plink_output_filename, self.this_trait.name, self.maf, webqtlConfig.TMPDIR, plink_output_filename) - - os.system(plink_command) - - count, p_values = self.parse_plink_output(plink_output_filename) - #gemma_command = './gemma -bfile %s -k output_%s.cXX.txt -lmm 1 -o %s_output' % ( - # self.dataset.group.name, - # self.dataset.group.name, - # self.dataset.group.name) - #print("gemma_command:" + gemma_command) - # - #os.system(gemma_command) - # - #included_markers, p_values = self.parse_gemma_output() - # - #self.dataset.group.get_specified_markers(markers = included_markers) - - #for marker in self.dataset.group.markers.markers: - # if marker['name'] not in included_markers: - # print("marker:", marker) - # self.dataset.group.markers.markers.remove(marker) - # #del self.dataset.group.markers.markers[marker] - - print("p_values:", pf(p_values)) - - self.dataset.group.markers.add_pvalues(p_values) - - return self.dataset.group.markers.markers - - - def gen_pheno_txt_file_plink(self, pheno_filename = ''): - ped_sample_list = self.get_samples_from_ped_file() - output_file = open("%s%s.txt" % (webqtlConfig.TMPDIR, pheno_filename), "wb") - header = 'FID\tIID\t%s\n' % self.this_trait.name - output_file.write(header) - - new_value_list = [] - - #if valueDict does not include some strain, value will be set to -9999 as missing value - for i, sample in enumerate(ped_sample_list): - try: - value = self.vals[i] - value = str(value).replace('value=','') - value = value.strip() - except: - value = -9999 - - new_value_list.append(value) - - - new_line = '' - for i, sample in enumerate(ped_sample_list): - j = i+1 - value = new_value_list[i] - new_line += '%s\t%s\t%s\n'%(sample, sample, value) - - if j%1000 == 0: - output_file.write(newLine) - new_line = '' - - if new_line: - output_file.write(new_line) - - output_file.close() - - # get strain name from ped file in order - def get_samples_from_ped_file(self): - - os.chdir("/home/zas1024/plink") - - ped_file= open("{}.ped".format(self.dataset.group.name),"r") - line = ped_file.readline() - sample_list=[] - - while line: - lineList = string.split(string.strip(line), '\t') - lineList = map(string.strip, lineList) - - sample_name = lineList[0] - sample_list.append(sample_name) - - line = ped_file.readline() - - return sample_list - - ################################################################ - # Generate Chr list, Chr OrderId and Retrieve Length Information - ################################################################ - #def getChrNameOrderIdLength(self,RISet=''): - # try: - # query = """ - # Select - # Chr_Length.Name,Chr_Length.OrderId,Length from Chr_Length, InbredSet - # where - # Chr_Length.SpeciesId = InbredSet.SpeciesId AND - # InbredSet.Name = '%s' - # Order by OrderId - # """ % (self.dataset.group.name) - # results =g.db.execute(query).fetchall() - # ChrList=[] - # ChrLengthMbList=[] - # ChrNameOrderIdDict={} - # ChrOrderIdNameDict={} - # - # for item in results: - # ChrList.append(item[0]) - # ChrNameOrderIdDict[item[0]]=item[1] # key is chr name, value is orderId - # ChrOrderIdNameDict[item[1]]=item[0] # key is orderId, value is chr name - # ChrLengthMbList.append(item[2]) - # - # except: - # ChrList=[] - # ChrNameOrderIdDict={} - # ChrLengthMbList=[] - # - # return ChrList,ChrNameOrderIdDict,ChrOrderIdNameDict,ChrLengthMbList - - - def parse_plink_output(self, output_filename): - plink_results={} - - threshold_p_value = 0.01 - - result_fp = open("%s%s.qassoc"% (webqtlConfig.TMPDIR, output_filename), "rb") - - header_line = result_fp.readline()# read header line - line = result_fp.readline() - - value_list = [] # initialize value list, this list will include snp, bp and pvalue info - p_value_dict = {} - count = 0 - - while line: - #convert line from str to list - line_list = self.build_line_list(line=line) - - # only keep the records whose chromosome name is in db - if self.species.chromosomes.chromosomes.has_key(int(line_list[0])) and line_list[-1] and line_list[-1].strip()!='NA': - - chr_name = self.species.chromosomes.chromosomes[int(line_list[0])] - snp = line_list[1] - BP = line_list[2] - p_value = float(line_list[-1]) - if threshold_p_value >= 0 and threshold_p_value <= 1: - if p_value < threshold_p_value: - p_value_dict[snp] = p_value - - if plink_results.has_key(chr_name): - value_list = plink_results[chr_name] - - # pvalue range is [0,1] - if threshold_p_value >=0 and threshold_p_value <= 1: - if p_value < threshold_p_value: - value_list.append((snp, BP, p_value)) - count += 1 - - plink_results[chr_name] = value_list - value_list = [] - else: - if threshold_p_value >= 0 and threshold_p_value <= 1: - if p_value < threshold_p_value: - value_list.append((snp, BP, p_value)) - count += 1 - - if value_list: - plink_results[chr_name] = value_list - - value_list=[] - - line = result_fp.readline() - else: - line = result_fp.readline() - - #if p_value_list: - # min_p_value = min(p_value_list) - #else: - # min_p_value = 0 - - return count, p_value_dict - - ###################################################### - # input: line: str,one line read from file - # function: convert line from str to list; - # output: lineList list - ####################################################### - def build_line_list(self, line=None): - - line_list = string.split(string.strip(line),' ')# irregular number of whitespaces between columns - line_list = [item for item in line_list if item <>''] - line_list = map(string.strip, line_list) - - return line_list - - #def gen_data(self, tempdata): - def gen_data(self, temp_uuid): - """Generates p-values for each marker""" - - self.dataset.group.get_markers() - - pheno_vector = np.array([val == "x" and np.nan or float(val) for val in self.vals]) - - #lmm_uuid = str(uuid.uuid4()) - - key = "pylmm:input:" + temp_uuid - print("key is:", pf(key)) - #with Bench("Loading cache"): - # result = Redis.get(key) - - if self.dataset.group.species == "human": - p_values, t_stats = self.gen_human_results(pheno_vector, key, temp_uuid) - #p_values = self.trim_results(p_values) - - else: - print("NOW CWD IS:", os.getcwd()) - genotype_data = [marker['genotypes'] for marker in self.dataset.group.markers.markers] - - no_val_samples = self.identify_empty_samples() - trimmed_genotype_data = self.trim_genotypes(genotype_data, no_val_samples) - - genotype_matrix = np.array(trimmed_genotype_data).T - - #print("pheno_vector: ", pf(pheno_vector)) - #print("genotype_matrix: ", pf(genotype_matrix)) - #print("genotype_matrix.shape: ", pf(genotype_matrix.shape)) - - #params = {"pheno_vector": pheno_vector, - # "genotype_matrix": genotype_matrix, - # "restricted_max_likelihood": True, - # "refit": False, - # "temp_data": tempdata} - - params = dict(pheno_vector = pheno_vector.tolist(), - genotype_matrix = genotype_matrix.tolist(), - restricted_max_likelihood = True, - refit = False, - temp_uuid = temp_uuid, - - # meta data - timestamp = datetime.datetime.now().isoformat(), - ) - - json_params = json.dumps(params) - #print("json_params:", json_params) - Redis.set(key, json_params) - Redis.expire(key, 60*60) - print("before printing command") - - command = 'python /home/zas1024/gene/wqflask/wqflask/my_pylmm/pyLMM/lmm.py --key {} --species {}'.format(key, - "other") - print("command is:", command) - print("after printing command") - - os.system(command) - - #t_stats, p_values = lmm.run(key) - #lmm.run(key) - - json_results = Redis.blpop("pylmm:results:" + temp_uuid, 45*60) - results = json.loads(json_results[1]) - p_values = [float(result) for result in results['p_values']] - print("p_values:", p_values) - #p_values = self.trim_results(p_values) - t_stats = results['t_stats'] - - #t_stats, p_values = lmm.run( - # pheno_vector, - # genotype_matrix, - # restricted_max_likelihood=True, - # refit=False, - # temp_data=tempdata - #) - #print("p_values:", p_values) - - self.dataset.group.markers.add_pvalues(p_values) - - #self.get_lod_score_cutoff() - - return self.dataset.group.markers.markers - - def trim_results(self, p_values): - print("len_p_values:", len(p_values)) - if len(p_values) > 500: - p_values.sort(reverse=True) - trimmed_values = p_values[:500] - - return trimmed_values - - #def gen_human_results(self, pheno_vector, tempdata): - def gen_human_results(self, pheno_vector, key, temp_uuid): - file_base = os.path.join(webqtlConfig.PYLMM_PATH, self.dataset.group.name) - - plink_input = input.plink(file_base, type='b') - input_file_name = os.path.join(webqtlConfig.SNP_PATH, self.dataset.group.name + ".snps.gz") - - pheno_vector = pheno_vector.reshape((len(pheno_vector), 1)) - covariate_matrix = np.ones((pheno_vector.shape[0],1)) - kinship_matrix = np.fromfile(open(file_base + '.kin','r'),sep=" ") - kinship_matrix.resize((len(plink_input.indivs),len(plink_input.indivs))) - - print("Before creating params") - - params = dict(pheno_vector = pheno_vector.tolist(), - covariate_matrix = covariate_matrix.tolist(), - input_file_name = input_file_name, - kinship_matrix = kinship_matrix.tolist(), - refit = False, - temp_uuid = temp_uuid, - - # meta data - timestamp = datetime.datetime.now().isoformat(), - ) - - print("After creating params") - - json_params = json.dumps(params) - Redis.set(key, json_params) - Redis.expire(key, 60*60) - - print("Before creating the command") - - command = 'python /home/zas1024/gene/wqflask/wqflask/my_pylmm/pyLMM/lmm.py --key {} --species {}'.format(key, - "human") - - print("command is:", command) - - os.system(command) - - json_results = Redis.blpop("pylmm:results:" + temp_uuid, 45*60) - results = json.loads(json_results[1]) - t_stats = results['t_stats'] - p_values = results['p_values'] - - - #p_values, t_stats = lmm.run_human(key) - - #p_values, t_stats = lmm.run_human( - # pheno_vector, - # covariate_matrix, - # input_file_name, - # kinship_matrix, - # loading_progress=tempdata - # ) - - return p_values, t_stats - - def get_lod_score_cutoff(self): - print("INSIDE GET LOD CUTOFF") - high_qtl_count = 0 - for marker in self.dataset.group.markers.markers: - if marker['lod_score'] > 1: - high_qtl_count += 1 - - if high_qtl_count > 1000: - return 1 - else: - return 0 - - def identify_empty_samples(self): - no_val_samples = [] - for sample_count, val in enumerate(self.vals): - if val == "x": - no_val_samples.append(sample_count) - return no_val_samples - - def trim_genotypes(self, genotype_data, no_value_samples): - trimmed_genotype_data = [] - for marker in genotype_data: - new_genotypes = [] - for item_count, genotype in enumerate(marker): - if item_count in no_value_samples: - continue - try: - genotype = float(genotype) - except ValueError: - genotype = np.nan - pass - new_genotypes.append(genotype) - trimmed_genotype_data.append(new_genotypes) - return trimmed_genotype_data - -def create_snp_iterator_file(group): - plink_file_base = os.path.join(webqtlConfig.PYLMM_PATH, group) - plink_input = input.plink(plink_file_base, type='b') - - data = dict(plink_input = list(plink_input), - numSNPs = plink_input.numSNPs) - - #input_dict = {} - # - #input_dict['plink_input'] = list(plink_input) - #input_dict['numSNPs'] = plink_input.numSNPs - # - - snp_file_base = os.path.join(webqtlConfig.SNP_PATH, group + ".snps.gz") - - with gzip.open(snp_file_base, "wb") as fh: - pickle.dump(data, fh, pickle.HIGHEST_PROTOCOL) - -#if __name__ == '__main__': -# import cPickle as pickle -# import gzip -# create_snp_iterator_file("HLC") - -if __name__ == '__main__': - import cPickle as pickle - import gzip - create_snp_iterator_file("HLC") +from __future__ import absolute_import, print_function, division + +from base.trait import GeneralTrait +from base import data_set #import create_dataset + +from pprint import pformat as pf + +import string +import sys +import datetime +import os +import collections +import uuid + +import numpy as np +from scipy import linalg + +import cPickle as pickle + +import simplejson as json + +from redis import Redis +Redis = Redis() + +from flask import Flask, g + +from base.trait import GeneralTrait +from base import data_set +from base import species +from base import webqtlConfig +from utility import webqtlUtil +from wqflask.my_pylmm.data import prep_data +from wqflask.my_pylmm.pyLMM import lmm +from wqflask.my_pylmm.pyLMM import input +from utility import helper_functions +from utility import Plot, Bunch +from utility import temp_data + +from utility.benchmark import Bench + + +class MarkerRegression(object): + + def __init__(self, start_vars, temp_uuid): + + helper_functions.get_species_dataset_trait(self, start_vars) + + #tempdata = temp_data.TempData(temp_uuid) + + self.json_data = {} + self.json_data['lodnames'] = ['lod.hk'] + + self.samples = [] # Want only ones with values + self.vals = [] + + for sample in self.dataset.group.samplelist: + value = start_vars['value:' + sample] + self.samples.append(str(sample)) + self.vals.append(value) + + self.mapping_method = start_vars['method'] + self.maf = start_vars['maf'] # Minor allele frequency + print("self.maf:", self.maf) + + self.dataset.group.get_markers() + if self.mapping_method == "gemma": + qtl_results = self.run_gemma() + elif self.mapping_method == "plink": + qtl_results = self.run_plink() + #print("qtl_results:", pf(qtl_results)) + elif self.mapping_method == "pylmm": + print("RUNNING PYLMM") + #self.qtl_results = self.gen_data(tempdata) + qtl_results = self.gen_data(str(temp_uuid)) + else: + print("RUNNING NOTHING") + + self.lod_cutoff = 2 + self.filtered_markers = [] + for marker in qtl_results: + if marker['chr'] > 0 or marker['chr'] == "X" or marker['chr'] == "X/Y": + if 'lod_score' in marker: + self.filtered_markers.append(marker) + + + self.json_data['chr'] = [] + self.json_data['pos'] = [] + self.json_data['lod.hk'] = [] + self.json_data['markernames'] = [] + + #Need to convert the QTL objects that qtl reaper returns into a json serializable dictionary + self.qtl_results = [] + for qtl in self.filtered_markers: + print("lod score is:", qtl['lod_score']) + self.json_data['chr'].append(str(qtl['chr'])) + self.json_data['pos'].append(qtl['Mb']) + self.json_data['lod.hk'].append(str(qtl['lod_score'])) + self.json_data['markernames'].append(qtl['name']) + + #Get chromosome lengths for drawing the interval map plot + chromosome_mb_lengths = {} + self.json_data['chrnames'] = [] + for key in self.species.chromosomes.chromosomes.keys(): + self.json_data['chrnames'].append([self.species.chromosomes.chromosomes[key].name, self.species.chromosomes.chromosomes[key].mb_length]) + + chromosome_mb_lengths[key] = self.species.chromosomes.chromosomes[key].mb_length + + self.js_data = dict( + json_data = self.json_data, + this_trait = self.this_trait.name, + data_set = self.dataset.name, + maf = self.maf, + chromosomes = chromosome_mb_lengths, + qtl_results = self.filtered_markers, + ) + + def run_gemma(self): + """Generates p-values for each marker using GEMMA""" + + #filename = webqtlUtil.genRandStr("{}_{}_".format(self.dataset.group.name, self.this_trait.name)) + self.gen_pheno_txt_file() + + os.chdir("/home/zas1024/gene/web/gemma") + + gemma_command = './gemma -bfile %s -k output_%s.cXX.txt -lmm 1 -o %s_output' % ( + self.dataset.group.name, + self.dataset.group.name, + self.dataset.group.name) + print("gemma_command:" + gemma_command) + + os.system(gemma_command) + + included_markers, p_values = self.parse_gemma_output() + + self.dataset.group.get_specified_markers(markers = included_markers) + + #for marker in self.dataset.group.markers.markers: + # if marker['name'] not in included_markers: + # print("marker:", marker) + # self.dataset.group.markers.markers.remove(marker) + # #del self.dataset.group.markers.markers[marker] + + self.dataset.group.markers.add_pvalues(p_values) + + return self.dataset.group.markers.markers + + + def parse_gemma_output(self): + included_markers = [] + p_values = [] + with open("/home/zas1024/gene/web/gemma/output/{}_output.assoc.txt".format(self.dataset.group.name)) as output_file: + for line in output_file: + if line.startswith("chr"): + continue + else: + included_markers.append(line.split("\t")[1]) + p_values.append(float(line.split("\t")[10])) + #p_values[line.split("\t")[1]] = float(line.split("\t")[10]) + print("p_values: ", p_values) + return included_markers, p_values + + def gen_pheno_txt_file(self): + """Generates phenotype file for GEMMA""" + + #with open("/home/zas1024/gene/web/gemma/tmp_pheno/{}.txt".format(filename), "w") as outfile: + # for sample, i in enumerate(self.samples): + # print("sample:" + str(i)) + # print("self.vals[i]:" + str(self.vals[sample])) + # outfile.write(str(i) + "\t" + str(self.vals[sample]) + "\n") + + with open("/home/zas1024/gene/web/gemma/{}.fam".format(self.dataset.group.name), "w") as outfile: + for i, sample in enumerate(self.samples): + outfile.write(str(sample) + " " + str(sample) + " 0 0 0 " + str(self.vals[i]) + "\n") + + #def gen_plink_for_gemma(self, filename): + # + # make_bed = "/home/zas1024/plink/plink --file /home/zas1024/plink/%s --noweb --no-fid --no-parents --no-sex --no-pheno --pheno %s%s.txt --out %s%s --make-bed" % (webqtlConfig.HTMLPATH, + # webqtlConfig.HTMLPATH, + # self.dataset.group.name, + # webqtlConfig.TMPDIR, + # filename, + # webqtlConfig.TMPDIR, + # filename) + # + # + + def run_plink(self): + + os.chdir("/home/zas1024/plink") + + plink_output_filename = webqtlUtil.genRandStr("%s_%s_"%(self.dataset.group.name, self.this_trait.name)) + + self.gen_pheno_txt_file_plink(pheno_filename = plink_output_filename) + + plink_command = './plink --noweb --ped %s.ped --no-fid --no-parents --no-sex --no-pheno --map %s.map --pheno %s/%s.txt --pheno-name %s --maf %s --missing-phenotype -9999 --out %s%s --assoc ' % (self.dataset.group.name, self.dataset.group.name, webqtlConfig.TMPDIR, plink_output_filename, self.this_trait.name, self.maf, webqtlConfig.TMPDIR, plink_output_filename) + + os.system(plink_command) + + count, p_values = self.parse_plink_output(plink_output_filename) + #gemma_command = './gemma -bfile %s -k output_%s.cXX.txt -lmm 1 -o %s_output' % ( + # self.dataset.group.name, + # self.dataset.group.name, + # self.dataset.group.name) + #print("gemma_command:" + gemma_command) + # + #os.system(gemma_command) + # + #included_markers, p_values = self.parse_gemma_output() + # + #self.dataset.group.get_specified_markers(markers = included_markers) + + #for marker in self.dataset.group.markers.markers: + # if marker['name'] not in included_markers: + # print("marker:", marker) + # self.dataset.group.markers.markers.remove(marker) + # #del self.dataset.group.markers.markers[marker] + + print("p_values:", pf(p_values)) + + self.dataset.group.markers.add_pvalues(p_values) + + return self.dataset.group.markers.markers + + + def gen_pheno_txt_file_plink(self, pheno_filename = ''): + ped_sample_list = self.get_samples_from_ped_file() + output_file = open("%s%s.txt" % (webqtlConfig.TMPDIR, pheno_filename), "wb") + header = 'FID\tIID\t%s\n' % self.this_trait.name + output_file.write(header) + + new_value_list = [] + + #if valueDict does not include some strain, value will be set to -9999 as missing value + for i, sample in enumerate(ped_sample_list): + try: + value = self.vals[i] + value = str(value).replace('value=','') + value = value.strip() + except: + value = -9999 + + new_value_list.append(value) + + + new_line = '' + for i, sample in enumerate(ped_sample_list): + j = i+1 + value = new_value_list[i] + new_line += '%s\t%s\t%s\n'%(sample, sample, value) + + if j%1000 == 0: + output_file.write(newLine) + new_line = '' + + if new_line: + output_file.write(new_line) + + output_file.close() + + # get strain name from ped file in order + def get_samples_from_ped_file(self): + + os.chdir("/home/zas1024/plink") + + ped_file= open("{}.ped".format(self.dataset.group.name),"r") + line = ped_file.readline() + sample_list=[] + + while line: + lineList = string.split(string.strip(line), '\t') + lineList = map(string.strip, lineList) + + sample_name = lineList[0] + sample_list.append(sample_name) + + line = ped_file.readline() + + return sample_list + + ################################################################ + # Generate Chr list, Chr OrderId and Retrieve Length Information + ################################################################ + #def getChrNameOrderIdLength(self,RISet=''): + # try: + # query = """ + # Select + # Chr_Length.Name,Chr_Length.OrderId,Length from Chr_Length, InbredSet + # where + # Chr_Length.SpeciesId = InbredSet.SpeciesId AND + # InbredSet.Name = '%s' + # Order by OrderId + # """ % (self.dataset.group.name) + # results =g.db.execute(query).fetchall() + # ChrList=[] + # ChrLengthMbList=[] + # ChrNameOrderIdDict={} + # ChrOrderIdNameDict={} + # + # for item in results: + # ChrList.append(item[0]) + # ChrNameOrderIdDict[item[0]]=item[1] # key is chr name, value is orderId + # ChrOrderIdNameDict[item[1]]=item[0] # key is orderId, value is chr name + # ChrLengthMbList.append(item[2]) + # + # except: + # ChrList=[] + # ChrNameOrderIdDict={} + # ChrLengthMbList=[] + # + # return ChrList,ChrNameOrderIdDict,ChrOrderIdNameDict,ChrLengthMbList + + + def parse_plink_output(self, output_filename): + plink_results={} + + threshold_p_value = 0.01 + + result_fp = open("%s%s.qassoc"% (webqtlConfig.TMPDIR, output_filename), "rb") + + header_line = result_fp.readline()# read header line + line = result_fp.readline() + + value_list = [] # initialize value list, this list will include snp, bp and pvalue info + p_value_dict = {} + count = 0 + + while line: + #convert line from str to list + line_list = self.build_line_list(line=line) + + # only keep the records whose chromosome name is in db + if self.species.chromosomes.chromosomes.has_key(int(line_list[0])) and line_list[-1] and line_list[-1].strip()!='NA': + + chr_name = self.species.chromosomes.chromosomes[int(line_list[0])] + snp = line_list[1] + BP = line_list[2] + p_value = float(line_list[-1]) + if threshold_p_value >= 0 and threshold_p_value <= 1: + if p_value < threshold_p_value: + p_value_dict[snp] = p_value + + if plink_results.has_key(chr_name): + value_list = plink_results[chr_name] + + # pvalue range is [0,1] + if threshold_p_value >=0 and threshold_p_value <= 1: + if p_value < threshold_p_value: + value_list.append((snp, BP, p_value)) + count += 1 + + plink_results[chr_name] = value_list + value_list = [] + else: + if threshold_p_value >= 0 and threshold_p_value <= 1: + if p_value < threshold_p_value: + value_list.append((snp, BP, p_value)) + count += 1 + + if value_list: + plink_results[chr_name] = value_list + + value_list=[] + + line = result_fp.readline() + else: + line = result_fp.readline() + + #if p_value_list: + # min_p_value = min(p_value_list) + #else: + # min_p_value = 0 + + return count, p_value_dict + + ###################################################### + # input: line: str,one line read from file + # function: convert line from str to list; + # output: lineList list + ####################################################### + def build_line_list(self, line=None): + + line_list = string.split(string.strip(line),' ')# irregular number of whitespaces between columns + line_list = [item for item in line_list if item <>''] + line_list = map(string.strip, line_list) + + return line_list + + #def gen_data(self, tempdata): + def gen_data(self, temp_uuid): + """Generates p-values for each marker""" + + pheno_vector = np.array([val == "x" and np.nan or float(val) for val in self.vals]) + + #lmm_uuid = str(uuid.uuid4()) + + key = "pylmm:input:" + temp_uuid + print("key is:", pf(key)) + #with Bench("Loading cache"): + # result = Redis.get(key) + + if self.dataset.group.species == "human": + p_values, t_stats = self.gen_human_results(pheno_vector, key, temp_uuid) + #p_values = self.trim_results(p_values) + + else: + print("NOW CWD IS:", os.getcwd()) + genotype_data = [marker['genotypes'] for marker in self.dataset.group.markers.markers] + + no_val_samples = self.identify_empty_samples() + trimmed_genotype_data = self.trim_genotypes(genotype_data, no_val_samples) + + genotype_matrix = np.array(trimmed_genotype_data).T + + #print("pheno_vector: ", pf(pheno_vector)) + #print("genotype_matrix: ", pf(genotype_matrix)) + #print("genotype_matrix.shape: ", pf(genotype_matrix.shape)) + + #params = {"pheno_vector": pheno_vector, + # "genotype_matrix": genotype_matrix, + # "restricted_max_likelihood": True, + # "refit": False, + # "temp_data": tempdata} + + params = dict(pheno_vector = pheno_vector.tolist(), + genotype_matrix = genotype_matrix.tolist(), + restricted_max_likelihood = True, + refit = False, + temp_uuid = temp_uuid, + + # meta data + timestamp = datetime.datetime.now().isoformat(), + ) + + json_params = json.dumps(params) + #print("json_params:", json_params) + Redis.set(key, json_params) + Redis.expire(key, 60*60) + print("before printing command") + + command = 'python /home/zas1024/gene/wqflask/wqflask/my_pylmm/pyLMM/lmm.py --key {} --species {}'.format(key, + "other") + print("command is:", command) + print("after printing command") + + os.system(command) + + #t_stats, p_values = lmm.run(key) + #lmm.run(key) + + json_results = Redis.blpop("pylmm:results:" + temp_uuid, 45*60) + results = json.loads(json_results[1]) + p_values = [float(result) for result in results['p_values']] + print("p_values:", p_values) + #p_values = self.trim_results(p_values) + t_stats = results['t_stats'] + + #t_stats, p_values = lmm.run( + # pheno_vector, + # genotype_matrix, + # restricted_max_likelihood=True, + # refit=False, + # temp_data=tempdata + #) + #print("p_values:", p_values) + + self.dataset.group.markers.add_pvalues(p_values) + + #self.get_lod_score_cutoff() + + return self.dataset.group.markers.markers + + def trim_results(self, p_values): + print("len_p_values:", len(p_values)) + if len(p_values) > 500: + p_values.sort(reverse=True) + trimmed_values = p_values[:500] + + return trimmed_values + + #def gen_human_results(self, pheno_vector, tempdata): + def gen_human_results(self, pheno_vector, key, temp_uuid): + file_base = os.path.join(webqtlConfig.PYLMM_PATH, self.dataset.group.name) + + plink_input = input.plink(file_base, type='b') + input_file_name = os.path.join(webqtlConfig.SNP_PATH, self.dataset.group.name + ".snps.gz") + + pheno_vector = pheno_vector.reshape((len(pheno_vector), 1)) + covariate_matrix = np.ones((pheno_vector.shape[0],1)) + kinship_matrix = np.fromfile(open(file_base + '.kin','r'),sep=" ") + kinship_matrix.resize((len(plink_input.indivs),len(plink_input.indivs))) + + print("Before creating params") + + params = dict(pheno_vector = pheno_vector.tolist(), + covariate_matrix = covariate_matrix.tolist(), + input_file_name = input_file_name, + kinship_matrix = kinship_matrix.tolist(), + refit = False, + temp_uuid = temp_uuid, + + # meta data + timestamp = datetime.datetime.now().isoformat(), + ) + + print("After creating params") + + json_params = json.dumps(params) + Redis.set(key, json_params) + Redis.expire(key, 60*60) + + print("Before creating the command") + + command = 'python /home/zas1024/gene/wqflask/wqflask/my_pylmm/pyLMM/lmm.py --key {} --species {}'.format(key, + "human") + + print("command is:", command) + + os.system(command) + + json_results = Redis.blpop("pylmm:results:" + temp_uuid, 45*60) + results = json.loads(json_results[1]) + t_stats = results['t_stats'] + p_values = results['p_values'] + + + #p_values, t_stats = lmm.run_human(key) + + #p_values, t_stats = lmm.run_human( + # pheno_vector, + # covariate_matrix, + # input_file_name, + # kinship_matrix, + # loading_progress=tempdata + # ) + + return p_values, t_stats + + def get_lod_score_cutoff(self): + print("INSIDE GET LOD CUTOFF") + high_qtl_count = 0 + for marker in self.dataset.group.markers.markers: + if marker['lod_score'] > 1: + high_qtl_count += 1 + + if high_qtl_count > 1000: + return 1 + else: + return 0 + + def identify_empty_samples(self): + no_val_samples = [] + for sample_count, val in enumerate(self.vals): + if val == "x": + no_val_samples.append(sample_count) + return no_val_samples + + def trim_genotypes(self, genotype_data, no_value_samples): + trimmed_genotype_data = [] + for marker in genotype_data: + new_genotypes = [] + for item_count, genotype in enumerate(marker): + if item_count in no_value_samples: + continue + try: + genotype = float(genotype) + except ValueError: + genotype = np.nan + pass + new_genotypes.append(genotype) + trimmed_genotype_data.append(new_genotypes) + return trimmed_genotype_data + +def create_snp_iterator_file(group): + plink_file_base = os.path.join(webqtlConfig.PYLMM_PATH, group) + plink_input = input.plink(plink_file_base, type='b') + + data = dict(plink_input = list(plink_input), + numSNPs = plink_input.numSNPs) + + #input_dict = {} + # + #input_dict['plink_input'] = list(plink_input) + #input_dict['numSNPs'] = plink_input.numSNPs + # + + snp_file_base = os.path.join(webqtlConfig.SNP_PATH, group + ".snps.gz") + + with gzip.open(snp_file_base, "wb") as fh: + pickle.dump(data, fh, pickle.HIGHEST_PROTOCOL) + +#if __name__ == '__main__': +# import cPickle as pickle +# import gzip +# create_snp_iterator_file("HLC") + +if __name__ == '__main__': + import cPickle as pickle + import gzip + create_snp_iterator_file("HLC") diff --git a/wqflask/wqflask/my_pylmm/data/genofile_parser.py b/wqflask/wqflask/my_pylmm/data/genofile_parser.py index baf6aee4..1f4760a9 100755 --- a/wqflask/wqflask/my_pylmm/data/genofile_parser.py +++ b/wqflask/wqflask/my_pylmm/data/genofile_parser.py @@ -96,8 +96,9 @@ class ConvertGenoFile(object): this_marker.chr = row_items[0] #this_marker.cM = row_items[2] if self.cm_exists and self.mb_exists: - this_marker.Mb = row_items[3] - genotypes = row_items[4:] + #print("cm and mb exists") + this_marker.Mb = row_items[2] + genotypes = row_items[3:] elif self.mb_exists: this_marker.Mb = row_items[2] genotypes = row_items[3:] @@ -193,7 +194,7 @@ if __name__=="__main__": New_Geno_Directory = """/home/zas1024/gene/web/new_genotypes/""" #Input_File = """/home/zas1024/gene/web/genotypes/BXD.geno""" #Output_File = """/home/zas1024/gene/wqflask/wqflask/pylmm/data/bxd.snps""" - convertob = ConvertGenoFile("/home/zas1024/gene/web/genotypes/Linsenbardt-Boehm.geno", "/home/zas1024/gene/web/new_genotypes/Linsenbardt-Boehm.json") + convertob = ConvertGenoFile("/home/zas1024/gene/web/genotypes/HSNIH.geno", "/home/zas1024/gene/web/new_genotypes/HSNIH.json") convertob.convert() #ConvertGenoFile.process_all(Old_Geno_Directory, New_Geno_Directory) #ConvertGenoFiles(Geno_Directory) diff --git a/wqflask/wqflask/static/new/css/.corr_matrix.css.swp b/wqflask/wqflask/static/new/css/.corr_matrix.css.swp deleted file mode 100755 index 24d852dc..00000000 Binary files a/wqflask/wqflask/static/new/css/.corr_matrix.css.swp and /dev/null differ diff --git a/wqflask/wqflask/static/new/css/interval_mapping.css b/wqflask/wqflask/static/new/css/interval_mapping.css index 5ebf7742..4a55d2e3 100755 --- a/wqflask/wqflask/static/new/css/interval_mapping.css +++ b/wqflask/wqflask/static/new/css/interval_mapping.css @@ -1,26 +1,26 @@ -.interval_map .y_axis path, -.interval_map .y_axis line { +.chr_interval_map .y_axis path, +.chr_interval_map .y_axis line { fill: none; stroke: black; shape-rendering: crispEdges; } -.interval_map .y_axis text { +.chr_interval_map .y_axis text { font-family: sans-serif; font-size: 14px; } -.interval_map .x_axis path, -.interval_map .x_axis line { +.chr_interval_map .x_axis path, +.chr_interval_map .x_axis line { fill: none; stroke: black; shape-rendering: crispEdges; } -.interval_map .x_axis text { +.chr_interval_map .x_axis text { text-anchor: end; font-family: sans-serif; font-size: 8px; } - +/* interval_map rect { stroke: WhiteSmoke; fill: white; @@ -29,4 +29,4 @@ interval_map rect { interval_map path { stroke: steelblue; stroke-width: 1; -} \ No newline at end of file +}*/ \ No newline at end of file diff --git a/wqflask/wqflask/static/new/css/marker_regression.css b/wqflask/wqflask/static/new/css/marker_regression.css index 56980026..d81b5021 100755 --- a/wqflask/wqflask/static/new/css/marker_regression.css +++ b/wqflask/wqflask/static/new/css/marker_regression.css @@ -1,22 +1,22 @@ -.manhattan_plot .y_axis path, -.manhattan_plot .y_axis line { +.chr_manhattan_plot .y_axis path, +.chr_manhattan_plot .y_axis line { fill: none; stroke: black; shape-rendering: crispEdges; } -.manhattan_plot .y_axis text { +.chr_manhattan_plot .y_axis text { font-family: sans-serif; font-size: 14px; } -.manhattan_plot .x_axis path, -.manhattan_plot .x_axis line { +.chr_manhattan_plot .x_axis path, +.chr_manhattan_plot .x_axis line { fill: none; stroke: black; shape-rendering: crispEdges; } -.manhattan_plot .x_axis text { +.chr_manhattan_plot .x_axis text { text-anchor: end; font-family: sans-serif; font-size: 10px; diff --git a/wqflask/wqflask/static/new/javascript/bar_chart.js b/wqflask/wqflask/static/new/javascript/bar_chart.js index 6f9b27e0..6b484232 100755 --- a/wqflask/wqflask/static/new/javascript/bar_chart.js +++ b/wqflask/wqflask/static/new/javascript/bar_chart.js @@ -1,52 +1,50 @@ -// Generated by CoffeeScript 1.6.1 -(function() { - var Bar_Chart, root, - __hasProp = {}.hasOwnProperty, - __indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; }; +// Generated by CoffeeScript 1.7.1 +var Bar_Chart, root, + __hasProp = {}.hasOwnProperty, + __indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; }; - root = typeof exports !== "undefined" && exports !== null ? exports : this; +root = typeof exports !== "undefined" && exports !== null ? exports : this; - Bar_Chart = (function() { - - function Bar_Chart(sample_list) { - var longest_sample_name, sample, - _this = this; - this.sample_list = sample_list; - this.sort_by = "name"; - this.get_samples(); - console.log("sample names:", this.sample_names); - if (this.sample_attr_vals.length > 0) { - this.get_distinct_attr_vals(); - this.get_attr_color_dict(this.distinct_attr_vals); +Bar_Chart = (function() { + function Bar_Chart(sample_list) { + var longest_sample_name, sample; + this.sample_list = sample_list; + this.sort_by = "name"; + this.get_samples(); + console.log("sample names:", this.sample_names); + if (this.sample_attr_vals.length > 0) { + this.get_distinct_attr_vals(); + this.get_attr_color_dict(this.distinct_attr_vals); + } + longest_sample_name = d3.max((function() { + var _i, _len, _ref, _results; + _ref = this.sample_names; + _results = []; + for (_i = 0, _len = _ref.length; _i < _len; _i++) { + sample = _ref[_i]; + _results.push(sample.length); } - longest_sample_name = d3.max((function() { - var _i, _len, _ref, _results; - _ref = this.sample_names; - _results = []; - for (_i = 0, _len = _ref.length; _i < _len; _i++) { - sample = _ref[_i]; - _results.push(sample.length); - } - return _results; - }).call(this)); - this.margin = { - top: 20, - right: 20, - bottom: longest_sample_name * 7, - left: 40 - }; - this.plot_width = this.sample_vals.length * 20 - this.margin.left - this.margin.right; - this.range = this.sample_vals.length * 20; - this.plot_height = 500 - this.margin.top - this.margin.bottom; - this.x_buffer = this.plot_width / 20; - this.y_buffer = this.plot_height / 20; - this.y_min = d3.min(this.sample_vals); - this.y_max = d3.max(this.sample_vals) * 1.1; - this.svg = this.create_svg(); - this.plot_height -= this.y_buffer; - this.create_scales(); - this.create_graph(); - d3.select("#color_attribute").on("change", function() { + return _results; + }).call(this)); + this.margin = { + top: 20, + right: 20, + bottom: longest_sample_name * 7, + left: 40 + }; + this.plot_width = this.sample_vals.length * 20 - this.margin.left - this.margin.right; + this.range = this.sample_vals.length * 20; + this.plot_height = 500 - this.margin.top - this.margin.bottom; + this.x_buffer = this.plot_width / 20; + this.y_buffer = this.plot_height / 20; + this.y_min = d3.min(this.sample_vals); + this.y_max = d3.max(this.sample_vals) * 1.1; + this.svg = this.create_svg(); + this.plot_height -= this.y_buffer; + this.create_scales(); + this.create_graph(); + d3.select("#color_attribute").on("change", (function(_this) { + return function() { _this.attribute = $("#color_attribute").val(); console.log("attr_color_dict:", _this.attr_color_dict); if (_this.sort_by = "name") { @@ -69,33 +67,40 @@ }); } return _this.add_legend(_this.attribute, _this.distinct_attr_vals[_this.attribute]); - }); - $(".sort_by_value").on("click", function() { + }; + })(this)); + $(".sort_by_value").on("click", (function(_this) { + return function() { console.log("sorting by value"); _this.sort_by = "value"; if (_this.attributes.length > 0) { _this.attribute = $("#color_attribute").val(); } return _this.rebuild_bar_graph(_this.sorted_samples()); - }); - $(".sort_by_name").on("click", function() { + }; + })(this)); + $(".sort_by_name").on("click", (function(_this) { + return function() { console.log("sorting by name"); _this.sort_by = "name"; if (_this.attributes.length > 0) { _this.attribute = $("#color_attribute").val(); } return _this.rebuild_bar_graph(_this.samples); - }); - d3.select("#color_by_trait").on("click", function() { + }; + })(this)); + d3.select("#color_by_trait").on("click", (function(_this) { + return function() { return _this.open_trait_selection(); - }); - } + }; + })(this)); + } - Bar_Chart.prototype.rebuild_bar_graph = function(samples) { - var sample, sample_names, x_scale, - _this = this; - console.log("samples:", samples); - this.svg.selectAll(".bar").data(samples).transition().duration(1000).style("fill", function(d) { + Bar_Chart.prototype.rebuild_bar_graph = function(samples) { + var sample, sample_names, x_scale; + console.log("samples:", samples); + this.svg.selectAll(".bar").data(samples).transition().duration(1000).style("fill", (function(_this) { + return function(d) { if (_this.attributes.length === 0 && (_this.trait_color_dict != null)) { console.log("SAMPLE:", d[0]); console.log("CHECKING:", _this.trait_color_dict[d[0]]); @@ -108,335 +113,366 @@ } else { return "steelblue"; } - }).attr("y", function(d) { + }; + })(this)).attr("y", (function(_this) { + return function(d) { return _this.y_scale(d[1]); - }).attr("height", function(d) { + }; + })(this)).attr("height", (function(_this) { + return function(d) { return _this.plot_height - _this.y_scale(d[1]); - }).select("title").text(function(d) { + }; + })(this)).select("title").text((function(_this) { + return function(d) { return d[1]; - }); - sample_names = (function() { - var _i, _len, _results; - _results = []; - for (_i = 0, _len = samples.length; _i < _len; _i++) { - sample = samples[_i]; - _results.push(sample[0]); - } - return _results; - })(); - console.log("sample_names2:", sample_names); - x_scale = d3.scale.ordinal().domain(sample_names).rangeRoundBands([0, this.range], 0.1, 0); - $('.bar_chart').find('.x.axis').remove(); - return this.add_x_axis(x_scale); - }; - - Bar_Chart.prototype.get_attr_color_dict = function(vals) { - var color, color_range, distinct_vals, i, key, this_color_dict, value, _i, _j, _len, _len1, _results, - _this = this; - this.attr_color_dict = {}; - console.log("vals:", vals); + }; + })(this)); + sample_names = (function() { + var _i, _len, _results; _results = []; - for (key in vals) { - if (!__hasProp.call(vals, key)) continue; - distinct_vals = vals[key]; - this_color_dict = {}; - if (distinct_vals.length < 10) { - color = d3.scale.category10(); - for (i = _i = 0, _len = distinct_vals.length; _i < _len; i = ++_i) { - value = distinct_vals[i]; - this_color_dict[value] = color(i); - } - } else { - console.log("distinct_values:", distinct_vals); - if (_.every(distinct_vals, function(d) { + for (_i = 0, _len = samples.length; _i < _len; _i++) { + sample = samples[_i]; + _results.push(sample[0]); + } + return _results; + })(); + console.log("sample_names2:", sample_names); + x_scale = d3.scale.ordinal().domain(sample_names).rangeRoundBands([0, this.range], 0.1, 0); + $('.bar_chart').find('.x.axis').remove(); + return this.add_x_axis(x_scale); + }; + + Bar_Chart.prototype.get_attr_color_dict = function(vals) { + var color, color_range, distinct_vals, i, key, this_color_dict, value, _i, _j, _len, _len1, _results; + this.attr_color_dict = {}; + console.log("vals:", vals); + _results = []; + for (key in vals) { + if (!__hasProp.call(vals, key)) continue; + distinct_vals = vals[key]; + this_color_dict = {}; + if (distinct_vals.length < 10) { + color = d3.scale.category10(); + for (i = _i = 0, _len = distinct_vals.length; _i < _len; i = ++_i) { + value = distinct_vals[i]; + this_color_dict[value] = color(i); + } + } else { + console.log("distinct_values:", distinct_vals); + if (_.every(distinct_vals, (function(_this) { + return function(d) { if (isNaN(d)) { return false; } else { return true; } - })) { - color_range = d3.scale.linear().domain([d3.min(distinct_vals), d3.max(distinct_vals)]).range([0, 255]); - for (i = _j = 0, _len1 = distinct_vals.length; _j < _len1; i = ++_j) { - value = distinct_vals[i]; - console.log("color_range(value):", parseInt(color_range(value))); - this_color_dict[value] = d3.rgb(parseInt(color_range(value)), 0, 0); - } + }; + })(this))) { + color_range = d3.scale.linear().domain([d3.min(distinct_vals), d3.max(distinct_vals)]).range([0, 255]); + for (i = _j = 0, _len1 = distinct_vals.length; _j < _len1; i = ++_j) { + value = distinct_vals[i]; + console.log("color_range(value):", parseInt(color_range(value))); + this_color_dict[value] = d3.rgb(parseInt(color_range(value)), 0, 0); } } - _results.push(this.attr_color_dict[key] = this_color_dict); } - return _results; - }; + _results.push(this.attr_color_dict[key] = this_color_dict); + } + return _results; + }; - Bar_Chart.prototype.get_trait_color_dict = function(samples, vals) { - var color, color_range, distinct_vals, i, key, sample, this_color_dict, value, _i, _j, _len, _len1, _results, - _this = this; - this.trait_color_dict = {}; - console.log("vals:", vals); - for (key in vals) { - if (!__hasProp.call(vals, key)) continue; - distinct_vals = vals[key]; - this_color_dict = {}; - if (distinct_vals.length < 10) { - color = d3.scale.category10(); - for (i = _i = 0, _len = distinct_vals.length; _i < _len; i = ++_i) { - value = distinct_vals[i]; - this_color_dict[value] = color(i); - } - } else { - console.log("distinct_values:", distinct_vals); - if (_.every(distinct_vals, function(d) { + Bar_Chart.prototype.get_trait_color_dict = function(samples, vals) { + var color, color_range, distinct_vals, i, key, sample, this_color_dict, value, _i, _j, _len, _len1, _results; + this.trait_color_dict = {}; + console.log("vals:", vals); + for (key in vals) { + if (!__hasProp.call(vals, key)) continue; + distinct_vals = vals[key]; + this_color_dict = {}; + if (distinct_vals.length < 10) { + color = d3.scale.category10(); + for (i = _i = 0, _len = distinct_vals.length; _i < _len; i = ++_i) { + value = distinct_vals[i]; + this_color_dict[value] = color(i); + } + } else { + console.log("distinct_values:", distinct_vals); + if (_.every(distinct_vals, (function(_this) { + return function(d) { if (isNaN(d)) { return false; } else { return true; } - })) { - color_range = d3.scale.linear().domain([d3.min(distinct_vals), d3.max(distinct_vals)]).range([0, 255]); - for (i = _j = 0, _len1 = distinct_vals.length; _j < _len1; i = ++_j) { - value = distinct_vals[i]; - console.log("color_range(value):", parseInt(color_range(value))); - this_color_dict[value] = d3.rgb(parseInt(color_range(value)), 0, 0); - } + }; + })(this))) { + color_range = d3.scale.linear().domain([d3.min(distinct_vals), d3.max(distinct_vals)]).range([0, 255]); + for (i = _j = 0, _len1 = distinct_vals.length; _j < _len1; i = ++_j) { + value = distinct_vals[i]; + console.log("color_range(value):", parseInt(color_range(value))); + this_color_dict[value] = d3.rgb(parseInt(color_range(value)), 0, 0); } } } - _results = []; - for (sample in samples) { - if (!__hasProp.call(samples, sample)) continue; - value = samples[sample]; - _results.push(this.trait_color_dict[sample] = this_color_dict[value]); - } - return _results; - }; + } + _results = []; + for (sample in samples) { + if (!__hasProp.call(samples, sample)) continue; + value = samples[sample]; + _results.push(this.trait_color_dict[sample] = this_color_dict[value]); + } + return _results; + }; - Bar_Chart.prototype.convert_into_colors = function(values) { - var color_range, i, value, _i, _len, _results; - color_range = d3.scale.linear().domain([d3.min(values), d3.max(values)]).range([0, 255]); + Bar_Chart.prototype.convert_into_colors = function(values) { + var color_range, i, value, _i, _len, _results; + color_range = d3.scale.linear().domain([d3.min(values), d3.max(values)]).range([0, 255]); + _results = []; + for (i = _i = 0, _len = values.length; _i < _len; i = ++_i) { + value = values[i]; + console.log("color_range(value):", color_range(parseInt(value))); + _results.push(this_color_dict[value] = d3.rgb(color_range(parseInt(value)), 0, 0)); + } + return _results; + }; + + Bar_Chart.prototype.get_samples = function() { + var attr_vals, attribute, key, sample, _i, _j, _len, _len1, _ref, _ref1; + this.sample_names = (function() { + var _i, _len, _ref, _results; + _ref = this.sample_list; _results = []; - for (i = _i = 0, _len = values.length; _i < _len; i = ++_i) { - value = values[i]; - console.log("color_range(value):", color_range(parseInt(value))); - _results.push(this_color_dict[value] = d3.rgb(color_range(parseInt(value)), 0, 0)); + for (_i = 0, _len = _ref.length; _i < _len; _i++) { + sample = _ref[_i]; + if (sample.value !== null) { + _results.push(sample.name); + } } return _results; - }; - - Bar_Chart.prototype.get_samples = function() { - var attr_vals, attribute, key, sample, _i, _j, _len, _len1, _ref, _ref1; - this.sample_names = (function() { - var _i, _len, _ref, _results; - _ref = this.sample_list; - _results = []; - for (_i = 0, _len = _ref.length; _i < _len; _i++) { - sample = _ref[_i]; - if (sample.value !== null) { - _results.push(sample.name); - } - } - return _results; - }).call(this); - this.sample_vals = (function() { - var _i, _len, _ref, _results; - _ref = this.sample_list; - _results = []; - for (_i = 0, _len = _ref.length; _i < _len; _i++) { - sample = _ref[_i]; - if (sample.value !== null) { - _results.push(sample.value); - } - } - return _results; - }).call(this); - this.attributes = (function() { - var _results; - _results = []; - for (key in this.sample_list[0]["extra_attributes"]) { - _results.push(key); - } - return _results; - }).call(this); - console.log("attributes:", this.attributes); - this.sample_attr_vals = []; - if (this.attributes.length > 0) { - _ref = this.sample_list; - for (_i = 0, _len = _ref.length; _i < _len; _i++) { - sample = _ref[_i]; - attr_vals = {}; - _ref1 = this.attributes; - for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) { - attribute = _ref1[_j]; - attr_vals[attribute] = sample["extra_attributes"][attribute]; - } - this.sample_attr_vals.push(attr_vals); + }).call(this); + this.sample_vals = (function() { + var _i, _len, _ref, _results; + _ref = this.sample_list; + _results = []; + for (_i = 0, _len = _ref.length; _i < _len; _i++) { + sample = _ref[_i]; + if (sample.value !== null) { + _results.push(sample.value); } } - return this.samples = _.zip(this.sample_names, this.sample_vals, this.sample_attr_vals); - }; - - Bar_Chart.prototype.get_distinct_attr_vals = function() { - var attribute, sample, _i, _len, _ref, _results; - this.distinct_attr_vals = {}; - _ref = this.sample_attr_vals; + return _results; + }).call(this); + this.attributes = (function() { + var _results; _results = []; + for (key in this.sample_list[0]["extra_attributes"]) { + _results.push(key); + } + return _results; + }).call(this); + console.log("attributes:", this.attributes); + this.sample_attr_vals = []; + if (this.attributes.length > 0) { + _ref = this.sample_list; for (_i = 0, _len = _ref.length; _i < _len; _i++) { sample = _ref[_i]; - _results.push((function() { - var _ref1, _results1; - _results1 = []; - for (attribute in sample) { - if (!this.distinct_attr_vals[attribute]) { - this.distinct_attr_vals[attribute] = []; - } - if (_ref1 = sample[attribute], __indexOf.call(this.distinct_attr_vals[attribute], _ref1) < 0) { - _results1.push(this.distinct_attr_vals[attribute].push(sample[attribute])); - } else { - _results1.push(void 0); - } - } - return _results1; - }).call(this)); + attr_vals = {}; + _ref1 = this.attributes; + for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) { + attribute = _ref1[_j]; + attr_vals[attribute] = sample["extra_attributes"][attribute]; + } + this.sample_attr_vals.push(attr_vals); } - return _results; - }; + } + return this.samples = _.zip(this.sample_names, this.sample_vals, this.sample_attr_vals); + }; - Bar_Chart.prototype.create_svg = function() { - var svg; - svg = d3.select("#bar_chart").append("svg").attr("class", "bar_chart").attr("width", this.plot_width + this.margin.left + this.margin.right).attr("height", this.plot_height + this.margin.top + this.margin.bottom).append("g").attr("transform", "translate(" + this.margin.left + "," + this.margin.top + ")"); - return svg; - }; + Bar_Chart.prototype.get_distinct_attr_vals = function() { + var attribute, sample, _i, _len, _ref, _results; + this.distinct_attr_vals = {}; + _ref = this.sample_attr_vals; + _results = []; + for (_i = 0, _len = _ref.length; _i < _len; _i++) { + sample = _ref[_i]; + _results.push((function() { + var _ref1, _results1; + _results1 = []; + for (attribute in sample) { + if (!this.distinct_attr_vals[attribute]) { + this.distinct_attr_vals[attribute] = []; + } + if (_ref1 = sample[attribute], __indexOf.call(this.distinct_attr_vals[attribute], _ref1) < 0) { + _results1.push(this.distinct_attr_vals[attribute].push(sample[attribute])); + } else { + _results1.push(void 0); + } + } + return _results1; + }).call(this)); + } + return _results; + }; - Bar_Chart.prototype.create_scales = function() { - this.x_scale = d3.scale.ordinal().domain(this.sample_names).rangeRoundBands([0, this.range], 0.1, 0); - return this.y_scale = d3.scale.linear().domain([this.y_min * 0.75, this.y_max]).range([this.plot_height, this.y_buffer]); - }; + Bar_Chart.prototype.create_svg = function() { + var svg; + svg = d3.select("#bar_chart").append("svg").attr("class", "bar_chart").attr("width", this.plot_width + this.margin.left + this.margin.right).attr("height", this.plot_height + this.margin.top + this.margin.bottom).append("g").attr("transform", "translate(" + this.margin.left + "," + this.margin.top + ")"); + return svg; + }; - Bar_Chart.prototype.create_graph = function() { - this.add_x_axis(this.x_scale); - this.add_y_axis(); - return this.add_bars(); - }; + Bar_Chart.prototype.create_scales = function() { + this.x_scale = d3.scale.ordinal().domain(this.sample_names).rangeRoundBands([0, this.range], 0.1, 0); + return this.y_scale = d3.scale.linear().domain([this.y_min * 0.75, this.y_max]).range([this.plot_height, this.y_buffer]); + }; - Bar_Chart.prototype.add_x_axis = function(scale) { - var xAxis, - _this = this; - xAxis = d3.svg.axis().scale(scale).orient("bottom"); - return this.svg.append("g").attr("class", "x axis").attr("transform", "translate(0," + this.plot_height + ")").call(xAxis).selectAll("text").style("text-anchor", "end").style("font-size", "12px").attr("dx", "-.8em").attr("dy", "-.3em").attr("transform", function(d) { + Bar_Chart.prototype.create_graph = function() { + this.add_x_axis(this.x_scale); + this.add_y_axis(); + return this.add_bars(); + }; + + Bar_Chart.prototype.add_x_axis = function(scale) { + var xAxis; + xAxis = d3.svg.axis().scale(scale).orient("bottom"); + return this.svg.append("g").attr("class", "x axis").attr("transform", "translate(0," + this.plot_height + ")").call(xAxis).selectAll("text").style("text-anchor", "end").style("font-size", "12px").attr("dx", "-.8em").attr("dy", "-.3em").attr("transform", (function(_this) { + return function(d) { return "rotate(-90)"; - }); - }; + }; + })(this)); + }; - Bar_Chart.prototype.add_y_axis = function() { - var yAxis; - yAxis = d3.svg.axis().scale(this.y_scale).orient("left").ticks(5); - return this.svg.append("g").attr("class", "y axis").call(yAxis).append("text").attr("transform", "rotate(-90)").attr("y", 6).attr("dy", ".71em").style("text-anchor", "end"); - }; + Bar_Chart.prototype.add_y_axis = function() { + var yAxis; + yAxis = d3.svg.axis().scale(this.y_scale).orient("left").ticks(5); + return this.svg.append("g").attr("class", "y axis").call(yAxis).append("text").attr("transform", "rotate(-90)").attr("y", 6).attr("dy", ".71em").style("text-anchor", "end"); + }; - Bar_Chart.prototype.add_bars = function() { - var _this = this; - return this.svg.selectAll(".bar").data(this.samples).enter().append("rect").style("fill", "steelblue").attr("class", "bar").attr("x", function(d) { + Bar_Chart.prototype.add_bars = function() { + return this.svg.selectAll(".bar").data(this.samples).enter().append("rect").style("fill", "steelblue").attr("class", "bar").attr("x", (function(_this) { + return function(d) { return _this.x_scale(d[0]); - }).attr("width", this.x_scale.rangeBand()).attr("y", function(d) { + }; + })(this)).attr("width", this.x_scale.rangeBand()).attr("y", (function(_this) { + return function(d) { return _this.y_scale(d[1]); - }).attr("height", function(d) { + }; + })(this)).attr("height", (function(_this) { + return function(d) { return _this.plot_height - _this.y_scale(d[1]); - }).append("svg:title").text(function(d) { + }; + })(this)).append("svg:title").text((function(_this) { + return function(d) { return d[1]; - }); - }; + }; + })(this)); + }; - Bar_Chart.prototype.sorted_samples = function() { - var sample_list, sorted, - _this = this; - sample_list = _.zip(this.sample_names, this.sample_vals, this.sample_attr_vals); - sorted = _.sortBy(sample_list, function(sample) { + Bar_Chart.prototype.sorted_samples = function() { + var sample_list, sorted; + sample_list = _.zip(this.sample_names, this.sample_vals, this.sample_attr_vals); + sorted = _.sortBy(sample_list, (function(_this) { + return function(sample) { return sample[1]; - }); - console.log("sorted:", sorted); - return sorted; - }; + }; + })(this)); + console.log("sorted:", sorted); + return sorted; + }; - Bar_Chart.prototype.add_legend = function(attribute, distinct_vals) { - var legend, legend_rect, legend_text, - _this = this; - legend = this.svg.append("g").attr("class", "legend").attr("height", 100).attr("width", 100).attr('transform', 'translate(-20,50)'); - legend_rect = legend.selectAll('rect').data(distinct_vals).enter().append("rect").attr("x", this.plot_width - 65).attr("width", 10).attr("height", 10).attr("y", function(d, i) { + Bar_Chart.prototype.add_legend = function(attribute, distinct_vals) { + var legend, legend_rect, legend_text; + legend = this.svg.append("g").attr("class", "legend").attr("height", 100).attr("width", 100).attr('transform', 'translate(-20,50)'); + legend_rect = legend.selectAll('rect').data(distinct_vals).enter().append("rect").attr("x", this.plot_width - 65).attr("width", 10).attr("height", 10).attr("y", (function(_this) { + return function(d, i) { return i * 20; - }).style("fill", function(d) { + }; + })(this)).style("fill", (function(_this) { + return function(d) { console.log("TEST:", _this.attr_color_dict[attribute][d]); return _this.attr_color_dict[attribute][d]; - }); - return legend_text = legend.selectAll('text').data(distinct_vals).enter().append("text").attr("x", this.plot_width - 52).attr("y", function(d, i) { + }; + })(this)); + return legend_text = legend.selectAll('text').data(distinct_vals).enter().append("text").attr("x", this.plot_width - 52).attr("y", (function(_this) { + return function(d, i) { return i * 20 + 9; - }).text(function(d) { + }; + })(this)).text((function(_this) { + return function(d) { return d; - }); - }; + }; + })(this)); + }; - Bar_Chart.prototype.open_trait_selection = function() { - var _this = this; - return $('#collections_holder').load('/collections/list?color_by_trait #collections_list', function() { + Bar_Chart.prototype.open_trait_selection = function() { + return $('#collections_holder').load('/collections/list?color_by_trait #collections_list', (function(_this) { + return function() { $.colorbox({ inline: true, href: "#collections_holder" }); return $('a.collection_name').attr('onClick', 'return false'); - }); - }; + }; + })(this)); + }; - Bar_Chart.prototype.color_by_trait = function(trait_sample_data) { - var distinct_values, trimmed_samples, - _this = this; - console.log("BXD1:", trait_sample_data["BXD1"]); - console.log("trait_sample_data:", trait_sample_data); - trimmed_samples = this.trim_values(trait_sample_data); - distinct_values = {}; - distinct_values["collection_trait"] = this.get_distinct_values(trimmed_samples); - this.get_trait_color_dict(trimmed_samples, distinct_values); - console.log("TRAIT_COLOR_DICT:", this.trait_color_dict); - console.log("SAMPLES:", this.samples); - if (this.sort_by = "value") { - return this.svg.selectAll(".bar").data(this.samples).transition().duration(1000).style("fill", function(d) { + Bar_Chart.prototype.color_by_trait = function(trait_sample_data) { + var distinct_values, trimmed_samples; + console.log("BXD1:", trait_sample_data["BXD1"]); + console.log("trait_sample_data:", trait_sample_data); + trimmed_samples = this.trim_values(trait_sample_data); + distinct_values = {}; + distinct_values["collection_trait"] = this.get_distinct_values(trimmed_samples); + this.get_trait_color_dict(trimmed_samples, distinct_values); + console.log("TRAIT_COLOR_DICT:", this.trait_color_dict); + console.log("SAMPLES:", this.samples); + if (this.sort_by = "value") { + return this.svg.selectAll(".bar").data(this.samples).transition().duration(1000).style("fill", (function(_this) { + return function(d) { console.log("this color:", _this.trait_color_dict[d[0]]); return _this.trait_color_dict[d[0]]; - }).select("title").text(function(d) { + }; + })(this)).select("title").text((function(_this) { + return function(d) { return d[1]; - }); - } else { - return this.svg.selectAll(".bar").data(this.sorted_samples()).transition().duration(1000).style("fill", function(d) { + }; + })(this)); + } else { + return this.svg.selectAll(".bar").data(this.sorted_samples()).transition().duration(1000).style("fill", (function(_this) { + return function(d) { console.log("this color:", _this.trait_color_dict[d[0]]); return _this.trait_color_dict[d[0]]; - }).select("title").text(function(d) { + }; + })(this)).select("title").text((function(_this) { + return function(d) { return d[1]; - }); - } - }; + }; + })(this)); + } + }; - Bar_Chart.prototype.trim_values = function(trait_sample_data) { - var sample, trimmed_samples, _i, _len, _ref; - trimmed_samples = {}; - _ref = this.sample_names; - for (_i = 0, _len = _ref.length; _i < _len; _i++) { - sample = _ref[_i]; - if (sample in trait_sample_data) { - trimmed_samples[sample] = trait_sample_data[sample]; - } + Bar_Chart.prototype.trim_values = function(trait_sample_data) { + var sample, trimmed_samples, _i, _len, _ref; + trimmed_samples = {}; + _ref = this.sample_names; + for (_i = 0, _len = _ref.length; _i < _len; _i++) { + sample = _ref[_i]; + if (sample in trait_sample_data) { + trimmed_samples[sample] = trait_sample_data[sample]; } - console.log("trimmed_samples:", trimmed_samples); - return trimmed_samples; - }; - - Bar_Chart.prototype.get_distinct_values = function(samples) { - var distinct_values; - distinct_values = _.uniq(_.values(samples)); - console.log("distinct_values:", distinct_values); - return distinct_values; - }; + } + console.log("trimmed_samples:", trimmed_samples); + return trimmed_samples; + }; - return Bar_Chart; + Bar_Chart.prototype.get_distinct_values = function(samples) { + var distinct_values; + distinct_values = _.uniq(_.values(samples)); + console.log("distinct_values:", distinct_values); + return distinct_values; + }; - })(); + return Bar_Chart; - root.Bar_Chart = Bar_Chart; +})(); -}).call(this); +root.Bar_Chart = Bar_Chart; diff --git a/wqflask/wqflask/static/new/javascript/box_plot.js b/wqflask/wqflask/static/new/javascript/box_plot.js index 736df9c9..4b80956f 100755 --- a/wqflask/wqflask/static/new/javascript/box_plot.js +++ b/wqflask/wqflask/static/new/javascript/box_plot.js @@ -1,57 +1,55 @@ -// Generated by CoffeeScript 1.6.1 -(function() { - var Box_Plot, root; +// Generated by CoffeeScript 1.7.1 +var Box_Plot, root; - root = typeof exports !== "undefined" && exports !== null ? exports : this; +root = typeof exports !== "undefined" && exports !== null ? exports : this; - Box_Plot = (function() { - - function Box_Plot(sample_list, sample_group) { - this.sample_list = sample_list; - this.sample_group = sample_group; - this.get_samples(); - this.margin = { - top: 10, - right: 50, - bottom: 20, - left: 50 - }; - this.plot_width = 200 - this.margin.left - this.margin.right; - this.plot_height = 500 - this.margin.top - this.margin.bottom; - this.min = d3.min(this.sample_vals); - this.max = d3.max(this.sample_vals); - this.svg = this.create_svg(); - this.enter_data(); - } +Box_Plot = (function() { + function Box_Plot(sample_list, sample_group) { + this.sample_list = sample_list; + this.sample_group = sample_group; + this.get_samples(); + this.margin = { + top: 10, + right: 50, + bottom: 20, + left: 50 + }; + this.plot_width = 200 - this.margin.left - this.margin.right; + this.plot_height = 500 - this.margin.top - this.margin.bottom; + this.min = d3.min(this.sample_vals); + this.max = d3.max(this.sample_vals); + this.svg = this.create_svg(); + this.enter_data(); + } - Box_Plot.prototype.get_samples = function() { - var sample; - return this.sample_vals = (function() { - var _i, _len, _ref, _results; - _ref = this.sample_list; - _results = []; - for (_i = 0, _len = _ref.length; _i < _len; _i++) { - sample = _ref[_i]; - if (sample.value !== null) { - _results.push(sample.value); - } + Box_Plot.prototype.get_samples = function() { + var sample; + return this.sample_vals = (function() { + var _i, _len, _ref, _results; + _ref = this.sample_list; + _results = []; + for (_i = 0, _len = _ref.length; _i < _len; _i++) { + sample = _ref[_i]; + if (sample.value !== null) { + _results.push(sample.value); } - return _results; - }).call(this); - }; + } + return _results; + }).call(this); + }; - Box_Plot.prototype.create_svg = function() { - var svg; - svg = d3.box().whiskers(this.inter_quartile_range(1.5)).width(this.plot_width - 30).height(this.plot_height - 30).domain([this.min, this.max]); - return svg; - }; + Box_Plot.prototype.create_svg = function() { + var svg; + svg = d3.box().whiskers(this.inter_quartile_range(1.5)).width(this.plot_width - 30).height(this.plot_height - 30).domain([this.min, this.max]); + return svg; + }; - Box_Plot.prototype.enter_data = function() { - return d3.select("#box_plot").selectAll("svg").data([this.sample_vals]).enter().append("svg:svg").attr("class", "box").attr("width", this.plot_width).attr("height", this.plot_height).append("svg:g").call(this.svg); - }; + Box_Plot.prototype.enter_data = function() { + return d3.select("#box_plot").selectAll("svg").data([this.sample_vals]).enter().append("svg:svg").attr("class", "box").attr("width", this.plot_width).attr("height", this.plot_height).append("svg:g").call(this.svg); + }; - Box_Plot.prototype.inter_quartile_range = function(k) { - var _this = this; + Box_Plot.prototype.inter_quartile_range = function(k) { + return (function(_this) { return function(d, i) { var inter_quartile_range, j, q1, q3; console.log("iqr d:", d); @@ -72,12 +70,11 @@ console.log("[i, j]", [i, j]); return [i, j]; }; - }; - - return Box_Plot; + })(this); + }; - })(); + return Box_Plot; - root.Box_Plot = Box_Plot; +})(); -}).call(this); +root.Box_Plot = Box_Plot; diff --git a/wqflask/wqflask/static/new/javascript/chr_interval_map.coffee b/wqflask/wqflask/static/new/javascript/chr_interval_map.coffee new file mode 100644 index 00000000..62ce4d3d --- /dev/null +++ b/wqflask/wqflask/static/new/javascript/chr_interval_map.coffee @@ -0,0 +1,293 @@ +class Chr_Interval_Map + constructor: (@plot_height, @plot_width, @chr) -> + @qtl_results = js_data.qtl_results + console.log("qtl_results are:", @qtl_results) + console.log("chr is:", @chr) + + @get_max_chr() + + @filter_qtl_results() + console.log("filtered results:", @these_results) + @get_qtl_count() + + @x_coords = [] + @y_coords = [] + @marker_names = [] + + console.time('Create coordinates') + @create_coordinates() + console.log("@x_coords: ", @x_coords) + console.log("@y_coords: ", @y_coords) + console.timeEnd('Create coordinates') + + # Buffer to allow for the ticks/labels to be drawn + @x_buffer = @plot_width/30 + @y_buffer = @plot_height/20 + + @x_max = d3.max(@x_coords) + @y_max = d3.max(@y_coords) * 1.2 + + @y_threshold = @get_lod_threshold() + + @svg = @create_svg() + + @plot_coordinates = _.zip(@x_coords, @y_coords, @marker_names) + console.log("coordinates:", @plot_coordinates) + + @plot_height -= @y_buffer + + @create_scales() + + console.time('Create graph') + @create_graph() + console.timeEnd('Create graph') + + get_max_chr: () -> + @max_chr = 0 + for key of js_data.chromosomes + console.log("key is:", key) + if parseInt(key) > @max_chr + @max_chr = parseInt(key) + + filter_qtl_results: () -> + @these_results = [] + this_chr = 100 + for result in @qtl_results + if result.chr == "X" + this_chr = @max_chr + else + this_chr = result.chr + console.log("this_chr is:", this_chr) + console.log("@chr[0] is:", parseInt(@chr[0])) + if this_chr > parseInt(@chr[0]) + break + if parseInt(this_chr) == parseInt(@chr[0]) + @these_results.push(result) + + get_qtl_count: () -> + high_qtl_count = 0 + for result in @these_results + if result.lrs_value > 1 + high_qtl_count += 1 + console.log("high_qtl_count:", high_qtl_count) + + #if high_qtl_count > 10000 + @y_axis_filter = 2 + #else if high_qtl_count > 1000 + # @y_axis_filter = 1 + #else + # @y_axis_filter = 0 + + create_coordinates: () -> + for result in @these_results + @x_coords.push(parseFloat(result.Mb)) + @y_coords.push(result.lrs_value) + @marker_names.push(result.name) + + create_svg: () -> + svg = d3.select("#topchart") + .append("svg") + .attr("class", "chr_interval_map") + .attr("width", @plot_width+@x_buffer) + .attr("height", @plot_height+@y_buffer) + .append("g") + return svg + + create_scales: () -> + console.log("chr[1] is:", @chr[1]) + @x_scale = d3.scale.linear() + .domain([0, @chr[1]]) + .range([@x_buffer, @plot_width]) + @y_scale = d3.scale.linear() + .domain([0, @y_max]) + .range([@plot_height, @y_buffer]) + + get_lod_threshold: () -> + if @y_max/2 > 2 + return @y_max/2 + else + return 2 + + create_graph: () -> + @add_border() + @add_x_axis() + @add_y_axis() + @add_title() + @add_back_button() + @add_path() + + add_border: () -> + border_coords = [[@y_buffer, @plot_height, @x_buffer, @x_buffer], + [@y_buffer, @plot_height, @plot_width, @plot_width], + [@y_buffer, @y_buffer, @x_buffer, @plot_width], + [@plot_height, @plot_height, @x_buffer, @plot_width]] + + @svg.selectAll("line") + .data(border_coords) + .enter() + .append("line") + .attr("y1", (d) => + return d[0] + ) + .attr("y2", (d) => + return d[1] + ) + .attr("x1", (d) => + return d[2] + ) + .attr("x2", (d) => + return d[3] + ) + .style("stroke", "#000") + + add_x_axis: () -> + @xAxis = d3.svg.axis() + .scale(@x_scale) + .orient("bottom") + .ticks(20) + + @xAxis.tickFormat((d) => + d3.format("d") #format as integer + return (d) + ) + + @svg.append("g") + .attr("class", "x_axis") + .attr("transform", "translate(0," + @plot_height + ")") + .call(@xAxis) + .selectAll("text") + .attr("text-anchor", "right") + .attr("font-size", "12px") + .attr("dx", "-1.6em") + .attr("transform", (d) => + return "translate(-12,0) rotate(-90)" + ) + + add_y_axis: () -> + @yAxis = d3.svg.axis() + .scale(@y_scale) + .orient("left") + .ticks(5) + + @svg.append("g") + .attr("class", "y_axis") + .attr("transform", "translate(" + @x_buffer + ",0)") + .call(@yAxis) + + add_title: () -> + @svg.append("text") + .attr("class", "title") + .text("Chr " + @chr[0]) + .attr("x", (d) => + return (@plot_width + @x_buffer)/2 + ) + .attr("y", @y_buffer + 20) + .attr("dx", "0em") + .attr("text-anchor", "middle") + .attr("font-family", "sans-serif") + .attr("font-size", "18px") + .attr("fill", "black") + + add_back_button: () -> + @svg.append("text") + .attr("class", "back") + .text("Return to full view") + .attr("x", @x_buffer*2) + .attr("y", @y_buffer/2) + .attr("dx", "0em") + .attr("text-anchor", "middle") + .attr("font-family", "sans-serif") + .attr("font-size", "18px") + .attr("cursor", "pointer") + .attr("fill", "black") + .on("click", @return_to_full_view) + + add_path: () -> + line_function = d3.svg.line() + .x( (d) => return @x_scale(d[0])) + .y( (d) => return @y_scale(d[1])) + .interpolate("linear") + + line_graph = @svg.append("path") + .attr("d", line_function(@plot_coordinates)) + .attr("stroke", "blue") + .attr("stroke-width", 1) + .attr("fill", "none") + + + #add_plot_points: () -> + # @plot_point = @svg.selectAll("circle") + # .data(@plot_coordinates) + # .enter() + # .append("circle") + # .attr("cx", (d) => + # return @x_scale(d[0]) + # ) + # .attr("cy", (d) => + # return @y_scale(d[1]) + # ) + # .attr("r", (d) => + # #if d[1] > 2 + # # return 3 + # #else + # return 2 + # ) + # .attr("fill", (d) => + # #if d[1] > 2 + # # return "white" + # #else + # return "black" + # ) + # .attr("stroke", "black") + # .attr("stroke-width", "1") + # .attr("id", (d) => + # return "point_" + String(d[2]) + # ) + # .classed("circle", true) + # .on("mouseover", (d) => + # console.log("d3.event is:", d3.event) + # console.log("d is:", d) + # this_id = "point_" + String(d[2]) + # d3.select("#" + this_id).classed("d3_highlight", true) + # .attr("r", 5) + # .attr("stroke", "none") + # .attr("fill", "blue") + # .call(@show_marker_in_table(d)) + # ) + # .on("mouseout", (d) => + # this_id = "point_" + String(d[2]) + # d3.select("#" + this_id).classed("d3_highlight", false) + # .attr("r", (d) => + # #if d[1] > 2 + # # return 3 + # #else + # return 2 + # ) + # .attr("fill", (d) => + # #if d[1] > 2 + # # return "white" + # #else + # return "black" + # ) + # .attr("stroke", "black") + # .attr("stroke-width", "1") + # ) + # .append("svg:title") + # .text((d) => + # return d[2] + # ) + + return_to_full_view: () -> + $('#topchart').remove() + $('#chart_container').append('
') + create_interval_map() + + show_marker_in_table: (marker_info) -> + console.log("in show_marker_in_table") + ### Searches for the select marker in the results table below ### + if marker_info + marker_name = marker_info[2] + $("#qtl_results_filter").find("input:first").val(marker_name).change() + #else + # marker_name = "" + #$("#qtl_results_filter").find("input:first").val(marker_name).change() diff --git a/wqflask/wqflask/static/new/javascript/chr_interval_map.js b/wqflask/wqflask/static/new/javascript/chr_interval_map.js new file mode 100644 index 00000000..a4752a12 --- /dev/null +++ b/wqflask/wqflask/static/new/javascript/chr_interval_map.js @@ -0,0 +1,224 @@ +// Generated by CoffeeScript 1.7.1 +var Chr_Interval_Map; + +Chr_Interval_Map = (function() { + function Chr_Interval_Map(plot_height, plot_width, chr) { + this.plot_height = plot_height; + this.plot_width = plot_width; + this.chr = chr; + this.qtl_results = js_data.qtl_results; + console.log("qtl_results are:", this.qtl_results); + console.log("chr is:", this.chr); + this.get_max_chr(); + this.filter_qtl_results(); + console.log("filtered results:", this.these_results); + this.get_qtl_count(); + this.x_coords = []; + this.y_coords = []; + this.marker_names = []; + console.time('Create coordinates'); + this.create_coordinates(); + console.log("@x_coords: ", this.x_coords); + console.log("@y_coords: ", this.y_coords); + console.timeEnd('Create coordinates'); + this.x_buffer = this.plot_width / 30; + this.y_buffer = this.plot_height / 20; + this.x_max = d3.max(this.x_coords); + this.y_max = d3.max(this.y_coords) * 1.2; + this.y_threshold = this.get_lod_threshold(); + this.svg = this.create_svg(); + this.plot_coordinates = _.zip(this.x_coords, this.y_coords, this.marker_names); + console.log("coordinates:", this.plot_coordinates); + this.plot_height -= this.y_buffer; + this.create_scales(); + console.time('Create graph'); + this.create_graph(); + console.timeEnd('Create graph'); + } + + Chr_Interval_Map.prototype.get_max_chr = function() { + var key, _results; + this.max_chr = 0; + _results = []; + for (key in js_data.chromosomes) { + console.log("key is:", key); + if (parseInt(key) > this.max_chr) { + _results.push(this.max_chr = parseInt(key)); + } else { + _results.push(void 0); + } + } + return _results; + }; + + Chr_Interval_Map.prototype.filter_qtl_results = function() { + var result, this_chr, _i, _len, _ref, _results; + this.these_results = []; + this_chr = 100; + _ref = this.qtl_results; + _results = []; + for (_i = 0, _len = _ref.length; _i < _len; _i++) { + result = _ref[_i]; + if (result.chr === "X") { + this_chr = this.max_chr; + } else { + this_chr = result.chr; + } + console.log("this_chr is:", this_chr); + console.log("@chr[0] is:", parseInt(this.chr[0])); + if (this_chr > parseInt(this.chr[0])) { + break; + } + if (parseInt(this_chr) === parseInt(this.chr[0])) { + _results.push(this.these_results.push(result)); + } else { + _results.push(void 0); + } + } + return _results; + }; + + Chr_Interval_Map.prototype.get_qtl_count = function() { + var high_qtl_count, result, _i, _len, _ref; + high_qtl_count = 0; + _ref = this.these_results; + for (_i = 0, _len = _ref.length; _i < _len; _i++) { + result = _ref[_i]; + if (result.lrs_value > 1) { + high_qtl_count += 1; + } + } + console.log("high_qtl_count:", high_qtl_count); + return this.y_axis_filter = 2; + }; + + Chr_Interval_Map.prototype.create_coordinates = function() { + var result, _i, _len, _ref, _results; + _ref = this.these_results; + _results = []; + for (_i = 0, _len = _ref.length; _i < _len; _i++) { + result = _ref[_i]; + this.x_coords.push(parseFloat(result.Mb)); + this.y_coords.push(result.lrs_value); + _results.push(this.marker_names.push(result.name)); + } + return _results; + }; + + Chr_Interval_Map.prototype.create_svg = function() { + var svg; + svg = d3.select("#topchart").append("svg").attr("class", "chr_interval_map").attr("width", this.plot_width + this.x_buffer).attr("height", this.plot_height + this.y_buffer).append("g"); + return svg; + }; + + Chr_Interval_Map.prototype.create_scales = function() { + console.log("chr[1] is:", this.chr[1]); + this.x_scale = d3.scale.linear().domain([0, this.chr[1]]).range([this.x_buffer, this.plot_width]); + return this.y_scale = d3.scale.linear().domain([0, this.y_max]).range([this.plot_height, this.y_buffer]); + }; + + Chr_Interval_Map.prototype.get_lod_threshold = function() { + if (this.y_max / 2 > 2) { + return this.y_max / 2; + } else { + return 2; + } + }; + + Chr_Interval_Map.prototype.create_graph = function() { + this.add_border(); + this.add_x_axis(); + this.add_y_axis(); + this.add_title(); + this.add_back_button(); + return this.add_path(); + }; + + Chr_Interval_Map.prototype.add_border = function() { + var border_coords; + border_coords = [[this.y_buffer, this.plot_height, this.x_buffer, this.x_buffer], [this.y_buffer, this.plot_height, this.plot_width, this.plot_width], [this.y_buffer, this.y_buffer, this.x_buffer, this.plot_width], [this.plot_height, this.plot_height, this.x_buffer, this.plot_width]]; + return this.svg.selectAll("line").data(border_coords).enter().append("line").attr("y1", (function(_this) { + return function(d) { + return d[0]; + }; + })(this)).attr("y2", (function(_this) { + return function(d) { + return d[1]; + }; + })(this)).attr("x1", (function(_this) { + return function(d) { + return d[2]; + }; + })(this)).attr("x2", (function(_this) { + return function(d) { + return d[3]; + }; + })(this)).style("stroke", "#000"); + }; + + Chr_Interval_Map.prototype.add_x_axis = function() { + this.xAxis = d3.svg.axis().scale(this.x_scale).orient("bottom").ticks(20); + this.xAxis.tickFormat((function(_this) { + return function(d) { + d3.format("d"); + return d; + }; + })(this)); + return this.svg.append("g").attr("class", "x_axis").attr("transform", "translate(0," + this.plot_height + ")").call(this.xAxis).selectAll("text").attr("text-anchor", "right").attr("font-size", "12px").attr("dx", "-1.6em").attr("transform", (function(_this) { + return function(d) { + return "translate(-12,0) rotate(-90)"; + }; + })(this)); + }; + + Chr_Interval_Map.prototype.add_y_axis = function() { + this.yAxis = d3.svg.axis().scale(this.y_scale).orient("left").ticks(5); + return this.svg.append("g").attr("class", "y_axis").attr("transform", "translate(" + this.x_buffer + ",0)").call(this.yAxis); + }; + + Chr_Interval_Map.prototype.add_title = function() { + return this.svg.append("text").attr("class", "title").text("Chr " + this.chr[0]).attr("x", (function(_this) { + return function(d) { + return (_this.plot_width + _this.x_buffer) / 2; + }; + })(this)).attr("y", this.y_buffer + 20).attr("dx", "0em").attr("text-anchor", "middle").attr("font-family", "sans-serif").attr("font-size", "18px").attr("fill", "black"); + }; + + Chr_Interval_Map.prototype.add_back_button = function() { + return this.svg.append("text").attr("class", "back").text("Return to full view").attr("x", this.x_buffer * 2).attr("y", this.y_buffer / 2).attr("dx", "0em").attr("text-anchor", "middle").attr("font-family", "sans-serif").attr("font-size", "18px").attr("cursor", "pointer").attr("fill", "black").on("click", this.return_to_full_view); + }; + + Chr_Interval_Map.prototype.add_path = function() { + var line_function, line_graph; + line_function = d3.svg.line().x((function(_this) { + return function(d) { + return _this.x_scale(d[0]); + }; + })(this)).y((function(_this) { + return function(d) { + return _this.y_scale(d[1]); + }; + })(this)).interpolate("linear"); + return line_graph = this.svg.append("path").attr("d", line_function(this.plot_coordinates)).attr("stroke", "blue").attr("stroke-width", 1).attr("fill", "none"); + }; + + Chr_Interval_Map.prototype.return_to_full_view = function() { + $('#topchart').remove(); + $('#chart_container').append('
'); + return create_interval_map(); + }; + + Chr_Interval_Map.prototype.show_marker_in_table = function(marker_info) { + var marker_name; + console.log("in show_marker_in_table"); + + /* Searches for the select marker in the results table below */ + if (marker_info) { + marker_name = marker_info[2]; + return $("#qtl_results_filter").find("input:first").val(marker_name).change(); + } + }; + + return Chr_Interval_Map; + +})(); diff --git a/wqflask/wqflask/static/new/javascript/chr_manhattan_plot.coffee b/wqflask/wqflask/static/new/javascript/chr_manhattan_plot.coffee index 8b27caa1..8b62d58a 100755 --- a/wqflask/wqflask/static/new/javascript/chr_manhattan_plot.coffee +++ b/wqflask/wqflask/static/new/javascript/chr_manhattan_plot.coffee @@ -1,5 +1,3 @@ -root = exports ? this - class Chr_Manhattan_Plot constructor: (@plot_height, @plot_width, @chr) -> @qtl_results = js_data.qtl_results @@ -87,9 +85,9 @@ class Chr_Manhattan_Plot @marker_names.push(result.name) create_svg: () -> - svg = d3.select("#manhattan_plot") + svg = d3.select("#topchart") .append("svg") - .attr("class", "manhattan_plot") + .attr("class", "chr_manhattan_plot") .attr("width", @plot_width+@x_buffer) .attr("height", @plot_height+@y_buffer) .append("g") @@ -100,7 +98,7 @@ class Chr_Manhattan_Plot .domain([0, @chr[1]]) .range([@x_buffer, @plot_width]) @y_scale = d3.scale.linear() - .domain([@y_axis_filter, @y_max]) + .domain([0, @y_max]) .range([@plot_height, @y_buffer]) get_lod_threshold: () -> @@ -203,6 +201,7 @@ class Chr_Manhattan_Plot .attr("fill", "black") .on("click", @return_to_full_view) + add_plot_points: () -> @plot_point = @svg.selectAll("circle") .data(@plot_coordinates) @@ -266,9 +265,9 @@ class Chr_Manhattan_Plot ) return_to_full_view: () -> - $('#manhattan_plot').remove() - $('#manhattan_plot_container').append('
') - root.manhattan_plot = new root.Manhattan_Plot + $('#topchart').remove() + $('#chart_container').append('
') + create_manhattan_plot() show_marker_in_table: (marker_info) -> console.log("in show_marker_in_table") @@ -279,5 +278,3 @@ class Chr_Manhattan_Plot #else # marker_name = "" #$("#qtl_results_filter").find("input:first").val(marker_name).change() - -root.Chr_Manhattan_Plot = Chr_Manhattan_Plot \ No newline at end of file diff --git a/wqflask/wqflask/static/new/javascript/chr_manhattan_plot.js b/wqflask/wqflask/static/new/javascript/chr_manhattan_plot.js index b7f64094..24d8b962 100755 --- a/wqflask/wqflask/static/new/javascript/chr_manhattan_plot.js +++ b/wqflask/wqflask/static/new/javascript/chr_manhattan_plot.js @@ -1,204 +1,223 @@ -// Generated by CoffeeScript 1.6.1 -(function() { - var Chr_Manhattan_Plot, root; - - root = typeof exports !== "undefined" && exports !== null ? exports : this; - - Chr_Manhattan_Plot = (function() { - - function Chr_Manhattan_Plot(plot_height, plot_width, chr) { - this.plot_height = plot_height; - this.plot_width = plot_width; - this.chr = chr; - this.qtl_results = js_data.qtl_results; - console.log("qtl_results are:", this.qtl_results); - console.log("chr is:", this.chr); - this.get_max_chr(); - this.filter_qtl_results(); - console.log("filtered results:", this.these_results); - this.get_qtl_count(); - this.x_coords = []; - this.y_coords = []; - this.marker_names = []; - console.time('Create coordinates'); - this.create_coordinates(); - console.log("@x_coords: ", this.x_coords); - console.log("@y_coords: ", this.y_coords); - console.timeEnd('Create coordinates'); - this.x_buffer = this.plot_width / 30; - this.y_buffer = this.plot_height / 20; - this.x_max = d3.max(this.x_coords); - this.y_max = d3.max(this.y_coords) * 1.2; - this.y_threshold = this.get_lod_threshold(); - this.svg = this.create_svg(); - this.plot_coordinates = _.zip(this.x_coords, this.y_coords, this.marker_names); - console.log("coordinates:", this.plot_coordinates); - this.plot_height -= this.y_buffer; - this.create_scales(); - console.time('Create graph'); - this.create_graph(); - console.timeEnd('Create graph'); - } - - Chr_Manhattan_Plot.prototype.get_max_chr = function() { - var key, _results; - this.max_chr = 0; - _results = []; - for (key in js_data.chromosomes) { - console.log("key is:", key); - if (parseInt(key) > this.max_chr) { - _results.push(this.max_chr = parseInt(key)); - } else { - _results.push(void 0); - } - } - return _results; - }; - - Chr_Manhattan_Plot.prototype.filter_qtl_results = function() { - var result, this_chr, _i, _len, _ref, _results; - this.these_results = []; - this_chr = 100; - _ref = this.qtl_results; - _results = []; - for (_i = 0, _len = _ref.length; _i < _len; _i++) { - result = _ref[_i]; - if (result.chr === "X") { - this_chr = this.max_chr; - } else { - this_chr = result.chr; - } - console.log("this_chr is:", this_chr); - console.log("@chr[0] is:", parseInt(this.chr[0])); - if (this_chr > parseInt(this.chr[0])) { - break; - } - if (parseInt(this_chr) === parseInt(this.chr[0])) { - _results.push(this.these_results.push(result)); - } else { - _results.push(void 0); - } +// Generated by CoffeeScript 1.7.1 +var Chr_Manhattan_Plot; + +Chr_Manhattan_Plot = (function() { + function Chr_Manhattan_Plot(plot_height, plot_width, chr) { + this.plot_height = plot_height; + this.plot_width = plot_width; + this.chr = chr; + this.qtl_results = js_data.qtl_results; + console.log("qtl_results are:", this.qtl_results); + console.log("chr is:", this.chr); + this.get_max_chr(); + this.filter_qtl_results(); + console.log("filtered results:", this.these_results); + this.get_qtl_count(); + this.x_coords = []; + this.y_coords = []; + this.marker_names = []; + console.time('Create coordinates'); + this.create_coordinates(); + console.log("@x_coords: ", this.x_coords); + console.log("@y_coords: ", this.y_coords); + console.timeEnd('Create coordinates'); + this.x_buffer = this.plot_width / 30; + this.y_buffer = this.plot_height / 20; + this.x_max = d3.max(this.x_coords); + this.y_max = d3.max(this.y_coords) * 1.2; + this.y_threshold = this.get_lod_threshold(); + this.svg = this.create_svg(); + this.plot_coordinates = _.zip(this.x_coords, this.y_coords, this.marker_names); + console.log("coordinates:", this.plot_coordinates); + this.plot_height -= this.y_buffer; + this.create_scales(); + console.time('Create graph'); + this.create_graph(); + console.timeEnd('Create graph'); + } + + Chr_Manhattan_Plot.prototype.get_max_chr = function() { + var key, _results; + this.max_chr = 0; + _results = []; + for (key in js_data.chromosomes) { + console.log("key is:", key); + if (parseInt(key) > this.max_chr) { + _results.push(this.max_chr = parseInt(key)); + } else { + _results.push(void 0); } - return _results; - }; - - Chr_Manhattan_Plot.prototype.get_qtl_count = function() { - var high_qtl_count, result, _i, _len, _ref; - high_qtl_count = 0; - _ref = this.these_results; - for (_i = 0, _len = _ref.length; _i < _len; _i++) { - result = _ref[_i]; - if (result.lod_score > 1) { - high_qtl_count += 1; - } + } + return _results; + }; + + Chr_Manhattan_Plot.prototype.filter_qtl_results = function() { + var result, this_chr, _i, _len, _ref, _results; + this.these_results = []; + this_chr = 100; + _ref = this.qtl_results; + _results = []; + for (_i = 0, _len = _ref.length; _i < _len; _i++) { + result = _ref[_i]; + if (result.chr === "X") { + this_chr = this.max_chr; + } else { + this_chr = result.chr; } - console.log("high_qtl_count:", high_qtl_count); - return this.y_axis_filter = 2; - }; - - Chr_Manhattan_Plot.prototype.create_coordinates = function() { - var result, _i, _len, _ref, _results; - _ref = this.these_results; - _results = []; - for (_i = 0, _len = _ref.length; _i < _len; _i++) { - result = _ref[_i]; - this.x_coords.push(parseFloat(result.Mb)); - this.y_coords.push(result.lod_score); - _results.push(this.marker_names.push(result.name)); + console.log("this_chr is:", this_chr); + console.log("@chr[0] is:", parseInt(this.chr[0])); + if (this_chr > parseInt(this.chr[0])) { + break; } - return _results; - }; - - Chr_Manhattan_Plot.prototype.create_svg = function() { - var svg; - svg = d3.select("#manhattan_plot").append("svg").attr("class", "manhattan_plot").attr("width", this.plot_width + this.x_buffer).attr("height", this.plot_height + this.y_buffer).append("g"); - return svg; - }; - - Chr_Manhattan_Plot.prototype.create_scales = function() { - this.x_scale = d3.scale.linear().domain([0, this.chr[1]]).range([this.x_buffer, this.plot_width]); - return this.y_scale = d3.scale.linear().domain([this.y_axis_filter, this.y_max]).range([this.plot_height, this.y_buffer]); - }; - - Chr_Manhattan_Plot.prototype.get_lod_threshold = function() { - if (this.y_max / 2 > 2) { - return this.y_max / 2; + if (parseInt(this_chr) === parseInt(this.chr[0])) { + _results.push(this.these_results.push(result)); } else { - return 2; + _results.push(void 0); } - }; - - Chr_Manhattan_Plot.prototype.create_graph = function() { - this.add_border(); - this.add_x_axis(); - this.add_y_axis(); - this.add_title(); - this.add_back_button(); - return this.add_plot_points(); - }; - - Chr_Manhattan_Plot.prototype.add_border = function() { - var border_coords, - _this = this; - border_coords = [[this.y_buffer, this.plot_height, this.x_buffer, this.x_buffer], [this.y_buffer, this.plot_height, this.plot_width, this.plot_width], [this.y_buffer, this.y_buffer, this.x_buffer, this.plot_width], [this.plot_height, this.plot_height, this.x_buffer, this.plot_width]]; - return this.svg.selectAll("line").data(border_coords).enter().append("line").attr("y1", function(d) { + } + return _results; + }; + + Chr_Manhattan_Plot.prototype.get_qtl_count = function() { + var high_qtl_count, result, _i, _len, _ref; + high_qtl_count = 0; + _ref = this.these_results; + for (_i = 0, _len = _ref.length; _i < _len; _i++) { + result = _ref[_i]; + if (result.lod_score > 1) { + high_qtl_count += 1; + } + } + console.log("high_qtl_count:", high_qtl_count); + return this.y_axis_filter = 2; + }; + + Chr_Manhattan_Plot.prototype.create_coordinates = function() { + var result, _i, _len, _ref, _results; + _ref = this.these_results; + _results = []; + for (_i = 0, _len = _ref.length; _i < _len; _i++) { + result = _ref[_i]; + this.x_coords.push(parseFloat(result.Mb)); + this.y_coords.push(result.lod_score); + _results.push(this.marker_names.push(result.name)); + } + return _results; + }; + + Chr_Manhattan_Plot.prototype.create_svg = function() { + var svg; + svg = d3.select("#topchart").append("svg").attr("class", "chr_manhattan_plot").attr("width", this.plot_width + this.x_buffer).attr("height", this.plot_height + this.y_buffer).append("g"); + return svg; + }; + + Chr_Manhattan_Plot.prototype.create_scales = function() { + this.x_scale = d3.scale.linear().domain([0, this.chr[1]]).range([this.x_buffer, this.plot_width]); + return this.y_scale = d3.scale.linear().domain([0, this.y_max]).range([this.plot_height, this.y_buffer]); + }; + + Chr_Manhattan_Plot.prototype.get_lod_threshold = function() { + if (this.y_max / 2 > 2) { + return this.y_max / 2; + } else { + return 2; + } + }; + + Chr_Manhattan_Plot.prototype.create_graph = function() { + this.add_border(); + this.add_x_axis(); + this.add_y_axis(); + this.add_title(); + this.add_back_button(); + return this.add_plot_points(); + }; + + Chr_Manhattan_Plot.prototype.add_border = function() { + var border_coords; + border_coords = [[this.y_buffer, this.plot_height, this.x_buffer, this.x_buffer], [this.y_buffer, this.plot_height, this.plot_width, this.plot_width], [this.y_buffer, this.y_buffer, this.x_buffer, this.plot_width], [this.plot_height, this.plot_height, this.x_buffer, this.plot_width]]; + return this.svg.selectAll("line").data(border_coords).enter().append("line").attr("y1", (function(_this) { + return function(d) { return d[0]; - }).attr("y2", function(d) { + }; + })(this)).attr("y2", (function(_this) { + return function(d) { return d[1]; - }).attr("x1", function(d) { + }; + })(this)).attr("x1", (function(_this) { + return function(d) { return d[2]; - }).attr("x2", function(d) { + }; + })(this)).attr("x2", (function(_this) { + return function(d) { return d[3]; - }).style("stroke", "#000"); - }; - - Chr_Manhattan_Plot.prototype.add_x_axis = function() { - var _this = this; - this.xAxis = d3.svg.axis().scale(this.x_scale).orient("bottom").ticks(20); - this.xAxis.tickFormat(function(d) { + }; + })(this)).style("stroke", "#000"); + }; + + Chr_Manhattan_Plot.prototype.add_x_axis = function() { + this.xAxis = d3.svg.axis().scale(this.x_scale).orient("bottom").ticks(20); + this.xAxis.tickFormat((function(_this) { + return function(d) { d3.format("d"); return d; - }); - return this.svg.append("g").attr("class", "x_axis").attr("transform", "translate(0," + this.plot_height + ")").call(this.xAxis).selectAll("text").attr("text-anchor", "right").attr("font-size", "12px").attr("dx", "-1.6em").attr("transform", function(d) { + }; + })(this)); + return this.svg.append("g").attr("class", "x_axis").attr("transform", "translate(0," + this.plot_height + ")").call(this.xAxis).selectAll("text").attr("text-anchor", "right").attr("font-size", "12px").attr("dx", "-1.6em").attr("transform", (function(_this) { + return function(d) { return "translate(-12,0) rotate(-90)"; - }); - }; - - Chr_Manhattan_Plot.prototype.add_y_axis = function() { - this.yAxis = d3.svg.axis().scale(this.y_scale).orient("left").ticks(5); - return this.svg.append("g").attr("class", "y_axis").attr("transform", "translate(" + this.x_buffer + ",0)").call(this.yAxis); - }; - - Chr_Manhattan_Plot.prototype.add_title = function() { - var _this = this; - return this.svg.append("text").attr("class", "title").text("Chr " + this.chr[0]).attr("x", function(d) { + }; + })(this)); + }; + + Chr_Manhattan_Plot.prototype.add_y_axis = function() { + this.yAxis = d3.svg.axis().scale(this.y_scale).orient("left").ticks(5); + return this.svg.append("g").attr("class", "y_axis").attr("transform", "translate(" + this.x_buffer + ",0)").call(this.yAxis); + }; + + Chr_Manhattan_Plot.prototype.add_title = function() { + return this.svg.append("text").attr("class", "title").text("Chr " + this.chr[0]).attr("x", (function(_this) { + return function(d) { return (_this.plot_width + _this.x_buffer) / 2; - }).attr("y", this.y_buffer + 20).attr("dx", "0em").attr("text-anchor", "middle").attr("font-family", "sans-serif").attr("font-size", "18px").attr("fill", "black"); - }; + }; + })(this)).attr("y", this.y_buffer + 20).attr("dx", "0em").attr("text-anchor", "middle").attr("font-family", "sans-serif").attr("font-size", "18px").attr("fill", "black"); + }; - Chr_Manhattan_Plot.prototype.add_back_button = function() { - return this.svg.append("text").attr("class", "back").text("Return to full view").attr("x", this.x_buffer * 2).attr("y", this.y_buffer / 2).attr("dx", "0em").attr("text-anchor", "middle").attr("font-family", "sans-serif").attr("font-size", "18px").attr("cursor", "pointer").attr("fill", "black").on("click", this.return_to_full_view); - }; + Chr_Manhattan_Plot.prototype.add_back_button = function() { + return this.svg.append("text").attr("class", "back").text("Return to full view").attr("x", this.x_buffer * 2).attr("y", this.y_buffer / 2).attr("dx", "0em").attr("text-anchor", "middle").attr("font-family", "sans-serif").attr("font-size", "18px").attr("cursor", "pointer").attr("fill", "black").on("click", this.return_to_full_view); + }; - Chr_Manhattan_Plot.prototype.add_plot_points = function() { - var _this = this; - return this.plot_point = this.svg.selectAll("circle").data(this.plot_coordinates).enter().append("circle").attr("cx", function(d) { + Chr_Manhattan_Plot.prototype.add_plot_points = function() { + return this.plot_point = this.svg.selectAll("circle").data(this.plot_coordinates).enter().append("circle").attr("cx", (function(_this) { + return function(d) { return _this.x_scale(d[0]); - }).attr("cy", function(d) { + }; + })(this)).attr("cy", (function(_this) { + return function(d) { return _this.y_scale(d[1]); - }).attr("r", function(d) { + }; + })(this)).attr("r", (function(_this) { + return function(d) { return 2; - }).attr("fill", function(d) { + }; + })(this)).attr("fill", (function(_this) { + return function(d) { return "black"; - }).attr("stroke", "black").attr("stroke-width", "1").attr("id", function(d) { + }; + })(this)).attr("stroke", "black").attr("stroke-width", "1").attr("id", (function(_this) { + return function(d) { return "point_" + String(d[2]); - }).classed("circle", true).on("mouseover", function(d) { + }; + })(this)).classed("circle", true).on("mouseover", (function(_this) { + return function(d) { var this_id; console.log("d3.event is:", d3.event); console.log("d is:", d); this_id = "point_" + String(d[2]); return d3.select("#" + this_id).classed("d3_highlight", true).attr("r", 5).attr("stroke", "none").attr("fill", "blue").call(_this.show_marker_in_table(d)); - }).on("mouseout", function(d) { + }; + })(this)).on("mouseout", (function(_this) { + return function(d) { var this_id; this_id = "point_" + String(d[2]); return d3.select("#" + this_id).classed("d3_highlight", false).attr("r", function(d) { @@ -206,33 +225,31 @@ }).attr("fill", function(d) { return "black"; }).attr("stroke", "black").attr("stroke-width", "1"); - }).append("svg:title").text(function(d) { + }; + })(this)).append("svg:title").text((function(_this) { + return function(d) { return d[2]; - }); - }; - - Chr_Manhattan_Plot.prototype.return_to_full_view = function() { - $('#manhattan_plot').remove(); - $('#manhattan_plot_container').append('
'); - return root.manhattan_plot = new root.Manhattan_Plot; - }; - - Chr_Manhattan_Plot.prototype.show_marker_in_table = function(marker_info) { - var marker_name; - console.log("in show_marker_in_table"); - /* Searches for the select marker in the results table below - */ - - if (marker_info) { - marker_name = marker_info[2]; - return $("#qtl_results_filter").find("input:first").val(marker_name).change(); - } - }; - - return Chr_Manhattan_Plot; - - })(); + }; + })(this)); + }; + + Chr_Manhattan_Plot.prototype.return_to_full_view = function() { + $('#topchart').remove(); + $('#chart_container').append('
'); + return create_manhattan_plot(); + }; + + Chr_Manhattan_Plot.prototype.show_marker_in_table = function(marker_info) { + var marker_name; + console.log("in show_marker_in_table"); + + /* Searches for the select marker in the results table below */ + if (marker_info) { + marker_name = marker_info[2]; + return $("#qtl_results_filter").find("input:first").val(marker_name).change(); + } + }; - root.Chr_Manhattan_Plot = Chr_Manhattan_Plot; + return Chr_Manhattan_Plot; -}).call(this); +})(); diff --git a/wqflask/wqflask/static/new/javascript/compare_traits_scatterplot.js b/wqflask/wqflask/static/new/javascript/compare_traits_scatterplot.js index a45eb3c0..34977878 100644 --- a/wqflask/wqflask/static/new/javascript/compare_traits_scatterplot.js +++ b/wqflask/wqflask/static/new/javascript/compare_traits_scatterplot.js @@ -1,124 +1,121 @@ -// Generated by CoffeeScript 1.6.1 -(function() { - var root; +// Generated by CoffeeScript 1.7.1 +var root; - root = typeof exports !== "undefined" && exports !== null ? exports : this; +root = typeof exports !== "undefined" && exports !== null ? exports : this; - root.create_scatterplot = function(json_ids, json_data) { - var data, h, halfh, halfw, indID, margin, mychart, totalh, totalw, w; - console.log("TESTING2"); - h = 400; - w = 500; - margin = { - left: 60, - top: 40, - right: 40, - bottom: 40, - inner: 5 - }; - halfh = h + margin.top + margin.bottom; - totalh = halfh * 2; - halfw = w + margin.left + margin.right; - totalw = halfw * 2; - mychart = scatterplot().xvar(0).yvar(1).xlab("X").ylab("Y").height(h).width(w).margin(margin); +root.create_scatterplot = function(json_ids, json_data) { + var data, h, halfh, halfw, indID, margin, mychart, totalh, totalw, w; + console.log("TESTING2"); + h = 400; + w = 500; + margin = { + left: 60, + top: 40, + right: 40, + bottom: 40, + inner: 5 + }; + halfh = h + margin.top + margin.bottom; + totalh = halfh * 2; + halfw = w + margin.left + margin.right; + totalw = halfw * 2; + mychart = scatterplot().xvar(0).yvar(1).xlab("X").ylab("Y").height(h).width(w).margin(margin); + data = json_data; + indID = json_ids; + d3.select("div#comparison_scatterplot").datum({ + data: data, + indID: indID + }).call(mychart); + return mychart.pointsSelect().on("mouseover", function(d) { + return d3.select(this).attr("r", mychart.pointsize() * 3); + }).on("mouseout", function(d) { + return d3.select(this).attr("r", mychart.pointsize()); + }); +}; + +root.create_scatterplots = function(trait_names, json_ids, json_data) { + var brush, brushend, brushmove, brushstart, chart, data, h, halfh, halfw, i, indID, margin, mychart, num_traits, svg, totalh, totalw, w, xscale, xshift, xvar, yscale, yshift, yvar, _i, _j, _k, _ref, _ref1, _ref2, _results; + console.log("json_data:", json_data); + console.log("trait_names:", trait_names); + num_traits = json_data.length; + console.log("num_traits:", num_traits); + h = 300; + w = 400; + margin = { + left: 60, + top: 40, + right: 40, + bottom: 40, + inner: 5 + }; + halfh = h + margin.top + margin.bottom; + totalh = halfh * (num_traits - 1); + halfw = w + margin.left + margin.right; + totalw = halfw; + xvar = []; + yvar = []; + xshift = []; + yshift = []; + for (i = _i = 0, _ref = num_traits - 1; 0 <= _ref ? _i <= _ref : _i >= _ref; i = 0 <= _ref ? ++_i : --_i) { + xvar.push(i); + yvar.push(0); + xshift.push(0); + yshift.push(halfh * i); + } + console.log("xvar:", xvar); + console.log("yvar:", yvar); + svg = d3.select("div#comparison_scatterplot").append("svg").attr("height", totalh).attr("width", totalw); + mychart = []; + chart = []; + for (i = _j = 1, _ref1 = num_traits - 1; 1 <= _ref1 ? _j <= _ref1 : _j >= _ref1; i = 1 <= _ref1 ? ++_j : --_j) { + mychart[i - 1] = scatterplot().xvar(xvar[i]).yvar(yvar[i]).nxticks(6).height(h).width(w).margin(margin).pointsize(4).xlab("" + trait_names[i - 1]).ylab("" + trait_names[0]).title("" + trait_names[0] + " vs. " + trait_names[i - 1]); data = json_data; indID = json_ids; - d3.select("div#comparison_scatterplot").datum({ + chart[i - 1] = svg.append("g").attr("id", "chart" + (i - 1)).attr("transform", "translate(" + xshift[i] + "," + yshift[i - 1] + ")"); + chart[i - 1].datum({ data: data, indID: indID - }).call(mychart); - return mychart.pointsSelect().on("mouseover", function(d) { - return d3.select(this).attr("r", mychart.pointsize() * 3); - }).on("mouseout", function(d) { - return d3.select(this).attr("r", mychart.pointsize()); - }); - }; - - root.create_scatterplots = function(trait_names, json_ids, json_data) { - var brush, brushend, brushmove, brushstart, chart, data, h, halfh, halfw, i, indID, margin, mychart, num_traits, svg, totalh, totalw, w, xscale, xshift, xvar, yscale, yshift, yvar, _i, _j, _k, _ref, _ref1, _ref2, _results; - console.log("json_data:", json_data); - console.log("trait_names:", trait_names); - num_traits = json_data.length; - console.log("num_traits:", num_traits); - h = 300; - w = 400; - margin = { - left: 60, - top: 40, - right: 40, - bottom: 40, - inner: 5 - }; - halfh = h + margin.top + margin.bottom; - totalh = halfh * (num_traits - 1); - halfw = w + margin.left + margin.right; - totalw = halfw; - xvar = []; - yvar = []; - xshift = []; - yshift = []; - for (i = _i = 0, _ref = num_traits - 1; 0 <= _ref ? _i <= _ref : _i >= _ref; i = 0 <= _ref ? ++_i : --_i) { - xvar.push(i); - yvar.push(0); - xshift.push(0); - yshift.push(halfh * i); - } - console.log("xvar:", xvar); - console.log("yvar:", yvar); - svg = d3.select("div#comparison_scatterplot").append("svg").attr("height", totalh).attr("width", totalw); - mychart = []; - chart = []; - for (i = _j = 1, _ref1 = num_traits - 1; 1 <= _ref1 ? _j <= _ref1 : _j >= _ref1; i = 1 <= _ref1 ? ++_j : --_j) { - mychart[i - 1] = scatterplot().xvar(xvar[i]).yvar(yvar[i]).nxticks(6).height(h).width(w).margin(margin).pointsize(4).xlab("" + trait_names[i - 1]).ylab("" + trait_names[0]).title("" + trait_names[0] + " vs. " + trait_names[i - 1]); - data = json_data; - indID = json_ids; - chart[i - 1] = svg.append("g").attr("id", "chart" + (i - 1)).attr("transform", "translate(" + xshift[i] + "," + yshift[i - 1] + ")"); - chart[i - 1].datum({ - data: data, - indID: indID - }).call(mychart[i - 1]); - } - brush = []; - brushstart = function(i) { - return function() { - var j, _k, _ref2; - for (j = _k = 0, _ref2 = num_traits - 2; 0 <= _ref2 ? _k <= _ref2 : _k >= _ref2; j = 0 <= _ref2 ? ++_k : --_k) { - if (j !== i) { - chart[j].call(brush[j].clear()); - } + }).call(mychart[i - 1]); + } + brush = []; + brushstart = function(i) { + return function() { + var j, _k, _ref2; + for (j = _k = 0, _ref2 = num_traits - 2; 0 <= _ref2 ? _k <= _ref2 : _k >= _ref2; j = 0 <= _ref2 ? ++_k : --_k) { + if (j !== i) { + chart[j].call(brush[j].clear()); } - return svg.selectAll("circle").attr("opacity", 0.6).classed("selected", false); - }; - }; - brushmove = function(i) { - return function() { - var e; - svg.selectAll("circle").classed("selected", false); - e = brush[i].extent(); - return chart[i].selectAll("circle").classed("selected", function(d, j) { - var circ, cx, cy, selected; - circ = d3.select(this); - cx = circ.attr("cx"); - cy = circ.attr("cy"); - selected = e[0][0] <= cx && cx <= e[1][0] && e[0][1] <= cy && cy <= e[1][1]; - if (selected) { - svg.selectAll("circle.pt" + j).classed("selected", true); - } - return selected; - }); - }; + } + return svg.selectAll("circle").attr("opacity", 0.6).classed("selected", false); }; - brushend = function() { - return svg.selectAll("circle").attr("opacity", 1); + }; + brushmove = function(i) { + return function() { + var e; + svg.selectAll("circle").classed("selected", false); + e = brush[i].extent(); + return chart[i].selectAll("circle").classed("selected", function(d, j) { + var circ, cx, cy, selected; + circ = d3.select(this); + cx = circ.attr("cx"); + cy = circ.attr("cy"); + selected = e[0][0] <= cx && cx <= e[1][0] && e[0][1] <= cy && cy <= e[1][1]; + if (selected) { + svg.selectAll("circle.pt" + j).classed("selected", true); + } + return selected; + }); }; - xscale = d3.scale.linear().domain([margin.left, margin.left + w]).range([margin.left, margin.left + w]); - yscale = d3.scale.linear().domain([margin.top, margin.top + h]).range([margin.top, margin.top + h]); - _results = []; - for (i = _k = 0, _ref2 = num_traits - 2; 0 <= _ref2 ? _k <= _ref2 : _k >= _ref2; i = 0 <= _ref2 ? ++_k : --_k) { - brush[i] = d3.svg.brush().x(xscale).y(yscale).on("brushstart", brushstart(i)).on("brush", brushmove(i)).on("brushend", brushend); - _results.push(chart[i].call(brush[i])); - } - return _results; }; - -}).call(this); + brushend = function() { + return svg.selectAll("circle").attr("opacity", 1); + }; + xscale = d3.scale.linear().domain([margin.left, margin.left + w]).range([margin.left, margin.left + w]); + yscale = d3.scale.linear().domain([margin.top, margin.top + h]).range([margin.top, margin.top + h]); + _results = []; + for (i = _k = 0, _ref2 = num_traits - 2; 0 <= _ref2 ? _k <= _ref2 : _k >= _ref2; i = 0 <= _ref2 ? ++_k : --_k) { + brush[i] = d3.svg.brush().x(xscale).y(yscale).on("brushstart", brushstart(i)).on("brush", brushmove(i)).on("brushend", brushend); + _results.push(chart[i].call(brush[i])); + } + return _results; +}; diff --git a/wqflask/wqflask/static/new/javascript/corr_matrix.js b/wqflask/wqflask/static/new/javascript/corr_matrix.js index 17625f99..cfe2159e 100644 --- a/wqflask/wqflask/static/new/javascript/corr_matrix.js +++ b/wqflask/wqflask/static/new/javascript/corr_matrix.js @@ -1,157 +1,154 @@ -// Generated by CoffeeScript 1.6.1 -(function() { - var iplotCorr, root; +// Generated by CoffeeScript 1.7.1 +var iplotCorr, root; - root = typeof exports !== "undefined" && exports !== null ? exports : this; +root = typeof exports !== "undefined" && exports !== null ? exports : this; - iplotCorr = function(data, chartOpts) { - var cells, chartdivid, colorScale, corXscale, corYscale, corZscale, corcolors, corr, corr_tip, corrplot, cortitle, drawScatter, height, i, j, margin, nGroup, ncorrX, ncorrY, nind, nvar, pixel_height, pixel_width, rectcolor, scat_tip, scatcolors, scatterplot, scattitle, svg, totalh, totalw, width, zlim, _ref, _ref1, _ref2, _ref3, _ref4, _ref5, _ref6, _ref7, _ref8, _ref9; - height = (_ref = chartOpts != null ? chartOpts.height : void 0) != null ? _ref : 450; - width = (_ref1 = chartOpts != null ? chartOpts.width : void 0) != null ? _ref1 : height; - margin = (_ref2 = chartOpts != null ? chartOpts.margin : void 0) != null ? _ref2 : { - left: 70, - top: 40, - right: 5, - bottom: 70, - inner: 5 - }; - corcolors = (_ref3 = chartOpts != null ? chartOpts.corcolors : void 0) != null ? _ref3 : ["darkslateblue", "white", "crimson"]; - zlim = (_ref4 = chartOpts != null ? chartOpts.zlim : void 0) != null ? _ref4 : [-1, 0, 1]; - rectcolor = (_ref5 = chartOpts != null ? chartOpts.rectcolor : void 0) != null ? _ref5 : d3.rgb(230, 230, 230); - cortitle = (_ref6 = chartOpts != null ? chartOpts.cortitle : void 0) != null ? _ref6 : ""; - scattitle = (_ref7 = chartOpts != null ? chartOpts.scattitle : void 0) != null ? _ref7 : ""; - scatcolors = (_ref8 = chartOpts != null ? chartOpts.scatcolors : void 0) != null ? _ref8 : null; - chartdivid = (_ref9 = chartOpts != null ? chartOpts.chartdivid : void 0) != null ? _ref9 : 'chart'; - totalh = height + margin.top + margin.bottom; - totalw = (width + margin.left + margin.right) * 2; - svg = d3.select("div#" + chartdivid).append("svg").attr("height", totalh).attr("width", totalw); - corrplot = svg.append("g").attr("id", "corplot").attr("transform", "translate(" + margin.left + "," + margin.top + ")"); - scatterplot = svg.append("g").attr("id", "scatterplot").attr("transform", "translate(" + (margin.left * 2 + margin.right + width) + "," + margin.top + ")"); - nind = data.indID.length; - nvar = data["var"].length; - ncorrX = data.cols.length; - ncorrY = data.rows.length; - corXscale = d3.scale.ordinal().domain(d3.range(ncorrX)).rangeBands([0, width]); - corYscale = d3.scale.ordinal().domain(d3.range(ncorrY)).rangeBands([height, 0]); - corZscale = d3.scale.linear().domain(zlim).range(corcolors); - pixel_width = corXscale(1) - corXscale(0); - pixel_height = corYscale(0) - corYscale(1); - corr = []; - for (i in data.corr) { - for (j in data.corr[i]) { - corr.push({ - row: i, - col: j, - value: data.corr[i][j] - }); - } +iplotCorr = function(data, chartOpts) { + var cells, chartdivid, colorScale, corXscale, corYscale, corZscale, corcolors, corr, corr_tip, corrplot, cortitle, drawScatter, height, i, j, margin, nGroup, ncorrX, ncorrY, nind, nvar, pixel_height, pixel_width, rectcolor, scat_tip, scatcolors, scatterplot, scattitle, svg, totalh, totalw, width, zlim, _ref, _ref1, _ref2, _ref3, _ref4, _ref5, _ref6, _ref7, _ref8, _ref9; + height = (_ref = chartOpts != null ? chartOpts.height : void 0) != null ? _ref : 450; + width = (_ref1 = chartOpts != null ? chartOpts.width : void 0) != null ? _ref1 : height; + margin = (_ref2 = chartOpts != null ? chartOpts.margin : void 0) != null ? _ref2 : { + left: 70, + top: 40, + right: 5, + bottom: 70, + inner: 5 + }; + corcolors = (_ref3 = chartOpts != null ? chartOpts.corcolors : void 0) != null ? _ref3 : ["darkslateblue", "white", "crimson"]; + zlim = (_ref4 = chartOpts != null ? chartOpts.zlim : void 0) != null ? _ref4 : [-1, 0, 1]; + rectcolor = (_ref5 = chartOpts != null ? chartOpts.rectcolor : void 0) != null ? _ref5 : d3.rgb(230, 230, 230); + cortitle = (_ref6 = chartOpts != null ? chartOpts.cortitle : void 0) != null ? _ref6 : ""; + scattitle = (_ref7 = chartOpts != null ? chartOpts.scattitle : void 0) != null ? _ref7 : ""; + scatcolors = (_ref8 = chartOpts != null ? chartOpts.scatcolors : void 0) != null ? _ref8 : null; + chartdivid = (_ref9 = chartOpts != null ? chartOpts.chartdivid : void 0) != null ? _ref9 : 'chart'; + totalh = height + margin.top + margin.bottom; + totalw = (width + margin.left + margin.right) * 2; + svg = d3.select("div#" + chartdivid).append("svg").attr("height", totalh).attr("width", totalw); + corrplot = svg.append("g").attr("id", "corplot").attr("transform", "translate(" + margin.left + "," + margin.top + ")"); + scatterplot = svg.append("g").attr("id", "scatterplot").attr("transform", "translate(" + (margin.left * 2 + margin.right + width) + "," + margin.top + ")"); + nind = data.indID.length; + nvar = data["var"].length; + ncorrX = data.cols.length; + ncorrY = data.rows.length; + corXscale = d3.scale.ordinal().domain(d3.range(ncorrX)).rangeBands([0, width]); + corYscale = d3.scale.ordinal().domain(d3.range(ncorrY)).rangeBands([height, 0]); + corZscale = d3.scale.linear().domain(zlim).range(corcolors); + pixel_width = corXscale(1) - corXscale(0); + pixel_height = corYscale(0) - corYscale(1); + corr = []; + for (i in data.corr) { + for (j in data.corr[i]) { + corr.push({ + row: i, + col: j, + value: data.corr[i][j] + }); } - scatterplot.append("rect").attr("height", height).attr("width", width).attr("fill", rectcolor).attr("stroke", "black").attr("stroke-width", 1).attr("pointer-events", "none"); - corr_tip = d3.tip().attr('class', 'd3-tip').html(function(d) { - return d3.format(".2f")(d.value); - }).direction('e').offset([0, 10]); - corrplot.call(corr_tip); - cells = corrplot.selectAll("empty").data(corr).enter().append("rect").attr("class", "cell").attr("x", function(d) { - return corXscale(d.col); - }).attr("y", function(d) { - return corYscale(d.row); - }).attr("width", corXscale.rangeBand()).attr("height", corYscale.rangeBand()).attr("fill", function(d) { - return corZscale(d.value); - }).attr("stroke", "none").attr("stroke-width", 2).on("mouseover", function(d) { - d3.select(this).attr("stroke", "black"); - corr_tip.show(d); - corrplot.append("text").attr("class", "corrlabel").attr("x", corXscale(d.col) + pixel_width / 2).attr("y", height + margin.bottom * 0.2).text(data["var"][data.cols[d.col]]).attr("dominant-baseline", "middle").attr("text-anchor", "middle"); - return corrplot.append("text").attr("class", "corrlabel").attr("y", corYscale(d.row) + pixel_height / 2).attr("x", -margin.left * 0.1).text(data["var"][data.rows[d.row]]).attr("dominant-baseline", "middle").attr("text-anchor", "end"); - }).on("mouseout", function(d) { - corr_tip.hide(d); - d3.selectAll("text.corrlabel").remove(); - return d3.select(this).attr("stroke", "none"); - }).on("click", function(d) { - return drawScatter(d.col, d.row); - }); - nGroup = d3.max(data.group); - if (!(scatcolors != null) || scatcolors.length < nGroup) { - if (nGroup === 1) { - scatcolors = [d3.rgb(150, 150, 150)]; - } else if (nGroup <= 3) { - scatcolors = ["crimson", "green", "darkslateblue"]; + } + scatterplot.append("rect").attr("height", height).attr("width", width).attr("fill", rectcolor).attr("stroke", "black").attr("stroke-width", 1).attr("pointer-events", "none"); + corr_tip = d3.tip().attr('class', 'd3-tip').html(function(d) { + return d3.format(".2f")(d.value); + }).direction('e').offset([0, 10]); + corrplot.call(corr_tip); + cells = corrplot.selectAll("empty").data(corr).enter().append("rect").attr("class", "cell").attr("x", function(d) { + return corXscale(d.col); + }).attr("y", function(d) { + return corYscale(d.row); + }).attr("width", corXscale.rangeBand()).attr("height", corYscale.rangeBand()).attr("fill", function(d) { + return corZscale(d.value); + }).attr("stroke", "none").attr("stroke-width", 2).on("mouseover", function(d) { + d3.select(this).attr("stroke", "black"); + corr_tip.show(d); + corrplot.append("text").attr("class", "corrlabel").attr("x", corXscale(d.col) + pixel_width / 2).attr("y", height + margin.bottom * 0.2).text(data["var"][data.cols[d.col]]).attr("dominant-baseline", "middle").attr("text-anchor", "middle"); + return corrplot.append("text").attr("class", "corrlabel").attr("y", corYscale(d.row) + pixel_height / 2).attr("x", -margin.left * 0.1).text(data["var"][data.rows[d.row]]).attr("dominant-baseline", "middle").attr("text-anchor", "end"); + }).on("mouseout", function(d) { + corr_tip.hide(d); + d3.selectAll("text.corrlabel").remove(); + return d3.select(this).attr("stroke", "none"); + }).on("click", function(d) { + return drawScatter(d.col, d.row); + }); + nGroup = d3.max(data.group); + if (!(scatcolors != null) || scatcolors.length < nGroup) { + if (nGroup === 1) { + scatcolors = [d3.rgb(150, 150, 150)]; + } else if (nGroup <= 3) { + scatcolors = ["crimson", "green", "darkslateblue"]; + } else { + if (nGroup <= 10) { + colorScale = d3.scale.category10(); } else { - if (nGroup <= 10) { - colorScale = d3.scale.category10(); - } else { - colorScale = d3.scale.category20(); - } - scatcolors = (function() { - var _results; - _results = []; - for (i in d3.range(nGroup)) { - _results.push(colorScale(i)); - } - return _results; - })(); + colorScale = d3.scale.category20(); } - } - scat_tip = d3.tip().attr('class', 'd3-tip').html(function(d, i) { - return data.indID[i]; - }).direction('e').offset([0, 10]); - scatterplot.call(scat_tip); - drawScatter = function(i, j) { - var xScale, xticks, yScale, yticks; - d3.selectAll("circle.points").remove(); - d3.selectAll("text.axes").remove(); - d3.selectAll("line.axes").remove(); - console.log("data.dat:", data.dat); - console.log("data.cols:", data.cols); - xScale = d3.scale.linear().domain(d3.extent(data.dat[data.cols[i]])).range([margin.inner, width - margin.inner]); - yScale = d3.scale.linear().domain(d3.extent(data.dat[data.rows[j]])).range([height - margin.inner, margin.inner]); - scatterplot.append("text").attr("id", "xaxis").attr("class", "axes").attr("x", width / 2).attr("y", height + margin.bottom * 0.7).text(data["var"][data.cols[i]]).attr("dominant-baseline", "middle").attr("text-anchor", "middle").attr("fill", "slateblue"); - scatterplot.append("text").attr("id", "yaxis").attr("class", "axes").attr("x", -margin.left * 0.8).attr("y", height / 2).text(data["var"][data.rows[j]]).attr("dominant-baseline", "middle").attr("text-anchor", "middle").attr("transform", "rotate(270," + (-margin.left * 0.8) + "," + (height / 2) + ")").attr("fill", "slateblue"); - xticks = xScale.ticks(5); - yticks = yScale.ticks(5); - scatterplot.selectAll("empty").data(xticks).enter().append("text").attr("class", "axes").text(function(d) { - return formatAxis(xticks)(d); - }).attr("x", function(d) { - return xScale(d); - }).attr("y", height + margin.bottom * 0.3).attr("dominant-baseline", "middle").attr("text-anchor", "middle"); - scatterplot.selectAll("empty").data(yticks).enter().append("text").attr("class", "axes").text(function(d) { - return formatAxis(yticks)(d); - }).attr("x", -margin.left * 0.1).attr("y", function(d) { - return yScale(d); - }).attr("dominant-baseline", "middle").attr("text-anchor", "end"); - scatterplot.selectAll("empty").data(xticks).enter().append("line").attr("class", "axes").attr("x1", function(d) { - return xScale(d); - }).attr("x2", function(d) { - return xScale(d); - }).attr("y1", 0).attr("y2", height).attr("stroke", "white").attr("stroke-width", 1); - scatterplot.selectAll("empty").data(yticks).enter().append("line").attr("class", "axes").attr("y1", function(d) { - return yScale(d); - }).attr("y2", function(d) { - return yScale(d); - }).attr("x1", 0).attr("x2", width).attr("stroke", "white").attr("stroke-width", 1); - return scatterplot.selectAll("empty").data(d3.range(nind)).enter().append("circle").attr("class", "points").attr("cx", function(d) { - return xScale(data.dat[data.cols[i]][d]); - }).attr("cy", function(d) { - return yScale(data.dat[data.rows[j]][d]); - }).attr("r", function(d) { - var x, y; - x = data.dat[data.cols[i]][d]; - y = data.dat[data.rows[j]][d]; - if ((x != null) && (y != null)) { - return 3; - } else { - return null; + scatcolors = (function() { + var _results; + _results = []; + for (i in d3.range(nGroup)) { + _results.push(colorScale(i)); } - }).attr("stroke", "black").attr("stroke-width", 1).attr("fill", function(d) { - return scatcolors[data.group[d] - 1]; - }).on("mouseover", scat_tip.show).on("mouseout", scat_tip.hide); - }; - corrplot.append("rect").attr("height", height).attr("width", width).attr("fill", "none").attr("stroke", "black").attr("stroke-width", 1).attr("pointer-events", "none"); - scatterplot.append("rect").attr("height", height).attr("width", width).attr("fill", "none").attr("stroke", "black").attr("stroke-width", 1).attr("pointer-events", "none"); - corrplot.append("text").text(cortitle).attr("id", "corrtitle").attr("x", width / 2).attr("y", -margin.top / 2).attr("dominant-baseline", "middle").attr("text-anchor", "middle"); - scatterplot.append("text").text(scattitle).attr("id", "scattitle").attr("x", width / 2).attr("y", -margin.top / 2).attr("dominant-baseline", "middle").attr("text-anchor", "middle"); - return d3.select("div#caption").style("opacity", 1); + return _results; + })(); + } + } + scat_tip = d3.tip().attr('class', 'd3-tip').html(function(d, i) { + return data.indID[i]; + }).direction('e').offset([0, 10]); + scatterplot.call(scat_tip); + drawScatter = function(i, j) { + var xScale, xticks, yScale, yticks; + d3.selectAll("circle.points").remove(); + d3.selectAll("text.axes").remove(); + d3.selectAll("line.axes").remove(); + console.log("data.dat:", data.dat); + console.log("data.cols:", data.cols); + xScale = d3.scale.linear().domain(d3.extent(data.dat[data.cols[i]])).range([margin.inner, width - margin.inner]); + yScale = d3.scale.linear().domain(d3.extent(data.dat[data.rows[j]])).range([height - margin.inner, margin.inner]); + scatterplot.append("text").attr("id", "xaxis").attr("class", "axes").attr("x", width / 2).attr("y", height + margin.bottom * 0.7).text(data["var"][data.cols[i]]).attr("dominant-baseline", "middle").attr("text-anchor", "middle").attr("fill", "slateblue"); + scatterplot.append("text").attr("id", "yaxis").attr("class", "axes").attr("x", -margin.left * 0.8).attr("y", height / 2).text(data["var"][data.rows[j]]).attr("dominant-baseline", "middle").attr("text-anchor", "middle").attr("transform", "rotate(270," + (-margin.left * 0.8) + "," + (height / 2) + ")").attr("fill", "slateblue"); + xticks = xScale.ticks(5); + yticks = yScale.ticks(5); + scatterplot.selectAll("empty").data(xticks).enter().append("text").attr("class", "axes").text(function(d) { + return formatAxis(xticks)(d); + }).attr("x", function(d) { + return xScale(d); + }).attr("y", height + margin.bottom * 0.3).attr("dominant-baseline", "middle").attr("text-anchor", "middle"); + scatterplot.selectAll("empty").data(yticks).enter().append("text").attr("class", "axes").text(function(d) { + return formatAxis(yticks)(d); + }).attr("x", -margin.left * 0.1).attr("y", function(d) { + return yScale(d); + }).attr("dominant-baseline", "middle").attr("text-anchor", "end"); + scatterplot.selectAll("empty").data(xticks).enter().append("line").attr("class", "axes").attr("x1", function(d) { + return xScale(d); + }).attr("x2", function(d) { + return xScale(d); + }).attr("y1", 0).attr("y2", height).attr("stroke", "white").attr("stroke-width", 1); + scatterplot.selectAll("empty").data(yticks).enter().append("line").attr("class", "axes").attr("y1", function(d) { + return yScale(d); + }).attr("y2", function(d) { + return yScale(d); + }).attr("x1", 0).attr("x2", width).attr("stroke", "white").attr("stroke-width", 1); + return scatterplot.selectAll("empty").data(d3.range(nind)).enter().append("circle").attr("class", "points").attr("cx", function(d) { + return xScale(data.dat[data.cols[i]][d]); + }).attr("cy", function(d) { + return yScale(data.dat[data.rows[j]][d]); + }).attr("r", function(d) { + var x, y; + x = data.dat[data.cols[i]][d]; + y = data.dat[data.rows[j]][d]; + if ((x != null) && (y != null)) { + return 3; + } else { + return null; + } + }).attr("stroke", "black").attr("stroke-width", 1).attr("fill", function(d) { + return scatcolors[data.group[d] - 1]; + }).on("mouseover", scat_tip.show).on("mouseout", scat_tip.hide); }; + corrplot.append("rect").attr("height", height).attr("width", width).attr("fill", "none").attr("stroke", "black").attr("stroke-width", 1).attr("pointer-events", "none"); + scatterplot.append("rect").attr("height", height).attr("width", width).attr("fill", "none").attr("stroke", "black").attr("stroke-width", 1).attr("pointer-events", "none"); + corrplot.append("text").text(cortitle).attr("id", "corrtitle").attr("x", width / 2).attr("y", -margin.top / 2).attr("dominant-baseline", "middle").attr("text-anchor", "middle"); + scatterplot.append("text").text(scattitle).attr("id", "scattitle").attr("x", width / 2).attr("y", -margin.top / 2).attr("dominant-baseline", "middle").attr("text-anchor", "middle"); + return d3.select("div#caption").style("opacity", 1); +}; - root.corr_matrix = iplotCorr; - -}).call(this); +root.corr_matrix = iplotCorr; diff --git a/wqflask/wqflask/static/new/javascript/create_corr_matrix.js b/wqflask/wqflask/static/new/javascript/create_corr_matrix.js index 64dc834d..ca5962f4 100644 --- a/wqflask/wqflask/static/new/javascript/create_corr_matrix.js +++ b/wqflask/wqflask/static/new/javascript/create_corr_matrix.js @@ -1,47 +1,44 @@ -// Generated by CoffeeScript 1.6.1 -(function() { - var get_data, get_options, root; +// Generated by CoffeeScript 1.7.1 +var get_data, get_options, root; - root = typeof exports !== "undefined" && exports !== null ? exports : this; +root = typeof exports !== "undefined" && exports !== null ? exports : this; - $(function() { - var chartOpts, data, mychart; - console.log("js_data:", js_data); - chartOpts = get_options(); - data = get_data(); - console.log(data); - return mychart = corr_matrix(data, chartOpts); - }); +$(function() { + var chartOpts, data, mychart; + console.log("js_data:", js_data); + chartOpts = get_options(); + data = get_data(); + console.log(data); + return mychart = corr_matrix(data, chartOpts); +}); - get_options = function() { - var chartOpts; - chartOpts = { - cortitle: "Correlation Matrix", - scattitle: "Scatterplot", - h: 450, - w: 450, - margin: { - left: 100, - top: 40, - right: 5, - bottom: 70, - inner: 5 - } - }; - return chartOpts; +get_options = function() { + var chartOpts; + chartOpts = { + cortitle: "Correlation Matrix", + scattitle: "Scatterplot", + h: 450, + w: 450, + margin: { + left: 100, + top: 40, + right: 5, + bottom: 70, + inner: 5 + } }; + return chartOpts; +}; - get_data = function() { - var data; - data = {}; - data["var"] = js_data.traits; - data.group = js_data.groups; - data.indID = js_data.samples; - data.dat = js_data.sample_data; - data.corr = js_data.corr_results; - data.cols = js_data.cols; - data.rows = js_data.rows; - return data; - }; - -}).call(this); +get_data = function() { + var data; + data = {}; + data["var"] = js_data.traits; + data.group = js_data.groups; + data.indID = js_data.samples; + data.dat = js_data.sample_data; + data.corr = js_data.corr_results; + data.cols = js_data.cols; + data.rows = js_data.rows; + return data; +}; diff --git a/wqflask/wqflask/static/new/javascript/create_interval_map.coffee b/wqflask/wqflask/static/new/javascript/create_interval_map.coffee new file mode 100644 index 00000000..cacba03e --- /dev/null +++ b/wqflask/wqflask/static/new/javascript/create_interval_map.coffee @@ -0,0 +1,91 @@ +create_interval_map = -> + h = 500 + w = 1200 + margin = {left:60, top:40, right:40, bottom: 40, inner:5} + halfh = (h+margin.top+margin.bottom) + totalh = halfh*2 + totalw = (w+margin.left+margin.right) + + # simplest use + #d3.json "data.json", (data) -> + mychart = lodchart().lodvarname("lod.hk") + .height(h) + .width(w) + .margin(margin) + + data = js_data.json_data + + d3.select("div#topchart") + .datum(data) + .call(mychart) + + # grab chromosome rectangles; color pink on hover + chrrect = mychart.chrSelect() + chrrect.on "mouseover", -> + d3.select(this).attr("fill", "#E9CFEC") + .on "mouseout", (d,i) -> + d3.select(this).attr("fill", -> + return "#F1F1F9" if i % 2 + "#FBFBFF") + + # animate points at markers on click + mychart.markerSelect() + .on "click", (d) -> + r = d3.select(this).attr("r") + d3.select(this) + .transition().duration(500).attr("r", r*3) + .transition().duration(500).attr("r", r) + +create_interval_map() + +$("#export").click => + #Get d3 SVG element + svg = $("#topchart").find("svg")[0] + + #Extract SVG text string + svg_xml = (new XMLSerializer).serializeToString(svg) + console.log("svg_xml:", svg_xml) + + #Set filename + filename = "interval_map_" + js_data.this_trait + + #Make a form with the SVG data + form = $("#exportform") + form.find("#data").val(svg_xml) + form.find("#filename").val(filename) + form.submit() + +# two LOD charts within one SVG +#d3.json "data.json", (data) -> +# mychart_em = lodchart().lodvarname("lod.em") +# .height(h) +# .width(w) +# .margin(margin) +# .ylab("LOD score (by EM)") +# .pointsize(1) +# .nyticks(9) +# .title("Standard interval mapping") +# mychart_hk = lodchart().lodvarname("lod.hk") +# .height(h) +# .width(w) +# .margin(margin) +# .ylab("LOD score (by H-K)") +# .linecolor("Crimson") +# .yticks([0, 1, 2, 4, 6, 8]) +# .title("Haley-Knott regression") +# +# svg = d3.select("div#bottomchart") +# .append("svg") +# .attr("height", totalh) +# .attr("width", totalw) +# +# chart1 = svg.append("g").attr("id", "chart1") +# +# chart2 = svg.append("g").attr("id", "chart2") +# .attr("transform", "translate(0, #{halfh})") +# +# chart1.datum(data) +# .call(mychart_em) +# +# chart2.datum(data) +# .call(mychart_hk) \ No newline at end of file diff --git a/wqflask/wqflask/static/new/javascript/create_interval_map.js b/wqflask/wqflask/static/new/javascript/create_interval_map.js new file mode 100644 index 00000000..5041cfea --- /dev/null +++ b/wqflask/wqflask/static/new/javascript/create_interval_map.js @@ -0,0 +1,53 @@ +// Generated by CoffeeScript 1.7.1 +var create_interval_map; + +create_interval_map = function() { + var chrrect, data, h, halfh, margin, mychart, totalh, totalw, w; + h = 500; + w = 1200; + margin = { + left: 60, + top: 40, + right: 40, + bottom: 40, + inner: 5 + }; + halfh = h + margin.top + margin.bottom; + totalh = halfh * 2; + totalw = w + margin.left + margin.right; + mychart = lodchart().lodvarname("lod.hk").height(h).width(w).margin(margin); + data = js_data.json_data; + d3.select("div#topchart").datum(data).call(mychart); + chrrect = mychart.chrSelect(); + chrrect.on("mouseover", function() { + return d3.select(this).attr("fill", "#E9CFEC"); + }).on("mouseout", function(d, i) { + return d3.select(this).attr("fill", function() { + if (i % 2) { + return "#F1F1F9"; + } + return "#FBFBFF"; + }); + }); + return mychart.markerSelect().on("click", function(d) { + var r; + r = d3.select(this).attr("r"); + return d3.select(this).transition().duration(500).attr("r", r * 3).transition().duration(500).attr("r", r); + }); +}; + +create_interval_map(); + +$("#export").click((function(_this) { + return function() { + var filename, form, svg, svg_xml; + svg = $("#topchart").find("svg")[0]; + svg_xml = (new XMLSerializer).serializeToString(svg); + console.log("svg_xml:", svg_xml); + filename = "interval_map_" + js_data.this_trait; + form = $("#exportform"); + form.find("#data").val(svg_xml); + form.find("#filename").val(filename); + return form.submit(); + }; +})(this)); diff --git a/wqflask/wqflask/static/new/javascript/create_manhattan_plot.coffee b/wqflask/wqflask/static/new/javascript/create_manhattan_plot.coffee new file mode 100644 index 00000000..258d5c01 --- /dev/null +++ b/wqflask/wqflask/static/new/javascript/create_manhattan_plot.coffee @@ -0,0 +1,57 @@ +create_manhattan_plot = -> + h = 500 + w = 1200 + margin = {left:60, top:40, right:40, bottom: 40, inner:5} + halfh = (h+margin.top+margin.bottom) + totalh = halfh*2 + totalw = (w+margin.left+margin.right) + + # simplest use + #d3.json "data.json", (data) -> + mychart = lodchart().lodvarname("lod.hk") + .height(h) + .width(w) + .margin(margin) + + data = js_data.json_data + + d3.select("div#topchart") + .datum(data) + .call(mychart) + + # grab chromosome rectangles; color pink on hover + chrrect = mychart.chrSelect() + chrrect.on "mouseover", -> + d3.select(this).attr("fill", "#E9CFEC") + .on "mouseout", (d,i) -> + d3.select(this).attr("fill", -> + return "#F1F1F9" if i % 2 + "#FBFBFF") + + # animate points at markers on click + mychart.markerSelect() + .on "click", (d) -> + r = d3.select(this).attr("r") + d3.select(this) + .transition().duration(500).attr("r", r*3) + .transition().duration(500).attr("r", r) + +create_manhattan_plot() + +$("#export").click => + #Get d3 SVG element + svg = $("#topchart").find("svg")[0] + + #Extract SVG text string + svg_xml = (new XMLSerializer).serializeToString(svg) + console.log("svg_xml:", svg_xml) + + #Set filename + filename = "manhattan_plot_" + js_data.this_trait + + #Make a form with the SVG data + form = $("#exportform") + form.find("#data").val(svg_xml) + form.find("#filename").val(filename) + form.submit() + diff --git a/wqflask/wqflask/static/new/javascript/create_manhattan_plot.js b/wqflask/wqflask/static/new/javascript/create_manhattan_plot.js new file mode 100644 index 00000000..7daaa921 --- /dev/null +++ b/wqflask/wqflask/static/new/javascript/create_manhattan_plot.js @@ -0,0 +1,53 @@ +// Generated by CoffeeScript 1.7.1 +var create_manhattan_plot; + +create_manhattan_plot = function() { + var chrrect, data, h, halfh, margin, mychart, totalh, totalw, w; + h = 500; + w = 1200; + margin = { + left: 60, + top: 40, + right: 40, + bottom: 40, + inner: 5 + }; + halfh = h + margin.top + margin.bottom; + totalh = halfh * 2; + totalw = w + margin.left + margin.right; + mychart = lodchart().lodvarname("lod.hk").height(h).width(w).margin(margin); + data = js_data.json_data; + d3.select("div#topchart").datum(data).call(mychart); + chrrect = mychart.chrSelect(); + chrrect.on("mouseover", function() { + return d3.select(this).attr("fill", "#E9CFEC"); + }).on("mouseout", function(d, i) { + return d3.select(this).attr("fill", function() { + if (i % 2) { + return "#F1F1F9"; + } + return "#FBFBFF"; + }); + }); + return mychart.markerSelect().on("click", function(d) { + var r; + r = d3.select(this).attr("r"); + return d3.select(this).transition().duration(500).attr("r", r * 3).transition().duration(500).attr("r", r); + }); +}; + +create_manhattan_plot(); + +$("#export").click((function(_this) { + return function() { + var filename, form, svg, svg_xml; + svg = $("#topchart").find("svg")[0]; + svg_xml = (new XMLSerializer).serializeToString(svg); + console.log("svg_xml:", svg_xml); + filename = "manhattan_plot_" + js_data.this_trait; + form = $("#exportform"); + form.find("#data").val(svg_xml); + form.find("#filename").val(filename); + return form.submit(); + }; +})(this)); diff --git a/wqflask/wqflask/static/new/javascript/dataset_select_menu.js b/wqflask/wqflask/static/new/javascript/dataset_select_menu.js index 3a2f044f..f4ca2c37 100755 --- a/wqflask/wqflask/static/new/javascript/dataset_select_menu.js +++ b/wqflask/wqflask/static/new/javascript/dataset_select_menu.js @@ -1,136 +1,137 @@ -// Generated by CoffeeScript 1.6.1 -(function() { - - $(function() { - var apply_default, dataset_info, group_info, make_default, open_window, populate_dataset, populate_group, populate_species, populate_type, process_json, redo_dropdown, - _this = this; - process_json = function(data) { - window.jdata = data; - populate_species(); - return apply_default(); - }; - $.ajax('/static/new/javascript/dataset_menu_structure.json', { - dataType: 'json', - success: process_json - }); - populate_species = function() { - var species_list; - species_list = this.jdata.species; - redo_dropdown($('#species'), species_list); +// Generated by CoffeeScript 1.7.1 +$(function() { + var apply_default, dataset_info, group_info, make_default, open_window, populate_dataset, populate_group, populate_species, populate_type, process_json, redo_dropdown; + process_json = function(data) { + window.jdata = data; + populate_species(); + return apply_default(); + }; + $.ajax('/static/new/javascript/dataset_menu_structure.json', { + dataType: 'json', + success: process_json + }); + populate_species = function() { + var species_list; + species_list = this.jdata.species; + redo_dropdown($('#species'), species_list); + return populate_group(); + }; + window.populate_species = populate_species; + populate_group = function() { + var group_list, species; + console.log("in populate group"); + species = $('#species').val(); + group_list = this.jdata.groups[species]; + redo_dropdown($('#group'), group_list); + return populate_type(); + }; + window.populate_group = populate_group; + populate_type = function() { + var group, species, type_list; + species = $('#species').val(); + group = $('#group').val(); + type_list = this.jdata.types[species][group]; + redo_dropdown($('#type'), type_list); + return populate_dataset(); + }; + window.populate_type = populate_type; + populate_dataset = function() { + var dataset_list, group, species, type; + species = $('#species').val(); + group = $('#group').val(); + type = $('#type').val(); + console.log("sgt:", species, group, type); + dataset_list = this.jdata.datasets[species][group][type]; + console.log("pop_dataset:", dataset_list); + return redo_dropdown($('#dataset'), dataset_list); + }; + window.populate_dataset = populate_dataset; + redo_dropdown = function(dropdown, items) { + var item, _i, _len, _results; + console.log("in redo:", dropdown, items); + dropdown.empty(); + _results = []; + for (_i = 0, _len = items.length; _i < _len; _i++) { + item = items[_i]; + _results.push(dropdown.append($(""; - }; - populate_sample_attributes_values_dropdown = function() { - var attribute_info, key, sample_attributes, selected_attribute, value, _i, _len, _ref, _ref1, _results; - console.log("in beginning of psavd"); - $('#attribute_values').empty(); - sample_attributes = {}; - _ref = js_data.attribute_names; - for (key in _ref) { - if (!__hasProp.call(_ref, key)) continue; - attribute_info = _ref[key]; - sample_attributes[attribute_info.name] = attribute_info.distinct_values; - } - console.log("[visa] attributes is:", sample_attributes); - selected_attribute = $('#exclude_menu').val().replace("_", " "); - console.log("selected_attribute is:", selected_attribute); - _ref1 = sample_attributes[selected_attribute]; - _results = []; - for (_i = 0, _len = _ref1.length; _i < _len; _i++) { - value = _ref1[_i]; - _results.push($(create_value_dropdown(value)).appendTo($('#attribute_values'))); - } - return _results; - }; - if (js_data.attribute_names.length > 0) { - populate_sample_attributes_values_dropdown(); } - $('#exclude_menu').change(populate_sample_attributes_values_dropdown); - block_by_attribute_value = function() { - var attribute_name, cell_class, exclude_by_value, - _this = this; - attribute_name = $('#exclude_menu').val(); - exclude_by_value = $('#attribute_values').val(); - cell_class = ".column_name-" + attribute_name; - return $(cell_class).each(function(index, element) { + console.log("towards end:", sample_sets); + return update_stat_values(sample_sets); + }; + show_hide_outliers = function() { + var label; + console.log("FOOBAR in beginning of show_hide_outliers"); + label = $('#show_hide_outliers').val(); + console.log("lable is:", label); + if (label === "Hide Outliers") { + return $('#show_hide_outliers').val("Show Outliers"); + } else if (label === "Show Outliers") { + console.log("Found Show Outliers"); + $('#show_hide_outliers').val("Hide Outliers"); + return console.log("Should be now Hide Outliers"); + } + }; + on_corr_method_change = function() { + var corr_method; + console.log("in beginning of on_corr_method_change"); + corr_method = $('select[name=corr_method]').val(); + console.log("corr_method is:", corr_method); + $('.correlation_desc').hide(); + $('#' + corr_method + "_r_desc").show().effect("highlight"); + if (corr_method === "lit") { + return $("#corr_sample_method_options").hide(); + } else { + return $("#corr_sample_method_options").show(); + } + }; + $('select[name=corr_method]').change(on_corr_method_change); + create_value_dropdown = function(value) { + return ""; + }; + populate_sample_attributes_values_dropdown = function() { + var attribute_info, key, sample_attributes, selected_attribute, value, _i, _len, _ref, _ref1, _results; + console.log("in beginning of psavd"); + $('#attribute_values').empty(); + sample_attributes = {}; + _ref = js_data.attribute_names; + for (key in _ref) { + if (!__hasProp.call(_ref, key)) continue; + attribute_info = _ref[key]; + sample_attributes[attribute_info.name] = attribute_info.distinct_values; + } + console.log("[visa] attributes is:", sample_attributes); + selected_attribute = $('#exclude_menu').val().replace("_", " "); + console.log("selected_attribute is:", selected_attribute); + _ref1 = sample_attributes[selected_attribute]; + _results = []; + for (_i = 0, _len = _ref1.length; _i < _len; _i++) { + value = _ref1[_i]; + _results.push($(create_value_dropdown(value)).appendTo($('#attribute_values'))); + } + return _results; + }; + if (js_data.attribute_names.length > 0) { + populate_sample_attributes_values_dropdown(); + } + $('#exclude_menu').change(populate_sample_attributes_values_dropdown); + block_by_attribute_value = function() { + var attribute_name, cell_class, exclude_by_value; + attribute_name = $('#exclude_menu').val(); + exclude_by_value = $('#attribute_values').val(); + cell_class = ".column_name-" + attribute_name; + return $(cell_class).each((function(_this) { + return function(index, element) { var row; if ($.trim($(element).text()) === exclude_by_value) { row = $(element).parent('tr'); return $(row).find(".trait_value_input").val("x"); } - }); - }; - $('#exclude_group').click(block_by_attribute_value); - block_by_index = function() { - var end_index, index, index_list, index_set, index_string, start_index, _i, _j, _k, _len, _len1, _ref, _results; - index_string = $('#remove_samples_field').val(); - index_list = []; - _ref = index_string.split(","); - for (_i = 0, _len = _ref.length; _i < _len; _i++) { - index_set = _ref[_i]; - if (index_set.indexOf('-') !== -1) { - try { - start_index = parseInt(index_set.split("-")[0]); - end_index = parseInt(index_set.split("-")[1]); - for (index = _j = start_index; start_index <= end_index ? _j <= end_index : _j >= end_index; index = start_index <= end_index ? ++_j : --_j) { - index_list.push(index); - } - } catch (error) { - alert("Syntax error"); + }; + })(this)); + }; + $('#exclude_group').click(block_by_attribute_value); + block_by_index = function() { + var end_index, error, index, index_list, index_set, index_string, start_index, _i, _j, _k, _len, _len1, _ref, _results; + index_string = $('#remove_samples_field').val(); + index_list = []; + _ref = index_string.split(","); + for (_i = 0, _len = _ref.length; _i < _len; _i++) { + index_set = _ref[_i]; + if (index_set.indexOf('-') !== -1) { + try { + start_index = parseInt(index_set.split("-")[0]); + end_index = parseInt(index_set.split("-")[1]); + for (index = _j = start_index; start_index <= end_index ? _j <= end_index : _j >= end_index; index = start_index <= end_index ? ++_j : --_j) { + index_list.push(index); } - } else { - index = parseInt(index_set); - console.log("index:", index); - index_list.push(index); + } catch (_error) { + error = _error; + alert("Syntax error"); } + } else { + index = parseInt(index_set); + console.log("index:", index); + index_list.push(index); } - console.log("index_list:", index_list); - _results = []; - for (_k = 0, _len1 = index_list.length; _k < _len1; _k++) { - index = index_list[_k]; - if ($('#block_group').val() === "primary") { - console.log("block_group:", $('#block_group').val()); - console.log("row:", $('#Primary_' + index.toString())); - _results.push($('#Primary_' + index.toString()).find('.trait_value_input').val("x")); - } else if ($('#block_group').val() === "other") { - console.log("block_group:", $('#block_group').val()); - console.log("row:", $('#Other_' + index.toString())); - _results.push($('#Other_' + index.toString()).find('.trait_value_input').val("x")); - } else { - _results.push(void 0); - } + } + console.log("index_list:", index_list); + _results = []; + for (_k = 0, _len1 = index_list.length; _k < _len1; _k++) { + index = index_list[_k]; + if ($('#block_group').val() === "primary") { + console.log("block_group:", $('#block_group').val()); + console.log("row:", $('#Primary_' + index.toString())); + _results.push($('#Primary_' + index.toString()).find('.trait_value_input').val("x")); + } else if ($('#block_group').val() === "other") { + console.log("block_group:", $('#block_group').val()); + console.log("row:", $('#Other_' + index.toString())); + _results.push($('#Other_' + index.toString()).find('.trait_value_input').val("x")); + } else { + _results.push(void 0); } - return _results; - }; - $('#block_by_index').click(block_by_index); - hide_no_value = function() { - var _this = this; - return $('.value_se').each(function(_index, element) { + } + return _results; + }; + $('#block_by_index').click(block_by_index); + hide_no_value = function() { + return $('.value_se').each((function(_this) { + return function(_index, element) { if ($(element).find('.trait_value_input').val() === 'x') { return $(element).hide(); } - }); - }; - $('#hide_no_value').click(hide_no_value); - block_outliers = function() { - var _this = this; - return $('.outlier').each(function(_index, element) { + }; + })(this)); + }; + $('#hide_no_value').click(hide_no_value); + block_outliers = function() { + return $('.outlier').each((function(_this) { + return function(_index, element) { return $(element).find('.trait_value_input').val('x'); - }); - }; - $('#block_outliers').click(block_outliers); - reset_samples_table = function() { - var _this = this; - return $('.trait_value_input').each(function(_index, element) { + }; + })(this)); + }; + $('#block_outliers').click(block_outliers); + reset_samples_table = function() { + return $('.trait_value_input').each((function(_this) { + return function(_index, element) { console.log("value is:", $(element).val()); $(element).val($(element).data('value')); console.log("data-value is:", $(element).data('value')); return $(element).parents('.value_se').show(); - }); - }; - $('#reset').click(reset_samples_table); - get_sample_table_data = function() { - var other_samples, primary_samples, samples, - _this = this; - samples = {}; - primary_samples = []; - other_samples = []; - $('#sortable1').find('.value_se').each(function(_index, element) { + }; + })(this)); + }; + $('#reset').click(reset_samples_table); + get_sample_table_data = function() { + var other_samples, primary_samples, samples; + samples = {}; + primary_samples = []; + other_samples = []; + $('#sortable1').find('.value_se').each((function(_this) { + return function(_index, element) { var attribute_info, key, row_data, _ref; row_data = {}; row_data.name = $.trim($(element).find('.column_name-Sample').text()); @@ -427,39 +434,38 @@ } console.log("row_data is:", row_data); return primary_samples.push(row_data); - }); - console.log("primary_samples is:", primary_samples); - samples.primary_samples = primary_samples; - samples.other_samples = other_samples; - return samples; - }; - export_sample_table_data = function() { - var format, json_sample_data, sample_data; - sample_data = get_sample_table_data(); - console.log("sample_data is:", sample_data); - json_sample_data = JSON.stringify(sample_data); - console.log("json_sample_data is:", json_sample_data); - $('input[name=export_data]').val(json_sample_data); - console.log("export_data is", $('input[name=export_data]').val()); - format = $('#export_format').val(); - if (format === "excel") { - $('#trait_data_form').attr('action', '/export_trait_excel'); - } else { - $('#trait_data_form').attr('action', '/export_trait_csv'); - } - console.log("action is:", $('#trait_data_form').attr('action')); - return $('#trait_data_form').submit(); - }; - $('#export').click(export_sample_table_data); - console.log("before registering block_outliers"); - $('#block_outliers').click(block_outliers); - console.log("after registering block_outliers"); - _.mixin(_.str.exports()); - $('#edit_sample_lists').change(edit_data_change); - console.log("loaded"); - make_table(); - edit_data_change(); - return console.log("end"); - }); - -}).call(this); + }; + })(this)); + console.log("primary_samples is:", primary_samples); + samples.primary_samples = primary_samples; + samples.other_samples = other_samples; + return samples; + }; + export_sample_table_data = function() { + var format, json_sample_data, sample_data; + sample_data = get_sample_table_data(); + console.log("sample_data is:", sample_data); + json_sample_data = JSON.stringify(sample_data); + console.log("json_sample_data is:", json_sample_data); + $('input[name=export_data]').val(json_sample_data); + console.log("export_data is", $('input[name=export_data]').val()); + format = $('#export_format').val(); + if (format === "excel") { + $('#trait_data_form').attr('action', '/export_trait_excel'); + } else { + $('#trait_data_form').attr('action', '/export_trait_csv'); + } + console.log("action is:", $('#trait_data_form').attr('action')); + return $('#trait_data_form').submit(); + }; + $('#export').click(export_sample_table_data); + console.log("before registering block_outliers"); + $('#block_outliers').click(block_outliers); + console.log("after registering block_outliers"); + _.mixin(_.str.exports()); + $('#edit_sample_lists').change(edit_data_change); + console.log("loaded"); + make_table(); + edit_data_change(); + return console.log("end"); +}); diff --git a/wqflask/wqflask/static/new/javascript/show_trait_mapping_tools.js b/wqflask/wqflask/static/new/javascript/show_trait_mapping_tools.js index 9b9070ba..1a2ad637 100755 --- a/wqflask/wqflask/static/new/javascript/show_trait_mapping_tools.js +++ b/wqflask/wqflask/static/new/javascript/show_trait_mapping_tools.js @@ -1,52 +1,50 @@ -// Generated by CoffeeScript 1.6.1 -(function() { - var root; +// Generated by CoffeeScript 1.7.1 +var root; - root = typeof exports !== "undefined" && exports !== null ? exports : this; +root = typeof exports !== "undefined" && exports !== null ? exports : this; - $(function() { - var composite_mapping_fields, get_progress, mapping_method_fields, submit_special, toggle_enable_disable, update_time_remaining, - _this = this; - submit_special = function() { - var url; - console.log("In submit_special"); - console.log("this is:", this); - console.log("$(this) is:", $(this)); - url = $(this).data("url"); - console.log("url is:", url); - $("#trait_data_form").attr("action", url); - return $("#trait_data_form").submit(); - }; - update_time_remaining = function(percent_complete) { - var minutes_remaining, now, period, total_seconds_remaining; - now = new Date(); - period = now.getTime() - root.start_time; - console.log("period is:", period); - if (period > 8000) { - total_seconds_remaining = (period / percent_complete * (100 - percent_complete)) / 1000; - minutes_remaining = Math.round(total_seconds_remaining / 60); - if (minutes_remaining < 3) { - return $('#time_remaining').text(Math.round(total_seconds_remaining) + " seconds remaining"); - } else { - return $('#time_remaining').text(minutes_remaining + " minutes remaining"); - } +$(function() { + var composite_mapping_fields, get_progress, mapping_method_fields, submit_special, toggle_enable_disable, update_time_remaining; + submit_special = function() { + var url; + console.log("In submit_special"); + console.log("this is:", this); + console.log("$(this) is:", $(this)); + url = $(this).data("url"); + console.log("url is:", url); + $("#trait_data_form").attr("action", url); + return $("#trait_data_form").submit(); + }; + update_time_remaining = function(percent_complete) { + var minutes_remaining, now, period, total_seconds_remaining; + now = new Date(); + period = now.getTime() - root.start_time; + console.log("period is:", period); + if (period > 8000) { + total_seconds_remaining = (period / percent_complete * (100 - percent_complete)) / 1000; + minutes_remaining = Math.round(total_seconds_remaining / 60); + if (minutes_remaining < 3) { + return $('#time_remaining').text(Math.round(total_seconds_remaining) + " seconds remaining"); + } else { + return $('#time_remaining').text(minutes_remaining + " minutes remaining"); } + } + }; + get_progress = function() { + var params, params_str, temp_uuid, url; + console.log("temp_uuid:", $("#temp_uuid").val()); + temp_uuid = $("#temp_uuid").val(); + params = { + key: temp_uuid }; - get_progress = function() { - var params, params_str, temp_uuid, url, - _this = this; - console.log("temp_uuid:", $("#temp_uuid").val()); - temp_uuid = $("#temp_uuid").val(); - params = { - key: temp_uuid - }; - params_str = $.param(params); - url = "/get_temp_data?" + params_str; - console.log("url:", url); - $.ajax({ - type: "GET", - url: url, - success: function(progress_data) { + params_str = $.param(params); + url = "/get_temp_data?" + params_str; + console.log("url:", url); + $.ajax({ + type: "GET", + url: url, + success: (function(_this) { + return function(progress_data) { var percent_complete; percent_complete = progress_data['percent_complete']; console.log("in get_progress data:", progress_data); @@ -58,11 +56,13 @@ } else { return root.start_time = new Date().getTime(); } - } - }); - return false; - }; - $("#interval_mapping_compute").click(function() { + }; + })(this) + }); + return false; + }; + $("#interval_mapping_compute").click((function(_this) { + return function() { var form_data, url; console.log("In interval mapping"); $("#progress_bar_container").modal(); @@ -92,17 +92,21 @@ console.log("settingInterval"); _this.my_timer = setInterval(get_progress, 1000); return false; - }); - $('#suggestive').hide(); - $('input[name=display_all]').change(function() { + }; + })(this)); + $('#suggestive').hide(); + $('input[name=display_all]').change((function(_this) { + return function() { console.log("check"); if ($('input[name=display_all]:checked').val() === "False") { return $('#suggestive').show(); } else { return $('#suggestive').hide(); } - }); - $("#marker_regression_compute").click(function() { + }; + })(this)); + $("#marker_regression_compute").click((function(_this) { + return function() { var form_data, url; $("#progress_bar_container").modal(); url = "/marker_regression"; @@ -129,8 +133,10 @@ console.log("settingInterval"); _this.my_timer = setInterval(get_progress, 1000); return false; - }); - $("#plink_compute").click(function() { + }; + })(this)); + $("#plink_compute").click((function(_this) { + return function() { var form_data, url; $("#static_progress_bar_container").modal(); url = "/marker_regression"; @@ -160,8 +166,10 @@ console.log("settingInterval"); _this.my_timer = setInterval(get_progress, 1000); return false; - }); - $("#gemma_compute").click(function() { + }; + })(this)); + $("#gemma_compute").click((function(_this) { + return function() { var form_data, url; $("#static_progress_bar_container").modal(); url = "/marker_regression"; @@ -191,24 +199,23 @@ console.log("settingInterval"); _this.my_timer = setInterval(get_progress, 1000); return false; - }); - composite_mapping_fields = function() { - return $(".composite_fields").toggle(); }; - mapping_method_fields = function() { - return $(".mapping_method_fields").toggle(); - }; - $("#use_composite_choice").change(composite_mapping_fields); - $("#mapping_method_choice").change(mapping_method_fields); - toggle_enable_disable = function(elem) { - return $(elem).prop("disabled", !$(elem).prop("disabled")); - }; - $("#choose_closet_control").change(function() { - return toggle_enable_disable("#control_locus"); - }); - return $("#display_all_lrs").change(function() { - return toggle_enable_disable("#suggestive_lrs"); - }); + })(this)); + composite_mapping_fields = function() { + return $(".composite_fields").toggle(); + }; + mapping_method_fields = function() { + return $(".mapping_method_fields").toggle(); + }; + $("#use_composite_choice").change(composite_mapping_fields); + $("#mapping_method_choice").change(mapping_method_fields); + toggle_enable_disable = function(elem) { + return $(elem).prop("disabled", !$(elem).prop("disabled")); + }; + $("#choose_closet_control").change(function() { + return toggle_enable_disable("#control_locus"); }); - -}).call(this); + return $("#display_all_lrs").change(function() { + return toggle_enable_disable("#suggestive_lrs"); + }); +}); diff --git a/wqflask/wqflask/static/new/javascript/stats.js b/wqflask/wqflask/static/new/javascript/stats.js index d874995f..6f67fcbe 100755 --- a/wqflask/wqflask/static/new/javascript/stats.js +++ b/wqflask/wqflask/static/new/javascript/stats.js @@ -1,110 +1,106 @@ -// Generated by CoffeeScript 1.6.1 -(function() { - var Stats, bxd_only; +// Generated by CoffeeScript 1.7.1 +var Stats, bxd_only; + +Stats = (function() { + function Stats(the_values) { + this.the_values = the_values; + } + + Stats.prototype.add_value = function(value) { + return this.the_values.push(value); + }; + + Stats.prototype.n_of_samples = function() { + return this.the_values.length; + }; + + Stats.prototype.sum = function() { + var total, value, _i, _len, _ref; + total = 0; + _ref = this.the_values; + for (_i = 0, _len = _ref.length; _i < _len; _i++) { + value = _ref[_i]; + total += value; + } + return total; + }; + + Stats.prototype.mean = function() { + return this.sum() / this.n_of_samples(); + }; + + Stats.prototype.median = function() { + var is_odd, median_position, the_values_sorted; + is_odd = this.the_values.length % 2; + median_position = Math.floor(this.the_values.length / 2); + the_values_sorted = this.the_values.sort(function(a, b) { + return a - b; + }); + if (is_odd) { + return the_values_sorted[median_position]; + } else { + return (the_values_sorted[median_position] + the_values_sorted[median_position - 1]) / 2; + } + }; + + Stats.prototype.std_dev = function() { + var step_a, step_b, sum, value, _i, _len, _ref; + sum = 0; + _ref = this.the_values; + for (_i = 0, _len = _ref.length; _i < _len; _i++) { + value = _ref[_i]; + step_a = Math.pow(value - this.mean(), 2); + sum += step_a; + } + step_b = sum / this.the_values.length; + return Math.sqrt(step_b); + }; - Stats = (function() { + Stats.prototype.std_error = function() { + return this.std_dev() / Math.sqrt(this.n_of_samples()); + }; - function Stats(the_values) { - this.the_values = the_values; - } + Stats.prototype.min = function() { + return Math.min.apply(Math, this.the_values); + }; + + Stats.prototype.max = function() { + return Math.max.apply(Math, this.the_values); + }; + + Stats.prototype.range = function() { + return this.max() - this.min(); + }; + + Stats.prototype.range_fold = function() { + return Math.pow(2, this.range()); + }; + + Stats.prototype.interquartile = function() { + var iq, length, q1, q3; + length = this.the_values.length; + console.log("in interquartile the_values are:", this.the_values); + console.log("length is:", length); + q1 = this.the_values[Math.floor(length * .25)]; + q3 = this.the_values[Math.floor(length * .75)]; + iq = q3 - q1; + return Math.pow(2, iq); + }; + + return Stats; + +})(); + +bxd_only = new Stats([3, 5, 7, 8]); + +console.log("[xred] bxd_only mean:", bxd_only.mean()); + +console.log("[xgreen] bxd_only median:", bxd_only.median()); + +console.log("[xpurple] bxd_only std_dev:", bxd_only.std_dev()); + +console.log("[xmagenta] bxd_only std_error:", bxd_only.std_error()); + +console.log("[xyellow] bxd_only min:", bxd_only.min()); - Stats.prototype.add_value = function(value) { - return this.the_values.push(value); - }; - - Stats.prototype.n_of_samples = function() { - return this.the_values.length; - }; - - Stats.prototype.sum = function() { - var total, value, _i, _len, _ref; - total = 0; - _ref = this.the_values; - for (_i = 0, _len = _ref.length; _i < _len; _i++) { - value = _ref[_i]; - total += value; - } - return total; - }; - - Stats.prototype.mean = function() { - return this.sum() / this.n_of_samples(); - }; - - Stats.prototype.median = function() { - var is_odd, median_position, the_values_sorted; - is_odd = this.the_values.length % 2; - median_position = Math.floor(this.the_values.length / 2); - the_values_sorted = this.the_values.sort(function(a, b) { - return a - b; - }); - if (is_odd) { - return the_values_sorted[median_position]; - } else { - return (the_values_sorted[median_position] + the_values_sorted[median_position - 1]) / 2; - } - }; - - Stats.prototype.std_dev = function() { - var step_a, step_b, sum, value, _i, _len, _ref; - sum = 0; - _ref = this.the_values; - for (_i = 0, _len = _ref.length; _i < _len; _i++) { - value = _ref[_i]; - step_a = Math.pow(value - this.mean(), 2); - sum += step_a; - } - step_b = sum / this.the_values.length; - return Math.sqrt(step_b); - }; - - Stats.prototype.std_error = function() { - return this.std_dev() / Math.sqrt(this.n_of_samples()); - }; - - Stats.prototype.min = function() { - return Math.min.apply(Math, this.the_values); - }; - - Stats.prototype.max = function() { - return Math.max.apply(Math, this.the_values); - }; - - Stats.prototype.range = function() { - return this.max() - this.min(); - }; - - Stats.prototype.range_fold = function() { - return Math.pow(2, this.range()); - }; - - Stats.prototype.interquartile = function() { - var iq, length, q1, q3; - length = this.the_values.length; - console.log("in interquartile the_values are:", this.the_values); - console.log("length is:", length); - q1 = this.the_values[Math.floor(length * .25)]; - q3 = this.the_values[Math.floor(length * .75)]; - iq = q3 - q1; - return Math.pow(2, iq); - }; - - return Stats; - - })(); - - bxd_only = new Stats([3, 5, 7, 8]); - - console.log("[xred] bxd_only mean:", bxd_only.mean()); - - console.log("[xgreen] bxd_only median:", bxd_only.median()); - - console.log("[xpurple] bxd_only std_dev:", bxd_only.std_dev()); - - console.log("[xmagenta] bxd_only std_error:", bxd_only.std_error()); - - console.log("[xyellow] bxd_only min:", bxd_only.min()); - - window.Stats = Stats; - -}).call(this); +window.Stats = Stats; diff --git a/wqflask/wqflask/static/new/javascript/thank_you.js b/wqflask/wqflask/static/new/javascript/thank_you.js index bffff179..c0a4f34b 100755 --- a/wqflask/wqflask/static/new/javascript/thank_you.js +++ b/wqflask/wqflask/static/new/javascript/thank_you.js @@ -1,10 +1,6 @@ -// Generated by CoffeeScript 1.6.1 -(function() { - - $(function() { - console.log("Starting transform"); - $('#login_out').text('Sign out').attr('href', '/logout').removeClass('modalize'); - return console.log("Transformed to sign out I hope"); - }); - -}).call(this); +// Generated by CoffeeScript 1.7.1 +$(function() { + console.log("Starting transform"); + $('#login_out').text('Sign out').attr('href', '/logout').removeClass('modalize'); + return console.log("Transformed to sign out I hope"); +}); diff --git a/wqflask/wqflask/static/new/javascript/validation.js b/wqflask/wqflask/static/new/javascript/validation.js index 275bcaa0..9536491b 100755 --- a/wqflask/wqflask/static/new/javascript/validation.js +++ b/wqflask/wqflask/static/new/javascript/validation.js @@ -1,51 +1,47 @@ -// Generated by CoffeeScript 1.6.1 -(function() { - - $(function() { - var remove_samples_is_valid, validate_remove_samples; - remove_samples_is_valid = function(input) { - var new_splats, pattern, splat, splats, _i, _len; - if (_.trim(input).length === 0) { - return true; - } - splats = input.split(","); - new_splats = (function() { - var _i, _len, _results; - _results = []; - for (_i = 0, _len = splats.length; _i < _len; _i++) { - input = splats[_i]; - _results.push(_.trim(input)); - } - return _results; - })(); - console.log("new_splats:", new_splats); - pattern = /^\d+\s*(?:-\s*\d+)?\s*$/; - for (_i = 0, _len = new_splats.length; _i < _len; _i++) { - splat = new_splats[_i]; - console.log("splat is:", splat); - if (!splat.match(pattern)) { - return false; - } - } +// Generated by CoffeeScript 1.7.1 +$(function() { + var remove_samples_is_valid, validate_remove_samples; + remove_samples_is_valid = function(input) { + var new_splats, pattern, splat, splats, _i, _len; + if (_.trim(input).length === 0) { return true; - }; - validate_remove_samples = function() { - /* - Check if input for the remove samples function is valid and notify the user if not - */ - - var input; - input = $('#remove_samples_field').val(); - console.log("input is:", input); - if (remove_samples_is_valid(input)) { - console.log("input is valid"); - return $('#remove_samples_invalid').hide(); - } else { - console.log("input isn't valid"); - return $('#remove_samples_invalid').show(); + } + splats = input.split(","); + new_splats = (function() { + var _i, _len, _results; + _results = []; + for (_i = 0, _len = splats.length; _i < _len; _i++) { + input = splats[_i]; + _results.push(_.trim(input)); + } + return _results; + })(); + console.log("new_splats:", new_splats); + pattern = /^\d+\s*(?:-\s*\d+)?\s*$/; + for (_i = 0, _len = new_splats.length; _i < _len; _i++) { + splat = new_splats[_i]; + console.log("splat is:", splat); + if (!splat.match(pattern)) { + return false; } - }; - return $('#remove_samples_field').change(validate_remove_samples); - }); + } + return true; + }; + validate_remove_samples = function() { -}).call(this); + /* + Check if input for the remove samples function is valid and notify the user if not + */ + var input; + input = $('#remove_samples_field').val(); + console.log("input is:", input); + if (remove_samples_is_valid(input)) { + console.log("input is valid"); + return $('#remove_samples_invalid').hide(); + } else { + console.log("input isn't valid"); + return $('#remove_samples_invalid').show(); + } + }; + return $('#remove_samples_field').change(validate_remove_samples); +}); diff --git a/wqflask/wqflask/templates/interval_mapping.html b/wqflask/wqflask/templates/interval_mapping.html index ad174b7b..25ee22ac 100755 --- a/wqflask/wqflask/templates/interval_mapping.html +++ b/wqflask/wqflask/templates/interval_mapping.html @@ -5,6 +5,7 @@ + {% endblock %} @@ -18,9 +19,16 @@

Whole Genome Mapping

+
+ + + +
-
- +
+
+ +

@@ -32,12 +40,10 @@ Index LRS Score - {% if method == "qtl_reaper" %} - Additive Effect - {% endif %} Chr Mb Locus + Additive Effect @@ -45,12 +51,10 @@ {{ loop.index }} {{ marker.lrs_value|float }} - {% if method == "qtl_reaper" %} - {{ marker.additive|float }} - {% endif %} {{ marker.chr|int }} {{ marker.Mb|float }} {{ marker.name }} + {{ marker.additive|float }} {% endfor %} @@ -73,8 +77,9 @@ + - + diff --git a/wqflask/wqflask/templates/marker_regression.html b/wqflask/wqflask/templates/marker_regression.html index defcd929..3dce5266 100755 --- a/wqflask/wqflask/templates/marker_regression.html +++ b/wqflask/wqflask/templates/marker_regression.html @@ -1,106 +1,121 @@ -{% extends "base.html" %} -{% block title %}Marker Regression{% endblock %} -{% block css %} - - - - - -{% endblock %} -{% block content %} - - {{ header("Marker Regression", - '{}: {}'.format(this_trait.name, this_trait.description_fmt)) }} - -
-
-

- Manhattan Plot -

-
-
-
- -
-
-
-

- Genome Association Results -

-
- - - - - - - - - - - - - {% for marker in filtered_markers %} - {% if marker.lod_score > lod_cutoff %} - - - - - - - - {% endif %} - {% endfor %} - -
IndexLOD ScoreChrMbLocus
{{loop.index}}{{marker.lod_score}}{{marker.chr}}{{marker.Mb}}{{marker.name}}
-
- - - -{% endblock %} - -{% block js %} - - - - - - - - - - - - - - - +{% extends "base.html" %} +{% block title %}Interval Mapping{% endblock %} +{% block css %} + + + + + + +{% endblock %} +{% block content %} + + {{ header("Mapping", + '{}: {}'.format(this_trait.name, this_trait.description_fmt)) }} + +
+
+

+ Whole Genome Mapping +

+
+ + + +
+ +
+
+
+ +
+
+
+

+ Results +

+
+ + + + + + + + + + + + {% for marker in filtered_markers %} + {% if marker.lod_score > lod_cutoff %} + + + + + + + + {% endif %} + {% endfor %} + +
IndexLOD ScoreChrMbLocus
{{loop.index}}{{marker.lod_score}}{{marker.chr}}{{marker.Mb}}{{marker.name}}
+ +
+ + + +{% endblock %} + +{% block js %} + + + + + + + + + + + + + + + + + + + {% endblock %} \ No newline at end of file diff --git a/wqflask/wqflask/templates/show_trait.html b/wqflask/wqflask/templates/show_trait.html index ae4adf25..f20d66ed 100755 --- a/wqflask/wqflask/templates/show_trait.html +++ b/wqflask/wqflask/templates/show_trait.html @@ -2,7 +2,6 @@ {% block title %}Trait Data and Analysis{% endblock %} {% block css %} - diff --git a/wqflask/wqflask/templates/show_trait_mapping_tools.html b/wqflask/wqflask/templates/show_trait_mapping_tools.html index 07f33d28..f8542c78 100755 --- a/wqflask/wqflask/templates/show_trait_mapping_tools.html +++ b/wqflask/wqflask/templates/show_trait_mapping_tools.html @@ -9,12 +9,14 @@
  • pyLMM
  • + {% if dataset.group.species == 'human' %}
  • PLINK
  • GEMMA
  • + {% endif %} @@ -22,7 +24,7 @@
    -
    +
    @@ -75,7 +77,7 @@
    -
    +
    @@ -149,7 +151,7 @@
    -