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