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