Debian Codegraph @

current/jgi/AssemblyStats2.java

raw symbols SCIP
1 package jgi;
2
3 import java.io.File;
4 import java.io.IOException;
5 import java.io.InputStream;
6 import java.io.PrintStream;
7 import java.util.ArrayList;
8 import java.util.Arrays;
9
10 import dna.AminoAcid;
11 import dna.FastaToChromArrays2;
12 import fileIO.FileFormat;
13 import fileIO.ReadWrite;
14 import fileIO.TextStreamWriter;
15 import json.JsonObject;
16 import shared.KillSwitch;
17 import shared.MetadataWriter;
18 import shared.Parse;
19 import shared.Parser;
20 import shared.PreParser;
21 import shared.Shared;
22 import shared.Timer;
23 import shared.Tools;
24 import structures.IntList;
25 import structures.LongList;
26
27
28 /**
29 * @author Brian Bushnell
30 * @date Sep 16, 2013
31 *
32 */
33 public final class AssemblyStats2 {
34
35 /*--------------------------------------------------------------*/
36
37 public static void main(String[] args){
38 AssemblyStats2 x=new AssemblyStats2(args);
39 x.process();
40
41 //Close the print stream if it was redirected
42 Shared.closeStream(outstream);
43 }
44
45 public AssemblyStats2(String[] args){
46
47 {//Preparse block for help, config files, and outstream
48 PreParser pp=new PreParser(args, outstream, null, false);
49 if(Shared.mainClass==null){Shared.mainClass=this.getClass();}
50 args=pp.args;
51 outstream=pp.outstream;
52 }
53
54 ReadWrite.USE_UNPIGZ=ReadWrite.USE_PIGZ=true;
55
56 int GCBINS_=200;
57 int MINSCAF_=0;
58 int gchistdecimals_=-1;
59
60 for(int i=0; i<args.length; i++){
61
62 if(true){
63 final 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.parseCommonStatic(arg, a, b)){
69 //do nothing
70 }else if(Parser.parseZip(arg, a, b)){
71 //do nothing
72 }else if(Parser.parseQuality(arg, a, b)){
73 //do nothing
74 }else if(arg.contains("=") && (a.equals("in") || a.equals("ref"))){
75 in=b;
76 }else if(a.equals("gc") || a.equals("gcout")){
77 gc=b;
78 if(b==null || "summaryonly".equalsIgnoreCase(b) || "none".equalsIgnoreCase(b)){
79 gc=null;
80 }
81 }else if(a.equals("gchist")){
82 gchistFile=b;
83 if(b==null || "none".equalsIgnoreCase(b)){
84 gchistFile=null;
85 }
86 }else if(a.equals("gchistdecimals")){
87 gchistdecimals_=Integer.parseInt(b);
88 }else if(a.equals("gcbins")){
89 int x=Integer.parseInt(b);
90 if(x>0){GCBINS_=Integer.parseInt(b);}
91 }else if(a.equals("shist") || a.equals("scaffoldhist")){
92 scaffoldHistFile=b;
93 if(b==null || "none".equalsIgnoreCase(b)){
94 scaffoldHistFile=null;
95 }
96 }else if(a.equals("out")){
97 out=b;
98 if(b==null || "summaryonly".equalsIgnoreCase(b) || "none".equalsIgnoreCase(b)){
99 out=null;
100 }else if("benchmark".equalsIgnoreCase(b)){
101 benchmark=true;
102 out=null;
103 gc=null;
104 }
105 }else if(a.equals("benchmark")){
106 benchmark=Parse.parseBoolean(b);
107 if(benchmark){
108 out=null;
109 gc=null;
110 }
111 }else if(a.equals("format")){
112 if("json".equalsIgnoreCase(b)){FORMAT=8;}
113 else{FORMAT=Integer.parseInt(b);}
114 if(FORMAT<0 || FORMAT>8){
115 throw new RuntimeException("\nUnknown format: "+FORMAT+"; valid values are 1 through 8.\n");
116 }
117 }else if(a.equals("json")){
118 if(Parse.parseBoolean(b)){FORMAT=8;}
119 else{FORMAT=1;}
120 }else if(a.equals("gcformat")){
121 GCFORMAT=Integer.parseInt(b);
122 if(GCFORMAT<0 || GCFORMAT>5){
123 throw new RuntimeException("\nUnknown gcformat: "+GCFORMAT+"; valid values are 0 through 5.\n");
124 }
125 }else if(a.equals("gcfraction")){
126 GC_FRACTION=Parse.parseBoolean(b);
127 }else if(a.equals("cutoff")){
128 cutoff=Parse.parseKMG(b);
129 }else if(a.equals("k") || a.equals("bbmapkmer")){
130 bbmapkmer=Integer.parseInt(b);
131 }else if(a.equals("printl90") || a.equals("l90") || a.equals("printn90") || a.equals("n90")){
132 printL90=Parse.parseBoolean(b);
133 }else if(a.equals("printextended") || a.equals("extended")){
134 printExtended=Parse.parseBoolean(b);
135 }else if(a.equals("overwrite") || a.equals("ow")){
136 overwrite=Parse.parseBoolean(b);
137 }else if(a.equals("n_")){
138 N_UNDERSCORE=Parse.parseBoolean(b);
139 }else if(a.equals("header") || a.equals("useheader")){
140 useheader=Parse.parseBoolean(b);
141 }else if(a.equals("addfilename") || a.equals("addname")){
142 addfilename=Parse.parseBoolean(b);
143 }else if(a.equals("minscaf") || a.equals("mincontig") || a.equals("minlen") || a.equals("min")){
144 MINSCAF_=Parse.parseIntKMG(b);
145 }else if(a.equals("showspeed") || a.equals("ss")){
146 showspeed=Parse.parseBoolean(b);
147 }else if(a.equals("printheadersize") || a.equals("phs")){
148 printheadersize=Parse.parseBoolean(b);
149 }else if(a.equals("skipduplicatelines") || a.equals("sdl")){
150 skipDuplicateLines=Parse.parseBoolean(b);
151 }else if(a.equals("printduplicatelines") || a.equals("pdl")){
152 skipDuplicateLines=!Parse.parseBoolean(b);
153 }else if(a.equals("showbbmap")){
154 if(!Parse.parseBoolean(b)){bbmapkmer=0;}
155 }else if(a.equals("contigbreak") || (arg.contains("=") && (a.equals("n")))){
156 maxNs=Integer.parseInt(b);
157 }
158
159 else if(a.equals("logsumoffset") || a.equals("logoffset")){
160 logSumOffset=Integer.parseInt(b);
161 }else if(a.equals("logsumbase") || a.equals("logbase")){
162 logSumBase=Double.parseDouble(b);
163 }else if(a.equals("squarelog") || a.equals("logsquare") || a.equals("logsquared")){
164 squareLog=Parse.parseBoolean(b);
165 }else if(a.equals("logpower")){
166 logPower=Double.parseDouble(b);
167 }else if(a.equals("powsum") || a.equals("powersum") || a.equals("powersumpower") || a.equals("powsumpower")){
168 powSumPower=Double.parseDouble(b);
169 }
170
171 else if(a.equalsIgnoreCase("assemblyScoreMinLen")){
172 assemblyScoreMinLen=Parse.parseKMG(b);
173 }else if(a.equalsIgnoreCase("assemblyScoreMaxLen")){
174 assemblyScoreMaxLen=Parse.parseKMG(b);
175 }else if(a.equalsIgnoreCase("alignedFraction") || a.equalsIgnoreCase("aligned") || a.equalsIgnoreCase("mapped")){
176 alignedFraction=Double.parseDouble(b);
177 if(alignedFraction>1){alignedFraction/=100;}
178 }else if(a.equals("score") || a.equals("assemblyscore")){
179 printAssemblyScore=Parse.parseBoolean(b);
180 }
181
182 else if(i>0 && (a.equals("n") || a.equals("-n")) && b!=null){
183 maxNs=Integer.parseInt(b);
184 }else if(in==null && i==0 && !arg.contains("=")){
185 in=arg;
186 }else{
187 throw new RuntimeException("Unknown parameter "+arg);
188 }
189 }
190 }
191
192 if(printExtended){
193 printL90=true;
194 }
195
196 {//Process parser fields
197 Parser.processQuality();
198 }
199
200 minScaffold=MINSCAF_;
201 gcbins=GCBINS_;
202
203 if(gchistdecimals_<1){
204 gchistdecimals_=3;
205 if(gcbins==2 || gcbins==5 || gcbins==10){
206 gchistdecimals_=1;
207 }else if(gcbins==20 || gcbins==25 || gcbins==50 || gcbins==100){
208 gchistdecimals_=2;
209 }
210 if(gcbins>1000 && gchistdecimals_<4){gchistdecimals_=4;}
211 if(gcbins>10000 && gchistdecimals_<5){gchistdecimals_=5;}
212 }
213 gchistDecimals1=gchistdecimals_;
214
215 if(maxNs<0){maxNs=10;}
216
217 if(out==null || out.equalsIgnoreCase("stdout") || out.equalsIgnoreCase("standardout")){out=null;}
218
219 clist=new LongList((int)Tools.min(1<<15, cutoff+1)); //Number of contigs of length x
220 slist=new LongList((int)Tools.min(1<<15, cutoff+1)); //Number of scaffolds of length x
221 sclist1=new LongList((int)Tools.min(1<<15, cutoff+1)); //Sum of contigs per scaffold of length x
222 sclist2=new LongList((int)Tools.min(1<<15, cutoff+1)); //Sum of contig lengths per scaffold of length x
223
224 llist=new LongList(64); //List of contig lengths for contigs at least cutoff in length
225 tlist=new ArrayList<Triple>(64); //List of scaf len, contigs, contig sum for scaffolds at least cutoff in length
226
227 gcbins2=(gcbins>=1000 ? gcbins : gcbins*10);
228
229 gchistArray=new long[gcbins2];
230 gchist_by_base=new long[gcbins2];
231
232 }
233
234 /*--------------------------------------------------------------*/
235
236 public void process(){
237 Timer t=new Timer();
238
239 InputStream is=null;
240 {
241 if(in==null){throw new RuntimeException("No input file.");}
242 if(in.equalsIgnoreCase("stdin") || in.equalsIgnoreCase("standardin")){
243 is=System.in;
244 }else{
245 File f=new File(in);
246 if((!f.exists() || f.isDirectory()) && !in.toLowerCase().startsWith("stdin")){
247 throw new RuntimeException("Input file does not appear to be valid: "+in);
248 }
249 }
250 }
251
252 long[] counts=null;
253 long sum=0;
254
255 boolean fastqMode=false;
256 if(is!=System.in){
257 FileFormat ff=null;
258 try {
259 ff=FileFormat.testInput(in, FileFormat.FA, null, false, true, true);
260 } catch (Throwable e) {
261 e.printStackTrace();
262 }
263 if(ff!=null){
264 fastqMode=ff.fastq();
265 }
266 assert(!ff.samOrBam()) : "AssemblyStats does not support sam/bam files, only fasta and fastq.";
267 // assert(ff==null || (!ff.fastq())) : "AssemblyStats only supports fasta files. To override this message, use the -da flag.";
268 }
269
270 if(is==null){is=ReadWrite.getInputStream(in, false, true);}
271 try {
272 if(benchmark){sum=bench(is);}
273 else{
274 if(fastqMode){
275 counts=countFastq(is, gc);
276 }else{
277 counts=countFasta(is, gc);
278 }
279 }
280 } catch (IOException e) {
281 e.printStackTrace();
282 }
283 try {
284 if(is!=System.in){is.close();}
285 } catch (IOException e) {
286 e.printStackTrace();
287 }
288
289 if(tlist!=null && tlist.size()>0){Shared.sort(tlist);}
290 if(llist!=null && llist.size>0){Shared.sort(llist.array, 0, llist.size);}
291
292 t.stop();
293
294 if(benchmark){
295 printBenchResults(t, counts, sum, in);
296 }else{
297 // outstream.println("\nclist="+clist+"\nslist="+slist+"\nsclist1="+sclist1+"\nsclist2="+sclist2+"\nllist="+llist+"\ntlist="+tlist+"\n"); //***
298 // outstream.println("\nclist.size="+clist.size+"\nslist.size="+slist.size+"\nsclist1.size="+sclist1.size+"\nsclist2.size="+sclist2.size+"\nllist.size="+llist.size+"\ntlist.size()="+tlist.size()+"\n"); //***
299 printResults(t, counts, sum, minScaffold, gc_std, in, clist, slist, sclist1, sclist2, llist, tlist, out);
300 // outstream.println("Printed results to "+out);
301 writeHistFile(scaffoldHistFile, slist, tlist, false);
302
303 if(gchistFile!=null){printGCHist(gchistFile);}
304 }
305 }
306
307 /*--------------------------------------------------------------*/
308
309 public long[] countFasta(final InputStream is, String gcout) throws IOException{
310
311 long limsum=0;
312 long headerlen=0;
313 final byte[] buf=new byte[32768];
314 final TextStreamWriter tswgc=(gcout==null ? null : new TextStreamWriter(gcout, overwrite, append, false));
315 if(tswgc!=null){
316 tswgc.start();
317 if(GCFORMAT==0 || GCFORMAT==1){
318 tswgc.println("#Name\tLength\tA\tC\tG\tT\tN\tIUPAC\tOther\tGC");
319 }else if(GCFORMAT==2){
320 tswgc.println("#Name\tGC");
321 }else if(GCFORMAT==3){
322 tswgc.println("#Name\tLength\tA\tC\tG\tT\tN\tIUPAC\tOther\tGC");
323 }else if(GCFORMAT==4){
324 tswgc.println("#Name\tLength\tGC");
325 }else if(GCFORMAT==5){
326 tswgc.println("#Name\tLength\tGC\tlogsum\tpowersum");
327 }else{
328 throw new RuntimeException("Unknown format.");
329 }
330 }
331 // assert(false) : GCFORMAT+", "+out+", "+tswgc;
332 final long[] counts=KillSwitch.allocLong1D(8);
333 final long[] overall=KillSwitch.allocLong1D(8);
334 final StringBuilder hdr=(gcout==null ? null : new StringBuilder());
335 boolean hdmode=false;
336
337 int i=0;
338 int lim=is.read(buf);
339 limsum+=lim;
340
341 int contigs=0;
342 int contiglen=0;
343 // int contiglensum=0;
344 int scaffoldlen=0;
345 int ns=0;
346
347 final IntList currentContigs=new IntList(10000);
348
349 while(lim>0){
350 if(hdmode){//Scan to end of header.
351 if(hdr==null){//Header is not being stored
352 while(i<lim){
353 final byte c=buf[i];
354 i++;
355 if(c<=slashr){
356 hdmode=false;
357 contiglen=0;
358 // contiglensum=0;
359 scaffoldlen=0;
360 ns=0;
361 contigs=0;
362 break;
363 }
364 headerlen++;
365 }
366 }else{//Store the header
367 while(i<lim){
368 final byte c=buf[i];
369 i++;
370 if(c<=slashr){
371 hdmode=false;
372 contiglen=0;
373 // contiglensum=0;
374 scaffoldlen=0;
375 ns=0;
376 contigs=0;
377 break;
378 }
379 hdr.append((char)c);
380 }
381 }
382 }
383
384 if(!hdmode){//Scan bases
385 while(i<lim){
386 final byte c=buf[i];
387 assert(c>=0) : i+(hdr==null ? "Non-ascii input." : "\nError with header: "+hdr);
388 final byte cnum=charToNum[c];
389 i++;
390
391 if(c==carrot){//Start of a new header
392 // assert(false) : scaffoldlen;
393 hdmode=true;
394 if(scaffoldlen>0){//if the scaffold was not blank
395
396 {//NEW
397 if(contiglen>0 || contigs==0){
398 currentContigs.set(contigs, contiglen);
399 contigs++;
400 // System.out.println("For header "+hdr+": added contig. len="+contiglen+", contigs="+contigs);
401 // contiglensum+=contiglen;
402 }
403 }
404
405 // assert(false);
406 if(scaffoldlen>=minScaffold){
407
408 int contiglensum=0;
409 {//NEW
410 // System.out.println("Dumping "+contigs+" contigs.");
411 for(int j=0; j<contigs; j++){
412 final int cl=currentContigs.get(j);
413 if(cl>0 || contigs==0){
414 contiglensum+=cl;
415 if(cl<cutoff){
416 clist.increment(cl, 1);
417 }else{
418 llist.add(cl);
419 }
420 }
421 }
422 }
423
424 if(scaffoldlen<cutoff){
425 slist.increment(scaffoldlen, 1);
426 sclist1.increment(scaffoldlen, contigs);
427 sclist2.increment(scaffoldlen, contiglensum);
428 }else{
429 tlist.add(new Triple(scaffoldlen, contigs, contiglensum));
430 }
431
432
433 if(hdr!=null){
434 if(tswgc!=null){tswgc.print(toString2(hdr, counts));}//if added for compiler benefit
435 headerlen+=hdr.length();
436 hdr.setLength(0);
437 }
438 {
439 long gc=counts[1]+counts[2];
440 long acgt=gc+counts[0]+counts[3];
441 if(acgt>0){
442 int index=Tools.min((int)((gc*gcbins2)/acgt),gcbins2-1);
443 gchistArray[index]++;
444 gchist_by_base[index]+=scaffoldlen;
445 // assert(false);
446 }
447 }
448 for(int j=0; j<counts.length; j++){
449 overall[j]+=counts[j];
450 counts[j]=0;
451 }
452 }else{
453 Arrays.fill(counts, 0);
454 if(hdr!=null){hdr.setLength(0);}
455 }
456 }
457
458 break;
459 }
460
461 if(c>slashr){
462 counts[cnum]++;
463 scaffoldlen++;
464
465 // if(c!=noref && c!=noref2){
466 if(cnum!=5){
467 ns=0;
468 contiglen++;
469 }else{
470 ns++;
471 if(ns==maxNs && contiglen>0){
472 // if(contiglen<cutoff){
473 // clist.increment(contiglen, 1);
474 // }else{
475 // llist.add(contiglen);
476 // }
477 //// clist.increment(contiglen, 1);
478 // contiglensum+=contiglen;
479 // contiglen=0;
480 // contigs++;
481
482 {//NEW
483 currentContigs.set(contigs, contiglen);
484 contiglen=0;
485 contigs++;
486 }
487 }
488 }
489 }
490 }
491 }
492 if(i>=lim){
493 i=0;
494 lim=is.read(buf);
495 limsum+=lim;
496 }
497 }
498
499 if(scaffoldlen>0){
500
501 // if(contiglen>0 || contigs==0){
502 // contigs++;
503 // contiglensum+=contiglen;
504 // if(contiglen<cutoff){
505 // clist.increment(contiglen, 1);
506 // }else{
507 // llist.add(contiglen);
508 // }
509 // }
510
511 {//NEW
512 if(contiglen>0 || contigs==0){
513 currentContigs.set(contigs, contiglen);
514 contigs++;
515 // contiglensum+=contiglen;
516 }
517 }
518
519 if(scaffoldlen>=minScaffold){
520
521 int contiglensum=0;
522 {//NEW
523 // System.out.println("Dumping "+contigs+" contigs.");
524 for(int j=0; j<contigs; j++){
525 final int cl=currentContigs.get(j);
526 if(cl>0 || contigs==0){
527 contiglensum+=cl;
528 if(cl<cutoff){
529 clist.increment(cl, 1);
530 }else{
531 llist.add(cl);
532 }
533 }
534 }
535 }
536
537 if(scaffoldlen<cutoff){
538 slist.increment(scaffoldlen, 1);
539 sclist1.increment(scaffoldlen, contigs);
540 sclist2.increment(scaffoldlen, contiglensum);
541 }else{
542 tlist.add(new Triple(scaffoldlen, contigs, contiglensum));
543 }
544
545
546 // slist.increment(scaffoldlen, 1);
547 // if(contiglen>0 || contigs==0){
548 // contigs++;
549 // contiglensum+=contiglen;
550 // clist.increment(contiglen, 1);
551 // }
552 // sclist1.increment(scaffoldlen, contigs);
553 // sclist2.increment(scaffoldlen, contiglensum);
554
555 if(hdr!=null){
556 if(tswgc!=null){tswgc.print(toString2(hdr, counts));}//if added for compiler benefit
557 hdr.setLength(0);
558 }
559
560 {
561 long gc=counts[1]+counts[2];
562 long acgt=gc+counts[0]+counts[3];
563 if(acgt>0){
564 int index=Tools.min((int)((gc*gcbins2)/acgt),gcbins2-1);
565 gchistArray[index]++;
566 gchist_by_base[index]+=scaffoldlen;
567 }
568 }
569 for(int j=0; j<counts.length; j++){
570 overall[j]+=counts[j];
571 counts[j]=0;
572 }
573 }
574 }
575
576 // outstream.println("clist="+clist+"\nslist="+slist+"\nsclist1="+sclist1+"\nsclist2="+sclist2+"\nllist="+llist+"\ntlist="+tlist); //***
577
578
579 if(tswgc!=null){
580 if(tswgc.fname.equalsIgnoreCase("stdout") || tswgc.fname.startsWith("stdout.")){
581 if(FORMAT>0 && (out==null || out.equalsIgnoreCase("stdout") || out.startsWith("stdout."))){
582 tswgc.print("\n");
583 }
584 }
585 tswgc.poison();
586 tswgc.waitForFinish();
587 }
588 LIMSUM=limsum;
589 HEADERLENSUM=headerlen;
590
591
592 gc_std=Tools.standardDeviationHistogram(gchistArray)/gcbins2;
593 gchistArray_downsampled=Tools.downsample(gchistArray, gcbins);
594
595 gc_bb_std=Tools.standardDeviationHistogram(gchist_by_base)/gcbins2;
596 gchist_by_base_downsampled=Tools.downsample(gchist_by_base, gcbins);
597
598 return overall;
599 }
600
601 public long[] countFastq(final InputStream is, String gcout) throws IOException{
602
603 long limsum=0;
604 long headerlen=0;
605 final byte[] buf=new byte[32768];
606 final TextStreamWriter tswgc=(gcout==null ? null : new TextStreamWriter(gcout, overwrite, false, false));
607 if(tswgc!=null){
608 tswgc.start();
609 if(GCFORMAT==0 || GCFORMAT==1){
610 tswgc.println("#Name\tLength\tA\tC\tG\tT\tN\tIUPAC\tOther\tGC");
611 }else if(GCFORMAT==2){
612 tswgc.println("#Name\tGC");
613 }else if(GCFORMAT==3){
614 tswgc.println("#Name\tLength\tA\tC\tG\tT\tN\tIUPAC\tOther\tGC");
615 }else if(GCFORMAT==4){
616 tswgc.println("#Name\tLength\tGC");
617 }else if(GCFORMAT==5){
618 tswgc.println("#Name\tLength\tGC\tlogsum\tpowersum");
619 }else{
620 throw new RuntimeException("Unknown format.");
621 }
622 }
623 // assert(false) : GCFORMAT+", "+out+", "+tswgc;
624 final long[] counts=KillSwitch.allocLong1D(8);
625 final long[] overall=KillSwitch.allocLong1D(8);
626 final StringBuilder hdr=(gcout==null ? null : new StringBuilder());
627 int line=0;
628
629 int i=0;
630 int lim=is.read(buf);
631 limsum+=lim;
632
633 int contigs=0;
634 int contiglen=0;
635 // int contiglensum=0;
636 int scaffoldlen=0;
637 int ns=0;
638
639 final IntList currentContigs=new IntList(10000);
640
641 while(lim>0){
642 if(line==0){//Scan to end of header.
643 // outstream.println("1");
644 if(hdr==null){//Header is not being stored
645 while(i<lim){
646 final byte c=buf[i];
647 i++;
648 if(c<=slashr){
649 line++;
650 // outstream.println("1.1");
651 contiglen=0;
652 // contiglensum=0;
653 scaffoldlen=0;
654 ns=0;
655 contigs=0;
656 break;
657 }
658 headerlen++;
659 }
660 }else{//Store the header
661 while(i<lim){
662 final byte c=buf[i];
663 i++;
664 if(c<=slashr){
665 line++;
666 // outstream.println("1.2");
667 contiglen=0;
668 // contiglensum=0;
669 scaffoldlen=0;
670 ns=0;
671 contigs=0;
672 break;
673 }
674 hdr.append((char)c);
675 }
676 }
677 }
678
679 if(line==1){//Scan bases
680 // outstream.println("2");
681 while(i<lim){
682 final byte c=buf[i];
683 final byte cnum=charToNum[c];
684 i++;
685
686 if(c<=slashr){//Finish the contig
687 // assert(false) : scaffoldlen;
688 line=(line+1)&3;
689 // outstream.println("2.1");
690 if(scaffoldlen>0){//if the scaffold was not blank
691
692 {//NEW
693 if(contiglen>0 || contigs==0){
694 currentContigs.set(contigs, contiglen);
695 contigs++;
696 // System.out.println("For header "+hdr+": added contig. len="+contiglen+", contigs="+contigs);
697 // contiglensum+=contiglen;
698 }
699 }
700
701 // assert(false);
702 if(scaffoldlen>=minScaffold){
703
704 int contiglensum=0;
705 {//NEW
706 // System.out.println("Dumping "+contigs+" contigs.");
707 for(int j=0; j<contigs; j++){
708 final int cl=currentContigs.get(j);
709 if(cl>0 || contigs==0){
710 contiglensum+=cl;
711 if(cl<cutoff){
712 clist.increment(cl, 1);
713 }else{
714 llist.add(cl);
715 }
716 }
717 }
718 }
719
720 if(scaffoldlen<cutoff){
721 slist.increment(scaffoldlen, 1);
722 sclist1.increment(scaffoldlen, contigs);
723 sclist2.increment(scaffoldlen, contiglensum);
724 }else{
725 tlist.add(new Triple(scaffoldlen, contigs, contiglensum));
726 }
727
728
729 if(hdr!=null){
730 if(tswgc!=null){tswgc.print(toString2(hdr, counts));}//if added for compiler benefit
731 headerlen+=hdr.length();
732 hdr.setLength(0);
733 }
734 {
735 long gc=counts[1]+counts[2];
736 long acgt=gc+counts[0]+counts[3];
737 if(acgt>0){
738 int index=Tools.min((int)((gc*gcbins2)/acgt),gcbins2-1);
739 gchistArray[index]++;
740 gchist_by_base[index]+=scaffoldlen;
741 // assert(false);
742 }
743 }
744 for(int j=0; j<counts.length; j++){
745 overall[j]+=counts[j];
746 counts[j]=0;
747 }
748 }else{
749 Arrays.fill(counts, 0);
750 if(hdr!=null){hdr.setLength(0);}
751 }
752 }
753
754 break;
755 }
756
757 if(c>slashr){
758 counts[cnum]++;
759 scaffoldlen++;
760
761 // if(c!=noref && c!=noref2){
762 if(cnum!=5){
763 ns=0;
764 contiglen++;
765 }else{
766 ns++;
767 if(ns==maxNs && contiglen>0){
768 // if(contiglen<cutoff){
769 // clist.increment(contiglen, 1);
770 // }else{
771 // llist.add(contiglen);
772 // }
773 //// clist.increment(contiglen, 1);
774 // contiglensum+=contiglen;
775 // contiglen=0;
776 // contigs++;
777
778 {//NEW
779 currentContigs.set(contigs, contiglen);
780 contiglen=0;
781 contigs++;
782 }
783 }
784 }
785 }
786 }
787 }
788
789 // outstream.println("3");
790 if(i>=lim){
791 i=0;
792 lim=is.read(buf);
793 limsum+=lim;
794 }
795
796 // outstream.println("4");
797 assert(line>1 || lim<=i || i==0) : line+", "+i+", "+lim;
798 while(i<lim && line>1){
799 final byte c=buf[i];
800 i++;
801 if(c<=slashr){
802 line=(line+1)&3;
803 }
804 }
805 }
806
807 if(tswgc!=null){
808 if(tswgc.fname.equalsIgnoreCase("stdout") || tswgc.fname.startsWith("stdout.")){
809 if(FORMAT>0 && (out==null || out.equalsIgnoreCase("stdout") || out.startsWith("stdout."))){
810 tswgc.print("\n");
811 }
812 }
813 tswgc.poison();
814 tswgc.waitForFinish();
815 }
816 LIMSUM=limsum;
817 HEADERLENSUM=headerlen;
818
819
820 gc_std=Tools.standardDeviationHistogram(gchistArray)/gcbins2;
821 gchistArray_downsampled=Tools.downsample(gchistArray, gcbins);
822
823 gc_bb_std=Tools.standardDeviationHistogram(gchist_by_base)/gcbins2;
824 gchist_by_base_downsampled=Tools.downsample(gchist_by_base, gcbins);
825
826 return overall;
827 }
828
829 /*--------------------------------------------------------------*/
830
831 private void printGCHist(String gchistFile){
832 if(!Tools.canWrite(gchistFile, overwrite)){
833 outstream.println("Can't write gc histogram because file exists and overwrite="+overwrite);
834 assert(false);
835 }else{
836 long gchistFilesum=shared.Vector.sum(gchistArray_downsampled);
837 long gchistFilesumbb=shared.Vector.sum(gchist_by_base_downsampled);
838 double invsum=(gchistFilesum==0 ? 0 : 1.0/gchistFilesum);
839 double invsumbb=(gchistFilesum==0 ? 0 : 1.0/gchistFilesumbb);
840 double invbins=1.0/(gcbins==0 ? 1 : gcbins);
841 // assert(false) : Arrays.toString(gchistArray);
842 StringBuilder sb=new StringBuilder();
843 sb.append(Tools.format("#GC\tscaffolds\tfraction\tlength\tlen_fraction\n"));
844 for(int i=0; i<gcbins; i++){
845 sb.append(Tools.format("%."+gchistDecimals1+"f\t%d\t%.5f\t%d\t%.5f\n",
846 i*invbins, gchistArray_downsampled[i], gchistArray_downsampled[i]*invsum, gchist_by_base_downsampled[i], gchist_by_base_downsampled[i]*invsumbb));
847 }
848 if(gchistFile.equalsIgnoreCase("stdout")){
849 System.out.println(sb);
850 }else{
851 ReadWrite.writeString(sb, gchistFile);
852 }
853 }
854 }
855
856
857 public static void printBenchResults(Timer t, long[] counts, long sum, String in){
858 outstream.println("Time: \t"+t);
859 long bytes=new File(in).length();
860 if(bytes<1){bytes=LIMSUM;}
861 double mbps1=bytes*1000d/t.elapsed;
862 double mbps2=sum*1000d/t.elapsed;
863 outstream.println(Tools.format("Raw Speed: \t%.2f MBytes/s",mbps1));
864 outstream.println(Tools.format("Uncompressed Speed:\t%.2f MBytes/s",mbps2));
865 }
866
867 public static double calcLogSumContigs(LongList clist, LongList llist, int cutoff, double base){
868 return calcLogSumCounts(clist, cutoff, base)+calcLogSumLengths(llist, cutoff, base);
869 }
870
871 public static double calcLogSumScaffolds(LongList slist, ArrayList<Triple> tlist, int cutoff, double base){
872 return calcLogSumCounts(slist, cutoff, base)+calcLogSumTriples(tlist, cutoff, base);
873 }
874
875 public static double calcPowerSumContigs(LongList clist, LongList llist, int cutoff, double power){
876 return calcPowerSumCounts(clist, cutoff, power)+calcPowerSumLengths(llist, cutoff, power);
877 }
878
879 public static double calcPowerSumScaffolds(LongList slist, ArrayList<Triple> tlist, int cutoff, double power){
880 return calcPowerSumCounts(slist, cutoff, power)+calcPowerSumTriples(tlist, cutoff, power);
881 }
882
883 public static double calcAssemblyScore(LongList slist, ArrayList<Triple> tlist, long min, long max, double aligned){
884 long lengthSum=0;
885 double scoreSum=0;
886 for(int i=(int)min; i<slist.size(); i++){
887 long count=slist.get(i);
888 lengthSum+=(i*count);
889 }
890 for(Triple t : tlist){
891 lengthSum+=t.length;
892 }
893
894 double mult=1.0/(1000*lengthSum);
895 for(int i=(int)min; i<slist.size(); i++){
896 long count=slist.get(i);
897 if(count>0){
898 scoreSum+=count*(i*Tools.min(max, i))*mult;
899 }
900 }
901 for(Triple t : tlist){
902 scoreSum+=(t.length*Tools.min(max, t.length))*mult;
903 }
904
905 return scoreSum+aligned*50;
906 }
907
908 public static double calcLogSumCounts(LongList counts, int cutoff, double base){
909 final double mult=1/Math.log(base);
910
911 double sum=0;
912 for(int i=cutoff, max=counts.size(); i<max; i++){
913 long count=counts.get(i);
914 if(count>0){
915 double log=mult*Math.log(i);
916 if(squareLog){log=log*log*0.05;}
917 else if(logPower!=1){log=Math.pow(log*0.12, logPower);}
918 double incr=log*count*i;
919 sum+=incr;
920 }
921 }
922 return sum;
923 }
924
925 private static double logsum(long len){
926 if(len<logSumOffset){return 0;}
927 final double mult=1/Math.log(logSumBase);
928 double log=mult*Math.log(len);
929 if(squareLog){log=log*log*0.05;}
930 else if(logPower!=1){log=Math.pow(log*0.12, logPower);}
931 double incr=log*len;
932 return incr/logSumOffset;
933 }
934
935 public static double calcLogSumLengths(LongList lengths, int cutoff, double base){
936 final double mult=1/Math.log(base);
937
938 double sum=0;
939 for(int i=0, max=lengths.size(); i<max; i++){
940 long length=lengths.get(i);
941 if(length>=cutoff){
942 double log=mult*Math.log(length);
943 if(squareLog){log=log*log*0.05;}
944 else if(logPower!=1){log=Math.pow(log*0.12, logPower);}
945 double incr=log*length;
946 sum+=incr;
947 }
948 }
949 return sum;
950 }
951
952 public static double calcLogSumTriples(ArrayList<Triple> triples, int cutoff, double base){
953 final double mult=1/Math.log(base);
954
955 double sum=0;
956 for(int i=0, max=triples.size(); i<max; i++){
957 long length=triples.get(i).length;
958 if(length>=cutoff){
959 double log=mult*Math.log(length);
960 if(squareLog){log=log*log*0.05;}
961 else if(logPower!=1){log=Math.pow(log*0.12, logPower);}
962 double incr=log*length;
963 sum+=incr;
964 }
965 }
966 return sum;
967 }
968
969 public static double calcPowerSumCounts(LongList counts, int cutoff, double power){
970 final double mult=1/Math.pow(1000, power);
971
972 double sum=0;
973 for(int i=cutoff, max=counts.size(); i<max; i++){
974 long count=counts.get(i);
975 if(count>0){
976 double pow=mult*Math.pow(i, power);
977 double incr=pow*count*i;
978 sum+=incr;
979 }
980 }
981 return sum;
982 }
983
984 private static double powersum(long len){
985 if(len<logSumOffset){return 0;}
986 final double mult=1/Math.pow(1000, powSumPower);
987 double pow=mult*Math.pow(len, powSumPower);
988 double incr=pow*len;
989 return incr/logSumOffset;
990 }
991
992 public static double calcPowerSumLengths(LongList lengths, int cutoff, double power){
993 final double mult=1/Math.pow(1000, power);
994
995 double sum=0;
996 for(int i=0, max=lengths.size(); i<max; i++){
997 long length=lengths.get(i);
998 if(length>=cutoff){
999 double pow=mult*Math.pow(length, power);
1000 double incr=pow*length;
1001 sum+=incr;
1002 }
1003 }
1004 return sum;
1005 }
1006
1007 public static double calcPowerSumTriples(ArrayList<Triple> triples, int cutoff, double power){
1008 final double mult=1/Math.pow(1000, power);
1009
1010 double sum=0;
1011 for(int i=0, max=triples.size(); i<max; i++){
1012 long length=triples.get(i).length;
1013 if(length>=cutoff){
1014 double pow=mult*Math.pow(length, power);
1015 double incr=pow*length;
1016 sum+=incr;
1017 }
1018 }
1019 return sum;
1020 }
1021
1022 public static void printResults(Timer t, long[] counts, long sum, long minScaffold, double gc_std, String in, LongList clist, LongList slist, LongList sclist1, LongList sclist2,
1023 LongList llist, ArrayList<Triple> tlist, String out){
1024
1025 String name=in;
1026 if(in!=null && !in.toLowerCase().startsWith("stdin")){
1027 try {
1028 File f=new File(in);
1029 name=f.getCanonicalPath();
1030 } catch (IOException e) {}
1031 }
1032
1033 long contigs=0;
1034 long scaffolds=0;
1035 long contiglen=0;
1036 long scaflen=0;
1037 long contigs1;
1038 long contiglen2;
1039 long maxScaf=0, maxContig=0;
1040 long[] carray=clist.array;
1041 long[] sarray=slist.array;
1042 long[] scarray1=sclist1.array;
1043 long[] scarray2=sclist2.array;
1044
1045 long[] larray=llist.array;
1046
1047 StringBuilder sb=new StringBuilder(), sb2=new StringBuilder();
1048
1049 for(int i=0; i<carray.length; i++){
1050 long x=carray[i];
1051 if(x>0){
1052 contigs+=x;
1053 contiglen+=(x*i);
1054 maxContig=i;
1055 }
1056 }
1057
1058 for(int i=0; i<sarray.length; i++){
1059 long x=sarray[i];
1060 if(x>0){
1061 scaffolds+=x;
1062 scaflen+=(x*i);
1063 maxScaf=i;
1064 }
1065 }
1066
1067 contigs+=llist.size;
1068 for(int i=0; i<llist.size; i++){
1069 long x=larray[i];
1070 assert(x>0);
1071 contiglen+=x;
1072 maxContig=Tools.max(maxContig, x);
1073 }
1074
1075 scaffolds+=tlist.size();
1076 for(Triple tp : tlist){
1077 scaflen+=tp.length;
1078 maxScaf=Tools.max(maxScaf, tp.length);
1079 }
1080
1081 if(FORMAT<3){
1082 sb.append("Main genome scaffold total: \t"+scaffolds+"\n");
1083 sb.append("Main genome contig total: \t"+contigs+"\n");
1084 }else if(FORMAT==7){
1085 sb.append("Main genome contig total: \t"+contigs+"\n");
1086 }
1087
1088 if(FORMAT==0){
1089 }else if(FORMAT==1){
1090 sb.append("Main genome scaffold sequence total:\t"+Tools.format("%.3f Mb",scaflen/1000000f)+"\n");
1091 sb.append("Main genome contig sequence total: \t"+Tools.format("%.3f Mb \t%.3f%% gap",contiglen/1000000f,(scaflen-contiglen)*100f/scaflen)+"\n");
1092 }else if(FORMAT==2){
1093 sb.append("Main genome scaffold sequence total:\t"+scaflen+"\n");
1094 sb.append("Main genome contig sequence total: \t"+Tools.format("%d \t%.3f%% gap",contiglen,(scaflen-contiglen)*100f/scaflen)+"\n");
1095 }else if(FORMAT==3 || FORMAT==6){
1096
1097 }else if(FORMAT==4){
1098
1099 }else if(FORMAT==5){
1100
1101 }else if(FORMAT==8){
1102
1103 }else if(FORMAT==7){
1104 sb.append("Main genome contig sequence total: \t"+Tools.format("%.3f Mb",contiglen/1000000f)+"\n");
1105 }else{throw new RuntimeException("Unknown format");}
1106
1107 if(FORMAT<3){
1108 sb2.append("\n");
1109 sb2.append("Minimum \tNumber \tNumber \tTotal \tTotal \tScaffold\n");
1110 sb2.append("Scaffold\tof \tof \tScaffold \tContig \tContig \n");
1111 sb2.append("Length \tScaffolds \tContigs \tLength \tLength \tCoverage\n");
1112 sb2.append("--------\t--------------\t--------------\t--------------\t--------------\t--------\n");
1113 }else if(FORMAT==7){
1114 sb2.append("\n");
1115 sb2.append("Minimum \tNumber \tTotal \n");
1116 sb2.append("Contig \tof \tContig \n");
1117 sb2.append("Length \tContigs \tLength \n");
1118 sb2.append("--------\t--------------\t--------------\n");
1119 }
1120
1121 final int[] lims;
1122
1123 if(FORMAT==7){
1124 int minScaf=-1;
1125 for(int i=0; i<carray.length && minScaf<0; i++){
1126 long x=sarray[i];
1127 if(x>0){minScaf=i;}
1128 }
1129 if(minScaf<0 && !tlist.isEmpty()){
1130 minScaf=(int)Tools.min(tlist.get(0).length, 250000000);
1131 }
1132 if(minScaf<1){minScaf=1;}
1133 int[] temp=new int[] {0, 50, 100, 250, 500, 1000, 2500, 5000, 10000, 25000, 50000, 100000,
1134 250000, 500000, 1000000, 2500000, 5000000, 10000000, 25000000, 50000000, 100000000, 250000000};
1135 ArrayList<Integer> tempList=new ArrayList<Integer>();
1136 tempList.add(0);
1137 for(int i=1; i<temp.length; i++){
1138 int x=temp[i];
1139 int prev=temp[i-1];
1140 if(x>=minScaf || i==temp.length-1){
1141 if(prev<minScaf){
1142 tempList.add(minScaf);
1143 }else{
1144 tempList.add(x);
1145 }
1146 }
1147 }
1148 lims=new int[tempList.size()];
1149 for(int i=0; i<lims.length; i++){
1150 lims[i]=tempList.get(i);
1151 }
1152 }else{
1153 lims=new int[] {0, 50, 100, 250, 500, 1000, 2500, 5000, 10000, 25000, 50000, 100000,
1154 250000, 500000, 1000000, 2500000, 5000000, 10000000, 25000000, 50000000, 100000000, 250000000};
1155 }
1156
1157 int lidx=0;
1158 int next=0;
1159 long csum=contigs;
1160 long ssum=scaffolds;
1161 long clen=contiglen;
1162 long slen=scaflen;
1163
1164 long ln50=-1;
1165 long ll50=-1;
1166 long cn50=-1;
1167 long cl50=-1;
1168
1169 long ln90=-1;
1170 long ll90=-1;
1171 long cn90=-1;
1172 long cl90=-1;
1173
1174 long s50=slen/2;
1175 long c50=clen/2;
1176
1177 long s90=(int)(slen*0.9f);
1178 long c90=(int)(clen*0.9f);
1179
1180 final int numOverCutoff=(FORMAT==7 ? 1000 : 50000);
1181 final int numOverCutoffPlusOne=numOverCutoff+1;
1182 long numOver50=0;
1183 long basesOver50=0;
1184 float fractionOver50=0;
1185
1186
1187 //Disable printing of 50~500 when not needed
1188 // {
1189 // boolean b=true;
1190 // for(int i=0; i<500 && i<sarray.length && b; i++){
1191 // b=(sarray[i]==0);
1192 // }
1193 // if(b){
1194 // lidx=Arrays.binarySearch(lims, 1000)-1;
1195 // lims[lidx]=0;
1196 // }
1197 // }
1198 if(skipDuplicateLines){
1199 int maxZero=-1;
1200 for(int i=0; i<sarray.length && sarray[i]==0; i++){
1201 maxZero=i;
1202 }
1203 if(maxZero>=50){
1204 for(int i=1; i<lims.length; i++){
1205 if(lims[i]<=maxZero){
1206 lidx=i-1;
1207 lims[lidx]=0;
1208 }else{break;}
1209 }
1210 }
1211 }
1212
1213 final int lim=slist.size;
1214 assert(lim<=sarray.length);
1215
1216 {
1217 //These two loops generate the scaffold table
1218 long prevSsum=-1, prevCsum=-1, prevSlen=-1, prevClen=-1;
1219 String prevLine=null;
1220 for(int i=0; i<lim && slen>0; i++){
1221 // System.out.println("\n<A1>\ti="+i+", lidx="+lidx+", lims.length="+lims.length+", next="+next+", sarray.length="+sarray.length+", slen="+slen);
1222
1223 if(i==next){
1224 prevLine=formatX(next, ssum, csum, slen, clen);
1225 // if(!skipDuplicateLines || ssum!=prevSsum || csum!=prevCsum || slen!=prevSlen || clen!=prevClen){
1226 if(prevLine!=null && (next==0 || next>=minScaffold)){
1227 sb2.append(prevLine);
1228 sb2.append('\n');
1229 prevLine=null;
1230 }
1231 // }
1232 prevSsum=ssum; prevCsum=csum; prevSlen=slen; prevClen=clen;
1233
1234 lidx++;
1235 if(lidx<lims.length){next=lims[lidx];}
1236 else{next=-1;}
1237 // System.out.println("<A2>\ti="+i+", lidx="+lidx+", lims.length="+lims.length+", next="+next+", sarray.length="+sarray.length+", slen="+slen);
1238 // System.out.prontln(sb2);
1239 }
1240 // System.out.println("<A3>\ti="+i+", lidx="+lidx+", lims.length="+lims.length+", next="+next+", sarray.length="+sarray.length+", slen="+slen);
1241
1242 if(i==numOverCutoffPlusOne){
1243 numOver50=ssum;
1244 basesOver50=slen;
1245 fractionOver50=slen*100f/scaflen;
1246 }
1247
1248 // long a=carray[i];
1249 long b=sarray[i];
1250 long c=scarray1[i];
1251 long d=scarray2[i];
1252
1253 if(b>0){
1254 csum-=c;
1255 ssum-=b;
1256 clen-=d;
1257 slen-=(b*i);
1258 }
1259
1260 if(ln50==-1 && slen<=s50){
1261 ln50=i;
1262 ll50=ssum+b;
1263 }
1264
1265 if(ln90==-1 && slen<=s90){
1266 ln90=i;
1267 ll90=ssum+b;
1268 }
1269 // System.out.println("<A4>\tb="+b+", c="+c+", d="+d+", csum="+csum+", ssum="+ssum+", clen="+clen+", slen="+slen);
1270
1271 // System.out.println("<A5>\ti="+i+", lidx="+lidx+", lims.length="+lims.length+", next="+next+", sarray.length="+sarray.length+", slen="+slen);
1272
1273 }
1274
1275 for(Triple tp : tlist){
1276 // assert(false) : tlist;
1277 while(tp.length>=next && lidx<lims.length){
1278
1279 prevLine=formatX(next, ssum, csum, slen, clen);
1280 // if(!skipDuplicateLines || ssum!=prevSsum || csum!=prevCsum || slen!=prevSlen || clen!=prevClen){
1281 if(prevLine!=null && (next==0 || next>=minScaffold)){
1282 sb2.append(prevLine);
1283 sb2.append('\n');
1284 prevLine=null;
1285 }
1286 // }
1287 prevSsum=ssum; prevCsum=csum; prevSlen=slen; prevClen=clen;
1288
1289 lidx++;
1290 if(lidx<lims.length){next=lims[lidx];}
1291 // System.out.println("<B>\n"+sb2+"\ni="+"?"+", lidx="+lidx+", lims.length="+lims.length+", next="+next);
1292 // else{next=-1;}
1293 }
1294
1295 if(numOver50==0 && tp.length>numOverCutoff){
1296 numOver50=ssum;
1297 basesOver50=slen;
1298 fractionOver50=slen*100f/scaflen;
1299 }
1300
1301 // long a=carray[i];
1302 long b=tp.length;
1303 long c=tp.contigs;
1304 long d=tp.contiglen;
1305
1306 if(b>0){
1307 csum-=c;
1308 ssum-=1;
1309 clen-=d;
1310 slen-=b;
1311 }
1312
1313 if(ln50==-1 && slen<=s50){
1314 ln50=b;
1315 ll50=ssum+1;
1316 }
1317
1318 if(ln90==-1 && slen<=s90){
1319 ln90=b;
1320 ll90=ssum+1;
1321 }
1322
1323 }
1324 if(prevLine!=null){
1325 sb2.append(prevLine);
1326 prevLine=null;
1327 }
1328 }
1329
1330 clen=contiglen;
1331 csum=contigs;
1332 for(int i=0; i<carray.length && clen>0; i++){
1333 long a=carray[i];
1334
1335 csum-=a;
1336 clen-=a*i;
1337
1338 if(cn50==-1 && clen<=c50){
1339 cn50=i;
1340 cl50=csum+a;
1341 }
1342
1343 if(cn90==-1 && clen<=c90){
1344 cn90=i;
1345 cl90=csum+a;
1346 }
1347 }
1348
1349 for(int i=0; i<llist.size && clen>0; i++){
1350 long a=larray[i];
1351
1352 csum-=1;
1353 clen-=a;
1354
1355 if(cn50==-1 && clen<=c50){
1356 cn50=a;
1357 cl50=csum+1;
1358 }
1359
1360 if(cn90==-1 && clen<=c90){
1361 cn90=a;
1362 cl90=csum+1;
1363 }
1364 }
1365
1366 ln50=Tools.max(ln50, 0);
1367 ll50=Tools.max(ll50, 0);
1368 cn50=Tools.max(cn50, 0);
1369 cl50=Tools.max(cl50, 0);
1370
1371 ln90=Tools.max(ln90, 0);
1372 ll90=Tools.max(ll90, 0);
1373 cn90=Tools.max(cn90, 0);
1374 cl90=Tools.max(cl90, 0);
1375
1376 double sLogSum=calcLogSumScaffolds(slist, tlist, logSumOffset, 2);
1377 double cLogSum=calcLogSumContigs(clist, llist, logSumOffset, 2);
1378 double sPowSum=calcPowerSumScaffolds(slist, tlist, logSumOffset, powSumPower);
1379 double cPowSum=calcPowerSumContigs(clist, llist, logSumOffset, powSumPower);
1380 double sAssemblyScore=calcAssemblyScore(slist, tlist, assemblyScoreMinLen, assemblyScoreMaxLen, alignedFraction);
1381
1382 // ByteStreamWriter tsw=new ByteStreamWriter((out==null ? "stdout" : out) , overwrite, append, false);
1383 TextStreamWriter tsw=new TextStreamWriter((out==null ? "stdout" : out) , overwrite, append, false);
1384 tsw.start();
1385
1386 lastL50=ln50;
1387 lastL90=ln90;
1388 lastSize=contiglen;
1389 lastContigs=contigs;
1390 lastMaxContig=maxContig;
1391 lastLogSum=sLogSum;
1392
1393 String sLogSumString=String.format((sLogSum/logSumOffset>=10000 ? "%.0f" : "%.3f"), sLogSum/logSumOffset);
1394 String cLogSumString=String.format((cLogSum/logSumOffset>=10000 ? "%.0f" : "%.3f"), cLogSum/logSumOffset);
1395 String sPowSumString=String.format((sPowSum/logSumOffset>=10000 ? "%.0f" : "%.3f"), sPowSum/logSumOffset);
1396 String cPowSumString=String.format((cPowSum/logSumOffset>=10000 ? "%.0f" : "%.3f"), cPowSum/logSumOffset);
1397 String sAssemblyScoreString=String.format((sAssemblyScore>=10000 ? "%.0f" : "%.3f"), sAssemblyScore);
1398
1399 if(FORMAT<1){
1400 //Do nothing
1401 }else if(FORMAT<3){
1402
1403 if(addfilename){sb.append("Filename: \t"+name+"\n");}
1404 sb.append("Main genome scaffold N/L50: \t"+ll50+"/"+formatKB(ln50, 3, 0)+"\n");
1405 sb.append("Main genome contig N/L50: \t"+cl50+"/"+formatKB(cn50, 3, 0)+"\n");
1406 if(printL90){
1407 sb.append("Main genome scaffold N/L90: \t"+ll90+"/"+formatKB(ln90, 3, 0)+"\n");
1408 sb.append("Main genome contig N/L90: \t"+cl90+"/"+formatKB(cn90, 3, 0)+"\n");
1409 }
1410 if(printExtended){
1411 sb.append("Main genome scaffold logsum: \t"+sLogSumString+"\n");
1412 sb.append("Main genome scaffold powersum: \t"+sPowSumString+"\n");
1413 }
1414 if(printExtended || printAssemblyScore){
1415 sb.append("Main genome assembly score: \t"+sAssemblyScoreString+"\n");
1416 }
1417 sb.append("Max scaffold length: \t"+formatKB(maxScaf, 3, 0)+"\n");
1418 sb.append("Max contig length: \t"+formatKB(maxContig, 3, 0)+"\n");
1419 sb.append("Number of scaffolds > 50 KB: \t"+numOver50+"\n");
1420 if(printExtended){
1421 sb.append("Number of bases in scaffolds>50 KB: \t"+basesOver50+"\n");
1422 }
1423
1424 sb.append("% main genome in scaffolds > 50 KB: \t"+Tools.format("%.2f%%", fractionOver50)+"\n");
1425 if(printheadersize){sb.append("Header:\t"+formatKB(HEADERLENSUM, 3, 0)+(HEADERLENSUM<1000 ? " bytes" : ""));}
1426
1427 // System.out.println();
1428 // System.out.println("Scaffolds: "+shared.Vector.sum(slist.array));
1429 // for(int i=0; i<slist.size; i++){
1430 // if(slist.array[i]>0){System.out.print(i+":"+slist.array[i]+", ");}
1431 // }
1432 // System.out.println();
1433 // System.out.println("Contigs:"+shared.Vector.sum(clist.array));
1434 // for(int i=0; i<clist.size; i++){
1435 // if(clist.array[i]>0){System.out.print(i+":"+clist.array[i]+", ");}
1436 // }
1437
1438 if(GCFORMAT==0){
1439 //Print nothing
1440 }else{
1441 if(GCFORMAT==1 || GCFORMAT==3 || GCFORMAT==4 || GCFORMAT==5){
1442 tsw.println("A\tC\tG\tT\tN\tIUPAC\tOther\tGC\tGC_stdev");
1443 }else{
1444 tsw.println("GC\tGC_stdev");
1445 }
1446 tsw.println(toString3(new StringBuilder(/*"Base Content"*/), counts, gc_std));
1447 }
1448
1449 tsw.println(sb);
1450 tsw.println(sb2);
1451 }else if(FORMAT==3 || FORMAT==6){
1452
1453 if(useheader){
1454 if(FORMAT==6){sb.append('#');}
1455 if(N_UNDERSCORE){sb.append("n_");}
1456 sb.append("scaffolds\t");
1457 if(N_UNDERSCORE){sb.append("n_");}
1458 sb.append("contigs\t");
1459 sb.append("scaf_bp\t");
1460 sb.append("contig_bp\t");
1461 sb.append("gap_pct\t");
1462 sb.append("scaf_N50\t");
1463 sb.append("scaf_L50\t");
1464 sb.append("ctg_N50\t");
1465 sb.append("ctg_L50\t");
1466 if(printL90){
1467 sb.append("scaf_N90\t");
1468 sb.append("scaf_L90\t");
1469 sb.append("ctg_N90\t");
1470 sb.append("ctg_L90\t");
1471 }
1472 if(printExtended){
1473 sb.append("scaf_logsum\t");
1474 sb.append("scaf_powsum\t");
1475 sb.append("ctg_logsum\t");
1476 sb.append("ctg_powsum\t");
1477 }
1478 if(printExtended || printAssemblyScore){
1479 sb.append("asm_score\t");
1480 }
1481 sb.append("scaf_max\t");
1482 sb.append("ctg_max\t");
1483 sb.append("scaf_n_gt50K\t");
1484 if(printExtended){
1485 sb.append("scaf_l_gt50k\t");
1486 }
1487 sb.append("scaf_pct_gt50K\t");
1488 sb.append("gc_avg\t");
1489 sb.append("gc_std");
1490 if(addfilename){sb.append("\tfilename");}
1491
1492 sb.append("\n");
1493 }
1494
1495 sb.append(scaffolds+"\t");
1496 sb.append(contigs+"\t");
1497 sb.append(scaflen+"\t");
1498 sb.append(Tools.format("%d",contiglen)+"\t");
1499 sb.append(Tools.format("%.3f",(scaflen-contiglen)*100f/scaflen)+"\t");
1500 sb.append(ll50+"\t");
1501 sb.append(formatKB(ln50, 3, 0)+"\t");
1502 sb.append(cl50+"\t");
1503 sb.append(formatKB(cn50, 3, 0)+"\t");
1504 if(printL90){
1505 sb.append(ll90+"\t");
1506 sb.append(formatKB(ln90, 3, 0)+"\t");
1507 sb.append(cl90+"\t");
1508 sb.append(formatKB(cn90, 3, 0)+"\t");
1509 }
1510 if(printExtended){
1511 sb.append(sLogSumString+"\t");
1512 sb.append(sPowSumString+"\t");
1513 sb.append(cLogSumString+"\t");
1514 sb.append(cPowSumString+"\t");
1515 }
1516 if(printExtended || printAssemblyScore){
1517 sb.append(sAssemblyScoreString+"\t");
1518 }
1519 sb.append(formatKB(maxScaf, 3, 0)+"\t");
1520 sb.append(formatKB(maxContig, 3, 0)+"\t");
1521 sb.append(numOver50+"\t");
1522 if(printExtended){
1523 sb.append(basesOver50+"\t");
1524 }
1525 sb.append(Tools.format("%.3f", fractionOver50)+"\t");
1526 sb.append(Tools.format("%.5f", (counts[1]+counts[2])*1.0/(counts[0]+counts[1]+counts[2]+counts[3]))+"\t");
1527 sb.append(Tools.format("%.5f", gc_std));
1528 if(addfilename){sb.append('\t').append(name);}
1529
1530 tsw.println(sb);
1531 }else if(FORMAT==8){//JSON
1532
1533 JsonObject jo=new JsonObject();
1534 jo.add("scaffolds", scaffolds);
1535 jo.add("contigs", contigs);
1536 jo.add("scaf_bp", scaflen);
1537 jo.add("contig_bp", contiglen);
1538 jo.addLiteral("gap_pct", (scaflen-contiglen)*100f/scaflen, 5);
1539 jo.add("scaf_N50", ll50);
1540 jo.add("scaf_L50", ln50);
1541 jo.add("ctg_N50", cl50);
1542 jo.add("ctg_L50", cn50);
1543
1544 jo.add("scaf_N90", ll90);
1545 jo.add("scaf_L90", ln90);
1546 jo.add("ctg_N90", cl90);
1547 jo.add("ctg_L90", cn90);
1548
1549 jo.addLiteral("scaf_logsum", sLogSumString);
1550 jo.addLiteral("scaf_powsum", sPowSumString);
1551 jo.addLiteral("ctg_logsum", cLogSumString);
1552 jo.addLiteral("ctg_powsum", cPowSumString);
1553 jo.addLiteral("asm_score", sAssemblyScoreString);
1554 jo.add("scaf_max", maxScaf);
1555 jo.add("ctg_max", maxContig);
1556 jo.add("scaf_n_gt50K", numOver50);
1557 jo.add("scaf_l_gt50k", basesOver50);
1558
1559 jo.add("scaf_pct_gt50K", fractionOver50);
1560 jo.addLiteral("gc_avg", (counts[1]+counts[2])*1.0/(counts[0]+counts[1]+counts[2]+counts[3]), 5);
1561 jo.addLiteral("gc_std", gc_std, 5);
1562 jo.add("filename", name);
1563
1564 tsw.println(jo.toString());
1565 }else if(FORMAT==4){
1566
1567 if(useheader){
1568
1569 if(N_UNDERSCORE){sb.append("n_");}
1570 sb.append("scaffolds\t");
1571 // sb.append("contigs\t");
1572 sb.append("scaf_bp\t");
1573 // sb.append("contig_bp\t");
1574 // sb.append("gap_pct\t");
1575 sb.append("scaf_N50\t");
1576 sb.append("scaf_L50\t");
1577 if(printL90){
1578 sb.append("scaf_N90\t");
1579 sb.append("scaf_L90\t");
1580 }
1581 if(printExtended){
1582 sb.append("scaf_logsum\t");
1583 sb.append("scaf_powsum\t");
1584 }
1585
1586 if(printExtended || printAssemblyScore){
1587 sb.append("asm_score\t");
1588 }
1589 // sb.append("ctg_N50\t");
1590 // sb.append("ctg_L50\t");
1591 sb.append("scaf_max\t");
1592 // sb.append("ctg_max\t");
1593 sb.append("scaf_n_gt50K");
1594 if(printExtended){
1595 sb.append("\tscaf_l_gt50k");
1596 }
1597 sb.append("\tscaf_pct_gt50K");
1598 sb.append("\tgc_avg");
1599 sb.append("\tgc_std");
1600 if(addfilename){sb.append("\tfilename");}
1601
1602 sb.append("\n");
1603 }
1604
1605 sb.append(scaffolds+"\t");
1606 // sb.append(contigs+"\t");
1607 sb.append(scaflen+"\t");
1608 // sb.append(Tools.format("%d",contiglen)+"\t");
1609 // sb.append(Tools.format("%.3f",(scaflen-contiglen)*100f/scaflen)+"\t");
1610 sb.append(ll50+"\t");
1611 sb.append(formatKB(ln50, 3, 0)+"\t");
1612 if(printL90){
1613 sb.append(ll90+"\t");
1614 sb.append(formatKB(ln90, 3, 0)+"\t");
1615 }
1616 if(printExtended){
1617 sb.append(sLogSumString+"\t");
1618 sb.append(sPowSumString+"\t");
1619 }
1620
1621 if(printExtended || printAssemblyScore){
1622 sb.append(sAssemblyScoreString+"\t");
1623 }
1624 // sb.append(cl50+"\t");
1625 // sb.append(formatKB(cn50, 3, 0)+"\t");
1626 sb.append(formatKB(maxScaf, 3, 0)+"\t");
1627 // sb.append(formatKB(maxContig, 3, 0)+"\t");
1628 sb.append(numOver50);
1629 if(printExtended){
1630 sb.append('\t').append(basesOver50);
1631 }
1632 sb.append(Tools.format("\t%.3f", fractionOver50));
1633
1634 sb.append(Tools.format("\t%.5f", (counts[1]+counts[2])*1.0/(counts[0]+counts[1]+counts[2]+counts[3]))+"\t");
1635 sb.append(Tools.format("\t%.5f", gc_std));
1636
1637 if(addfilename){sb.append('\t').append(name);}
1638 tsw.println(sb);
1639 }else if(FORMAT==5){
1640
1641 if(useheader){
1642 // sb.append("scaffolds\t");
1643 if(N_UNDERSCORE){sb.append("n_");}
1644 sb.append("contigs\t");
1645 // sb.append("scaf_bp\t");
1646 sb.append("contig_bp\t");
1647 sb.append("gap_pct\t");
1648 // sb.append("scaf_N50\t");
1649 // sb.append("scaf_L50\t");
1650 sb.append("ctg_N50\t");
1651 sb.append("ctg_L50\t");
1652 if(printL90){
1653 sb.append("ctg_N90\t");
1654 sb.append("ctg_L90\t");
1655 }
1656 if(printExtended){
1657 sb.append("ctg_logsum\t");
1658 sb.append("ctg_powsum\t");
1659 }
1660
1661 if(printExtended || printAssemblyScore){
1662 sb.append("asm_score\t");
1663 }
1664 // sb.append("scaf_max\t");
1665 sb.append("ctg_max\t");
1666 // sb.append("scaf_n_gt50K\t");
1667 // sb.append("scaf_pct_gt50K\t");
1668 sb.append("gc_avg\t");
1669 sb.append("gc_std");
1670 if(addfilename){sb.append("\tfilename");}
1671
1672 sb.append("\n");
1673 }
1674
1675 // sb.append(scaffolds+"\t");
1676 sb.append(contigs+"\t");
1677 // sb.append(scaflen+"\t");
1678 sb.append(Tools.format("%d",contiglen)+"\t");
1679 sb.append(Tools.format("%.3f",(scaflen-contiglen)*100f/scaflen)+"\t");
1680 // sb.append(ll50+"\t");
1681 // sb.append(formatKB(ln50, 3, 0)+"\t");
1682 sb.append(cl50+"\t");
1683 sb.append(formatKB(cn50, 3, 0)+"\t");
1684 if(printL90){
1685 sb.append(cl90+"\t");
1686 sb.append(formatKB(cn90, 3, 0)+"\t");
1687 }
1688 if(printExtended){
1689 sb.append(cLogSumString+"\t");
1690 sb.append(cPowSumString+"\t");
1691 }
1692 if(printExtended || printAssemblyScore){
1693 sb.append(sAssemblyScoreString+"\t");
1694 }
1695 // sb.append(formatKB(maxScaf, 3, 0)+"\t");
1696 sb.append(formatKB(maxContig, 3, 0)+"\t");
1697 // sb.append(numOver50+"\t");
1698 // sb.append(Tools.format("%.3f", fractionOver50)+"\t");
1699 sb.append(Tools.format("%.5f", (counts[1]+counts[2])*1.0/(counts[0]+counts[1]+counts[2]+counts[3]))+"\t");
1700 sb.append(Tools.format("%.5f", gc_std));
1701 if(addfilename){sb.append('\t').append(name);}
1702 tsw.println(sb);
1703 }else if(FORMAT==7){
1704
1705 if(addfilename){sb.append("Filename: \t"+name+"\n");}
1706 sb.append("Main genome contig N/L50: \t"+cl50+"/"+formatKB(cn50, 3, 0)+"\n");
1707 if(printL90){
1708 sb.append("Main genome contig N/L90: \t"+cl90+"/"+formatKB(cn90, 3, 0)+"\n");
1709 }
1710 if(printExtended){
1711 // sb.append("Main genome contig logsum: \t"+cLogSumString+"\n");
1712 }
1713 sb.append("Max contig length: \t"+formatKB(maxContig, 3, 0)+"\n");
1714 sb.append("Number of contigs > 1 KB: \t"+numOver50+"\n");
1715 sb.append("% main genome in contigs > 1 KB: \t"+Tools.format("%.2f%%", fractionOver50)+"\n");
1716 if(printheadersize){sb.append("Header:\t"+formatKB(HEADERLENSUM, 3, 0)+(HEADERLENSUM<1000 ? " bytes" : ""));}
1717
1718 if(GCFORMAT==0){
1719 //Print nothing
1720 }else{
1721 if(GCFORMAT==1 || GCFORMAT==3 || GCFORMAT==4 || GCFORMAT==5){
1722 tsw.println("A\tC\tG\tT\tGC\tGC_stdev");
1723 }else{
1724 tsw.println("GC\tGC_stdev");
1725 }
1726 tsw.println(toString3(new StringBuilder(/*"Base Content"*/), counts, gc_std));
1727 }
1728
1729 tsw.println(sb);
1730 tsw.println(sb2);
1731 }
1732 tsw.poisonAndWait();
1733
1734 if(showspeed){
1735 if(!printheadersize){outstream.println("Header:\t"+formatKB(HEADERLENSUM, 3, 0)+(HEADERLENSUM<1000 ? " bytes" : ""));}
1736 outstream.println("Time: \t"+t);
1737 long bytes=new File(in).length();
1738 if(bytes<1){bytes=LIMSUM;}
1739 double mbps=bytes*1000d/t.elapsed;
1740 double mbpps=shared.Vector.sum(counts)*1000d/t.elapsed;
1741 outstream.println(Tools.format("Speed:\t%.2f MBytes/s",mbps));
1742 outstream.println(Tools.format(" \t%.2f MBases/s",mbpps));
1743 }
1744
1745 if(bbmapkmer>0){
1746 outstream.println("BBMap minimum memory estimate at k="+bbmapkmer+": "+estimateBBMapMemory(counts, scaffolds, HEADERLENSUM, bbmapkmer));
1747 }
1748
1749 MetadataWriter.write(null, scaffolds, scaflen, 0, 0, false);
1750 }
1751
1752 private static long bbmapMemoryBytes(long[] acgtn, long scaffolds,
1753 long headerlen, int k) {
1754
1755 long keyspace=(1L<<(2*k));
1756 long defined=acgtn[0]+acgtn[1]+acgtn[2]+acgtn[3];
1757 long undefined=acgtn[4];
1758 long midpad=(scaffolds*(FastaToChromArrays2.MID_PADDING));
1759 long total=defined+undefined+midpad;
1760 int chromlen=FastaToChromArrays2.MAX_LENGTH-FastaToChromArrays2.END_PADDING-FastaToChromArrays2.START_PADDING;
1761 int chroms=(int)(total/chromlen);
1762 int chromsperblock=Integer.MAX_VALUE/chromlen;
1763 int blocks=(chroms+chromsperblock-1)/chromsperblock;
1764 long memperblock=keyspace*4;
1765 long memforcounts=keyspace*4;
1766
1767 long mem=0;
1768 mem+=total; //reference bulk, including inter-scaffold padding
1769 mem+=(chroms*(FastaToChromArrays2.END_PADDING+FastaToChromArrays2.START_PADDING)); //reference tip padding
1770 mem+=headerlen; //Header name byte arrays
1771 mem+=(scaffolds*(4+4+4+16+8)); //Other structures for scaffold info
1772 mem+=(blocks*(memperblock)); //start array for each block
1773 mem+=memforcounts; //count array
1774 mem+=(defined*4); //key lists
1775 mem=(long)(mem/0.66); //Expand to compensate for garbage collection
1776 if(k>13){mem=mem+1000000000;}
1777 return mem;
1778 }
1779
1780 private static CharSequence estimateBBMapMemory(long[] acgtn, long scaffolds,
1781 long headerlen, int k) {
1782 long mem=180+bbmapMemoryBytes(acgtn, scaffolds, headerlen, k)/1000000; //in megabytes
1783 if(mem>4000){
1784 return "-Xmx"+((mem+1500)/1000)+"g \t(at least "+(long)Math.ceil((((mem+1500)/0.85)/1000))+" GB physical RAM)";
1785 }else if(mem>2100){
1786 return "-Xmx"+((mem+999)/1000)+"g \t(at least "+(long)Math.ceil((((mem+999)/0.85)/1000))+" GB physical RAM)";
1787 }else{
1788 return "-Xmx"+(((((mem*11)/8+50))/10)*10)+"m \t(at least "+((((long)(((mem*10)/8+50)/0.82))/10)*10)+" MB physical RAM)";
1789 }
1790 }
1791
1792
1793 public static long bench(InputStream is) throws IOException{
1794 final byte[] buf=new byte[32768];
1795 long sum=0;
1796 for(long len=is.read(buf); len>0; len=is.read(buf)){sum+=len;}
1797 return sum;
1798 }
1799
1800
1801
1802 private static void writeHistFile(String fname, LongList slist, ArrayList<Triple> tlist, boolean ascending){
1803 if(fname==null){return;}
1804 TextStreamWriter tsw=new TextStreamWriter(fname, overwrite, false, false);
1805 tsw.start();
1806 tsw.print("#scaffolds\tlength\n");
1807 long num=0, len=0;
1808
1809 final long[] array=slist.array;
1810 final int lim=slist.size;
1811
1812 StringBuilder sb=new StringBuilder(32);
1813
1814 if(ascending){
1815 for(int i=0; i<lim; i++){
1816 final long a=array[i];
1817 if(a>0){
1818 len+=(a*i);
1819 num+=a;
1820 sb.append(num);
1821 sb.append('\t');
1822 sb.append(len);
1823 sb.append('\n');
1824 tsw.print(sb.toString());
1825 sb.setLength(0);
1826 }
1827 }
1828
1829 if(tlist!=null){
1830 for(Triple t : tlist){
1831 len+=t.length;
1832 num++;
1833 sb.append(num);
1834 sb.append('\t');
1835 sb.append(len);
1836 sb.append('\n');
1837 tsw.print(sb.toString());
1838 sb.setLength(0);
1839 }
1840 }
1841 }else{
1842
1843 if(tlist!=null){
1844 for(int i=tlist.size()-1; i>=0; i--){
1845 Triple t=tlist.get(i);
1846 len+=t.length;
1847 num++;
1848 sb.append(num);
1849 sb.append('\t');
1850 sb.append(len);
1851 sb.append('\n');
1852 tsw.print(sb.toString());
1853 sb.setLength(0);
1854 }
1855 }
1856 for(int i=lim-1; i>=0; i--){
1857 final long a=array[i];
1858 if(a>0){
1859 len+=(a*i);
1860 num+=a;
1861 sb.append(num);
1862 sb.append('\t');
1863 sb.append(len);
1864 sb.append('\n');
1865 tsw.print(sb.toString());
1866 sb.setLength(0);
1867 }
1868 }
1869 }
1870 tsw.poisonAndWait();
1871 }
1872
1873 private static String toString2(StringBuilder sb, long[] counts){
1874 final long a=counts[0], c=counts[1], g=counts[2], t=counts[3], iupac=counts[4], n=counts[5], other=counts[6], control=counts[7];
1875 long sumDef=a+c+g+t;
1876 long sumAll=sumDef+iupac+n+other;
1877 double invDef=1.0/sumDef, invAll=1.0/sumAll;
1878 double iupacD=iupac*invAll;
1879 double otherD=other*invAll;
1880 if(iupac>0 && iupacD<0.0001){iupacD=0.0001;}
1881 if(other>0 && otherD<0.0001){otherD=0.0001;}
1882 if(GCFORMAT==0 || GCFORMAT==1){
1883 return sb.append(Tools.format("\t%d\t%.4f\t%.4f\t%.4f\t%.4f\t%.4f\t%.4f\t%.4f\t%.4f\n",
1884 sumAll, a*invDef, c*invDef, g*invDef, t*invDef, n*invAll, iupacD, otherD, (g+c)*invDef)).toString();
1885 }else if(GCFORMAT==2){
1886 return sb.append(Tools.format("\t%.4f\n", (g+c)*invDef)).toString();
1887 }else if(GCFORMAT==3){
1888 return sb.append(Tools.format("\t%d\t%.4f\t%.4f\t%.4f\t%.4f\t%.4f\t%.4f\t%.4f\t%.4f\n",
1889 sumAll, a*invDef, c*invDef, g*invDef, t*invDef, n*invAll, iupacD, otherD, (g+c)*invDef)).toString();
1890 }else if(GCFORMAT==4){
1891 return sb.append(Tools.format("\t%d\t%.4f\n", sumAll, (g+c)*invDef)).toString();
1892 }else if(GCFORMAT==5){
1893 return sb.append(Tools.format("\t%d\t%.4f\t%.2f\t%.2f\n", sumAll, (g+c)*invDef, logsum(sumAll), powersum(sumAll))).toString();
1894 }else{
1895 throw new RuntimeException("Unknown format.");
1896 }
1897 }
1898
1899 private static String toString3(StringBuilder sb, long[] counts, double gc_std){
1900 final long a=counts[0], c=counts[1], g=counts[2], t=counts[3], iupac=counts[4], n=counts[5], other=counts[6], control=counts[7];
1901 long sumDef=a+c+g+t;
1902 long sumAll=sumDef+iupac+n+other;
1903 double invDef=1.0/sumDef, invAll=1.0/sumAll;
1904 double iupacD=iupac*invAll;
1905 double otherD=other*invAll;
1906 if(iupac>0 && iupacD<0.0001){iupacD=0.0001;}
1907 if(other>0 && otherD<0.0001){otherD=0.0001;}
1908 if(FORMAT==7){
1909 return sb.append(Tools.format("%.4f\t%.4f\t%.4f\t%.4f\t%.4f\t%.4f\n",
1910 a*invDef, c*invDef, g*invDef, t*invDef, (g+c)*invDef, gc_std)).toString();
1911 }else if(GCFORMAT==0 || GCFORMAT==1 || GCFORMAT==3 || GCFORMAT==4 || GCFORMAT==5){
1912 if(GC_FRACTION){
1913 return sb.append(Tools.format("%.4f\t%.4f\t%.4f\t%.4f\t%.4f\t%.4f\t%.4f\t%.4f\t%.4f\n",
1914 a*invDef, c*invDef, g*invDef, t*invDef, n*invAll, iupacD, otherD, (g+c)*invDef, gc_std)).toString();
1915 }
1916 return sb.append(Tools.format("%d\t%d\t%d\t%d\t%d\t%d\t%d\t%.4f\t%.4f\n",
1917 a, c, g, t, n, iupac, other, (g+c)*invDef, gc_std)).toString();
1918 }else if(GCFORMAT==2){
1919 return sb.append(Tools.format("%.4f\t%.4f\n", (g+c)*invDef, gc_std)).toString();
1920 }else{
1921 throw new RuntimeException("Unknown format.");
1922 }
1923
1924 }
1925
1926
1927 private static final String formatX(int next, long ssum, long csum, long slen, long clen){
1928 float cov=clen*100f/slen;
1929
1930 final String s;
1931 if(FORMAT<=1){
1932 s=formatKB_all(next, 1, 7)+" \t"+formatComma(ssum, 14)+"\t"+formatComma(csum, 14)+"\t"+formatComma(slen, 14)+"\t"+formatComma(clen, 14)+"\t"+formatPercent(cov);
1933 }else if(FORMAT==7){
1934 if(next==0){return null;}
1935 s=formatKB_all(next, 1, 7)+" \t"+formatComma(csum, 14)+"\t"+formatComma(clen, 14);
1936 }else if(FORMAT>=2){
1937 s=formatKB_all(next, 1, 7)+" \t"+formatComma(ssum, 14)+"\t"+formatComma(csum, 14)+"\t"+formatComma(slen, 14)+"\t"+formatComma(clen, 14)+"\t"+formatPercent(cov);
1938 }else{
1939 throw new RuntimeException("Unknown format: "+FORMAT);
1940 }
1941 return s;
1942 }
1943
1944 private static final String formatKB(long x, int precision, int width){
1945 String s;
1946 if(FORMAT>=2 || x<1000){
1947 s=Long.toString(x);
1948 }else if(x<1000000){
1949 s=Tools.format("%."+precision+"f",x/1000f);
1950 while(s.contains(".") && (s.endsWith("0") || s.endsWith("."))){s=s.substring(0, s.length()-1);}
1951 s=s+" Kbp";
1952 }else{
1953 s=Tools.format("%."+precision+"f",x/1000000f);
1954 while(s.contains(".") && (s.endsWith("0") || s.endsWith("."))){s=s.substring(0, s.length()-1);}
1955 s=s+" Mbp";
1956 }
1957 while(s.length()<width){s=" "+s;}
1958 return s;
1959 }
1960
1961 private static final String formatKB_all(long x, int precision, int width){
1962 String s;
1963
1964 if(x==0){s="All";}
1965 else if(FORMAT>=2 || x<1000){
1966 s=Long.toString(x);
1967 }else if(x<1000000){
1968 s=Tools.format("%."+precision+"f",x/1000f);
1969 while(s.contains(".") && (s.endsWith("0") || s.endsWith("."))){s=s.substring(0, s.length()-1);}
1970 s=s+" Kbp";
1971 }else{
1972 s=Tools.format("%."+precision+"f",x/1000000f);
1973 while(s.contains(".") && (s.endsWith("0") || s.endsWith("."))){s=s.substring(0, s.length()-1);}
1974 s=s+" Mbp";
1975 }
1976
1977 while(s.length()<width){s=" "+s;}
1978 return s;
1979 }
1980
1981 private static final StringBuilder formatComma(long x, int width){
1982 StringBuilder sb=new StringBuilder(width);
1983 if(FORMAT<=1){
1984 sb.append(x%1000);
1985 x/=1000;
1986 int len=3;
1987 while(x>0){
1988 while(sb.length()<len){sb.insert(0, '0');}
1989 sb.insert(0, (x%1000)+",");
1990 x/=1000;
1991 len+=4;
1992 }
1993 }else if(FORMAT>=2){
1994 sb.append(x);
1995 }else{
1996 throw new RuntimeException("Unknown format: "+FORMAT);
1997 }
1998 while(sb.length()<width){
1999 sb.insert(0, ' ');
2000 }
2001 return sb;
2002 }
2003
2004 private static final String formatPercent(float x){
2005 String s=Tools.format("%.2f%%", x);
2006 while(s.length()<8){s=" "+s;}
2007 return s;
2008 }
2009
2010 protected void reset(){
2011 // clist=null;
2012 // slist=null;
2013 // sclist1=null;
2014 // sclist2=null;
2015 //
2016 // gchistArray=null;
2017 // gc_std=0;
2018 //
2019 // llist=null;
2020 // tlist=null;
2021
2022 clist.clear();
2023 slist.clear();
2024 sclist1.clear();
2025 sclist2.clear();
2026 llist.clear();
2027 tlist.clear();
2028
2029 Arrays.fill(gchistArray, 0);
2030 Arrays.fill(gchist_by_base, 0);
2031
2032 gchistArray_downsampled=null;
2033 gchist_by_base_downsampled=null;
2034
2035 gc_std=0;
2036 gc_bb_std=0;
2037
2038 LIMSUM=0;
2039 HEADERLENSUM=0;
2040 }
2041
2042 /**
2043 * @return charToNum array
2044 */
2045 public static final byte[] makeCharToNum() {
2046 byte[] r=new byte[256];
2047 Arrays.fill(r, (byte)6);
2048 r['a']=r['A']=0;
2049 r['c']=r['C']=1;
2050 r['g']=r['G']=2;
2051 r['t']=r['T']=3;
2052 r['u']=r['U']=3;
2053 r['n']=r['N']=5;
2054 r['x']=r['X']=4;
2055 for(byte b : AminoAcid.degenerateBases){
2056 if(b!=' '){
2057 r[b]=r[Tools.toLowerCase(b)]=4;
2058 }
2059 }
2060 r['\n']=r['\r']=r['>']=r['@']=r['+']=7;
2061 return r;
2062 }
2063
2064 /*--------------------------------------------------------------*/
2065
2066 private static final byte[] charToNum=makeCharToNum();
2067 public static int GCFORMAT=1;
2068 public static boolean GC_FRACTION=true;
2069 public static int FORMAT=1;
2070 private static long cutoff=1000000;
2071
2072 private static long LIMSUM=0;
2073 private static long HEADERLENSUM=0;
2074
2075 private static int bbmapkmer=0;//13;
2076 public static boolean overwrite=true;
2077 public static boolean append=false;
2078 public static boolean useheader=true;
2079 public static boolean addfilename=false;
2080 public static boolean printL90=true;
2081 public static boolean printExtended=false;
2082 public static int logSumOffset=1000;
2083 public static double powSumPower=0.25;
2084 public static double logSumBase=2;
2085 public static boolean squareLog=false;
2086 public static double logPower=1.0;
2087 public static boolean showspeed=false;//true;
2088 public static boolean printheadersize=false;
2089 public static boolean skipDuplicateLines=true;
2090 public static boolean N_UNDERSCORE=true;
2091
2092 public static long assemblyScoreMinLen=2000;
2093 public static long assemblyScoreMaxLen=50000;
2094 public static double alignedFraction=0;
2095 public static boolean printAssemblyScore=false;
2096
2097 private static final byte slashr='\r', slashn='\n', carrot='>', at='@', noref='N', noref2='n';
2098
2099 /*--------------------------------------------------------------*/
2100
2101 private boolean benchmark=false;
2102 private String in=null, out=null, gc=null, gchistFile=null, scaffoldHistFile=null;
2103 private int maxNs=-1;
2104
2105 /** Number of decimal places for GC histogram */
2106 private final int gchistDecimals1;
2107
2108 /** Number of bins for output (subsampled) GC content histogram */
2109 private final int gcbins;
2110
2111 /** Number of bins for internal GC content histogram */
2112 private final int gcbins2;
2113
2114 /** Minimum scaffold length to count */
2115 private final int minScaffold;
2116
2117 /** Number of contigs of length x */
2118 private final LongList clist;
2119
2120 /** Number of scaffolds of length x */
2121 private final LongList slist;
2122
2123 /** Sum of contigs per scaffold of length x */
2124 private final LongList sclist1;
2125
2126 /** Sum of contig lengths per scaffold of length x */
2127 private final LongList sclist2;
2128
2129 /** List of contig lengths for contigs at least cutoff in length */
2130 private final LongList llist;
2131
2132 /** List of scaf len, contigs, contig sum for scaffolds at least cutoff in length */
2133 private final ArrayList<Triple> tlist;
2134
2135 /** Downsampled gc histogram */
2136 private final long[] gchistArray;
2137
2138 /** Downsampled gc histogram */
2139 private long[] gchistArray_downsampled;
2140
2141 /** gc standard deviation */
2142 private double gc_std;
2143
2144 /** Downsampled gc histogram, using base counts rather than scaffold counts */
2145 private final long[] gchist_by_base;
2146
2147 /** Downsampled gc histogram, using base counts rather than scaffold counts */
2148 private long[] gchist_by_base_downsampled;
2149
2150 /** gc standard deviation, using base counts rather than scaffold counts */
2151 private double gc_bb_std;
2152
2153 public static double lastLogSum;
2154 public static long lastL90;
2155 public static long lastL50;
2156 public static long lastSize;
2157 public static long lastContigs;
2158 public static long lastMaxContig;
2159
2160 public static PrintStream outstream=System.out;
2161
2162 /*--------------------------------------------------------------*/
2163
2164 private static class Triple implements Comparable<Triple>{
2165
2166 Triple(long len_, long contigs_, long contiglen_){
2167 length=len_;
2168 contigs=contigs_;
2169 contiglen=contiglen_;
2170 }
2171
2172 @Override
2173 public int compareTo(Triple o) {
2174 if(length>o.length){return 1;}
2175 if(length<o.length){return -1;}
2176 return (int)(contiglen-o.contiglen);
2177 }
2178
2179 @Override
2180 public boolean equals(Object o){return equals((Triple)o);}
2181
2182 public boolean equals(Triple o){
2183 return length==o.length && contiglen==o.contiglen;
2184 }
2185
2186 @Override
2187 public int hashCode() {
2188 assert(false) : "This class should not be hashed.";
2189 return super.hashCode();
2190 }
2191
2192 @Override
2193 public String toString(){return length+","+contigs+","+contiglen;}
2194
2195 public final long length;
2196 public final long contigs;
2197 public final long contiglen;
2198
2199 }
2200
2201 /*--------------------------------------------------------------*/
2202
2203
2204
2205 /*
2206
2207 fasta_stats2.linux -n <number of N between contigs> contigs.fa
2208 e.g.
2209
2210 fasta_stats2.linux -n 0 contigs.fa # for aplg assemblies
2211 fasta_stats2.linux -n 10 contigs.fa # for velvet
2212
2213
2214
2215 Main genome scaffold total: 1610
2216 Main genome contig total: 7844
2217 Main genome scaffold sequence total: 726.6 MB
2218 Main genome contig sequence total: 689.4 MB (-> 5.1% gap)
2219 Main genome scaffold N/L50: 6/62.2 MB
2220 Main genome contig N/L50: 331/429.0 KB
2221 Number of scaffolds > 50 KB: 122
2222 % main genome in scaffolds > 50 KB: 98.9%
2223
2224 Minimum Number Number Total Total Scaffold
2225 Scaffold of of Scaffold Contig Contig
2226 Length Scaffolds Contigs Length Length Coverage
2227 -------- --------- ------- ----------- ----------- --------
2228 All 1,610 7,844 726,616,606 689,442,341 94.88%
2229 1 kb 1,610 7,844 726,616,606 689,442,341 94.88%
2230 2.5 kb 1,468 7,677 726,334,758 689,171,164 94.88%
2231 5 kb 537 6,496 723,058,922 685,949,825 94.87%
2232 10 kb 321 6,176 721,557,480 684,511,419 94.87%
2233 25 kb 138 5,900 718,873,396 681,879,275 94.85%
2234 50 kb 122 5,854 718,322,923 681,420,273 94.86%
2235 100 kb 83 5,660 715,543,850 679,452,337 94.96%
2236 250 kb 47 5,326 709,779,897 675,162,461 95.12%
2237 500 kb 32 5,073 704,645,704 671,472,605 95.29%
2238 1 mb 19 4,735 695,996,631 664,862,860 95.53%
2239 2.5 mb 15 4,587 689,883,367 659,102,480 95.54%
2240 5 mb 13 4,463 681,669,379 651,024,951 95.50%
2241 */
2242
2243 }