Debian Codegraph @

current/jgi/CrossContaminate.java

raw symbols SCIP
1 package jgi;
2
3 import java.io.PrintStream;
4 import java.util.ArrayList;
5 import java.util.Collections;
6 import java.util.Random;
7
8 import fileIO.ByteFile;
9 import fileIO.ByteFile1;
10 import fileIO.ByteFile2;
11 import fileIO.ByteStreamWriter;
12 import fileIO.FileFormat;
13 import fileIO.ReadWrite;
14 import shared.Parse;
15 import shared.Parser;
16 import shared.PreParser;
17 import shared.Shared;
18 import shared.Timer;
19 import shared.Tools;
20 import sort.Shuffle;
21 import sort.Shuffle.ShuffleThread;
22 import stream.ConcurrentGenericReadInputStream;
23 import stream.ConcurrentReadInputStream;
24 import stream.FastaReadInputStream;
25 import stream.Read;
26 import structures.ListNum;
27
28
29 /**
30 * Generates artificial cross-contaminated data by mixing reads.
31 * Takes input from multiple files, and writes output to the same number of files.
32 * @author Brian Bushnell
33 * @date Oct 27, 2014
34 *
35 */
36 public class CrossContaminate {
37
38 /*--------------------------------------------------------------*/
39 /*---------------- Initialization ----------------*/
40 /*--------------------------------------------------------------*/
41
42 public static void main(String[] args){
43 Timer t=new Timer();
44 CrossContaminate x=new CrossContaminate(args);
45 x.process(t);
46
47 //Close the print stream if it was redirected
48 Shared.closeStream(x.outstream);
49 }
50
51 public CrossContaminate(String[] args){
52
53 {//Preparse block for help, config files, and outstream
54 PreParser pp=new PreParser(args, getClass(), false);
55 args=pp.args;
56 outstream=pp.outstream;
57 }
58
59 boolean setInterleaved=false; //Whether it was explicitly set.
60
61 Shared.capBuffers(4);
62 ReadWrite.USE_PIGZ=ReadWrite.USE_UNPIGZ=true;
63 ReadWrite.setZipThreads(Shared.threads());
64
65
66 ArrayList<String> inTemp=new ArrayList<String>();
67 ArrayList<String> outTemp=new ArrayList<String>();
68
69 Parser parser=new Parser();
70 for(int i=0; i<args.length; i++){
71 String arg=args[i];
72 String[] split=arg.split("=");
73 String a=split[0].toLowerCase();
74 String b=split.length>1 ? split[1] : null;
75
76 if(Parser.parseQuality(arg, a, b)){
77 //do nothing
78 }else if(Parser.parseZip(arg, a, b)){
79 //do nothing
80 }else if(Parser.parseFasta(arg, a, b)){
81 //do nothing
82 }else if(Parser.parseCommonStatic(arg, a, b)){
83 //do nothing
84 }else if(parser.parseCommon(arg, a, b)){
85 //do nothing
86 }else if(parser.parseInterleaved(arg, a, b)){
87 //do nothing
88 }else if(a.equals("verbose")){
89 verbose=Parse.parseBoolean(b);
90 ByteFile1.verbose=verbose;
91 ByteFile2.verbose=verbose;
92 stream.FastaReadInputStream.verbose=verbose;
93 ConcurrentGenericReadInputStream.verbose=verbose;
94 stream.FastqReadInputStream.verbose=verbose;
95 ReadWrite.verbose=verbose;
96 }else if(a.equals("in")){
97 assert(b!=null) : "Bad parameter: "+arg;
98 String[] split2=b.split(",");
99 for(String name : split2){
100 inNames.add(name);
101 }
102 }else if(a.equals("out")){
103 assert(b!=null) : "Bad parameter: "+arg;
104 String[] split2=b.split(",");
105 for(String name : split2){
106 outNames.add(name);
107 }
108 }else if(a.equals("innamefile")){
109 assert(b!=null) : "Bad parameter: "+arg;
110 String[] split2=b.split(",");
111 for(String name : split2){
112 inTemp.add(name);
113 }
114 }else if(a.equals("outnamefile")){
115 assert(b!=null) : "Bad parameter: "+arg;
116 String[] split2=b.split(",");
117 for(String name : split2){
118 outTemp.add(name);
119 }
120 }else if(a.equals("shuffle")){
121 shuffle=Parse.parseBoolean(b);
122 }else if(a.equals("seed")){
123 seed=Long.parseLong(b);
124 }else if(a.equals("minsinks") || a.equals("ns")){
125 minSinks=Integer.parseInt(b);
126 }else if(a.equals("maxsinks") || a.equals("xs")){
127 maxSinks=Integer.parseInt(b);
128 }else if(a.equals("minprob") || a.equals("np")){
129 minProb=Double.parseDouble(b);
130 }else if(a.equals("maxprob") || a.equals("xp")){
131 maxProb=Double.parseDouble(b);
132 }else if(a.equals("showspeed")){
133 showspeed=Parse.parseBoolean(b);
134 }else if(a.equals("shufflethreads")){
135 shufflethreads=Integer.parseInt(b);
136 }else{
137 outstream.println("Unknown parameter "+args[i]);
138 assert(false) : "Unknown parameter "+args[i];
139 // throw new RuntimeException("Unknown parameter "+args[i]);
140 }
141 }
142
143
144 {//Process parser fields
145 Parser.processQuality();
146
147 maxReads=parser.maxReads;
148
149 overwrite=parser.overwrite;
150 append=parser.append;
151
152 setInterleaved=parser.setInterleaved;
153 }
154
155 assert(FastaReadInputStream.settingsOK());
156
157 DecontaminateByNormalization.parseStringsFromFiles(inTemp);
158 DecontaminateByNormalization.parseStringsFromFiles(outTemp);
159
160 inNames.addAll(inTemp);
161 outNames.addAll(outTemp);
162 inTemp=outTemp=null;
163
164 if(inNames.isEmpty() || inNames.size()!=outNames.size()){
165 assert(false) : inNames+"\n"+outNames;
166 throw new RuntimeException("Error - at least one input file is required, and # input files must equal # output files.");
167 }
168
169 assert(minSinks<=maxSinks);
170 minSinks=Tools.max(0, minSinks);
171 maxSinks=Tools.min(inNames.size()-1, maxSinks);
172 assert(minSinks<=maxSinks) : minSinks+", "+maxSinks;
173
174 assert(minProb<=maxProb);
175 assert(minProb>=0 && maxProb<=1);
176
177 minProbPow=Math.log(minProb);
178 maxProbPow=Math.log(maxProb);
179
180 if(!ByteFile.FORCE_MODE_BF1 && !ByteFile.FORCE_MODE_BF2 && Shared.threads()>2){
181 ByteFile.FORCE_MODE_BF2=true;
182 }
183
184 if(!Tools.testInputFiles(true, true, inNames.toArray(new String[0]))){
185 outstream.println(outNames);
186 throw new RuntimeException("Can't find some input files:\n"+inNames+"\n");
187 }
188
189 if(!Tools.testOutputFiles(overwrite, append, false, outNames.toArray(new String[0]))){
190 outstream.println(outNames);
191 throw new RuntimeException("\n\noverwrite="+overwrite+"; Can't write to output files.\n");
192 }
193
194 if(seed>0){randy.setSeed(seed);}
195
196 vessels=makeVessels(outNames);
197 }
198
199 /*--------------------------------------------------------------*/
200 /*---------------- Outer Methods ----------------*/
201 /*--------------------------------------------------------------*/
202
203 void process(Timer t){
204
205 outstream.println("Processing data.");
206 for(int i=0; i<inNames.size(); i++){
207 try{
208 processOneSource(i);
209 }catch(Throwable e){
210 System.err.println("Failed to open file "+inNames.get(i)+"\nException:"+e+"\n");
211 errorState=true;
212 }
213 }
214
215 for(Vessel v : vessels){
216 errorState|=v.close();
217 }
218
219 if(shuffle){
220 shuffle(shufflethreads);
221 }
222
223 t.stop();
224
225 if(showspeed){
226 outstream.println(Tools.timeReadsBasesProcessed(t, readsProcessed, basesProcessed, 8));
227 }
228
229 if(errorState){
230 throw new RuntimeException(getClass().getName()+" terminated in an error state; the output may be corrupt.");
231 }
232 }
233
234 /*--------------------------------------------------------------*/
235 /*---------------- Inner Methods ----------------*/
236 /*--------------------------------------------------------------*/
237
238 void shuffle(final int threads){
239 outstream.println("Shuffling output in "+threads+" thread"+(threads==1 ? "." : "s."));
240 Shuffle.showSpeed=Shuffle.printClass=false;
241 Shuffle.setMaxThreads(threads);
242 for(Vessel v : vessels){
243 ShuffleThread st=new ShuffleThread(v.fname, null, v.fname, null, Shuffle.SHUFFLE, true);
244 st.start();
245 }
246 Shuffle.waitForFinish();
247 }
248
249 void processOneSource(int sourceNum){
250 String fname=inNames.get(sourceNum);
251
252 FileFormat ffin=FileFormat.testInput(fname, FileFormat.FASTQ, null, true, true);
253
254 final ConcurrentReadInputStream cris;
255 {
256 cris=ConcurrentReadInputStream.getReadInputStream(maxReads, true, ffin, null);
257 if(verbose){outstream.println("Started cris");}
258 cris.start(); //4567
259 }
260 final boolean paired=cris.paired();
261 if(verbose){
262 if(!ffin.samOrBam()){outstream.println("Input is being processed as "+(paired ? "paired" : "unpaired"));}
263 }
264
265 ArrayList<Vessel> sinks=assignSinks(vessels, sourceNum);
266
267 {
268
269 ListNum<Read> ln=cris.nextList();
270 ArrayList<Read> reads=(ln!=null ? ln.list : null);
271
272 // outstream.println("Fetched "+reads);
273
274 if(reads!=null && !reads.isEmpty()){
275 Read r=reads.get(0);
276 assert((r.mate!=null)==paired);
277 }
278
279 while(ln!=null && reads!=null && reads.size()>0){//ln!=null prevents a compiler potential null access warning
280
281 for(int idx=0; idx<reads.size(); idx++){
282 final Read r1=reads.get(idx);
283 final Read r2=r1.mate;
284
285 final int initialLength1=r1.length();
286 final int initialLength2=(r1.mateLength());
287
288 {
289 readsProcessed++;
290 basesProcessed+=initialLength1;
291 }
292 if(r2!=null){
293 readsProcessed++;
294 basesProcessed+=initialLength2;
295 }
296
297 addRead(r1, sinks);
298 }
299
300 cris.returnList(ln);
301 ln=cris.nextList();
302 reads=(ln!=null ? ln.list : null);
303 }
304 if(ln!=null){
305 cris.returnList(ln.id, ln.list==null || ln.list.isEmpty());
306 }
307 }
308
309 errorState|=ReadWrite.closeStream(cris);
310 }
311
312 private void addRead(Read r, ArrayList<Vessel> list){
313 double p=randy.nextDouble();
314 for(Vessel v : list){
315 if(p>=v.prob){
316 v.bsw.println(r, true);
317 r=null;
318 break;
319 }
320 }
321 assert(r==null) : p+"\n"+list;
322 }
323
324 private ArrayList<Vessel> makeVessels(ArrayList<String> strings){
325 ArrayList<Vessel> list=new ArrayList<Vessel>(strings.size());
326 for(String s : strings){
327 Vessel v=new Vessel(s, true);
328 list.add(v);
329 }
330 return list;
331 }
332
333 private ArrayList<Vessel> assignSinks(ArrayList<Vessel> list, int sourceNum){
334 int potential=list.size()-1;
335 assert(potential>=minSinks && maxSinks<=potential) : potential+", "+minSinks+", "+maxSinks;
336 int range=maxSinks-minSinks+1;
337
338 int sinks=minSinks+(range>0 ? randy.nextInt(range) : 0);
339 assert(sinks>=0);
340
341 for(Vessel v : list){v.prob=0;}
342 ArrayList<Vessel> sinklist=(ArrayList<Vessel>) list.clone();
343 list=null;
344 Vessel source=sinklist.remove(sourceNum);
345 if(verbose || true){
346 System.err.println("Source: \t"+inNames.get(sourceNum));
347 System.err.println("Sinks: \t"+sinks);
348 }
349
350 while(sinklist.size()>sinks){
351 int x=randy.nextInt(sinklist.size());
352 sinklist.set(x, sinklist.get(sinklist.size()-1));
353 sinklist.remove(sinklist.size()-1);
354 }
355 // if(verbose){System.err.println("Sinklist:\n"+sinklist);}
356
357 {
358 double probRange=maxProbPow-minProbPow;
359
360 assert(probRange>=0) : minProb+", "+maxProb+", "+minProbPow+", "+maxProbPow+", "+probRange;
361
362 double remaining=1.0;
363 for(Vessel v : sinklist){
364 double c=Math.pow(Math.E, minProbPow+randy.nextDouble()*probRange)*remaining;
365 remaining-=c;
366 v.prob=c;
367 }
368 source.prob=remaining;
369 sinklist.add(source);
370 if(verbose || true){System.err.println("Sinklist:\t"+sinklist+"\n");}
371 double d=0;
372 for(Vessel v : sinklist){
373 d+=v.prob;
374 v.prob=d;
375 }
376 // if(verbose){System.err.println("Sinklist:\t"+sinklist);}
377 d=0;
378 for(Vessel v : sinklist){
379 double temp=v.prob;
380 v.prob=d;
381 d=temp;
382 }
383 // if(verbose){System.err.println("Sinklist:\t"+sinklist);}
384 }
385 Collections.reverse(sinklist);
386 assert(sinklist.get(sinklist.size()-1).prob==0.0) : sinklist;
387
388 // if(verbose){
389 // System.err.println("Sinklist:\t"+sinklist);
390 // System.err.println();
391 // }
392 if(verbose || true){System.err.println();}
393
394 return sinklist;
395 }
396
397 /*--------------------------------------------------------------*/
398 /*---------------- Inner Classes ----------------*/
399 /*--------------------------------------------------------------*/
400
401 private class Vessel{
402
403 public Vessel(String fname_, boolean allowSubprocess){
404 fname=fname_;
405 ff=FileFormat.testOutput(fname, FileFormat.FASTQ, null, allowSubprocess, overwrite, append, false);
406 bsw=new ByteStreamWriter(ff);
407 bsw.start();
408 }
409
410 public boolean close(){
411 return bsw.poisonAndWait();
412 }
413
414 @Override
415 public String toString(){
416 return fname+", "+Tools.format("%.6f", prob);
417 }
418
419 final String fname;
420 final FileFormat ff;
421 final ByteStreamWriter bsw;
422
423 double prob;
424
425 }
426
427 /*--------------------------------------------------------------*/
428 /*---------------- Fields ----------------*/
429 /*--------------------------------------------------------------*/
430
431
432 /*--------------------------------------------------------------*/
433
434 private ArrayList<String> inNames=new ArrayList<String>();
435 private ArrayList<String> outNames=new ArrayList<String>();
436
437 private ArrayList<Vessel> vessels;
438
439 /*--------------------------------------------------------------*/
440
441 private long maxReads=-1;
442 private long seed=-1;
443
444 private int minSinks=1;
445 private int maxSinks=8;
446 private double minProb=0.000005;
447 private double maxProb=0.025;
448
449 private double minProbPow=Math.log(minProb);
450 private double maxProbPow=Math.log(maxProb);
451
452 // private double root=3.0;
453 //
454 // private double minProbRoot=Math.pow(minProb, 1/root);
455 // private double maxProbRoot=Math.pow(maxProb, 1/root);
456
457 private final Random randy=new Random();
458
459 long readsProcessed=0;
460 long basesProcessed=0;
461
462 private int shufflethreads=3;
463
464 private boolean shuffle=false;
465 private boolean showspeed=true;
466
467 /*--------------------------------------------------------------*/
468
469
470 /*--------------------------------------------------------------*/
471 /*---------------- Common Fields ----------------*/
472 /*--------------------------------------------------------------*/
473
474 private PrintStream outstream=System.err;
475 public static boolean verbose=false;
476 public boolean errorState=false;
477 private boolean overwrite=true;
478 private boolean append=false;
479
480 }