comparison rank_pathways_pct.py @ 22:95a05c1ef5d5

update to devshed revision aaece207bd01
author Richard Burhans <burhans@bx.psu.edu>
date Mon, 11 Mar 2013 11:28:06 -0400
parents
children 8997f2ca8c7a
comparison
equal deleted inserted replaced
21:d6b961721037 22:95a05c1ef5d5
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3 #
4 # calcfreq.py
5 #
6 # Copyright 2011 Oscar Bedoya-Reina <oscar@niska.bx.psu.edu>
7 #
8 # This program is free software; you can redistribute it and/or modify
9 # it under the terms of the GNU General Public License as published by
10 # the Free Software Foundation; either version 2 of the License, or
11 # (at your option) any later version.
12 #
13 # This program is distributed in the hope that it will be useful,
14 # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 # GNU General Public License for more details.
17 #
18 # You should have received a copy of the GNU General Public License
19 # along with this program; if not, write to the Free Software
20 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
21 # MA 02110-1301, USA.
22
23 import argparse,os,sys
24 from decimal import Decimal,getcontext
25 from LocationFile import LocationFile
26 from fisher import pvalue
27
28 #method to rank the the pthways by mut. freq.
29 def rankd(ltfreqs):
30 ordvals=sorted(ltfreqs)#sort and reverse freqs.
31 #~
32 outrnk=[]
33 tmpFreq0,tmpCount,pval,tmpPthw=ordvals.pop()#the highest possible value
34 crank=1
35 outrnk.append('\t'.join([str(tmpCount),str(tmpFreq0),str(crank),str(pval),tmpPthw]))
36 totalnvals=len(ordvals)
37 cnt=0
38 while totalnvals>cnt:
39 cnt+=1
40 tmpFreq,tmpCount,pval,tmpPthw=ordvals.pop()
41 if tmpFreq!=tmpFreq0:
42 crank=len(outrnk)+1
43 tmpFreq0=tmpFreq
44 outrnk.append('\t'.join([str(tmpCount),str(tmpFreq),str(crank),str(pval),tmpPthw]))
45 return outrnk
46
47
48 def main():
49 parser = argparse.ArgumentParser(description='Obtain KEGG images from a list of genes.')
50 parser.add_argument('--input',metavar='input TXT file',type=str,help='the input file with the table in txt format')
51 parser.add_argument('--output',metavar='output TXT file',type=str,help='the output file with the table in txt format. Column 1 is the count of genes in the list, Column 2 is the percentage of the pathway genes present on the list. Column 3 is the rank based on column 2')
52 parser.add_argument('--posKEGGclmn',metavar='column number',type=int,help='the column with the KEGG pathway code/name')
53 parser.add_argument('--KEGGgeneposcolmn',metavar='column number',type=int,help='column with the KEGG gene code')
54 parser.add_argument('--loc_file',metavar='location file',type=str,help='location file')
55 parser.add_argument('--species',metavar='species',type=str,help='species')
56 #~Open arguments
57 class C(object):
58 pass
59 fulargs=C()
60 parser.parse_args(sys.argv[1:],namespace=fulargs)
61 #test input vars
62 inputf,outputf,posKEGGclmn,Kgeneposcolmn=fulargs.input,fulargs.output,fulargs.posKEGGclmn,fulargs.KEGGgeneposcolmn
63 locf,species=fulargs.loc_file,fulargs.species
64 #make a dictionary of valid genes
65 posKEGGclmn-=1
66 Kgeneposcolmn-=1
67 dKEGGcPthws=dict([(x.split('\t')[Kgeneposcolmn],set(x.split('\t')[posKEGGclmn].split('.'))) for x in open(inputf).read().splitlines()[1:] if x.split('\t')[posKEGGclmn] not in set(['U','N'])])
68 for u in ['U','N']:
69 try:
70 a=dKEGGcPthws.pop(u)
71 except:
72 pass
73 getcontext().prec=2#set 2 decimal places
74 sdGenes=set([x for x in dKEGGcPthws.keys() if x.find('.')>-1])
75 while True:#to correct names with more than one gene
76 try:
77 mgenes=sdGenes.pop()
78 pthwsAssotd=dKEGGcPthws.pop(mgenes)
79 mgenes=mgenes.split('.')
80 for eachg in mgenes:
81 dKEGGcPthws[eachg]=pthwsAssotd
82 except:
83 break
84 #~ Count genes
85
86 location_file = LocationFile(locf)
87 prefix, kxml_dir_path, dict_file = location_file.get_values(species)
88 dPthContsTotls = {}
89 try:
90 with open(dict_file) as fh:
91 for line in fh:
92 line = line.rstrip('\r\n')
93 value, key = line.split('\t')
94 dPthContsTotls[key] = int(value)
95 except IOError, err:
96 print >> sys.stderr, 'Error opening dict file {0}: {1}'.format(dict_file, err.strerror)
97 sys.exit(1)
98
99 dPthContsTmp=dict([(x,0) for x in dPthContsTotls.keys()])#create a list of genes
100 sdGenes=set(dKEGGcPthws.keys())#list of all genes
101 cntGens=0
102 ltGens=len(sdGenes)
103 while cntGens<ltGens:
104 cGen=sdGenes.pop()
105 sKEGGcPthws=dKEGGcPthws.pop(cGen)
106 for eachP in sKEGGcPthws:
107 if eachP!='N':
108 if eachP in dPthContsTmp:
109 dPthContsTmp[eachP]+=1
110 else:
111 print >> sys.stderr, "Error: pathway not found in database: '{0}'".format(eachP)
112 sys.exit(1)
113 cntGens+=1
114 #~ Calculate Freqs.
115 ltfreqs=[]
116 cntAllKEGGinGnm=sum(dPthContsTotls.values())
117 cntListKEGGinGnm=sum(dPthContsTmp.values())
118 cntAllKEGGNOTinGnm=cntAllKEGGinGnm-cntListKEGGinGnm
119 for pthw in dPthContsTotls:
120 cntAllKEGGinpthw=Decimal(dPthContsTotls[pthw])
121 try:
122 cntListKEGGinpthw=Decimal(dPthContsTmp[pthw])
123 except:
124 cntListKEGGinpthw=Decimal('0')
125 cntAllKEGGNOTinpthw=cntAllKEGGinpthw-cntListKEGGinpthw
126 pval=pvalue(cntListKEGGinpthw,cntAllKEGGNOTinpthw,cntListKEGGinGnm,cntAllKEGGNOTinGnm)
127
128 ltfreqs.append([(cntListKEGGinpthw/cntAllKEGGinpthw),cntListKEGGinpthw,Decimal(str(pval.two_tail))*1,pthw])
129 #~ ltfreqs=[((Decimal(dPthContsTmp[x])/Decimal(dPthContsTotls[x])),Decimal(dPthContsTmp[x]),x) for x in dPthContsTotls]
130 tabllfreqs='\n'.join(rankd(ltfreqs))
131 salef=open(outputf,'w')
132 salef.write(tabllfreqs)
133 salef.close()
134 return 0
135
136
137 if __name__ == '__main__':
138 main()