65
|
1 #!/usr/bin/env python
|
|
2 # encoding: utf-8
|
|
3 '''
|
|
4 DNASampleSplitter -- shortdesc
|
|
5
|
|
6 DNASampleSplitter is a description
|
|
7
|
|
8 It defines classes_and_methods
|
|
9
|
76
|
10 @author: John Carlos Ignacio, Milcah Kigoni, Yaw Nti-Addae
|
65
|
11
|
|
12 @copyright: 2017 Cornell University. All rights reserved.
|
|
13
|
|
14 @license: MIT License
|
|
15
|
|
16 @contact: yn259@cornell.edu
|
|
17 @deffield updated: Updated
|
|
18 '''
|
|
19
|
|
20 import sys
|
|
21 import os
|
|
22 import math
|
|
23 import pandas as pd
|
76
|
24 import tempfile
|
65
|
25
|
|
26 from optparse import OptionParser
|
|
27 from __builtin__ import str
|
|
28 from subprocess import call
|
|
29
|
|
30 __all__ = []
|
76
|
31 __version__ = 0.2
|
65
|
32 __date__ = '2017-06-20'
|
76
|
33 __updated__ = '2017-06-27'
|
65
|
34
|
|
35 DEBUG = 1
|
|
36 TESTRUN = 0
|
|
37 PROFILE = 0
|
|
38
|
|
39 parents = {}
|
|
40
|
76
|
41 samplefiles = {}
|
|
42 genotypefiles = {}
|
|
43
|
|
44 def splitfile(my_file, sample_data, isSample):
|
|
45 temp_parents = parents
|
65
|
46 header = ''
|
|
47 fj_header = ''
|
|
48 with open(my_file) as infile:
|
|
49 for line in infile:
|
|
50 if line[:2] == '# ':
|
|
51 fj_header += line
|
|
52 elif header == '':
|
|
53 if fj_header == '':
|
|
54 fj_header = '# fjFile = PHENOTYPE\n'
|
|
55 header_list = line.split('\t')
|
|
56 if header_list[0] != '':
|
|
57 header_list[0] = ''
|
|
58 line = "\t".join(header_list)
|
|
59 header = fj_header+line
|
|
60 else:
|
|
61 lst = line.split('\t')
|
|
62 dnarun = lst[0]
|
|
63 dnarun_data = sample_data[sample_data.dnarun_name == dnarun]
|
|
64 group = list(dnarun_data.dnasample_sample_group)[0]
|
|
65 cycle = list(dnarun_data.dnasample_sample_group_cycle)[0]
|
|
66
|
|
67 isParent = False
|
76
|
68 for key in temp_parents:
|
|
69 value = temp_parents[key]
|
65
|
70 if dnarun in value:
|
76
|
71 name = my_file + "_" + key
|
|
72 if isSample:
|
|
73 continue
|
|
74 if name not in samplefiles:
|
|
75 filename = tempfile.NamedTemporaryFile(delete=False).name
|
|
76 print("sample file %s has filename %s" % (name, filename))
|
|
77 samplefiles[name] = filename
|
65
|
78 f = open(filename, "w")
|
|
79 f.write('%s' % header)
|
|
80 else:
|
76
|
81 filename = samplefiles.get(name)
|
65
|
82 f=open(filename, "a+")
|
76
|
83 f.write('%s' % line)
|
65
|
84 isParent = True
|
|
85
|
|
86 if isParent:
|
|
87 continue
|
|
88
|
|
89 if isinstance(group, float) and math.isnan(group):
|
|
90 continue
|
76
|
91 elif isSample == 1:
|
65
|
92 # get parent data #
|
|
93
|
76
|
94 filename = tempfile.NamedTemporaryFile(delete=False).name
|
65
|
95 # get file name for genotype data
|
|
96 if isinstance(cycle, float) and math.isnan(cycle):
|
76
|
97 # save genotype data to file
|
|
98 if my_file + "_" + group not in genotypefiles:
|
|
99 genotypefiles[my_file + "_" + group] = filename
|
|
100 print("genotype file %s has filename %s" % (my_file + "_" + group, filename))
|
|
101 f = open(filename, "w")
|
|
102 f.write('%s' % header)
|
|
103 else :
|
|
104 f=open(filename, "a+")
|
|
105 f.write('%s' % line)
|
65
|
106 else:
|
76
|
107 # save genotype data to file
|
|
108 if group not in genotypefiles:
|
|
109 genotypefiles[my_file + "_" + group+'_'+cycle] = filename
|
|
110 f = open(filename, "w")
|
|
111 f.write('%s' % header)
|
|
112 else :
|
|
113 f=open(filename, "a+")
|
|
114 f.write('%s' % line)
|
65
|
115
|
76
|
116
|
|
117
|
65
|
118 def splitData(samplefile, genofile):
|
|
119 # Split sample file #
|
|
120 sample_data = pd.read_table(samplefile, dtype='str')
|
|
121 group_list = sample_data.dnasample_sample_group.drop_duplicates()
|
|
122 for index, item in group_list.iteritems():
|
|
123 if isinstance(item, float):
|
|
124 if math.isnan(item):
|
|
125 continue
|
|
126 elif isinstance(item, str):
|
|
127 if not item:
|
|
128 continue
|
|
129 df = sample_data[sample_data.dnasample_sample_group == item]
|
|
130
|
|
131 # store dnaruns of parents in a dictionary
|
|
132 par1 = list(set(filter(lambda x: str(x) != 'nan', df.germplasm_par1)))
|
|
133 par2 = list(set(filter(lambda x: str(x) != 'nan', df.germplasm_par2)))
|
|
134 lst1 = list(sample_data.loc[sample_data.germplasm_name.isin(par1), 'dnarun_name'])
|
|
135 lst2 = list(sample_data.loc[sample_data.germplasm_name.isin(par2), 'dnarun_name'])
|
|
136 mergedlst = lst1 + lst2
|
|
137
|
|
138 subgroup_list = df.dnasample_sample_group_cycle.drop_duplicates()
|
|
139 for idx, sub in subgroup_list.iteritems():
|
|
140 if isinstance(sub, float):
|
|
141 if math.isnan(sub):
|
|
142 # df.to_csv(samplefile+"_"+item+".txt", index=None, na_rep='', sep="\t", mode="w", line_terminator="\n")
|
|
143 if not item in parents and mergedlst:
|
|
144 parents.update({item : mergedlst})
|
|
145 continue
|
|
146 elif isinstance(sub, str):
|
|
147 if not sub:
|
|
148 # df.to_csv(samplefile+"_"+item+".txt", index=None, na_rep='', sep="\t", mode="w", line_terminator="\n")
|
|
149 continue
|
|
150
|
|
151 subkey = item+'_'+sub
|
|
152 if not subkey in parents and mergedlst:
|
|
153 parents.update({subkey : lst1+lst2})
|
|
154 # df_sub = df[df.dnasample_sample_group_cycle == sub]
|
|
155 # df_sub.to_csv(samplefile+"_"+item+"_"+sub+".txt", index=None, na_rep='', sep="\t", mode="w", line_terminator="\n")
|
|
156
|
|
157 # Split genotype file based on sample information #
|
76
|
158 splitfile(samplefile, sample_data, 0)
|
|
159 splitfile(samplefile, sample_data, 1)
|
|
160 splitfile(genofile, sample_data, 0)
|
|
161 splitfile(genofile, sample_data, 1)
|
65
|
162
|
76
|
163 def createProjectFile(samplefile, genofile, jarfile, separator, missing, qtlfile, mapfile, project):
|
|
164 sample_data = pd.read_table(samplefile, dtype='str')
|
|
165 groups = sample_data.dnasample_sample_group.drop_duplicates()
|
|
166 for index, key in groups.iteritems():
|
|
167 if isinstance(key, float) and math.isnan(key):
|
|
168 continue
|
|
169 df = sample_data[sample_data.dnasample_sample_group == key]
|
|
170 subgroup_list = df.dnasample_sample_group_cycle.drop_duplicates()
|
|
171 for idx, sub in subgroup_list.iteritems():
|
|
172 if isinstance(sub, float) and math.isnan(sub):
|
|
173 name = key
|
|
174 elif isinstance(sub, str) and not sub:
|
|
175 name = key
|
|
176 else:
|
|
177 name = key+'_'+sub
|
|
178 name = str(name)
|
|
179 sfile = samplefiles.get(samplefile + "_" + name)
|
|
180 gfile = genotypefiles.get(genofile + "_" + name)
|
|
181 gfile += '.tmp'
|
|
182 cmd = ['java', '-cp',jarfile,'jhi.flapjack.io.cmd.CreateProject','-A','-g',gfile,'-t',sfile,'-p',project,'-n',name,'-S',separator,'-M',missing,'-C']
|
|
183 if qtlfile:
|
|
184 cmd += ['-q',qtlfile]
|
|
185 if mapfile:
|
|
186 cmd += ['-m',mapfile]
|
|
187 print(cmd)
|
|
188 call(cmd)
|
65
|
189
|
76
|
190 def createHeader(samplefile, genofile, headerjar):
|
|
191 sample_data = pd.read_table(samplefile, dtype='str')
|
|
192 groups = sample_data.dnasample_sample_group.drop_duplicates()
|
|
193 for index, key in groups.iteritems():
|
|
194 if isinstance(key, float) and math.isnan(key):
|
|
195 continue
|
|
196 df = sample_data[sample_data.dnasample_sample_group == key]
|
|
197 subgroup_list = df.dnasample_sample_group_cycle.drop_duplicates()
|
|
198 for idx, sub in subgroup_list.iteritems():
|
|
199 if isinstance(sub, float) and math.isnan(sub):
|
|
200 name = key
|
|
201 elif isinstance(sub, str) and not sub:
|
|
202 name = key
|
|
203 else:
|
|
204 name = key+'_'+sub
|
|
205 name = str(name)
|
|
206 print("samplefile %s name %s" % (samplefile, name))
|
|
207 sfile = samplefiles.get(samplefile + "_" + name)
|
|
208 print("sfile %s" + sfile)
|
|
209 gfile = genotypefiles.get(genofile + "_" + name)
|
|
210 print("gfile %s" + gfile)
|
|
211
|
|
212 cmd = ['java','-jar',headerjar,sfile,gfile,gfile+'.tmp']
|
|
213 call(cmd)
|
65
|
214
|
|
215 def main(argv=None):
|
|
216 '''Command line options.'''
|
|
217
|
|
218 program_name = os.path.basename(sys.argv[0])
|
|
219 program_version = "v0.1"
|
|
220 program_build_date = "%s" % __updated__
|
|
221
|
|
222 program_version_string = '%%prog %s (%s)' % (program_version, program_build_date)
|
|
223 #program_usage = '''usage: spam two eggs''' # optional - will be autogenerated by optparse
|
|
224 program_longdesc = '''''' # optional - give further explanation about what the program does
|
|
225 program_license = "Copyright 2017 user_name (organization_name) \
|
|
226 Licensed under the Apache License 2.0\nhttp://www.apache.org/licenses/LICENSE-2.0"
|
|
227
|
|
228 if argv is None:
|
|
229 argv = sys.argv[1:]
|
|
230 try:
|
|
231 # setup option parser
|
|
232 parser = OptionParser(version=program_version_string, epilog=program_longdesc, description=program_license)
|
|
233 parser.add_option("-g", "--geno", dest="genofile", help="set input genotype file path [default: %default]", metavar="FILE")
|
|
234 parser.add_option("-s", "--sample", dest="samplefile", help="set input sample file path [default: %default]", metavar="FILE")
|
|
235 parser.add_option("-m", "--mapfile", dest="mapfile", help="set input map file path [default: %default]", metavar="FILE")
|
|
236 parser.add_option("-q", "--qtlfile", dest="qtlfile", help="set input QTL file path [default: %default]", metavar="FILE")
|
76
|
237 parser.add_option("-j", "--jar", dest="jarfile", help="set Flapjack project creator jar file path [default: %default]", metavar="FILE", default='jars/flapjack.jar')
|
|
238 parser.add_option("-J", "--headerjar", dest="headerjar", help="set Flapjack header creator jar file path [default: %default]", metavar="FILE", default='jars/pedigreeheader.jar')
|
|
239 parser.add_option("-S", "--separator", dest="separator", help="declare separator for genotypes, \"\" for no separator [default: \"\"]", metavar="STRING", default='')
|
|
240 parser.add_option("-M", "--missingGenotype", dest="missing", help="set missing genotype string [default: %default]", metavar="STRING", default='NN')
|
65
|
241 parser.add_option("-v", "--verbose", dest="verbose", action="count", help="set verbosity level [default: %default]")
|
76
|
242 parser.add_option("-p", "--project", dest="project", help="name of output file [default: %default]")
|
65
|
243
|
|
244 # process options
|
|
245 (opts, args) = parser.parse_args(argv)
|
|
246
|
|
247 if opts.verbose > 0:
|
|
248 print("verbosity level = %d" % opts.verbose)
|
|
249 if opts.genofile:
|
|
250 print("genofile = %s" % opts.genofile)
|
|
251 else:
|
76
|
252 sys.stderr.write("No genotype file detected!\n")
|
|
253 sys.exit()
|
65
|
254 if opts.samplefile:
|
|
255 print("samplefile = %s" % opts.samplefile)
|
|
256 else:
|
76
|
257 sys.stderr.write("No sample file detected!\n")
|
|
258 sys.exit()
|
65
|
259 if opts.mapfile:
|
|
260 print("mapfile = %s" % opts.mapfile)
|
|
261 else:
|
76
|
262 sys.stderr.write("No map file detected!\n")
|
65
|
263 if opts.qtlfile:
|
|
264 print("qtlfile = %s" % opts.qtlfile)
|
|
265 else:
|
76
|
266 sys.stderr.write("No QTL file detected!\n")
|
65
|
267 if opts.jarfile:
|
|
268 print("jarfile = %s" % opts.jarfile)
|
|
269 else:
|
76
|
270 sys.stderr.write("No Flapjack project creator jar file detected!\n")
|
65
|
271 if opts.headerjar:
|
|
272 print("headerjar = %s" % opts.headerjar)
|
|
273 else:
|
76
|
274 sys.stderr.write("No Flapjack header creator jar file detected!\n")
|
65
|
275
|
|
276 # MAIN BODY #
|
|
277 splitData(samplefile=opts.samplefile, genofile=opts.genofile)
|
76
|
278 createHeader(samplefile=opts.samplefile, genofile=opts.genofile, headerjar=opts.headerjar)
|
|
279 createProjectFile(samplefile=opts.samplefile, genofile=opts.genofile, jarfile=opts.jarfile, separator=opts.separator, missing=opts.missing,qtlfile=opts.qtlfile,mapfile=opts.mapfile, project=opts.project)
|
65
|
280
|
|
281
|
|
282 except Exception, e:
|
|
283 indent = len(program_name) * " "
|
|
284 sys.stderr.write(program_name + ": " + repr(e) + "\n")
|
|
285 sys.stderr.write(indent + " for help use --help")
|
|
286 return 2
|
|
287
|
|
288
|
|
289 if __name__ == "__main__":
|
|
290 # if DEBUG:
|
|
291 # sys.argv.append("-h")
|
|
292 if TESTRUN:
|
|
293 import doctest
|
|
294 doctest.testmod()
|
|
295 if PROFILE:
|
|
296 import cProfile
|
|
297 import pstats
|
|
298 profile_filename = 'DNASampleSplitter_profile.txt'
|
|
299 cProfile.run('main()', profile_filename)
|
|
300 statsfile = open("profile_stats.txt", "wb")
|
|
301 p = pstats.Stats(profile_filename, stream=statsfile)
|
|
302 stats = p.strip_dirs().sort_stats('cumulative')
|
|
303 stats.print_stats()
|
|
304 statsfile.close()
|
|
305 sys.exit(0)
|
|
306 sys.exit(main()) |