From 34b0cc3a931e266b6382c961d6321ccc9b3ac430 Mon Sep 17 00:00:00 2001 From: Zachary Sloan Date: Tue, 8 Jan 2013 17:16:45 -0600 Subject: Created IndChromosome class in species.py and wrote functions for chromosome-related attributes Began to try and pass qtlreaper results as js_data to use when drawing graphs --- wqflask/base/species.py | 83 +++++++++++++++++----- .../wqflask/marker_regression/marker_regression.py | 81 +++++++++++---------- wqflask/wqflask/views.py | 11 +-- 3 files changed, 119 insertions(+), 56 deletions(-) diff --git a/wqflask/base/species.py b/wqflask/base/species.py index 85f076ca..9d4cac4c 100644 --- a/wqflask/base/species.py +++ b/wqflask/base/species.py @@ -6,14 +6,17 @@ from flask import Flask, g #from MySQLdb import escape_string as escape +from utility import Bunch + from pprint import pformat as pf class TheSpecies(object): def __init__(self, dataset): self.dataset = dataset print("self.dataset is:", pf(self.dataset.__dict__)) - self.chromosomes = Chromosomes(self.dataset.group.name) - self.genome_length = self.chromosomes.get_genome_length() + self.chromosomes = Chromosomes(self.dataset) + self.genome_mb_length = self.chromosomes.get_genome_mb_length() + #@property #def chromosomes(self): @@ -27,10 +30,22 @@ class TheSpecies(object): # # return chromosomes +class IndChromosome(object): + def __init__(self, length): + self.length = length + + @property + def mb_length(self): + """Chromosome length in megabases""" + return self.length / 1000000 + + def set_cm_length(self, genofile_chr): + self.cm_length = genofile_chr[-1].cM - genofile_chr[0].cM class Chromosomes(object): - def __init__(self, group_name): + def __init__(self, dataset): + self.dataset = dataset self.chromosomes = collections.OrderedDict() results = g.db.execute(""" @@ -40,27 +55,63 @@ class Chromosomes(object): Chr_Length.SpeciesId = InbredSet.SpeciesId AND InbredSet.Name = %s Order by OrderId - """, group_name).fetchall() + """, self.dataset.group.name).fetchall() print("bike:", results) for item in results: - self.chromosomes[item.Name] = item.Length + self.chromosomes[item.Name] = IndChromosome(item.Length) + + self.set_mb_graph_interval() + self.get_cm_length_list() + + + def set_mb_graph_interval(self): + """Empirical megabase interval""" + + #if self.chromosomes: + assert self.chromosomes, "Have to add some code back in apparently to set it to 1" + self.mb_graph_interval = self.get_genome_mb_length()/(len(self.chromosomes)*12) + #else: + #self.mb_graph_interval = 1 - print("self.chromosomes:", self.chromosomes) + def get_genome_mb_length(self): + """Gets the sum of each chromosome's length in megabases""" - def get_mb_length(self): - """Gets the chromosome length in megabases""" + return sum([ind_chromosome.mb_length for ind_chromosome in self.chromosomes.values()]) - mb_lengths = chr_length/1000000.0 for name, chr_length in self.chromosomes - return mb_lengths + def get_genome_cm_length(self): + """Gets the sum of each chromosome's length in centimorgans""" - def get_genome_length(self): - """Gets the sum of each chromosome's length""" + return sum([ind_chromosome.cm_length for ind_chromosome in self.chromosomes.values()]) - genome_length = 0 - for name, value in self.chromosomes.items(): - genome_length += value + def get_cm_length_list(self): + """Chromosome length in centimorgans + + Calculates the length in centimorgans by subtracting the centimorgan position + of the last marker in a chromosome by the position of the first marker + + """ + + self.dataset.group.read_genotype_file() + + self.cm_length_list = [] + + for chromosome in self.dataset.group.genotype: + self.cm_length_list.append(chromosome[-1].cM - chromosome[0].cM) + + print("self.cm_length_list:", pf(self.cm_length_list)) + + assert len(self.cm_length_list) == len(self.chromosomes), "Uh-oh lengths should be equal!" + for counter, chromosome in enumerate(self.chromosomes.values()): + chromosome.cm_length = self.cm_length_list[counter] + #self.chromosomes[counter].cm_length = item + + for key, value in self.chromosomes.items(): + print("bread - %s: %s" % (key, pf(vars(value)))) + - return genome_length \ No newline at end of file +# Testing +#if __name__ == '__main__': +# foo = dict(bar=dict(length)) \ No newline at end of file diff --git a/wqflask/wqflask/marker_regression/marker_regression.py b/wqflask/wqflask/marker_regression/marker_regression.py index 0aad4e54..73f1246f 100755 --- a/wqflask/wqflask/marker_regression/marker_regression.py +++ b/wqflask/wqflask/marker_regression/marker_regression.py @@ -256,54 +256,58 @@ class MarkerRegression(object): #for i, indChr in enumerate(self.genotype): # self.ChrList.append((indChr.name, i)) - self.cursor.execute(""" - Select - Length from Chr_Length, InbredSet - where - Chr_Length.SpeciesId = InbredSet.SpeciesId AND - InbredSet.Name = '%s' AND - Chr_Length.Name in (%s) - Order by - OrderId - """ % (fd.RISet, string.join(map(lambda X: "'%s'" % X[0], self.ChrList[1:]), ", "))) - - self.ChrLengthMbList = self.cursor.fetchall() - self.ChrLengthMbList = map(lambda x: x[0]/1000000.0, self.ChrLengthMbList) - self.ChrLengthMbSum = reduce(lambda x, y:x+y, self.ChrLengthMbList, 0.0) - if self.ChrLengthMbList: - self.MbGraphInterval = self.ChrLengthMbSum/(len(self.ChrLengthMbList)*12) #Empirical Mb interval - else: - self.MbGraphInterval = 1 - - self.ChrLengthCMList = [] - for i, _chr in enumerate(self.genotype): - self.ChrLengthCMList.append(_chr[-1].cM - _chr[0].cM) - self.ChrLengthCMSum = reduce(lambda x, y:x+y, self.ChrLengthCMList, 0.0)# used for calculate plot scale + #self.cursor.execute(""" + # Select + # Length from Chr_Length, InbredSet + # where + # Chr_Length.SpeciesId = InbredSet.SpeciesId AND + # InbredSet.Name = '%s' AND + # Chr_Length.Name in (%s) + # Order by + # OrderId + # """ % (fd.RISet, string.join(map(lambda X: "'%s'" % X[0], self.ChrList[1:]), ", "))) + # + #self.ChrLengthMbList = self.cursor.fetchall() + #self.ChrLengthMbList = map(lambda x: x[0]/1000000.0, self.ChrLengthMbList) + #self.ChrLengthMbSum = reduce(lambda x, y:x+y, self.ChrLengthMbList, 0.0) + #if self.ChrLengthMbList: + # self.MbGraphInterval = self.ChrLengthMbSum/(len(self.ChrLengthMbList)*12) #Empirical Mb interval + #else: + # self.MbGraphInterval = 1 + # + #self.ChrLengthCMList = [] + #for i, _chr in enumerate(self.genotype): + # self.ChrLengthCMList.append(_chr[-1].cM - _chr[0].cM) + #self.ChrLengthCMSum = reduce(lambda x, y:x+y, self.ChrLengthCMList, 0.0)# used for calculate plot scale - self.GraphInterval = self.MbGraphInterval #Mb + #self.GraphInterval = self.MbGraphInterval #Mb # begin: common part with human data - intCanvas = pid.PILCanvas(size=(self.graphWidth,self.graphHeight)) - gifmap = self.plotIntMapping(fd, intCanvas, startMb = self.startMb, endMb = self.endMb, showLocusForm= "") - filename= webqtlUtil.genRandStr("Itvl_") - intCanvas.save(os.path.join(webqtlConfig.IMGDIR, filename), format='png') - intImg=HT.Image('/image/'+filename+'.png', border=0, usemap='#WebQTLImageMap') + #intCanvas = pid.PILCanvas(size=(self.graphWidth,self.graphHeight)) + #gifmap = self.plotIntMapping(fd, intCanvas, startMb = self.startMb, endMb = self.endMb, showLocusForm= "") + #filename= webqtlUtil.genRandStr("Itvl_") + #intCanvas.save(os.path.join(webqtlConfig.IMGDIR, filename), format='png') + #intImg=HT.Image('/image/'+filename+'.png', border=0, usemap='#WebQTLImageMap') ################################################################ # footnote goes here ################################################################ - btminfo = HT.Paragraph(Id="smallsize") #Small('More information about this graph is available here.') - - if (self.additiveChecked): - btminfo.append(HT.BR(), 'A positive additive coefficient (', HT.Font('green', color='green'), ' line) indicates that %s alleles increase trait values. In contrast, a negative additive coefficient (' % fd.ppolar, HT.Font('red', color='red'), ' line) indicates that %s alleles increase trait values.' % fd.mpolar) + #btminfo = HT.Paragraph(Id="smallsize") #Small('More information about this graph is available here.') + #if (self.additiveChecked): + # btminfo.append(HT.BR(), 'A positive additive coefficient (', HT.Font('green', color='green'), ' line) indicates that %s alleles increase trait values. In contrast, a negative additive coefficient (' % fd.ppolar, HT.Font('red', color='red'), ' line) indicates that %s alleles increase trait values.' % fd.mpolar) - TD_LR = HT.TR(HT.TD(HT.Blockquote(gifmap,intImg, HT.P()), bgColor='#eeeeee', height = 200)) - self.dict['body'] = str(datadiv)+str(TD_LR)+str(resultstable)+str(HT.TR(HT.TD(descriptionTable))) + #TD_LR = HT.TR(HT.TD(HT.Blockquote(gifmap,intImg, HT.P()), bgColor='#eeeeee', height = 200)) + # + #self.dict['body'] = str(datadiv)+str(TD_LR)+str(resultstable)+str(HT.TR(HT.TD(descriptionTable))) # end: common part with human data - + + self.js_data = dict( + qtl_results = self.pure_qtl_results, + #lrs_array = vars(self.lrs_array), + ) @@ -467,7 +471,12 @@ class MarkerRegression(object): filtered_results = self.qtl_results else: suggestive_results = [] + self.pure_qtl_results = [] for result in self.qtl_results: + self.pure_qtl_results.append(dict(locus=dict(cM=result.locus.cM, + chromosome=result.locus.chr), + lrs=result.lrs, + additive=result.additive)) if result.lrs > self.lrs_thresholds.suggestive: suggestive_results.append(result) filtered_results = suggestive_results diff --git a/wqflask/wqflask/views.py b/wqflask/wqflask/views.py index f6c0dfb0..fc628d77 100644 --- a/wqflask/wqflask/views.py +++ b/wqflask/wqflask/views.py @@ -151,10 +151,10 @@ def show_trait_page(): def marker_regression_page(): template_vars = marker_regression.MarkerRegression(request.form) #print("js_data before dump:", template_vars.js_data) - #template_vars.js_data = json.dumps(template_vars.js_data, - # default=json_default_handler, - # indent=" ") - #print("js_data after dump:", template_vars.js_data) + template_vars.js_data = json.dumps(template_vars.js_data, + default=json_default_handler, + indent=" ") + print("[dub] js_data after dump:", template_vars.js_data) print("marker_regression template_vars:", pf(template_vars.__dict__)) return render_template("marker_regression.html", **template_vars.__dict__) @@ -190,6 +190,9 @@ def json_default_handler(obj): # Handle custom objects if hasattr(obj, '__dict__'): return obj.__dict__ + #elif type(obj) == "Dataset": + # print("Not going to serialize Dataset") + # return None else: raise TypeError, 'Object of type %s with value of %s is not JSON serializable' % ( type(obj), repr(obj)) -- cgit v1.2.3