Debian Codegraph @

current/jgi/MakeContaminatedGenomes.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.Random;
7
8 import dna.AminoAcid;
9 import fileIO.ByteFile;
10 import fileIO.ByteFile1;
11 import fileIO.ByteFile2;
12 import fileIO.ByteStreamWriter;
13 import fileIO.FileFormat;
14 import fileIO.ReadWrite;
15 import fileIO.TextFile;
16 import shared.Parse;
17 import shared.Parser;
18 import shared.PreParser;
19 import shared.Shared;
20 import shared.Timer;
21 import shared.Tools;
22 import stream.ConcurrentGenericReadInputStream;
23 import stream.ConcurrentReadInputStream;
24 import stream.FASTQ;
25 import stream.FastaReadInputStream;
26 import stream.Read;
27 import structures.ByteBuilder;
28
29
30 /**
31 * Fuses files together randomly to make chimeric genomes.
32 * @author Brian Bushnell
33 * @date Oct 7, 2014
34 *
35 */
36 public class MakeContaminatedGenomes {
37
38 public static void main(String[] args){
39 Timer t=new Timer();
40 MakeContaminatedGenomes x=new MakeContaminatedGenomes(args);
41 x.process(t);
42
43 //Close the print stream if it was redirected
44 Shared.closeStream(x.outstream);
45 }
46
47 public MakeContaminatedGenomes(String[] args){
48
49 {//Preparse block for help, config files, and outstream
50 PreParser pp=new PreParser(args, getClass(), false);
51 args=pp.args;
52 outstream=pp.outstream;
53 }
54
55 Shared.capBuffers(4);
56 ReadWrite.USE_PIGZ=ReadWrite.USE_UNPIGZ=true;
57 ReadWrite.setZipThreads(Shared.threads());
58
59 FASTQ.FORCE_INTERLEAVED=FASTQ.TEST_INTERLEAVED=false;
60
61 Parser parser=new Parser();
62 for(int i=0; i<args.length; i++){
63 String arg=args[i];
64 String[] split=arg.split("=");
65 String a=split[0].toLowerCase();
66 String b=split.length>1 ? split[1] : null;
67
68 if(parser.parse(arg, a, b)){
69 //do nothing
70 }else if(a.equals("verbose")){
71 verbose=Parse.parseBoolean(b);
72 ByteFile1.verbose=verbose;
73 ByteFile2.verbose=verbose;
74 stream.FastaReadInputStream.verbose=verbose;
75 ConcurrentGenericReadInputStream.verbose=verbose;
76 stream.FastqReadInputStream.verbose=verbose;
77 ReadWrite.verbose=verbose;
78 }else if(a.equals("chimeras") || a.equals("count")){
79 chimeras=Integer.parseInt(b);
80 }else if(a.equals("seed")){
81 seed=Long.parseLong(b);
82 }else if(a.equals("exp")){
83 exponent1=exponent2=Double.parseDouble(b);
84 }else if(a.equals("exp1")){
85 exponent1=Double.parseDouble(b);
86 }else if(a.equals("exp2")){
87 exponent2=Double.parseDouble(b);
88 }else if(a.equals("delimiter")){
89 delimiter=b;
90 }else if(a.equals("regex")){
91 regex=b;
92 }else if(a.equals("subrate")){
93 subRate=Double.parseDouble(b);
94 }else if(a.equals("indelrate")){
95 indelRate=Double.parseDouble(b);
96 }else if(a.equals("id") || a.equals("ani") || a.equals("identity")){
97 errorRate=Double.parseDouble(b);
98 subRate=0.99*errorRate;
99 indelRate=0.01*errorRate;
100 }else if(parser.in1==null && i==0 && Tools.looksLikeInputStream(arg)){
101 parser.in1=arg;
102 }else{
103 outstream.println("Unknown parameter "+args[i]);
104 assert(false) : "Unknown parameter "+args[i];
105 // throw new RuntimeException("Unknown parameter "+args[i]);
106 }
107 }
108
109 errorRate=subRate+indelRate;
110
111 {//Process parser fields
112 Parser.processQuality();
113
114 fofn=parser.in1;
115
116 outPattern=parser.out1;
117 }
118
119 assert(FastaReadInputStream.settingsOK());
120
121 if(fofn==null){throw new RuntimeException("Error - at least one input file is required.");}
122
123 if(!ByteFile.FORCE_MODE_BF1 && !ByteFile.FORCE_MODE_BF2 && Shared.threads()>2){
124 ByteFile.FORCE_MODE_BF2=true;
125 }
126
127 if(outPattern!=null && outPattern.equalsIgnoreCase("null")){outPattern=null;}
128
129 fffofn=FileFormat.testInput(fofn, FileFormat.TXT, null, true, true);
130 }
131
132 void process(Timer t){
133 final String[] in=TextFile.toStringLines(fffofn);
134 // final long sizes[]=calcSizes(in);
135 final Random randy=Shared.threadLocalRandom(seed);
136
137 final StringBuilder sb=new StringBuilder();
138 for(int cid=0; cid<chimeras; cid++){
139 String s=makeOne(in, randy, cid);
140 sb.append(s).append('\n');
141 }
142 if(outNames!=null){
143 ReadWrite.writeString(sb, outNames);
144 }
145
146 t.stop();
147 outstream.println(Tools.timeReadsBasesProcessed(t, readsProcessed, basesProcessed, 8));
148
149 if(errorState){
150 throw new RuntimeException(getClass().getName()+" terminated in an error state; the output may be corrupt.");
151 }
152 }
153
154 /* Calculates the size of each fasta file in an array */
155 // private long[] calcSizes(String[] in){
156 // long[] sizes=new long[in.length];
157 // for(int i=0; i<in.length; i++){
158 // ByteFile bf=ByteFile.makeByteFile(in[i], true);
159 // long[] symbols=new long[255];
160 // for(byte[] line=bf.nextLine(); line!=null; line=bf.nextLine()){
161 // if(line.length>0 && line[0]!='>'){
162 // assert(Tools.isLetter(line[0]));
163 // for(byte b : line){
164 // symbols[b]++;
165 // }
166 // }
167 // }
168 // final long defined=symbols['A']+symbols['C']+symbols['G']+symbols['T'];
169 // final long total=shared.Vector.sum(symbols);
170 // sizes[i]=total;
171 // }
172 // return sizes;
173 // }
174
175 String makeOne(String[] in, Random randy, int cid){
176 // System.err.println("A");
177 int a=randy.nextInt(in.length);
178 int b=a;
179 while(b==a){
180 b=randy.nextInt(in.length);
181 }
182 double fracA=Math.pow(randy.nextDouble(), exponent1);
183 double fracB=Math.pow(randy.nextDouble(), exponent2);
184 // System.err.println("B: "+fracA+", "+fracB);
185
186 FileFormat ffa=FileFormat.testInput(in[a], FileFormat.FASTA, null, true, true);
187 FileFormat ffb=FileFormat.testInput(in[b], FileFormat.FASTA, null, true, true);
188 // System.err.println("B1");
189
190 ArrayList<Read> readsA=ConcurrentReadInputStream.getReads(-1, false, ffa, null, null, null);
191 // System.err.println("B2: "+readsA.size());
192 ArrayList<Read> readsB=ConcurrentReadInputStream.getReads(-1, false, ffb, null, null, null);
193 // System.err.println("B3: "+readsB.size());
194
195 return writeChimera(in[a], in[b], readsA, readsB, fracA, fracB, randy, cid);
196 }
197
198 String writeChimera(String inA, String inB, ArrayList<Read> readsA, ArrayList<Read> readsB, double fracA, double fracB, Random randy, int cid){
199 ByteBuilder bb=new ByteBuilder();
200 long sizeA=0, sizeB=0;
201 for(Read r : readsA){
202 readsProcessed++;
203 basesProcessed+=r.length();
204 processRead(r, bb, fracA, randy);
205 sizeA+=r.length();
206 }
207 // System.err.println("D: "+sizeA);
208 for(Read r : readsB){
209 readsProcessed++;
210 basesProcessed+=r.length();
211 processRead(r, bb, fracB, randy);
212 sizeB+=r.length();
213 }
214 // System.err.println("E: "+sizeB);
215
216 final String out;
217 if(fracA>=fracB){
218 // System.err.println("F");
219 out=outPattern.replaceFirst(regex, delimiter+sizeA+delimiter+Tools.format("%.3f", fracA)+delimiter+ReadWrite.stripToCore(inA)+delimiter+sizeB+delimiter+Tools.format("%.3f", fracB)+delimiter+ReadWrite.stripToCore(inB)+delimiter+cid+delimiter);
220 ByteStreamWriter bsw=new ByteStreamWriter(out, true, false, true);
221 bsw.start();
222 // System.err.println("G");
223 for(Read r : readsA){bsw.println(r);}
224 for(Read r : readsB){bsw.println(r);}
225 // System.err.println("H");
226 bsw.poisonAndWait();
227 }else{
228 // System.err.println("I");
229 out=outPattern.replaceFirst(regex, delimiter+sizeB+delimiter+Tools.format("%.3f", fracB)+delimiter+ReadWrite.stripToCore(inB)+delimiter+sizeA+delimiter+Tools.format("%.3f", fracA)+delimiter+ReadWrite.stripToCore(inA)+delimiter+cid+delimiter);
230 ByteStreamWriter bsw=new ByteStreamWriter(out, true, false, true);
231 bsw.start();
232 // System.err.println("J");
233 for(Read r : readsB){bsw.println(r);}
234 for(Read r : readsA){bsw.println(r);}
235 // System.err.println("K");
236 bsw.poisonAndWait();
237 }
238 // System.err.println("L");
239 return out;
240 }
241
242 public void processRead(Read r, ByteBuilder bb, double genomeFraction, Random randy){
243
244 //Setup
245 bb.clear();
246 r.quality=null;
247
248 long mutationsAdded=0;
249
250 //Handle genomeFraction
251 if(genomeFraction<1){
252 final byte[] bases0=r.bases;
253 int retain=(int)(bases0.length*(genomeFraction));
254 // System.err.println("retain: "+retain);
255 if(retain<bases0.length){
256 final int start=randy.nextInt(bases0.length);
257 int i=0, j=start;
258 for(; i<retain && j<bases0.length; i++, j++){
259 bb.append(bases0[j]);
260 }
261 j=0;
262
263 if(i<retain){mutationsAdded++;} //Chimeric junction
264
265 for(; i<retain; i++, j++){
266 bb.append(bases0[j]);
267 }
268 r.bases=bb.toBytes();
269 bb.clear();
270 }
271 }
272
273 //Handle mutations
274 //Not really the point of this tool but easy to add
275 //Here, subs+indels=errors
276 if(errorRate>0){
277 final byte[] bases=r.bases;
278 for(int i=0; i<bases.length; i++){
279 byte b=bases[i];
280 float x=randy.nextFloat();
281 if(x<errorRate && AminoAcid.isFullyDefined(b)){
282 mutationsAdded++;
283 if(x<subRate){
284 b=AminoAcid.numberToBase[((AminoAcid.baseToNumber[b]+randy.nextInt(3)+1)&3)];
285 bb.append(b);
286 }else if(randy.nextBoolean()){//del
287 //do nothing
288 }else{//ins
289 i--;
290 b=AminoAcid.numberToBase[randy.nextInt(4)];
291 bb.append(b);
292 }
293 }else{
294 bb.append(b);
295 }
296 }
297 //Modify read
298 r.bases=bb.toBytes();
299 }
300 // if(prefix!=null){
301 // r.id=prefix+r.numericID;
302 // }
303 basesRetained+=r.bases.length;
304 }
305
306
307 /*--------------------------------------------------------------*/
308
309 /*--------------------------------------------------------------*/
310
311 private String fofn=null;
312
313 private String outPattern=null;
314 private String outNames=null;
315
316 private int chimeras=1;
317 private long seed=-1;
318 double exponent1=1;
319 double exponent2=1;
320 String delimiter="_";
321 String regex="#";
322
323 double subRate=0;
324 double indelRate=0;
325 double errorRate=0;
326 long basesRetained=0;
327
328 long readsProcessed=0;
329 long basesProcessed=0;
330
331 private PrintStream outstream=System.err;
332
333 /*--------------------------------------------------------------*/
334
335 private final FileFormat fffofn;
336
337 /*--------------------------------------------------------------*/
338
339 public static boolean verbose=false;
340 public boolean errorState=false;
341 private boolean overwrite=true;
342 private boolean append=false;
343
344 }