Debian Codegraph @

current/jgi/MutateGenome2.java

raw symbols SCIP
1 package jgi;
2
3 import java.util.ArrayList;
4 import java.util.Arrays;
5 import java.util.Random;
6
7 import dna.AminoAcid;
8 import fileIO.ByteStreamWriter;
9 import fileIO.FileFormat;
10 import fileIO.ReadWrite;
11 import shared.Parse;
12 import shared.Parser;
13 import shared.PreParser;
14 import shared.Shared;
15 import shared.Timer;
16 import shared.Tools;
17 import stream.ConcurrentReadInputStream;
18 import stream.ConcurrentReadOutputStream;
19 import stream.FASTQ;
20 import stream.Read;
21 import structures.ByteBuilder;
22 import structures.ListNum;
23 import var2.Var;
24
25 /**
26 * @author Brian Bushnell
27 * @date June 1, 2016
28 *
29 */
30 public class MutateGenome2 {
31
32 public static void main(String[] args){
33 Timer t=new Timer();
34 MutateGenome2 x=new MutateGenome2(args);
35 x.process(t);
36
37 //Close the print stream if it was redirected
38 Shared.closeStream(x.outstream);
39 }
40
41 public MutateGenome2(String[] args){
42
43 {//Preparse block for help, config files, and outstream
44 PreParser pp=new PreParser(args, getClass(), false);
45 args=pp.args;
46 outstream=pp.outstream;
47 }
48
49 Shared.setBufferLen(1);
50 FASTQ.FORCE_INTERLEAVED=FASTQ.TEST_INTERLEAVED=false;
51
52 Parser parser=new Parser();
53 parser.overwrite=true;
54 for(int i=0; i<args.length; i++){
55 String arg=args[i];
56 String[] split=arg.split("=");
57 String a=split[0].toLowerCase();
58 String b=split.length>1 ? split[1] : null;
59
60 if(parser.parse(arg, a, b)){
61 //do nothing
62 }else if(a.equals("parse_flag_goes_here")){
63 //Set a variable here
64 }else if(a.equals("period")){
65 period=Integer.parseInt(b);
66 }else if(a.equals("subrate") || a.equals("snprate")){
67 subRate=Float.parseFloat(b);
68 if(subRate>1){subRate/=100;}
69 }else if(a.equals("indelrate")){
70 indelRate=Float.parseFloat(b);
71 if(indelRate>1){indelRate/=100;}
72 }else if(a.equals("maxindel")){
73 maxIndel=Parse.parseIntKMG(b);
74 }else if(a.equals("indelspacing")){
75 indelSpacing=Parse.parseIntKMG(b);
76 }else if(a.equals("seed")){
77 seed=Long.parseLong(b);
78 }else if(a.equals("ploidy")){
79 ploidy=Integer.parseInt(b);
80 }else if(a.equals("nohomopolymers") || a.equals("nohomo") || a.equals("banhomopolymers") || a.equals("banhomo")){
81 banHomopolymers=Parse.parseBoolean(b);
82 }else if(a.equalsIgnoreCase("hetrate")){
83 hetRate=Float.parseFloat(b);
84 }else if(a.equals("prefix")){
85 prefix=b;
86 }else if(a.equals("vcf") || a.equals("outvcf") || a.equals("vcfout") || a.equals("vars") || a.equals("varsout") || a.equals("outvars")){
87 outVcf=b;
88 }else if(a.equals("id") || a.equals("identity")){
89 float x=Float.parseFloat(b);
90 if(x>1){x=x/100;}
91 x=1-x;
92 indelRate=x*0.01f;
93 subRate=x*0.99f;
94 }else if(a.equals("fraction") || a.equals("completeness")){
95 float x=Float.parseFloat(b);
96 if(x>1){x=x/100;}
97 genomeFraction=x;
98 }else{
99 outstream.println("Unknown parameter "+args[i]);
100 assert(false) : "Unknown parameter "+args[i];
101 // throw new RuntimeException("Unknown parameter "+args[i]);
102 }
103 }
104 errorRate=subRate+indelRate;
105 errorRate2=subRate+(indelRate*0.16666f*(maxIndel+1));
106
107 assert(subRate>=0 && subRate<=1) : "Substitution rate must be between 0 and 1, inclusive. Invalid value: "+subRate;
108 assert(indelRate>=0 && indelRate<=1) : "Indel rate must be between 0 and 1, inclusive. Invalid value: "+indelRate;
109 assert(errorRate>=0 && errorRate<=1) : "Total error rate must be between 0 and 1, inclusive. Invalid value: "+errorRate;
110
111 System.err.println(Tools.format("Target Identity: \t%.2f%%", (1-errorRate2)*100));
112 System.err.println(Tools.format("Substitution Rate: \t%.2f%%", subRate*100));
113 System.err.println(Tools.format("Indel Rate: \t%.2f%%", indelRate*100));
114
115 randy=Shared.threadLocalRandom(seed);
116
117 {//Process parser fields
118 Parser.processQuality();
119
120 maxReads=parser.maxReads;
121 in1=parser.in1;
122 out1=parser.out1;
123 overwrite=parser.overwrite;
124 append=parser.append;
125 }
126
127 //Ensure there is an input file
128 if(in1==null){throw new RuntimeException("Error - at least one input file is required.");}
129
130 //Ensure output files can be written
131 if(!Tools.testOutputFiles(overwrite, append, false, out1, outVcf)){
132 outstream.println((out1==null)+", "+(outVcf==null)+", "+out1+", "+outVcf);
133 throw new RuntimeException("\n\noverwrite="+overwrite+"; Can't write to output files "+out1+", "+outVcf+"\n");
134 }
135
136 //Ensure input files can be read
137 if(!Tools.testInputFiles(false, true, in1)){
138 throw new RuntimeException("\nCan't read some input files.\n");
139 }
140
141 //Ensure that no file was specified multiple times
142 if(!Tools.testForDuplicateFiles(true, in1, out1, outVcf)){
143 throw new RuntimeException("\nSome file names were specified multiple times.\n");
144 }
145
146 ffout1=FileFormat.testOutput(out1, FileFormat.FASTA, null, true, overwrite, append, false);
147 ffoutVcf=FileFormat.testOutput(outVcf, FileFormat.VCF, null, true, overwrite, append, false);
148 ffin1=FileFormat.testInput(in1, FileFormat.FASTA, null, true, true);
149 }
150
151 void process(Timer t){
152
153 final ConcurrentReadInputStream cris;
154 {
155 cris=ConcurrentReadInputStream.getReadInputStream(maxReads, true, ffin1, null);
156 cris.start();
157 }
158
159 final ConcurrentReadOutputStream ros;
160 if(out1!=null){
161 final int buff=4;
162
163 if(cris.paired() && (in1==null || !in1.contains(".sam"))){
164 outstream.println("Writing interleaved.");
165 }
166
167 assert(!out1.equalsIgnoreCase(in1) && !out1.equalsIgnoreCase(in1)) : "Input file and output file have same name.";
168
169 ros=ConcurrentReadOutputStream.getStream(ffout1, null, buff, null, false);
170 ros.start();
171 }else{ros=null;}
172
173 {
174
175 ListNum<Read> ln=cris.nextList();
176 ArrayList<Read> reads=(ln!=null ? ln.list : null);
177
178 if(reads!=null && !reads.isEmpty()){
179 Read r=reads.get(0);
180 assert((ffin1==null || ffin1.samOrBam()) || (r.mate!=null)==cris.paired());
181 }
182 ByteBuilder[] bba=new ByteBuilder[ploidy];
183 for(int i=0; i<bba.length; i++){bba[i]=new ByteBuilder();}
184 ArrayList<String> headers=(ffoutVcf==null ? null : new ArrayList<String>());
185 ArrayList<SmallVar> vars=(ffoutVcf==null ? null : new ArrayList<SmallVar>());
186 ArrayList<SmallVar> varsTemp=(ffoutVcf==null ? null : new ArrayList<SmallVar>());
187
188 while(ln!=null && reads!=null && reads.size()>0){//ln!=null prevents a compiler potential null access warning
189 if(verbose){outstream.println("Fetched "+reads.size()+" reads.");}
190
191 ArrayList<Read> mutants=new ArrayList<Read>(ploidy*reads.size());
192 for(int idx=0; idx<reads.size(); idx++){
193 final Read r1=reads.get(idx);
194
195 readsProcessed++;
196 basesProcessed+=r1.length();
197
198 ArrayList<Read> mutant=processRead(r1, bba, varsTemp, headers);
199 mutants.addAll(mutant);
200 if(vars!=null){vars.addAll(varsTemp);}
201 }
202
203 if(ros!=null){ros.add(mutants, ln.id);}
204
205 cris.returnList(ln);
206 if(verbose){outstream.println("Returned a list.");}
207 ln=cris.nextList();
208 reads=(ln!=null ? ln.list : null);
209 }
210 if(ln!=null){
211 cris.returnList(ln.id, ln.list==null || ln.list.isEmpty());
212 }
213
214 writeVars(vars, headers);
215 }
216
217 ReadWrite.closeStreams(cris, ros);
218 if(verbose){outstream.println("Finished.");}
219
220
221 {
222 t.stop();
223
224 //Calculate units per nanosecond
225 double brnano=basesRetained/(double)(t.elapsed);
226
227 //Add "k" and "m" for large numbers
228 long mutationsAdded=subsAdded+insAdded+delsAdded+junctionsAdded;
229 String brstring=(basesRetained<100000 ? ""+basesRetained : basesRetained<100000000 ? (basesRetained/1000)+"k" : (basesRetained/1000000)+"m");
230 String mastring=(mutationsAdded<100000 ? ""+mutationsAdded : mutationsAdded<100000000 ? (mutationsAdded/1000)+"k" : (mutationsAdded/1000000)+"m");
231 String sastring=(subsAdded<100000 ? ""+subsAdded : subsAdded<100000000 ? (subsAdded/1000)+"k" : (subsAdded/1000000)+"m");
232 String iastring=(insAdded<100000 ? ""+insAdded : insAdded<100000000 ? (insAdded/1000)+"k" : (insAdded/1000000)+"m");
233 String dastring=(delsAdded<100000 ? ""+delsAdded : delsAdded<100000000 ? (delsAdded/1000)+"k" : (delsAdded/1000000)+"m");
234 String jastring=(junctionsAdded<100000 ? ""+junctionsAdded : junctionsAdded<100000000 ? (junctionsAdded/1000)+"k" : (junctionsAdded/1000000)+"m");
235
236 //Format the strings so they have they are right-justified
237 while(brstring.length()<8){brstring=" "+brstring;}
238 while(mastring.length()<8){mastring=" "+mastring;}
239 while(sastring.length()<8){sastring=" "+sastring;}
240 while(iastring.length()<8){iastring=" "+iastring;}
241 while(dastring.length()<8){dastring=" "+dastring;}
242 while(jastring.length()<8){jastring=" "+jastring;}
243
244 outstream.println(Tools.timeReadsBasesProcessed(t, readsProcessed, basesProcessed, 8));
245 if(genomeFraction<1){outstream.println("Bases Retained: "+brstring+" \t"+Tools.format("%.2fm bases/sec", brnano*1000));}
246 outstream.println("Mutations Added: "+mastring+" \t"+Tools.format("%.2f%% Identity", 100f-mutationLengthAdded*100f/basesProcessed));
247 outstream.println("Subs Added: "+sastring);
248 outstream.println("Insertions Added: "+iastring);
249 outstream.println("Deletions Added: "+dastring);
250 outstream.println("Junctions Added: "+jastring);
251 }
252
253 t.stop();
254 }
255
256 public int[] makePresentArray(){
257 int[] present=new int[ploidy];
258 if(ploidy>1 && randy.nextFloat()<hetRate){
259 int sum=0;
260 while(sum<1 || sum>=ploidy){
261 sum=0;
262 Arrays.fill(present, 0);
263 for(int i=0; i<ploidy; i++){
264 int x=randy.nextInt(2);
265 sum+=x;
266 present[i]=x;
267 }
268 }
269 }else{
270 Arrays.fill(present, 1);
271 }
272 return present;
273 }
274
275 public boolean isHomopolymerDel(byte[] bases, int pos, int len){
276 final byte b=bases[pos];
277 for(int i=1; i<len; i++){
278 if(bases[pos+i]!=b){return false;}
279 }
280 if(pos>0 && bases[pos-1]==b){return true;}
281 if(pos<bases.length-1 && bases[pos+1]==b){return true;}
282 return false;
283 }
284
285 public boolean isHomopolymerIns(byte[] bases, int pos, byte b){
286 if(b==bases[pos]){return true;}
287 if(pos>0 && b==bases[pos-1]){return true;}
288 return false;
289 }
290
291 public boolean isHomopolymerIns(byte[] bases, int pos, StringBuilder sb){
292 byte b=(byte) sb.charAt(0);
293 for(int i=1; i<sb.length(); i++) {
294 if(sb.charAt(i)!=b){return false;}
295 }
296 return isHomopolymerIns(bases, pos, b);
297 }
298
299 public ArrayList<Read> processRead(Read r, ByteBuilder[] bba, ArrayList<SmallVar> vars, ArrayList<String> headers){
300
301 if(r.aminoacid()) {
302 return processReadAmino(r, bba, vars, headers);
303 }
304
305 //Setup
306 for(ByteBuilder bb : bba){bb.clear();}
307 r.quality=null;
308 if(headers!=null){headers.add("<ID="+r.id+",length="+r.length()+">");}
309 if(vars!=null){vars.clear();}
310
311 //Handle genomeFraction
312 if(genomeFraction<1){
313 final byte[] bases0=r.bases;
314 int retain=(int)(bases0.length*(genomeFraction));
315 if(retain<bases0.length){
316 final int start=randy.nextInt(bases0.length);
317 int i=0, j=start;
318 for(; i<retain && j<bases0.length; i++, j++){
319 bba[0].append(bases0[j]);
320 }
321 j=0;
322
323 if(i<retain){
324 junctionsAdded++;
325 mutationLengthAdded++;
326 } //Chimeric junction
327
328 for(; i<retain; i++, j++){
329 bba[0].append(bases0[j]);
330 }
331 r.bases=bba[0].toBytes();
332 bba[0].clear();
333 }
334 }
335
336 //Handle mutations
337 final byte[] bases=r.bases;
338
339 if(period>-1){
340 int basesSinceMutation=0;
341 char prevChar='N';
342 for(int i=0; i<bases.length; i++){
343 final byte b0=bases[i];
344 byte b=b0;
345 if(basesSinceMutation>=period && AminoAcid.isFullyDefined(b)){
346 basesSinceMutation=0;
347 float x=randy.nextFloat()*errorRate;
348 int[] present=makePresentArray();
349 if(x<subRate){
350 b=AminoAcid.numberToBase[((AminoAcid.baseToNumber[b]+randy.nextInt(3)+1)&3)];
351
352 for(int haplo=0; haplo<ploidy; haplo++){
353 if(present[haplo]==1){
354 bba[haplo].append(b);
355 }else{
356 bba[haplo].append(b0);
357 }
358 }
359 if(vars!=null){vars.add(new SmallVar(SUB, i, i+1, Character.toString((char)b), Character.toString((char)b0), prevChar, r.id, r.numericID, present));}
360 subsAdded++;
361 mutationLengthAdded++;
362 }else if(randy.nextBoolean()){//del
363 if(banHomopolymers && isHomopolymerDel(bases, i, 1)) {
364 i--;
365 }else{
366 for(int haplo=0; haplo<ploidy; haplo++){
367 if(present[haplo]==1){
368 //do nothing
369 }else{
370 bba[haplo].append(b0);
371 }
372 }
373 if(vars!=null){vars.add(new SmallVar(DEL, i, i+1, "", Character.toString((char)b0), prevChar, r.id, r.numericID, present));}
374 delsAdded++;
375 mutationLengthAdded++;
376 }
377 }else{//ins
378 b=AminoAcid.numberToBase[randy.nextInt(4)];
379 while(banHomopolymers && isHomopolymerIns(bases, i, b)) {
380 b=AminoAcid.numberToBase[randy.nextInt(4)];
381 }
382 for(int haplo=0; haplo<ploidy; haplo++){
383 if(present[haplo]==1){
384 bba[haplo].append(b);
385 }else{
386 //do nothing
387 }
388 }
389 if(vars!=null){vars.add(new SmallVar(INS, i, i, Character.toString((char)b), "", prevChar, r.id, r.numericID, present));}
390 i--;
391 insAdded++;
392 mutationLengthAdded++;
393 }
394 }else{
395 basesSinceMutation++;
396 for(ByteBuilder bb : bba){
397 bb.append(b);
398 }
399 }
400 prevChar=(char) b0;
401 }
402 }else{
403 char prevChar='N';
404 int lastIndel=-1;
405 for(int i=0; i<bases.length; i++){
406 final byte b0=bases[i];
407 byte b=b0;
408 float x=randy.nextFloat();
409 if(x<errorRate && AminoAcid.isFullyDefined(b)){
410 int[] present=makePresentArray();
411 // System.err.println(x+", "+errorRate+", "+subRate);
412 if(x<subRate){
413 subsAdded++;
414 mutationLengthAdded++;
415 b=AminoAcid.numberToBase[((AminoAcid.baseToNumber[b]+randy.nextInt(3)+1)&3)];
416 for(int haplo=0; haplo<ploidy; haplo++){
417 if(present[haplo]==1){
418 bba[haplo].append(b);
419 }else{
420 bba[haplo].append(b0);
421 }
422 }
423 if(vars!=null){vars.add(new SmallVar(SUB, i, i+1, Character.toString((char)b), Character.toString((char)b0), prevChar, r.id, r.numericID, present));}
424 }else if(i-lastIndel>indelSpacing){
425 int lim=Tools.min(maxIndel, bases.length-i-1);
426 if(lim>=1){
427 int len=1+(Tools.min(randy.nextInt(lim), randy.nextInt(lim), randy.nextInt(lim)));
428
429 if(randy.nextBoolean()){//del
430 if(banHomopolymers && isHomopolymerDel(bases, i, len)) {
431 i--;
432 }else{
433 delsAdded++;
434 mutationLengthAdded+=len;
435 byte[] ref=new byte[len];
436 for(int rpos=0; rpos<len; rpos++){ref[rpos]=bases[i+rpos];}
437 //do nothing
438 for(int haplo=0; haplo<ploidy; haplo++){
439 if(present[haplo]==1){
440 //do nothing
441 }else{
442 bba[haplo].append(ref);
443 }
444 }
445 if(vars!=null){vars.add(new SmallVar(DEL, i, i+len, "", new String(bases, i, len), prevChar, r.id, r.numericID, present));}
446 i=i+len-1;
447 }
448 }else{//ins
449 insAdded++;
450 mutationLengthAdded+=len;
451 if(len==1){
452 b=AminoAcid.numberToBase[randy.nextInt(4)];
453 while(banHomopolymers && isHomopolymerIns(bases, i, b)) {
454 b=AminoAcid.numberToBase[randy.nextInt(4)];
455 }
456 for(int haplo=0; haplo<ploidy; haplo++){
457 if(present[haplo]==1){
458 bba[haplo].append(b);
459 }else{
460 //do nothing
461 }
462 }
463 if(vars!=null){vars.add(new SmallVar(INS, i, i, Character.toString((char)b), "", prevChar, r.id, r.numericID, present));}
464 }else{
465 StringBuilder sb=new StringBuilder();
466 while(sb.length()==0 || (banHomopolymers && isHomopolymerIns(bases, i, sb))) {
467 sb.setLength(0);
468 while(sb.length()<len){
469 b=AminoAcid.numberToBase[randy.nextInt(4)];
470 sb.append((char)b);
471 }
472 }
473 for(int haplo=0; haplo<ploidy; haplo++){
474 if(present[haplo]==1){
475 bba[haplo].append(sb);
476 }else{
477 //do nothing
478 }
479 }
480 if(vars!=null){vars.add(new SmallVar(INS, i, i, sb.toString(), "", prevChar, r.id, r.numericID, present));}
481 }
482 i--;
483 }
484 lastIndel=i;
485 }
486 }
487 }else{
488 for(ByteBuilder bb : bba){
489 bb.append(b);
490 }
491 }
492 prevChar=(char) b0;
493 }
494 }
495
496 condenseVars(vars);
497
498 //Modify read
499 r.bases=bba[0].toBytes();
500
501 if(prefix!=null){
502 r.id=prefix+r.numericID;
503 }
504 basesRetained+=r.bases.length;
505
506 ArrayList<Read> ret=new ArrayList<Read>();
507 if(ploidy==1){ret.add(r);}
508 else{
509 for(int i=0; i<ploidy; i++){
510 ret.add(new Read(bba[i].toBytes(), null, r.id+"_haplo_"+i, r.numericID));
511 }
512 }
513 return ret;
514 }
515
516 public ArrayList<Read> processReadAmino(Read r, ByteBuilder[] bba, ArrayList<SmallVar> vars, ArrayList<String> headers){
517
518 assert(r.aminoacid());
519
520 //Setup
521 for(ByteBuilder bb : bba){bb.clear();}
522 r.quality=null;
523 if(headers!=null){headers.add("<ID="+r.id+",length="+r.length()+">");}
524 if(vars!=null){vars.clear();}
525
526 //Handle genomeFraction
527 if(genomeFraction<1){
528 final byte[] bases0=r.bases;
529 int retain=(int)(bases0.length*(genomeFraction));
530 if(retain<bases0.length){
531 final int start=randy.nextInt(bases0.length);
532 int i=0, j=start;
533 for(; i<retain && j<bases0.length; i++, j++){
534 bba[0].append(bases0[j]);
535 }
536 j=0;
537
538 if(i<retain){
539 junctionsAdded++;
540 mutationLengthAdded++;
541 } //Chimeric junction
542
543 for(; i<retain; i++, j++){
544 bba[0].append(bases0[j]);
545 }
546 r.bases=bba[0].toBytes();
547 bba[0].clear();
548 }
549 }
550
551 //Handle mutations
552 final byte[] bases=r.bases;
553
554 if(period>-1){
555 int basesSinceMutation=0;
556 char prevChar='X';
557 for(int i=0; i<bases.length; i++){
558 final byte b0=bases[i];
559 byte b=b0;
560 if(basesSinceMutation>=period && AminoAcid.isFullyDefinedAA(b)){
561 basesSinceMutation=0;
562 float x=randy.nextFloat()*errorRate;
563 int[] present=makePresentArray();
564 if(x<subRate){
565 b=AminoAcid.numberToAcid[((AminoAcid.acidToNumber[b]+randy.nextInt(20)+1)%21)];
566
567 for(int haplo=0; haplo<ploidy; haplo++){
568 if(present[haplo]==1){
569 bba[haplo].append(b);
570 }else{
571 bba[haplo].append(b0);
572 }
573 }
574 if(vars!=null){vars.add(new SmallVar(SUB, i, i+1, Character.toString((char)b), Character.toString((char)b0), prevChar, r.id, r.numericID, present));}
575 subsAdded++;
576 mutationLengthAdded++;
577 }else if(randy.nextBoolean()){//del
578 for(int haplo=0; haplo<ploidy; haplo++){
579 if(present[haplo]==1){
580 //do nothing
581 }else{
582 bba[haplo].append(b0);
583 }
584 }
585 if(vars!=null){vars.add(new SmallVar(DEL, i, i+1, "", Character.toString((char)b0), prevChar, r.id, r.numericID, present));}
586 delsAdded++;
587 mutationLengthAdded++;
588 }else{//ins
589 b=AminoAcid.numberToAcid[randy.nextInt(21)];
590 for(int haplo=0; haplo<ploidy; haplo++){
591 if(present[haplo]==1){
592 bba[haplo].append(b);
593 }else{
594 //do nothing
595 }
596 }
597 if(vars!=null){vars.add(new SmallVar(INS, i, i, Character.toString((char)b), "", prevChar, r.id, r.numericID, present));}
598 i--;
599 insAdded++;
600 mutationLengthAdded++;
601 }
602 }else{
603 basesSinceMutation++;
604 for(ByteBuilder bb : bba){
605 bb.append(b);
606 }
607 }
608 prevChar=(char) b0;
609 }
610 }else{
611 char prevChar='N';
612 int lastIndel=-1;
613 for(int i=0; i<bases.length; i++){
614 final byte b0=bases[i];
615 byte b=b0;
616 float x=randy.nextFloat();
617 if(x<errorRate && AminoAcid.isFullyDefinedAA(b)){
618 int[] present=makePresentArray();
619 // System.err.println(x+", "+errorRate+", "+subRate);
620 if(x<subRate){
621 subsAdded++;
622 mutationLengthAdded++;
623 b=AminoAcid.numberToAcid[((AminoAcid.acidToNumber[b]+randy.nextInt(20)+1)%21)];
624 for(int haplo=0; haplo<ploidy; haplo++){
625 if(present[haplo]==1){
626 bba[haplo].append(b);
627 }else{
628 bba[haplo].append(b0);
629 }
630 }
631 if(vars!=null){vars.add(new SmallVar(SUB, i, i+1, Character.toString((char)b), Character.toString((char)b0), prevChar, r.id, r.numericID, present));}
632 }else if(i-lastIndel>indelSpacing){
633 int lim=Tools.min(maxIndel, bases.length-i-1);
634 if(lim>=1){
635 int len=1+(Tools.min(randy.nextInt(lim), randy.nextInt(lim), randy.nextInt(lim)));
636
637 if(randy.nextBoolean()){//del
638 delsAdded++;
639 mutationLengthAdded+=len;
640 byte[] ref=new byte[len];
641 for(int rpos=0; rpos<len; rpos++){ref[rpos]=bases[i+rpos];}
642 //do nothing
643 for(int haplo=0; haplo<ploidy; haplo++){
644 if(present[haplo]==1){
645 //do nothing
646 }else{
647 bba[haplo].append(ref);
648 }
649 }
650 if(vars!=null){vars.add(new SmallVar(DEL, i, i+len, "", new String(bases, i, len), prevChar, r.id, r.numericID, present));}
651 i=i+len-1;
652 }else{//ins
653 insAdded++;
654 mutationLengthAdded+=len;
655 if(len==1){
656 b=AminoAcid.numberToAcid[randy.nextInt(21)];
657 for(int haplo=0; haplo<ploidy; haplo++){
658 if(present[haplo]==1){
659 bba[haplo].append(b);
660 }else{
661 //do nothing
662 }
663 }
664 if(vars!=null){vars.add(new SmallVar(INS, i, i, Character.toString((char)b), "", prevChar, r.id, r.numericID, present));}
665 }else{
666 StringBuilder sb=new StringBuilder();
667 while(sb.length()<len){
668 b=AminoAcid.numberToAcid[randy.nextInt(21)];
669 sb.append((char)b);
670 }
671 for(int haplo=0; haplo<ploidy; haplo++){
672 if(present[haplo]==1){
673 bba[haplo].append(sb);
674 }else{
675 //do nothing
676 }
677 }
678 if(vars!=null){vars.add(new SmallVar(INS, i, i, sb.toString(), "", prevChar, r.id, r.numericID, present));}
679 }
680 i--;
681 }
682 lastIndel=i;
683 }
684 }
685 }else{
686 for(ByteBuilder bb : bba){
687 bb.append(b);
688 }
689 }
690 prevChar=(char) b0;
691 }
692 }
693
694 condenseVars(vars);
695
696 //Modify read
697 r.bases=bba[0].toBytes();
698
699 if(prefix!=null){
700 r.id=prefix+r.numericID;
701 }
702 basesRetained+=r.bases.length;
703
704 ArrayList<Read> ret=new ArrayList<Read>();
705 if(ploidy==1){ret.add(r);}
706 else{
707 for(int i=0; i<ploidy; i++){
708 ret.add(new Read(bba[i].toBytes(), null, r.id+"_haplo_"+i, r.numericID));
709 }
710 }
711 return ret;
712 }
713
714 /*--------------------------------------------------------------*/
715
716 private void condenseVars(ArrayList<SmallVar> vars){
717 if(vars==null || vars.size()<2){return;}
718
719 {//Pass 1: fuse indels into subs
720 SmallVar current=null;
721 for(int i=0; i<vars.size(); i++){
722 SmallVar next=vars.get(i);
723 if(next.type==SUB){
724 current=null;
725 }else if(current==null){
726 current=next;
727 }else if(current.stop==next.start && current.type!=next.type && current.sharesPhase(next)){
728 if(current.type==DEL){
729 assert(next.type==INS) : next.type;
730 //Change the del to a sub
731 current.type=SUB;
732 current.alt=next.alt;
733 current=null;
734 vars.set(i, null);
735 }else if(current.type==INS){
736 assert(next.type==DEL) : next.type;
737 //Change the ins to a sub
738 current.type=SUB;
739 current.ref=next.ref;
740 current.stop=next.stop;
741 current=null;
742 vars.set(i, null);
743 }else{
744 assert(false) : current.type;
745 }
746 }else{
747 current=next;
748 }
749 }
750 Tools.condenseStrict(vars);
751 if(vars.size()<2){return;}
752 }
753
754 {//Pass 2: lengthen indels
755 SmallVar current=null;
756 for(int i=0; i<vars.size(); i++){
757 SmallVar next=vars.get(i);
758 if(next.type==SUB){
759 current=null;
760 if(!next.valid()){vars.set(i, null);}
761 }else if(current==null){
762 current=next;
763 }else if(current.stop==next.start && current.type==next.type && current.sharesPhase(next)){
764 if(current.type==DEL){
765 assert(next.type==DEL) : next.type;
766 //Lengthen the deletion
767 current.stop=next.stop;
768 current.ref+=next.ref;
769 vars.set(i, null);
770 }else if(current.type==INS){
771 assert(next.type==INS) : next.type;
772 //Lengthen the insertion
773 current.alt+=next.alt;
774 vars.set(i, null);
775 }else{
776 assert(false) : current.type;
777 }
778 }else{
779 current=next;
780 }
781 }
782 Tools.condenseStrict(vars);
783 }
784 }
785
786 void writeVars(ArrayList<SmallVar> vars, ArrayList<String> headers){
787 if(ffoutVcf==null){return;}
788 ByteStreamWriter bsw=new ByteStreamWriter(ffoutVcf);
789 bsw.start();
790 ByteBuilder bb=new ByteBuilder();
791 bb.appendln("##fileformat=VCFv4.2");
792 bb.appendln("##BBMapVersion="+Shared.BBTOOLS_VERSION_STRING);
793 bb.appendln("##Program=MutateGenome");
794 for(String s : headers){
795 bb.append("##contig=").appendln(s);
796 }
797 bb.appendln("##FILTER=<ID=FAIL,Description=\"Fail\">");
798 bb.appendln("##FILTER=<ID=PASS,Description=\"Pass\">");
799 bb.appendln("##INFO=<ID=SN,Number=1,Type=Integer,Description=\"Scaffold Number\">");
800 bb.appendln("##INFO=<ID=STA,Number=1,Type=Integer,Description=\"Start\">");
801 bb.appendln("##INFO=<ID=STO,Number=1,Type=Integer,Description=\"Stop\">");
802 bb.appendln("##INFO=<ID=TYP,Number=1,Type=String,Description=\"Type\">");
803 bb.appendln("##FORMAT=<ID=GT,Number=1,Type=String,Description=\"Genotype\">");
804 bb.appendln("##FORMAT=<ID=SC,Number=1,Type=Float,Description=\"Score\">");
805 bb.appendln("##FORMAT=<ID=PF,Number=1,Type=String,Description=\"Pass Filter\">");
806 bb.appendln("#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\tFORMAT\t"+(out1==null ? "sample" : ReadWrite.stripToCore(out1)));
807
808 bsw.print(bb);
809 bb.clear();
810
811 for(SmallVar v : vars){
812 v.toVcf(bb);
813 bb.nl();
814 if(bb.length()>=64000){
815 bsw.print(bb);
816 bb.clear();
817 }
818 }
819 if(bb.length()>=0){
820 bsw.print(bb);
821 bb.clear();
822 }
823 errorState=bsw.poisonAndWait()|errorState;
824 }
825
826 /*--------------------------------------------------------------*/
827
828 private static class SmallVar{
829
830 SmallVar(int type_, int start_, int stop_, String alt_, String ref_, char prevChar_, String rname_, long scafNum_, int[] present_){
831 type=type_;
832 start=start_;
833 stop=stop_;
834 alt=alt_;
835 ref=ref_;
836 prevChar=prevChar_;
837 rname=rname_;
838 scafNum=scafNum_;
839 present=present_;
840 }
841
842 boolean valid(){
843 return type!=SUB || !alt.equals(ref);
844 }
845
846 void toVcf(ByteBuilder bb){
847 bb.append(rname).append('\t');
848 if(type==SUB){
849 bb.append(start+1).append('\t');
850 bb.append('.').append('\t');
851 bb.append(ref).append('\t');
852 bb.append(alt).append('\t');
853 }else if(type==DEL || type==INS){
854 bb.append(start).append('\t');
855 bb.append('.').append('\t');
856 bb.append(prevChar).append(ref).append('\t');
857 bb.append(prevChar).append(alt).append('\t');
858 }else{assert(false);}
859 bb.append("60.00").append('\t');
860 bb.append("PASS").append('\t');
861 bb.append("SN=").append(scafNum).append(';');
862 bb.append("STA=").append(start).append(';');
863 bb.append("STO=").append(stop).append(';');
864 bb.append("TYP=").append(Var.typeArray[type]).append('\t');
865 bb.append("GT:SC:PF").append('\t');
866 bb.append(present[0]);
867 for(int i=1; i<present.length; i++){bb.append('|').append(present[i]);}
868 bb.append(':');
869 bb.append("60.00").append(':');
870 bb.append("PASS");
871 }
872
873 boolean sharesPhase(SmallVar sv){
874 for(int i=0; i<present.length; i++){
875 if(present[i]!=sv.present[i]){return false;}
876 }
877 return true;
878 }
879
880 int type;
881 final int start;
882 int stop;
883 String ref;
884 String alt;
885 final char prevChar;
886 final String rname;
887 final long scafNum;
888
889 final int[] present;
890
891 }
892
893 /*--------------------------------------------------------------*/
894
895 private String in1=null;
896 private String out1=null;
897 private String outVcf=null;
898
899 private String prefix=null;
900
901 private final FileFormat ffin1;
902 private final FileFormat ffout1;
903 private final FileFormat ffoutVcf;
904
905 /*--------------------------------------------------------------*/
906
907 private long maxReads=-1;
908 // private long mutationsAdded=0;
909
910 private int ploidy=1;
911 private float hetRate=0.5f;
912
913 private long mutationLengthAdded=0;
914 private long subsAdded=0;
915 private long insAdded=0;
916 private long delsAdded=0;
917 private long junctionsAdded=0;
918
919 private int period=-1;
920
921 private float genomeFraction=1;
922 private long basesRetained;
923
924 private long readsProcessed=0;
925 private long basesProcessed=0;
926
927 private float subRate=0;
928 private float indelRate=0;
929 private int maxIndel=1;
930 private int indelSpacing=10;
931 private boolean banHomopolymers=false;
932 private final float errorRate;
933 private final float errorRate2;
934
935 private final Random randy;
936 private long seed=-1;
937
938 /*--------------------------------------------------------------*/
939
940 /** True if an error was encountered */
941 public boolean errorState=false;
942 /** Overwrite existing output files */
943 private boolean overwrite=true;
944 /** Append to existing output files */
945 private boolean append=false;
946
947 private static final int SUB=Var.SUB, INS=Var.INS, DEL=Var.DEL;
948
949 private java.io.PrintStream outstream=System.err;
950 public static boolean verbose=false;
951
952 }