Debian Codegraph @

current/jgi/RenameReads.java

raw symbols SCIP
1 package jgi;
2
3 import java.io.File;
4 import java.io.PrintStream;
5 import java.util.ArrayList;
6 import java.util.regex.Pattern;
7
8 import dna.Data;
9 import fileIO.ByteFile;
10 import fileIO.ByteFile1;
11 import fileIO.ByteFile2;
12 import fileIO.FileFormat;
13 import fileIO.ReadWrite;
14 import hiseq.IlluminaHeaderParser2;
15 import shared.Parse;
16 import shared.Parser;
17 import shared.PreParser;
18 import shared.Shared;
19 import shared.Timer;
20 import shared.Tools;
21 import stream.ConcurrentGenericReadInputStream;
22 import stream.ConcurrentReadInputStream;
23 import stream.ConcurrentReadOutputStream;
24 import stream.FASTQ;
25 import stream.FastaReadInputStream;
26 import stream.Read;
27 import structures.ByteBuilder;
28 import structures.ListNum;
29 import structures.Quantizer;
30 import tracker.ReadStats;
31
32 /**
33 * @author Brian Bushnell
34 * @date Aug 23, 2013
35 *
36 */
37 public class RenameReads {
38
39 public static void main(String[] args){
40 Timer t=new Timer();
41 RenameReads x=new RenameReads(args);
42 x.process(t);
43
44 //Close the print stream if it was redirected
45 Shared.closeStream(x.outstream);
46 }
47
48 public RenameReads(String[] args){
49
50 {//Preparse block for help, config files, and outstream
51 PreParser pp=new PreParser(args, getClass(), false);
52 args=pp.args;
53 outstream=pp.outstream;
54 }
55
56 Parser parser=new Parser();
57
58
59 Shared.capBuffers(4);
60 ReadWrite.USE_PIGZ=ReadWrite.USE_UNPIGZ=true;
61 ReadWrite.setZipThreads(Shared.threads());
62
63
64 for(int i=0; i<args.length; i++){
65 String arg=args[i];
66 String[] split=Parse.splitOnFirst(arg, '=');
67 String a=split[0].toLowerCase();
68 String b=split.length>1 ? split[1] : null;
69
70 if(Parser.parseCommonStatic(arg, a, b)){
71 //do nothing
72 }else if(Parser.parseZip(arg, a, b)){
73 //do nothing
74 }else if(Parser.parseQuality(arg, a, b)){
75 //do nothing
76 }else if(Parser.parseFasta(arg, a, b)){
77 //do nothing
78 }else if(parser.parseInterleaved(arg, a, b)){
79 //do nothing
80 }else if(a.equals("passes")){
81 assert(false) : "'passes' is disabled.";
82 // passes=Integer.parseInt(b);
83 }else if(a.equals("verbose")){
84 verbose=Parse.parseBoolean(b);
85 ByteFile1.verbose=verbose;
86 ByteFile2.verbose=verbose;
87 stream.FastaReadInputStream.verbose=verbose;
88 ConcurrentGenericReadInputStream.verbose=verbose;
89 stream.FastqReadInputStream.verbose=verbose;
90 ReadWrite.verbose=verbose;
91 }else if(a.equalsIgnoreCase("fixSRA")){
92 fixSRA=Parse.parseBoolean(b);
93 }else if(a.equals("reads") || a.equals("maxreads")){
94 maxReads=Parse.parseKMG(b);
95 }else if(a.equals("build") || a.equals("genome")){
96 Data.setGenome(Integer.parseInt(b));
97 }else if(a.equals("in") || a.equals("input") || a.equals("in1") || a.equals("input1")){
98 in1=b;
99 }else if(a.equals("prefix") || a.equals("p")){
100 prefix=b;
101 }else if(a.equals("suffix")){
102 suffix=b;
103 }else if(a.equals("in2") || a.equals("input2")){
104 in2=b;
105 }else if(a.equals("out") || a.equals("output") || a.equals("out1") || a.equals("output1")){
106 out1=b;
107 }else if(a.equals("out2") || a.equals("output2")){
108 out2=b;
109 }else if(a.equals("qfin") || a.equals("qfin1")){
110 qfin1=b;
111 }else if(a.equals("qfout") || a.equals("qfout1")){
112 qfout1=b;
113 }else if(a.equals("qfin2")){
114 qfin2=b;
115 }else if(a.equals("qfout2")){
116 qfout2=b;
117 }else if(a.equals("extin")){
118 extin=b;
119 }else if(a.equals("extout")){
120 extout=b;
121 }else if(a.equals("trimright")){
122 trimRight=Integer.parseInt(b);
123 }else if(a.equals("trimleft")){
124 trimLeft=Integer.parseInt(b);
125 }else if(a.equals("trimbeforesymbol")){
126 trimBeforeSymbol=Integer.parseInt(b);
127 }else if(a.equals("symbol")){
128 String s=Parse.parseSymbol(b);
129 assert(s.length()==1) : "'"+s+"'";
130 symbol=s.charAt(0);
131 }
132
133 else if(a.equals("append") || a.equals("app")){
134 append=ReadStats.append=Parse.parseBoolean(b);
135 }else if(a.equals("overwrite") || a.equals("ow")){
136 overwrite=Parse.parseBoolean(b);
137 }else if(a.equals("renamebyinsert")){
138 renameByInsert=Parse.parseBoolean(b);
139 }else if(a.equals("renamebytrim")){
140 renameByTrim=Parse.parseBoolean(b);
141 }else if(a.equals("renamebycoordinates") || a.equals("coordinates") || a.equals("coords")){
142 renameByCoords=Parse.parseBoolean(b);
143 }else if(a.equals("quantize") || a.equals("quantizesticky")){
144 quantizeQuality=Quantizer.parse(arg, a, b);
145 }else if(a.equals("addprefix")){
146 addPrefix=Parse.parseBoolean(b);
147 }else if(a.equals("addpairnum")){
148 addPairnum=Parse.parseBoolean(b);
149 }else if(a.equals("prefixonly")){
150 prefixOnly=Parse.parseBoolean(b);
151 }else if(a.equals("underscore") || a.equals("addunderscore")){
152 addUnderscore=Parse.parseBoolean(b);
153 }else if(a.startsWith("minscaf") || a.startsWith("mincontig")){
154 stream.FastaReadInputStream.MIN_READ_LEN=Integer.parseInt(b);
155 }else if(in1==null && i==0 && Tools.looksLikeInputStream(arg)){
156 in1=arg;
157 }else{
158 System.err.println("Unknown parameter "+args[i]);
159 assert(false) : "Unknown parameter "+args[i];
160 // throw new RuntimeException("Unknown parameter "+args[i]);
161 }
162
163 renameByMapping=FASTQ.TAG_CUSTOM;
164 }
165
166 if(addUnderscore && prefix!=null && !prefix.endsWith("_") && !prefixOnly){prefix+="_";}
167 if(!addPairnum){pairnums=new String[] {"",""};}
168
169 {//Process parser fields
170 Parser.processQuality();
171 }
172
173 // assert(false) : prefix;
174 if(prefix==null || prefix.length()<1){prefix="";}
175 // else if(!prefix.endsWith("_") && !prefixOnly){
176 // prefix=prefix+"_";
177 // }
178
179 if(renameByInsert){
180 prefix="insert=";
181 FASTQ.PARSE_CUSTOM=true;
182 }else if(renameByTrim){
183 prefix="";
184 FASTQ.PARSE_CUSTOM=true;
185 }
186
187 if(in1!=null && in2==null && in1.indexOf('#')>-1 && !new File(in1).exists()){
188 in2=in1.replace("#", "2");
189 in1=in1.replace("#", "1");
190 }
191 if(out1!=null && out2==null && out1.indexOf('#')>-1){
192 out2=out1.replace("#", "2");
193 out1=out1.replace("#", "1");
194 }
195 if(in2!=null){
196 if(FASTQ.FORCE_INTERLEAVED){System.err.println("Reset INTERLEAVED to false because paired input files were specified.");}
197 FASTQ.FORCE_INTERLEAVED=FASTQ.TEST_INTERLEAVED=false;
198 }
199
200 assert(FastaReadInputStream.settingsOK());
201
202 if(in1==null){throw new RuntimeException("Error - at least one input file is required.");}
203 if(!ByteFile.FORCE_MODE_BF1 && !ByteFile.FORCE_MODE_BF2 && Shared.threads()>2){
204 ByteFile.FORCE_MODE_BF2=true;
205 }
206
207 if(out1==null && out2!=null){throw new RuntimeException("Error - cannot define out2 without defining out1.");}
208
209 if(!parser.setInterleaved){
210 assert(in1!=null && (out1!=null || out2==null)) : "\nin1="+in1+"\nin2="+in2+"\nout1="+out1+"\nout2="+out2+"\n";
211 if(in2!=null){ //If there are 2 input streams.
212 FASTQ.FORCE_INTERLEAVED=FASTQ.TEST_INTERLEAVED=false;
213 outstream.println("Set INTERLEAVED to "+FASTQ.FORCE_INTERLEAVED);
214 }else{ //There is one input stream.
215 if(out2!=null){
216 FASTQ.FORCE_INTERLEAVED=true;
217 FASTQ.TEST_INTERLEAVED=false;
218 outstream.println("Set INTERLEAVED to "+FASTQ.FORCE_INTERLEAVED);
219 }
220 }
221 }
222
223 if(out1!=null && out1.equalsIgnoreCase("null")){out1=null;}
224 if(out2!=null && out2.equalsIgnoreCase("null")){out2=null;}
225
226 if(!Tools.testOutputFiles(overwrite, append, false, out1, out2)){
227 throw new RuntimeException("\n\noverwrite="+overwrite+"; Can't write to output files "+out1+", "+out2+"\n");
228 }
229
230 ffout1=FileFormat.testOutput(out1, FileFormat.FASTQ, extout, true, overwrite, append, false);
231 ffout2=FileFormat.testOutput(out2, FileFormat.FASTQ, extout, true, overwrite, append, false);
232
233 ffin1=FileFormat.testInput(in1, FileFormat.FASTQ, extin, true, true);
234 ffin2=FileFormat.testInput(in2, FileFormat.FASTQ, extin, true, true);
235
236 if(renameByMapping){
237 assert(ffout1==null || ffout1.fastq()) : "Currently renameByMapping requires fastq output.";
238 }
239 }
240
241 void process(Timer t){
242
243 final ConcurrentReadInputStream cris;
244 {
245 cris=ConcurrentReadInputStream.getReadInputStream(maxReads, true, ffin1, ffin2, qfin1, qfin2);
246 cris.start(); //4567
247 }
248
249 // TextStreamWriter tsw=new TextStreamWriter(args[2], false, false, true);
250 // tsw.start();
251
252 ConcurrentReadOutputStream ros=null;
253 if(out1!=null){
254 final int buff=4;
255
256 if(cris.paired() && out2==null && (in1==null || !in1.contains(".sam"))){
257 outstream.println("Writing interleaved.");
258 }
259
260 assert(!out1.equalsIgnoreCase(in1) && !out1.equalsIgnoreCase(in1)) : "Input file and output file have same name.";
261 assert(out2==null || (!out2.equalsIgnoreCase(in1) && !out2.equalsIgnoreCase(in2))) : "out1 and out2 have same name.";
262
263 ros=ConcurrentReadOutputStream.getStream(ffout1, ffout2, qfout1, qfout2, buff, null, false);
264 ros.start();
265 }
266
267 ListNum<Read> ln=cris.nextList();
268 ArrayList<Read> reads=(ln!=null ? ln.list : null);
269 IlluminaHeaderParser2 ihp=new IlluminaHeaderParser2();
270 ByteBuilder bb=new ByteBuilder();
271
272 long x=0;
273 while(ln!=null && reads!=null && reads.size()>0){//ln!=null prevents a compiler potential null access warning
274
275 for(Read r1 : reads){
276 final Read r2=r1.mate;
277 // assert(false) : trimBeforeSymbol+", '"+symbol+"'";
278
279 if(quantizeQuality){
280 final byte[] quals1=r1.quality, quals2=(r2==null ? null : r2.quality);
281 Quantizer.quantize(quals1);
282 Quantizer.quantize(quals2);
283 }
284
285 if(trimRight>0 || trimLeft>0 || trimBeforeSymbol>0) {
286 if(trimRight>0 || trimLeft>0){
287 r1.id=trim(r1.id, trimLeft, trimRight);
288 if(r2!=null) {r2.id=trim(r2.id, trimLeft, trimRight);}
289 }
290 if(trimBeforeSymbol>0){
291 r1.id=trimBeforeSymbol(r1.id, trimBeforeSymbol, symbol);
292 if(r2!=null) {r2.id=trimBeforeSymbol(r2.id, trimBeforeSymbol, symbol);}
293 }
294 }else if(fixSRA){
295 fixSRA(r1);
296 fixSRA(r2);
297 }else if(renameByCoords){
298 bb.clear().colon().colon().colon();
299 ihp.parse(r1);
300 ihp.appendCoordinates(bb).space().append(1).colon();
301 r1.id=bb.toString();
302 if(r2!=null) {
303 bb.set(bb.length-2, (byte)'2');
304 r2.id=bb.toString();
305 }
306 }else if(renameByMapping){
307 //Should be handled automatically, if output is fastq.
308 }else if(r2!=null && (renameByInsert || renameByTrim)){
309
310 r1.setMapped(true);
311 r2.setMapped(true);
312 x=Read.insertSizeMapped(r1, r2, false);
313 if(verbose){System.err.println("True Insert: "+x);}
314 if(renameByTrim){
315 r1.id=r1.numericID+"_"+r1.length()+"_"+Tools.min(x, r1.length())+pairnums[0];
316 r2.id=r2.numericID+"_"+r2.length()+"_"+Tools.min(x, r2.length())+pairnums[1];
317 }else{
318 String s=prefix+x;
319 r1.id=s+(addPairnum ? " 1:"+r1.numericID : "");
320 if(r2!=null){
321 r2.id=s+(addPairnum ? " 2:"+r1.numericID : "");
322 }
323 }
324
325 }else if(prefixOnly){
326 r1.id=prefix;
327 if(r2!=null){
328 r2.id=prefix;
329 }
330 x++;
331 }else if(addPrefix){
332 r1.id=prefix+r1.id;
333 if(r2!=null){
334 r2.id=prefix+r2.id;
335 }
336 x++;
337 }else if(suffix!=null) {
338 r1.id+="\t"+suffix;
339 if(r2!=null) {r2.id+="\t"+suffix;}
340 }else{
341 r1.id=prefix+x;
342 if(r2!=null){
343 r1.id=r1.id+pairnums[0];
344 r2.id=prefix+x+pairnums[1];
345 }
346 x++;
347 }
348 }
349 if(ros!=null){ros.add(reads, ln.id);}
350 cris.returnList(ln);
351 ln=cris.nextList();
352 reads=(ln!=null ? ln.list : null);
353 }
354 cris.returnList(ln);
355 errorState|=ReadWrite.closeStreams(cris, ros);
356
357 t.stop();
358 System.err.println("Time: "+t);
359 }
360
361 private void fixSRA(Read r){
362 //SRR1726611.11001 HWI-ST797:117:D091UACXX:4:1101:21093:8249 length=101
363 if(r==null){return;}
364 String id=r.id;
365 String[] split=spacePattern.split(id);
366 assert(split.length==3) : "Unrecognized format: "+id;
367 assert(split.length>0 && split[0].indexOf(':')<0) : "Unrecognized format: "+id;
368 if(split.length>1){
369 r.id=split[1]+pairnums[r.pairnum()];
370 }
371 }
372
373 private static String trim(String s, int left, int right) {
374 assert(left>=0 && right>=0) : left+", "+right;
375 assert(left>0 || right>0) : left+", "+right;
376 int len=s.length()-left-right;
377 if(len<0) {return "";}
378 else if(len>=s.length()) {return s;}
379 return s.substring(left, left+len);
380 }
381
382 private static String trimBeforeSymbol(String s, int right, char symbol) {
383 int pos=s.lastIndexOf(symbol);
384 // assert(false) : pos+", '"+symbol+"', "+right;
385 if(pos<0) {return s;}
386 int len=Tools.max(0, pos-right);
387 // assert(false) : pos+", "+len+", "+right;
388 String ret=s.substring(0, len)+s.substring(pos);
389 // assert(false) : pos+", "+len+", "+right+"\n"+s+"\n"+ret+"\n";
390 return ret;
391 }
392
393 private PrintStream outstream=System.err;
394
395 private String in1=null;
396 private String in2=null;
397
398 private String qfin1=null;
399 private String qfin2=null;
400
401 private String out1=null;
402 private String out2=null;
403
404 private String qfout1=null;
405 private String qfout2=null;
406
407 private String extin=null;
408 private String extout=null;
409
410 private String prefix=null;
411 private String suffix=null;
412
413 private final FileFormat ffin1;
414 private final FileFormat ffin2;
415
416 private final FileFormat ffout1;
417 private final FileFormat ffout2;
418
419 private boolean overwrite=true;
420 private boolean append=false;
421 private boolean verbose=false;
422 private long maxReads=-1;
423 public boolean errorState=false;
424
425 public int trimBeforeSymbol=0;
426 public char symbol;
427 public int trimRight=0;
428 public int trimLeft=0;
429
430 public boolean addUnderscore=true;
431 public boolean renameByMapping=false;
432 public boolean renameByInsert=false;
433 public boolean renameByTrim=false;
434 public boolean renameByCoords=false;
435 public boolean addPrefix=false;
436 public boolean prefixOnly=false;
437 public boolean fixSRA=false;
438 public boolean addPairnum=true;
439 public boolean quantizeQuality=false;
440 private String[] pairnums={" 1:", " 2:"};
441
442 private static final Pattern spacePattern=Pattern.compile("\\s+");
443 private static final Pattern whitespacePattern=Pattern.compile(" ");
444
445 }