1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591
|
package jgi;
import java.io.File;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import dna.AminoAcid;
import dna.Data;
import fileIO.ByteFile;
import fileIO.ByteStreamWriter;
import fileIO.FileFormat;
import fileIO.ReadWrite;
import gff.GffLine;
import prok.CallGenes;
import prok.GeneCaller;
import prok.GeneModel;
import prok.GeneModelParser;
import prok.Orf;
import prok.ProkObject;
import shared.Parse;
import shared.Parser;
import shared.PreParser;
import shared.Shared;
import shared.Timer;
import shared.Tools;
import sketch.Sketch;
import sketch.SketchHeap;
import sketch.SketchMakerMini;
import sketch.SketchObject;
import sketch.SketchTool;
import stream.ConcurrentReadInputStream;
import stream.ConcurrentReadOutputStream;
import stream.FASTQ;
import stream.FastaReadInputStream;
import stream.Read;
import stream.ReadInputStream;
import stream.SamLine;
import structures.ListNum;
import structures.LongPair;
import structures.Range;
import template.Accumulator;
import template.ThreadWaiter;
import tracker.ReadStats;
/**
* Checks the strandedness of RNA-seq reads.
*
* @author Brian Bushnell
* @date August 7, 2023
*
*/
public class CheckStrand2 implements Accumulator<CheckStrand2.ProcessThread> {
/*--------------------------------------------------------------*/
/*---------------- Initialization ----------------*/
/*--------------------------------------------------------------*/
/**
* Code entrance from the command line.
* @param args Command line arguments
*/
public static void main(String[] args){
//Start a timer immediately upon code entrance.
Timer t=new Timer();
//Create an instance of this class
CheckStrand2 x=new CheckStrand2(args);
//Run the object
x.process(t);
//Close the print stream if it was redirected
Shared.closeStream(x.outstream);
}
/**
* Constructor.
* @param args Command line arguments
*/
public CheckStrand2(String[] args){
{//Preparse block for help, config files, and outstream
PreParser pp=new PreParser(args, getClass(), false);
args=pp.args;
outstream=pp.outstream;
}
//Set shared static variables prior to parsing
ReadWrite.USE_PIGZ=ReadWrite.USE_UNPIGZ=true;
ReadWrite.setZipThreads(Shared.threads());
{//Parse the arguments
final Parser parser=parse(args);
Parser.processQuality();
maxReads=parser.maxReads;
overwrite=ReadStats.overwrite=parser.overwrite;
append=ReadStats.append=parser.append;
setInterleaved=parser.setInterleaved;
in1=parser.in1;
in2=parser.in2;
qfin1=parser.qfin1;
qfin2=parser.qfin2;
extin=parser.extin;
out1=parser.out1;
extout=parser.extout;
}
validateParams();
doPoundReplacement(); //Replace # with 1 and 2
adjustInterleaving(); //Make sure interleaving agrees with number of input and output files
fixExtensions(); //Add or remove .gz or .bz2 as needed
checkFileExistence(); //Ensure files can be read and written
checkStatics(); //Adjust file-related static fields as needed for this program
//Create output FileFormat objects
ffout1=FileFormat.testOutput(out1, FileFormat.TXT, extout, true, overwrite, append, false);
//Create input FileFormat objects
ffin1=FileFormat.testInput(in1, FileFormat.FASTQ, extin, true, true);
ffin2=FileFormat.testInput(in2, FileFormat.FASTQ, extin, true, true);
//Allows unchanged sam output for sam input.
SamLine.SET_FROM_OK=true;
//If there is a gff file that will not be used, nullify it.
if(gff!=null) {
if(transcriptome) {
System.err.println("Ignoring gff file due to transcriptome mode.");
gff=null;
}else if(!ffin1.samOrBam() && fna==null) {
System.err.println("Ignoring gff file due to using unaligned reads with no reference.");
gff=null;
}
}
//Decide whether gene-calling is needed, and pick a gene model.
if((fna!=null && (gff==null || passes>1) && !transcriptome && !rnaContigs) || scoreReadGenes) {
if(pgmFile==null){pgmFile=Data.findPath("?model.pgm");}
final GeneModel pgm0=GeneModelParser.loadModel(pgmFile);
if(passes<2 || fna==null || transcriptome) {pgm=pgm0;}
else {
Timer t=new Timer();
System.err.print("Refining gene model: ");
pgm=CallGenes.makeMultipassModel(pgm0, genomeSequence(), gff, passes);
if(streamGenome) {genomeSequenceCache=null;}//To save memory
t.stopAndPrint();
}
gCaller=CallGenes.makeGeneCaller(pgm);
}else {
pgm=null;
gCaller=null;
}
}
/*--------------------------------------------------------------*/
/*---------------- Initialization Helpers ----------------*/
/*--------------------------------------------------------------*/
/** Parse arguments from the command line */
private Parser parse(String[] args){
//Create a parser object
Parser parser=new Parser();
//Set any necessary Parser defaults here
//parser.foo=bar;
parser.out1=out1;
//Parse each argument
for(int i=0; i<args.length; i++){
String arg=args[i];
//Break arguments into their constituent parts, in the form of "a=b"
String[] split=arg.split("=");
String a=split[0].toLowerCase();
String b=split.length>1 ? split[1] : null;
if(b!=null && b.equalsIgnoreCase("null")){b=null;}
if(a.equals("verbose")){
verbose=Parse.parseBoolean(b);
}else if(a.equals("parse_flag_goes_here")){
long fake_variable=Parse.parseKMG(b);
//Set a variable here
}else if(a.equals("size") || a.equals("len") || a.equals("length") ||
a.equals("sketchsize") || a.equals("sketchlen")){
sketchSize=Parse.parseIntKMG(b);
}else if(a.equals("samplerate")){
samplerate=Float.parseFloat(b);
}else if(a.equals("sampleseed") || a.equals("seed")){
sampleseed=Long.parseLong(b);
}else if(a.equals("ref") || a.equals("fna")){
fna=b;
}else if(a.equals("gff")){
gff=b;
}else if(a.equals("merge")){
mergePairs=Parse.parseBoolean(b);
}else if(a.equals("bin") || a.equals("binlen")){
binlen=Parse.parseIntKMG(b);
}else if(a.equals("scoregenes") || a.equals("scorereads") || a.equals("callgenes")
|| a.equals("callreads") || a.equals("kfa")){
scoreReadGenes=Parse.parseBoolean(b);
}else if(a.equals("pgm") || a.equals("model")){
pgmFile=b;
}else if(a.equals("streamgenome")){
streamGenome=Parse.parseBoolean(b);
}else if(a.equals("stopanalysis") || a.equals("orf")){
doStopAnalysis=Parse.parseBoolean(b);
}else if(a.equalsIgnoreCase("polya")){
testPolyA=Parse.parseBoolean(b);
}else if(a.equalsIgnoreCase("transcriptome")){
transcriptome=Parse.parseBoolean(b);
}else if(a.equalsIgnoreCase("rnacontigs")){
rnaContigs=Parse.parseBoolean(b);
}else if(a.equalsIgnoreCase("normalize")){
normalize=Parse.parseBoolean(b);
}else if(a.equalsIgnoreCase("minreads")){
minReads=Integer.parseInt(b);
}else if(a.equalsIgnoreCase("genome")){
transcriptome=!Parse.parseBoolean(b);
}else if(a.equalsIgnoreCase("outp") || a.equalsIgnoreCase("outplus")){
outPlus=b;
}else if(a.equalsIgnoreCase("outm") || a.equalsIgnoreCase("outminus")){
outMinus=b;
}else if(a.equalsIgnoreCase("firstorf")){
useFirstORF=Parse.parseBoolean(b);
}else if(a.equalsIgnoreCase("minpolya") || a.equalsIgnoreCase("polyalen")
|| a.equalsIgnoreCase("polyalength")){
minPolyA=Integer.parseInt(b);
}else if(a.equalsIgnoreCase("passes")){
passes=Integer.parseInt(b);
}else if(a.equalsIgnoreCase("2pass") || a.equalsIgnoreCase("twopass")){
if(Parse.parseBoolean(b)) {passes=2;}
}else if(parser.parse(arg, a, b)){//Parse standard flags in the parser
//do nothing
}else{
boolean parsed=false;
if(b==null && arg.indexOf('=')<0) {
File f=new File(arg);
String ext=ReadWrite.rawExtension(a);
if(f.isFile() && f.canRead()) {
if(parser.in1==null && (FileFormat.isSamOrBamExt(ext) || FileFormat.isFastqExt(ext))) {
outstream.println("Set input to "+f.getName());
parser.in1=arg;
parsed=true;
}else if(gff==null && FileFormat.isGffExt(ext)) {
outstream.println("Set gff to "+f.getName());
gff=arg;
parsed=true;
}else if(fna==null && FileFormat.isFastaExt(ext)) {
outstream.println("Set ref to "+f.getName());
fna=arg;
parsed=true;
}
}
}
if(!parsed) {
outstream.println("Unknown parameter "+args[i]);
assert(false) : "Unknown parameter "+args[i];
}
}
}
return parser;
}
/** Replace # with 1 and 2 in headers */
private void doPoundReplacement(){
//Do input file # replacement
if(in1!=null && in2==null && in1.indexOf('#')>-1 && !new File(in1).exists()){
in2=in1.replace("#", "2");
in1=in1.replace("#", "1");
}
//Ensure there is an input file
if(in1==null){throw new RuntimeException("Error - at least one input file is required.");}
}
/** Add or remove .gz or .bz2 as needed */
private void fixExtensions(){
in1=Tools.fixExtension(in1);
in2=Tools.fixExtension(in2);
qfin1=Tools.fixExtension(qfin1);
qfin2=Tools.fixExtension(qfin2);
}
/** Ensure files can be read and written */
private void checkFileExistence(){
//Ensure output files can be written
if(!Tools.testOutputFiles(overwrite, append, false, out1, outPlus, outMinus)){
outstream.println((out1==null)+", "+(outPlus==null)+", "+(outMinus==null)+
", "+out1+", "+outPlus+", "+outMinus);
throw new RuntimeException("\n\noverwrite="+overwrite+"; "
+ "Can't write to output files "+out1+", "+outPlus+", "+outMinus+"\n");
}
//Ensure input files can be read
if(!Tools.testInputFiles(false, true, in1, in2)){
throw new RuntimeException("\nCan't read some input files.\n");
}
//Ensure that no file was specified multiple times
if(!Tools.testForDuplicateFiles(true, in1, in2, out1, outPlus, outMinus)){
throw new RuntimeException("\nSome file names were specified multiple times.\n");
}
}
/** Make sure interleaving agrees with number of input and output files */
private void adjustInterleaving(){
//Adjust interleaved detection based on the number of input files
if(in2!=null){
if(FASTQ.FORCE_INTERLEAVED){outstream.println("Reset INTERLEAVED to false because paired input files were specified.");}
FASTQ.FORCE_INTERLEAVED=FASTQ.TEST_INTERLEAVED=false;
}
//Adjust interleaved settings based on number of output files
if(!setInterleaved){
if(in2!=null){ //If there are 2 input streams.
FASTQ.FORCE_INTERLEAVED=FASTQ.TEST_INTERLEAVED=false;
// outstream.println("Set INTERLEAVED to "+FASTQ.FORCE_INTERLEAVED);
}
}
}
/** Adjust file-related static fields as needed for this program */
private static void checkStatics(){
//Adjust the number of threads for input file reading
if(!ByteFile.FORCE_MODE_BF1 && !ByteFile.FORCE_MODE_BF2 && Shared.threads()>2){
ByteFile.FORCE_MODE_BF2=true;
}
assert(FastaReadInputStream.settingsOK());
}
/** Ensure parameter ranges are within bounds and required parameters are set */
private boolean validateParams(){
// assert(minfoo>0 && minfoo<=maxfoo) : minfoo+", "+maxfoo;
return true;
}
/*--------------------------------------------------------------*/
/*---------------- Outer Methods ----------------*/
/*--------------------------------------------------------------*/
/** Create read streams and process all data */
void process(Timer t){
//Turn off read validation in the input threads to increase speed
final boolean vic=Read.VALIDATE_IN_CONSTRUCTOR;
Read.VALIDATE_IN_CONSTRUCTOR=Shared.threads()<4;
makeTools();
makeGeneSketches();
if(ffin1.samOrBam()) {//Aligned reads
if(gffLines==null) {//Features not yet loaded
if(gff!=null) {
gffLines=CheckStrand.getGffLines(gff, types);
}else if(fna!=null && !transcriptome && !rnaContigs) {
ArrayList<Read> reads=genomeSequence();
System.err.print("Calling genes from genome: ");
ArrayList<Orf> orfs=gCaller.callGenes(reads);
gffLines=Orf.toGffLines(orfs);
}
}
if(gffLines!=null) {
SamLine.RNAME_AS_BYTES=false;//Must come before cris starts
rangeMap=GffLine.makeRangeMap(gffLines);
}
if(binlen>0) {
binMap=new ConcurrentHashMap<String, ArrayList<LongPair>>();
}
}
//Create a read input stream
final ConcurrentReadInputStream cris=makeCris();
final ConcurrentReadOutputStream crosP=makeCros(outPlus);
final ConcurrentReadOutputStream crosM=makeCros(outMinus);
//Reset counters
readsIn=readsProcessed=0;
basesIn=basesProcessed=0;
readsMerged=0;
//Process the reads in separate threads
spawnThreads(cris, crosP, crosM);
if(verbose){outstream.println("Finished; closing streams.");}
//Write anything that was accumulated by ReadStats
errorState|=ReadStats.writeAll();
//Close the read streams
errorState|=ReadWrite.closeStreams(cris, crosP, crosM);
//Reset read validation
Read.VALIDATE_IN_CONSTRUCTOR=vic;
outstream.println();
analyze();
//Report timing and results
t.stop();
outstream.println();
outstream.println(Tools.timeReadsBasesProcessed(t, readsIn, basesIn, 8));
// outstream.println(Tools.readsBasesOut(readsProcessed, basesProcessed, readsOut, basesOut, 8, false));
//Throw an exception of there was an error in a thread
if(errorState){
throw new RuntimeException(getClass().getName()+" terminated in an error state; the output may be corrupt.");
}
}
/** Do math on the raw results to determine strandedness and major strand */
void analyze() {
double[] results=CheckStrand.calcStrandedness(canonSketch, fwdSketch);
double[] resultsN=CheckStrand.calcStrandednessNormalized(canonSketch, fwdSketch);
double[] refResults=(canonGeneSketch==null ? null : CheckStrand.calcPMRatioWithGeneSketches(
canonSketch, fwdSketch, canonGeneSketch, plusSketch, minusSketch));
outputResults(results, resultsN, refResults);
}
/**
* Start a read input stream from the read files
* @return The stream.
*/
private ConcurrentReadInputStream makeCris(){
ConcurrentReadInputStream cris=ConcurrentReadInputStream.getReadInputStream(
maxReads, true, ffin1, ffin2, qfin1, qfin2);
cris.setSampleRate(samplerate, sampleseed);
cris.start(); //Start the stream
if(verbose){outstream.println("Started cris");}
boolean paired=cris.paired();
if(!ffin1.samOrBam()){//Announce whether the data is being procesed as paired
outstream.println("Input is being processed as "+(paired ? "paired" : "unpaired"));
}
return cris;
}
/**
* Start a read output stream for some destination
* @param fname Destination file for stream
* @return The stream.
*/
private ConcurrentReadOutputStream makeCros(String fname){
if(fname==null) {return null;}
//Select output buffer size based on whether it needs to be ordered
final boolean ordered=true;
final int buff=(ordered ? Tools.mid(16, 128, (Shared.threads()*2)/3) : 8);
final FileFormat ffout=FileFormat.testOutput(
fname, ffin1.format(), null, true, overwrite, false, ordered);
final ConcurrentReadOutputStream ros=ConcurrentReadOutputStream.getStream(
ffout, null, buff, null, true);
ros.start(); //Start the stream
return ros;
}
/**
* Set Sketch static parameters and generate SketchTools
* for forward and canonical kmers.
*/
private void makeTools() {
if(verbose){System.err.println("Setting sketch params.");}
SketchObject.AUTOSIZE=false;
SketchObject.k=32;
SketchObject.k2=-1;//Otherwise the estimates are too high
SketchObject.setK=true;
SketchObject.sampleseed=sampleseed;
// SketchObject.defaultParams.minKeyOccuranceCount=2;
SketchObject.AUTOSIZE=false;
SketchObject.AUTOSIZE_LINEAR=false;
SketchObject.targetSketchSize=sketchSize;
SketchObject.SET_TARGET_SIZE=true;
SketchObject.processSSU=false;
SketchObject.defaultParams.parse("trackcounts", "trackcounts", null);
SketchObject.defaultParams.samplerate=samplerate;
SketchObject.postParse();
canonTool=new SketchTool(sketchSize, 0, true, true, true);
fwdTool=new SketchTool(sketchSize, 0, true, true, false);
}
/*--------------------------------------------------------------*/
/*---------------- Thread Management ----------------*/
/*--------------------------------------------------------------*/
/** Spawn process threads */
private void spawnThreads(final ConcurrentReadInputStream cris,
ConcurrentReadOutputStream crosP, ConcurrentReadOutputStream crosM){
//Do anything necessary prior to processing
//Determine how many threads may be used
final int maxThreads=mergePairs ? 64 : 16; //This is to limit memory use by sketches
final int threads=Tools.min(maxThreads, Shared.threads());
//Fill a list with ProcessThreads
ArrayList<ProcessThread> alpt=new ArrayList<ProcessThread>(threads);
for(int i=0; i<threads; i++){
alpt.add(new ProcessThread(cris, crosP, crosM, i));
}
//Start the threads and wait for them to finish
ThreadWaiter.startThreads(alpt);
//
// //While that's going, process the ref
// makeGeneSketches();
boolean success=ThreadWaiter.waitForThreadsToFinish(alpt, this);
outstream.println("Finished processing "+readsIn+" reads and "+basesIn+" bases.");
errorState&=!success;
//Do anything necessary after processing
//This transforms SketchHeaps (used for building Sketches) into finished Sketches.
canonSketch=new Sketch(canonHeap, false, true, null);
fwdSketch=new Sketch(fwdHeap, false, true, null);
}
@Override
public final void accumulate(ProcessThread pt){
synchronized(pt) {
readsIn+=pt.readsInT;
basesIn+=pt.basesInT;
readsProcessed+=pt.readsProcessedT;
basesProcessed+=pt.basesProcessedT;
readsMerged+=pt.readsMergedT;
fCountSum+=pt.fCountSumT;
rCountSum+=pt.rCountSumT;
fPosSum+=pt.fPosSumT;
rPosSum+=pt.rPosSumT;
Tools.add(fBestFrame, pt.fBestFrameT);
Tools.add(rBestFrame, pt.rBestFrameT);
Tools.add(ACGTCount, pt.ACGTCountT);
polyACount+=pt.polyACountT;
polyTCount+=pt.polyTCountT;
gCallerPlusCount+=pt.gCallerPlusCountT;
gCallerMinusCount+=pt.gCallerMinusCountT;
gCallerPlusCalled+=pt.gCallerPlusCalledT;
gCallerMinusCalled+=pt.gCallerMinusCalledT;
gCallerPlusScore+=pt.gCallerPlusScoreT;
gCallerMinusScore+=pt.gCallerMinusScoreT;
plusAlignedReads+=pt.plusAlignedReadsT;
minusAlignedReads+=pt.minusAlignedReadsT;
allAlignedReads+=pt.allAlignedReadsT;
samLinesProcessed+=pt.samLinesProcessedT;
samLinesAlignedToFeatures+=pt.samLinesAlignedToFeaturesT;
errorState|=(!pt.success);
if(!pt.canonSmm.isEmpty()) {
if(canonHeap==null){canonHeap=pt.canonSmm.heap();}
else{canonHeap.add(pt.canonSmm.heap());}
}
if(!pt.fwdSmm.isEmpty()) {
if(fwdHeap==null){fwdHeap=pt.fwdSmm.heap();}
else{fwdHeap.add(pt.fwdSmm.heap());}
}
}
}
@Override
public final boolean success(){return !errorState;}
/*--------------------------------------------------------------*/
/*---------------- Inner Methods ----------------*/
/*--------------------------------------------------------------*/
/**
* Generate sketches of the reference transcriptome.
* @return True if successful.
*/
private boolean makeGeneSketches() {
genes=grabGenes();
if(genes==null) {return false;}
outstream.println("Processing "+genes.size()+" genes.");
Sketch[] geneSketches=CheckStrand.sketchGenes(genes, canonTool, fwdTool);
if(geneSketches==null) {return false;}
canonGeneSketch=geneSketches[0];
plusSketch=geneSketches[1];
minusSketch=geneSketches[2];
return true;
}
/**
* Load the reference transcriptome; requires a reference fasta file.
* In transcriptome mode, the fasta file is simply loaded and returned.
* In genome mode, uses a gff if provided, otherwise the genes are called
* using CallGenes. Then the genes are cut from the reference like CutGff.
* Does not currently fuse exons together, and is untested on Euk annotations,
* but they are expected to work fine (as long as a gff is provided).
* @return Gene sequences, sense strand as plus.
*/
private ArrayList<Read> grabGenes(){
if(fna==null) {return null;}
final ArrayList<Read> genes;
Timer t=new Timer();
if(transcriptome || rnaContigs) {
System.err.print("Loading genes from transcriptome: ");
genes=genomeSequence(); //Skips loading if already cached
}else if(gff!=null) {
System.err.print("Loading genes from genome and gff: ");
HashMap<String, Read> map=(genomeSequenceCache==null ?
CheckStrand.getSequenceMap(fna) : CheckStrand.getSequenceMap(genomeSequence()));
genes=CheckStrand.grabGenes(gffLines, map);
}else{
ArrayList<Read> reads=genomeSequence();
if(gffLines==null) {
System.err.print("Calling genes from genome: ");
ArrayList<Orf> orfs=gCaller.callGenes(reads);
gffLines=Orf.toGffLines(orfs);
}
HashMap<String, Read> map=CheckStrand.getSequenceMap(reads);
genes=CheckStrand.grabGenes(gffLines, map);
}
t.stopAndPrint();
return (genes==null || genes.isEmpty()) ? null : genes;
}
/**
* Calls genes while streaming the fasta to save memory.
* Works fine but for some reason is extremely slow.
* @param fna Genome fasta.
* @return Gene sequences.
*/
@Deprecated
private ArrayList<Read> callGenes(String fna){
final ConcurrentReadInputStream cris=makeFastaCris(fna);
ArrayList<Read> genes=CheckStrand.callGenes(cris, gCaller);
//Close the input stream
errorState|=ReadWrite.closeStream(cris);
return genes;
}
/**
* Creates a read input stream for the fasta reference.
* @param fname Fasta path.
* @return The stream.
*/
private ConcurrentReadInputStream makeFastaCris(String fname){
FileFormat ffin=FileFormat.testInput(fname, FileFormat.FA, null, true, true);
ConcurrentReadInputStream cris=ConcurrentReadInputStream.getReadInputStream(-1, false, ffin, null);
cris.start(); //Start the stream
if(verbose){outstream.println("Started cris");}
return cris;
}
/**
* Print the final program results.
* @param results Results from read kmer depth analysis
* @param refResults Results based on transcriptome kmer comparison
*/
private void outputResults(double[] results, double[] resultsN, double[] refResults){
if(ffout1==null) {return;}
ByteStreamWriter bsw=new ByteStreamWriter(ffout1);
bsw.start();
final double invReads=1.0/readsProcessed;
final double invBases=1.0/basesProcessed;
//Results based on read kmer depth
if(doDepthAnalysis){
double strandedness=results[4];
double strandednessN=resultsN[4];
double depth=results[5];
double nonUniqueFraction=results[7];
bsw.println("Depth_Analysis:");
bsw.println(String.format("Strandedness:\t%.2f%%", strandedness*100));
bsw.println(String.format("StrandednessN:\t%.2f%%", strandednessN*100));
bsw.println(String.format("AvgKmerDepth:\t%.3f", depth));
bsw.println(String.format("Kmers>Depth1:\t%.4f", nonUniqueFraction));
}
//Results based on stop codons
if(doStopAnalysis){
bsw.println();
boolean plus=(fPosSum>=rPosSum);
double gc=(ACGTCount[1]+ACGTCount[2])/(1.0*shared.Vector.sum(ACGTCount));
bsw.println("Stop_Codon_Analysis:");
bsw.println(String.format("MajorStrandORF:\t"+(plus ? "Plus" : "Minus")));
bsw.println(String.format("AvgReadLen:\t%.2f", basesProcessed*invReads));
bsw.println(String.format("AvgORFLen+:\t%.2f", fPosSum*invReads));
bsw.println(String.format("AvgORFLen-:\t%.2f", rPosSum*invReads));
bsw.println(String.format("AvgStopCount+:\t%.4f", fCountSum*invReads));
bsw.println(String.format("AvgStopCount-:\t%.4f", rCountSum*invReads));
bsw.println(String.format("GC_Content:\t%.4f", gc));
//Frame analysis seemed useless so I suppressed it,
//but this prints which frame has the longest ORF
long[] bestFrame=(plus ? fBestFrame : rBestFrame);
double invSum=1.0/shared.Vector.sum(bestFrame);
// bsw.println(String.format("FrameStats"/*+(plus ? "+" : "-")*/+":\t%.4f\t%.4f\t%.4f",
// bestFrame[0]*invSum, bestFrame[1]*invSum, bestFrame[2]*invSum));
}
//Results based on terminal poly-As versus poly-Ts
//TODO: Read 2 should also be used for this analysis... otherwise the insert size interferes...
if(testPolyA) {
bsw.println();
boolean plus=(polyACount>=polyTCount);
bsw.println("PolyA_Analysis:");
bsw.println(String.format("MajorStrandPA:\t"+(plus ? "Plus" : "Minus")));
bsw.println(String.format("PolyA/(PA+PT):\t%.6f", (polyACount/(1.0*(polyACount+polyTCount)))));
bsw.println(String.format("PolyAFraction:\t%.6f", polyACount*invReads));
}
//Results based on comparing transcriptome kmers to read kmers
if(refResults!=null) {
bsw.println();
double pmRatio=refResults[0];
double aFraction=refResults[1];
double bFraction=refResults[2];
boolean plus=(pmRatio>=0.5);
bsw.println("Ref_Analysis:");
bsw.println("MajorStrandREF:\t"+(plus ? "Plus" : "Minus"));
bsw.println(String.format("P/(P+M)_Ratio:\t%.6f", pmRatio));
bsw.println(String.format("GeneCoverage:\t%.4f", aFraction));
bsw.println(String.format("GenePrecision:\t%.4f", bFraction));
}
// if(scoreReadGenes) {
// bsw.println();
// double readsCalled=(gCallerPlusCount+gCallerMinusCount);
// double pmRatio=gCallerPlusCount/(1.0*readsCalled);
// double pScore=gCallerPlusScore/(1.0*readsCalled);
// double mScore=gCallerMinusScore/(1.0*readsCalled);
// boolean plus=(pmRatio>=0.5);
// bsw.println("Kmer_Frequency_Analysis:");
// bsw.println("MajorStrandKFA:\t"+(plus ? "Plus" : "Minus"));
// bsw.println(String.format("P/(P+M)_Ratio:\t%.6f", pmRatio));
// bsw.println(String.format("AvgScorePlus:\t%.6f", pScore));
// bsw.println(String.format("AvgScoreMinus:\t%.6f", mScore));
// bsw.println(String.format("UsedFraction:\t%.6f", readsCalled*invReads));
// }
//Results based on calling and scoring genes on each side of the read
if(scoreReadGenes) {
bsw.println();
double readsCalled=(gCallerPlusCount+gCallerMinusCount);
double pmRatio=gCallerPlusCount/(1.0*readsCalled);
double pScore=gCallerPlusScore/(1.0*gCallerPlusCalled);
double mScore=gCallerMinusScore/(1.0*gCallerMinusCalled);
boolean plus=(pmRatio>=0.5);
bsw.println("Read_Gene_Calling_Analysis:");
bsw.println("MajorStrandRGC:\t"+(plus ? "Plus" : "Minus"));
bsw.println(String.format("P/(P+M)_Ratio:\t%.6f", pmRatio));
bsw.println(String.format("AvgScorePlus:\t%.6f", pScore));
bsw.println(String.format("AvgScoreMinus:\t%.6f", mScore));
bsw.println(String.format("UsedFraction:\t%.6f", readsCalled*invReads));
}
//Alignment-based results
//TODO: Add a flag; should probably be disabled for euks with no gff
if(ffin1.samOrBam() && (transcriptome || rnaContigs || gff!=null || fna!=null)) {
long genesAligned=0;
long genesGT1=0;
double strandednessSumNorm=0;
double pmRatioSum=0;
long plusGeneCount=0;
double minorSum=0, majorSum=0, maxMinorSum=0, expectedSum=0;
{//Normalized Statistics
for(LongPair p : geneMap.values()) {
if(p.a+p.b>0) {
float pmRatio=p.a/(float)(p.a+p.b);
genesAligned++;
pmRatioSum+=pmRatio;
plusGeneCount+=(pmRatio>0.5f ? 1 : 0);
if(p.a+p.b>=minReads) {
float strandedness=CheckStrand.strandedness(p.a, p.b);
assert(strandedness>=0 && strandedness<=1.01) : strandedness+", "+p.a+", "+p.b;
strandednessSumNorm+=strandedness;
genesGT1++;
assert(strandednessSumNorm<=genesGT1) : strandednessSumNorm+", "+genesGT1;
minorSum+=p.min();
majorSum+=p.max();
maxMinorSum+=p.sum()/2;
expectedSum+=CheckStrand.expectedMinorAlleleCount(p.sum());
}
}
}
}
final double[] binStrandedness=binStrandedness();
final boolean plus=(plusAlignedReads>=minusAlignedReads);
final long readsAligned0=plusAlignedReads+minusAlignedReads;
final long readsAligned=Tools.max(1, readsAligned0);
final double alignmentRate=allAlignedReads/(1.0*samLinesProcessed);
final double alignmentRate2=samLinesAlignedToFeatures/(1.0*samLinesProcessed);
final double pmRatio=plusAlignedReads/(1.0*readsAligned);
double strandednessALN=Tools.max(plusAlignedReads, minusAlignedReads)/(1.0*readsAligned);
if(rnaContigs) {
//strandednessALN=CheckStrand.strandedness(minorSum, majorSum);
if(minorSum<=expectedSum) {//Expected case
strandednessALN=1-0.5f*(minorSum/expectedSum);//0.5-1
}else{//Rare case; overly unstranded
double range=maxMinorSum-expectedSum;
double dif=minorSum-expectedSum;
strandednessALN=0.5f*(1-(dif/range));
}
}
bsw.println();
bsw.println("Alignment_Results:");
bsw.println(String.format("StrandednessAL:\t%.2f%%", strandednessALN*100));
assert(strandednessSumNorm<=genesGT1) : strandednessSumNorm+", "+genesGT1;
bsw.println(String.format("StrandednessAN:\t%.2f%%", 100*strandednessSumNorm/genesGT1));
// assert(false) : strandednessSumNorm+", "+genesGT1;
if(binStrandedness!=null) {
bsw.println(String.format("StrandednessB:\t%.2f%%", binStrandedness[0]*100));
bsw.println(String.format("StrandednessBN:\t%.2f%%", binStrandedness[1]*100));
bsw.println(String.format("StrandednessBS:\t%.2f%%", binStrandedness[2]*100));
bsw.println(String.format("StrandednessBNS:\t%.2f%%", binStrandedness[3]*100));
}
if(!rnaContigs) {
bsw.println("MajorStrandAL:\t"+(plus ? "Plus" : "Minus"));
bsw.println(String.format("P/(P+M)_Ratio:\t%.6f", pmRatio));
bsw.println(String.format("P/(P+M)_RatioN:\t%.6f", pmRatioSum/genesAligned));
}
if(!transcriptome) {
bsw.println(String.format("PlusFeatures:\t%.6f", plusGeneCount/(float)genesAligned));
}
bsw.println(String.format("AlignmentRate:\t%.6f", alignmentRate));
if(!transcriptome && !rnaContigs) {bsw.println(String.format("Feature-Mapped:\t%.6f", alignmentRate2));}
// bsw.println(String.format("Plus-mapped:\t%d", plusAlignedReads));
// bsw.println(String.format("Minus-mapped:\t%d", minusAlignedReads));
}
//Displays fraction of reads merged
if(mergePairs && readsProcessed<readsIn) {
bsw.println();
bsw.println(String.format("PairMergeRate:\t%.4f", readsMerged/(1.0*readsProcessed)));
}
errorState=bsw.poisonAndWait() | errorState;
}
double[] binStrandedness() {
if(binMap==null || binMap.isEmpty()) {return null;}
long binsAligned=0;
long binsGT1=0;
double strandednessSumNorm=0;
double pmRatioSum=0;
double simpleSumNorm=0;
long plusBinCount=0;
double minorSum=0, majorSum=0, maxMinorSum=0, expectedSum=0;
for(ArrayList<LongPair> list : binMap.values()) {
for(LongPair p : list) {
if(p!=null && p.a+p.b>0) {
float pmRatio=p.a/(float)(p.a+p.b);
binsAligned++;
pmRatioSum+=pmRatio;
plusBinCount+=(pmRatio>0.5f ? 1 : 0);
if(p.a+p.b>=minReads) {
float strandedness=CheckStrand.strandedness(p.a, p.b);
assert(strandedness>=0 && strandedness<=1.01) : strandedness+", "+p.a+", "+p.b;
strandednessSumNorm+=strandedness;
binsGT1++;
assert(strandednessSumNorm<=binsGT1) : strandednessSumNorm+", "+binsGT1;
minorSum+=p.min();
majorSum+=p.max();
maxMinorSum+=p.sum()/2;
expectedSum+=CheckStrand.expectedMinorAlleleCount(p.sum());
simpleSumNorm+=p.max()/(double)p.sum();
}
}
}
}
double strandedness=CheckStrand.strandedness((long)minorSum, (long)majorSum, (long)maxMinorSum, (float)expectedSum);
double strandednessN=strandednessSumNorm/binsGT1;
double strandednessS=majorSum/(majorSum+minorSum);
double strandednessNS=simpleSumNorm/binsGT1;
return new double[] {strandedness, strandednessN, strandednessS, strandednessNS};
}
/**
* Manages a cached copy of the ref fasta to prevent reading it multiple times.
* @return The reference, as Read objects.
*/
private ArrayList<Read> genomeSequence(){
assert(fna!=null);
if(genomeSequenceCache==null) {
genomeSequenceCache=ReadInputStream.toReads(fna, FileFormat.FASTA, -1);
}
return genomeSequenceCache;
}
/*--------------------------------------------------------------*/
void incrementGeneMap(String gene, ConcurrentHashMap<String, LongPair> map, int senseStrand, int amt){
if(gene==null) {return;}
LongPair pair=map.get(gene);
if(pair==null) {
map.putIfAbsent(gene, new LongPair());
pair=map.get(gene);
}
synchronized(pair) {
if(senseStrand==0) {pair.a+=amt;}
else {pair.b+=amt;}
}
}
void incrementBinMap(String gene, ConcurrentHashMap<String, ArrayList<LongPair>> map, int pos, int strand, int amt){
if(gene==null || map==null) {return;}
ArrayList<LongPair> list=map.get(gene);
if(list==null) {
map.putIfAbsent(gene, new ArrayList<LongPair>());
list=map.get(gene);
}
int idx=Tools.max(0, pos)/binlen;
increment(list, idx, strand, amt);
}
void increment(ArrayList<LongPair> list, int idx, int strand, int amt) {
LongPair bin;
synchronized(list) {
while(list.size()<=idx) {list.add(null);}
bin=list.get(idx);
if(bin==null) {
bin=new LongPair();
list.set(idx, bin);
}
}
synchronized(bin) {
if(strand==0) {bin.a+=amt;}
else {bin.b+=amt;}
}
}
/*--------------------------------------------------------------*/
/*---------------- Inner Classes ----------------*/
/*--------------------------------------------------------------*/
/**
* Handles all operations on input reads,
* such as merging, sketching, and stop-codon finding. */
class ProcessThread extends Thread {
//Constructor
ProcessThread(final ConcurrentReadInputStream cris_,
ConcurrentReadOutputStream crosP_, ConcurrentReadOutputStream crosM_, final int tid_){
cris=cris_;
crosP=crosP_;
crosM=crosM_;
tid=tid_;//Thread ID
canonSmm=new SketchMakerMini(canonTool, SketchObject.ONE_SKETCH, minEntropy, minProb, minQual);
fwdSmm=new SketchMakerMini(fwdTool, SketchObject.ONE_SKETCH, minEntropy, minProb, minQual);
gCallerT=(scoreReadGenes ? CallGenes.makeGeneCaller(pgm) : null);
// if(gCallerT!=null) {gCallerT.keepAtLeastOneOrf=true;}//Increases usage rate, but decreases precision
}
//Called by start()
@Override
public void run(){
//Do anything necessary prior to processing
//Process the reads
processInner();
//Do anything necessary after processing
//Indicate successful exit status
success=true;
}
/** Fetch lists of reads from the input stream. */
void processInner(){
//Grab the first ListNum of reads
ListNum<Read> ln=cris.nextList();
//As long as there is a nonempty read list...
while(ln!=null && ln.size()>0){
if(verbose){outstream.println("Fetched "+ln.size()+" reads.");}
processList(ln);
//Notify the input stream that the list was used
cris.returnList(ln);
//Fetch a new list
ln=cris.nextList();
}
//Notify the input stream that the final list was used
if(ln!=null){
cris.returnList(ln.id, ln.list==null || ln.list.isEmpty());
}
}
/** Iterate through the reads */
void processList(ListNum<Read> ln){
//Grab the actual read list from the ListNum
final ArrayList<Read> reads=ln.list;
pReads=(crosP==null ? null : new ArrayList<Read>());
mReads=(crosM==null ? null : new ArrayList<Read>());
//Loop through each read in the list
for(int idx=0; idx<reads.size(); idx++){
final Read r1=reads.get(idx);
final Read r2=r1.mate;
//Validate reads in worker threads
if(!r1.validated()){r1.validate(true);}
if(r2!=null && !r2.validated()){r2.validate(true);}
//Track the initial length for statistics
final int initialLength1=r1.length();
final int initialLength2=r1.mateLength();
//Increment counters
readsInT+=r1.pairCount();
basesInT+=initialLength1+initialLength2;
processReadPair(r1, r2);
}
//Output reads to the output streams
if(crosP!=null){crosP.add(pReads, ln.id);}
if(crosM!=null){crosM.add(mReads, ln.id);}
pReads=mReads=null;
}
/**
* Process a read or a read pair.
* @param r1 Read 1
* @param r2 Read 2 (may be null)
*/
void processReadPair(Read r1, Read r2){
if(r1.bases==null) {return;} //Especially for sam lines
final SamLine sl=r1.samline;
if(sl!=null) {//This means the input was a sam or bam file
processSamLine(r1, sl);
if(sl.pairnum()>0) {return;}//Don't process read 2 from sam input
}
//Merge pairs here if needed.
if(mergePairs && r2!=null){
final int insert=BBMerge.findOverlapStrict(r1, r2, false);
if(insert>0){
r2.reverseComplement();
r1=r1.joinRead(insert);
r2=null;
readsMergedT++;
}
}
readsProcessedT++;
basesProcessedT+=r1.length();
r1.mate=null;
if(doStopAnalysis) {countStopCodons(r1);}
canonSmm.processReadNucleotide(r1);
fwdSmm.processReadNucleotide(r1);
if(testPolyA) {analyzePolyA(r1);}
if(scoreReadGenes) {scoreGenes2(r1);}
}
/**
* Counts stop codons in each frame, and the longest ORF per frame.
*/
void countStopCodons(Read r) {
final byte[] bases=r.bases;
if(bases.length<5) {return;}
final int k=3;
final int shift=2*k;
final int shift2=shift-2;
final int mask=0b111111;
int kmer=0;
int rkmer=0;
int len=0;
Arrays.fill(fCount, 0);
Arrays.fill(rCount, 0);
Arrays.fill(fPos, bases.length);
Arrays.fill(rPos, bases.length);
Arrays.fill(fMaxOrf, -1);
Arrays.fill(rMaxOrf, -1);
Arrays.fill(fLastStop, 0);
Arrays.fill(rLastStop, 0);
for(int i=0; i<bases.length; i++){
byte b=bases[i];
int x=AminoAcid.baseToNumber[b];
int x2=AminoAcid.baseToComplementNumber[b];
kmer=((kmer<<2)|x)&mask;
rkmer=((rkmer>>>2)|(x2<<shift2))&mask;
if(x<0){
len=0;
rkmer=0;
}else{
len++;
ACGTCountT[x]++;
}
if(len>=k){
final int j=i%3;
final byte aa=AminoAcid.codeToByte[kmer];
final byte raa=AminoAcid.codeToByte[rkmer];
if(aa=='*'){
// System.err.println("aa="+Character.toString(aa));
fCount[j]++;
fPos[j]=Tools.min(fPos[j], i);//TODO: This only tracks the first ORF, not the longest
final int orfLen=i-fLastStop[j];
fLastStop[j]=i;
fMaxOrf[j]=Tools.max(fMaxOrf[j], orfLen);
}
if(raa=='*') {
final int i2=bases.length-i-2;
rCount[j]++;
rPos[j]=Tools.min(rPos[j], i2);
final int orfLen=rLastStop[j]-i2;
rLastStop[j]=i2;
rMaxOrf[j]=Tools.max(rMaxOrf[j], orfLen);
// System.err.println(i2+", "+rLastStop[j]+", "+rMaxOrf[j]);
}
}
}
fCountSumT+=Tools.min(fCount);
rCountSumT+=Tools.min(rCount);
for(int i=0; i<3; i++) {
if(fMaxOrf[i]<0) {fMaxOrf[i]=bases.length;}
if(rMaxOrf[i]<0) {rMaxOrf[i]=bases.length;}
}
final int[] fORF=(useFirstORF ? fPos : fMaxOrf);
final int[] rORF=(useFirstORF ? rPos : rMaxOrf);
final int mfp=Tools.max(fORF);
final int mrp=Tools.max(rORF);
fPosSumT+=mfp;
rPosSumT+=mrp;
// fBestFrameT[Tools.maxIndex(fORF)]++;
// rBestFrameT[Tools.maxIndex(rORF)]++;
for(int i=0; i<3; i++) {//This is better since it increments all equal ones
if(fORF[i]==mfp){fBestFrameT[i]++;}
if(rORF[i]==mrp){rBestFrameT[i]++;}
}
// assert(false) : "\n"+Arrays.toString(fCount)+"\n"+Arrays.toString(rCount)+"\n"+Arrays.toString(fPos)+"\n"+Arrays.toString(rPos);
}
/**
* Counts tip poly-As and poly-Ts.
* TODO: Should take into account pairnum so read 2 can be used.
*/
void analyzePolyA(Read r) {
final int trailingPolyA=r.countTrailing('A'), leadingPolyT=r.countLeading('T');
// final int trailingPolyT, leadingPolyA;//These two should be spurious, but could be used to infer whether the poly-A is due to real poly-A tails.
if(trailingPolyA>leadingPolyT && trailingPolyA>minPolyA) {polyACountT++;}
else if(trailingPolyA<leadingPolyT && leadingPolyT>minPolyA) {polyTCountT++;}
}
/**
* Calls genes on both strands, and records which strand
* had the highest-scoring gene.
*/
void scoreGenes2(Read r) {
ArrayList<Orf> list;
list=gCallerT.callGenes(r, true);
// System.err.print((list==null ? 0 : list.size())+", ");
// Orf bestPlus=null;
// Orf bestMinus=null;
final float min=-99999;
float plusScore=min, minusScore=min;
if(list!=null && !list.isEmpty()) {
for(Orf orf : list) {
// if(orf.strand==0) {
// if(bestPlus==null || bestPlus.score()<orf.score()) {bestPlus=orf;}
// }else {
// if(bestMinus==null || bestMinus.score()<orf.score()) {bestMinus=orf;}
// }
if(orf.strand==0) {
plusScore=Tools.max(plusScore, orf.score());
}else {
minusScore=Tools.max(minusScore, orf.score());
}
}
}
//This block is to ensure the uncalled strand gets a lower score,
//in case the called strand has a negative score
if(plusScore==min && minusScore==min) {
plusScore=minusScore=0;
}else if(plusScore==min) {
plusScore=Tools.min(0, minusScore*1.5f-1);
}else if(minusScore==min) {
minusScore=Tools.min(0, plusScore*1.5f-1);
}
// if(plusScore<=0 && minusScore<=0) {return;}
gCallerPlusScoreT+=plusScore;
gCallerMinusScoreT+=minusScore;
if(plusScore>minusScore) {gCallerPlusCountT++;}
else if(minusScore>plusScore){gCallerMinusCountT++;}
if(plusScore>0){gCallerPlusCalledT++;}
if(minusScore>0){gCallerMinusCalledT++;}
}
@Deprecated
/**
* Old version; just looked at enriched interior kmers instead of
* doing normal gene-calling. Didn't work very will.
*/
void scoreGenes(Read r) {
byte[] bases=r.bases;
double plusScoreCDS=gCaller.scoreFeature(bases, ProkObject.CDS);//These scores are suspiciously low; I wonder if frame tracking is working correctly?
double plusScore16S=gCaller.scoreFeature(bases, ProkObject.r16S);
double plusScore5S=gCaller.scoreFeature(bases, ProkObject.r5S);
AminoAcid.reverseComplementBasesInPlace(bases);
double minusScoreCDS=gCaller.scoreFeature(bases, ProkObject.CDS);
double minusScore16S=gCaller.scoreFeature(bases, ProkObject.r16S);
double minusScore5S=gCaller.scoreFeature(bases, ProkObject.r5S);
AminoAcid.reverseComplementBasesInPlace(bases);
double maxCDS=Tools.max(plusScoreCDS, minusScoreCDS)*1.6;
double max16S=Tools.max(plusScore16S, minusScore16S)*1.2;
double max5S=Tools.max(plusScore5S, minusScore5S)*0.9;
boolean cds=maxCDS>=max16S;
boolean r5s=max5S>=max16S && max5S>=maxCDS;
double plusScore=r5s ? plusScore5S : cds ? plusScoreCDS : plusScore16S;
double minusScore=r5s ? minusScore5S : cds ? minusScoreCDS : minusScore16S;
//Doesn't fit the model well...
if(plusScore<0.97 && minusScore<0.97) {return;}
gCallerPlusScoreT+=plusScore;
gCallerMinusScoreT+=minusScore;
if(plusScore>=minusScore) {gCallerPlusCountT++;}
else {gCallerMinusCountT++;}
}
/**
* Associate an aligned read with the plus or minus strand.
* @param r1 The read.
* @param sl The read's SamLine.
*/
void processSamLine(final Read r1, final SamLine sl) {
if(!sl.primary() || sl.supplementary()) {return;}
samLinesProcessedT++;
if(!sl.mapped()) {return;}
allAlignedReadsT++;
//Flip read 2's associated strand.
final int mappedStrand=(sl.strand()^sl.pairnum());
//The strand on which the gene is located.
int senseStrand=-1;
String gene=null;
if(transcriptome) {
senseStrand=mappedStrand;
gene=sl.rnameS();
}else if(rnaContigs) {
senseStrand=mappedStrand;
gene=sl.rnameS();
}else if(gffLines!=null){//Try to figure out the sense strand
final int start=sl.start(false, false);
// final int stop=sl.stop(start, false, false);
// final int p=(start+stop)/2;
final int p=start;//A point used as proxy for the read location
//Get the ranges for the contig
String rname=sl.rnameS();
Range[] ranges=rangeMap.get(rname);
//Retry the name, trimmed to the first whitespace
if(ranges==null) {ranges=rangeMap.get(sl.rnamePrefix());}
// assert(ranges!=null) : "Can't find rname "+sl.rnameS()+":\n"+sl+"\n";// in "+rangeMap.keySet()+"\n"+sl;
if(ranges!=null) {
//Find the range containing the proxy point
int idx=Range.findIndex(p, ranges);
if(idx<0) {idx=-idx-1;}
if(idx<0 || idx>=ranges.length){return;}
final Range r=ranges[idx];
//List of features overlapping the point
final ArrayList<GffLine> lines=(ArrayList<GffLine>) r.obj1;
for(int i=lines.size()-1; i>=0; i--) {//Now to select a line...
final GffLine line=lines.get(i);
//TODO: With multiple overlapping features, this may or may not be the best one
if(r.intersects(line.start, line.stop)) {
senseStrand=mappedStrand^line.strand;
gene=sl.rnameS();
break;
}
}
}
}
if(gene!=null) {
incrementGeneMap(gene, geneMap, senseStrand, 1);
incrementBinMap(gene, binMap, sl.pos, mappedStrand, 1);
//Track results according to the determined strand
if(senseStrand==0) {
samLinesAlignedToFeaturesT++;
plusAlignedReadsT++;
if(crosP!=null) {pReads.add(r1);}
}else if(senseStrand==1){
samLinesAlignedToFeaturesT++;
minusAlignedReadsT++;
if(crosM!=null) {mReads.add(r1);}
}else {
assert(senseStrand==-1);
}
}
}
/** Number of reads in to this thread */
protected long readsInT=0;
/** Number of bases in to this thread */
protected long basesInT=0;
/** Number of reads processed by this thread */
protected long readsProcessedT=0;
/** Number of bases processed by this thread */
protected long basesProcessedT=0;
/** Number of reads merged by this thread */
protected long readsMergedT=0;
/** True only if this thread has completed successfully */
boolean success=false;
/** Shared input stream */
private final ConcurrentReadInputStream cris;
private final ConcurrentReadOutputStream crosP;
private final ConcurrentReadOutputStream crosM;
private ArrayList<Read> pReads, mReads;
final SketchMakerMini canonSmm;
final SketchMakerMini fwdSmm;
//These are just buffers
/** Counts of stop codons on forward strand */
private final int[] fCount=new int[3];
/** Counts of stop codons on reverse strand */
private final int[] rCount=new int[3];
/** Longest initial ORF on forward strand */
private final int[] fPos=new int[3];
/** Longest initial ORF on reverse strand */
private final int[] rPos=new int[3];
/** Longest ORF on forward strand */
private final int[] fMaxOrf=new int[3];
/** Longest ORF on reverse strand */
private final int[] rMaxOrf=new int[3];
/** Last stop seen on forward strand */
private final int[] fLastStop=new int[3];
/** Last stop seen on reverse strand */
private final int[] rLastStop=new int[3];
private long fCountSumT;
private long rCountSumT;
private long fPosSumT;
private long rPosSumT;
private final long[] fBestFrameT=new long[3];
private final long[] rBestFrameT=new long[3];
private final long[] ACGTCountT=new long[4];
private long polyACountT=0;
private long polyTCountT=0;
private long gCallerPlusCountT=0;
private long gCallerMinusCountT=0;
private long gCallerPlusCalledT=0;
private long gCallerMinusCalledT=0;
private double gCallerPlusScoreT=0;
private double gCallerMinusScoreT=0;
private long plusAlignedReadsT=0;
private long minusAlignedReadsT=0;
private long allAlignedReadsT=0;
private long samLinesProcessedT=0;
private long samLinesAlignedToFeaturesT=0;
private GeneCaller gCallerT;
/** Thread ID */
final int tid;
}
/*--------------------------------------------------------------*/
/*---------------- Fields ----------------*/
/*--------------------------------------------------------------*/
/** Primary input file path */
private String in1=null;
/** Secondary input file path */
private String in2=null;
private String qfin1=null;
private String qfin2=null;
String fna=null;
String gff=null;
String pgmFile=null;
private String types="CDS,rRNA,tRNA,ncRNA,exon,5S,16S,23S";
private ArrayList<GffLine> gffLines=null;
private ConcurrentHashMap<String, ArrayList<LongPair>> binMap;
/**
* Map associating with contig names with ordered arrays of nonoverlapping ranges
* Each range has attached a list of features that fully contain it. */
private HashMap<String, Range[]> rangeMap;
/** Primary output file path */
private String out1="stdout.txt";
/** Output file path for plus-aligned reads */
private String outPlus=null;
/** Output file path for minus-aligned reads */
private String outMinus=null;
/** Override input file extension */
private String extin=null;
/** Override output file extension */
private String extout=null;
/** Whether interleaved was explicitly set. */
private boolean setInterleaved=false;
private int binlen=0;
/*--------------------------------------------------------------*/
/** Number of reads processed */
protected long readsIn=0;
/** Number of bases processed */
protected long basesIn=0;
/** Number of reads processed */
protected long readsProcessed=0;
/** Number of bases processed */
protected long basesProcessed=0;
protected long readsMerged=0;
/** Quit after processing this many input reads; -1 means no limit */
private long maxReads=-1;
private float samplerate=1;
private long sampleseed=17;
private int sketchSize=80000;
private float minEntropy=0;
private float minProb=0;
private byte minQual=0;
private boolean mergePairs=false;
private final boolean doDepthAnalysis=true;
private boolean doStopAnalysis=true;
private boolean testPolyA=true;
private ArrayList<Read> genes;
private SketchTool canonTool;
private SketchTool fwdTool;
private SketchHeap canonHeap=null;
private SketchHeap fwdHeap=null;
private Sketch canonSketch=null;
private Sketch fwdSketch=null;
private Sketch canonGeneSketch=null;
private Sketch plusSketch=null;
private Sketch minusSketch=null;
private long fCountSum=0;
private long rCountSum=0;
private long fPosSum=0;
private long rPosSum=0;
private boolean useFirstORF=false;
private final long[] fBestFrame=new long[3];
private final long[] rBestFrame=new long[3];
private final long[] ACGTCount=new long[4];
private long polyACount=0;
private long polyTCount=0;
private int minPolyA=6;
private long gCallerPlusCount=0;
private long gCallerMinusCount=0;
private long gCallerPlusCalled=0;
private long gCallerMinusCalled=0;
private double gCallerPlusScore=0;
private double gCallerMinusScore=0;
private long plusAlignedReads=0;
private long minusAlignedReads=0;
private long allAlignedReads=0;
private long samLinesProcessed=0;
private long samLinesAlignedToFeatures=0;
//Possibly should change this to scoring the best orf per strand
//This gave the wrong answer for a metatranscriptome
private boolean scoreReadGenes=true;
private final GeneModel pgm;
private final GeneCaller gCaller;
private int passes=2;
private boolean streamGenome=false;
private ArrayList<Read> genomeSequenceCache=null;
ConcurrentHashMap<String, LongPair> geneMap=new ConcurrentHashMap<String, LongPair>();
/** Whether the input reference is a transcriptome or genome */
private boolean transcriptome=false;
/** True for unknown sense contigs from RNA-seq data */
private boolean rnaContigs=false;
private boolean normalize=false;
private int minReads=2;//Don't calculate strandedness from fewer reads
/*--------------------------------------------------------------*/
/*---------------- Final Fields ----------------*/
/*--------------------------------------------------------------*/
/** Primary input file */
private final FileFormat ffin1;
/** Secondary input file */
private final FileFormat ffin2;
/** Primary output file */
private final FileFormat ffout1;
@Override
public final ReadWriteLock rwlock() {return rwlock;}
private final ReadWriteLock rwlock=new ReentrantReadWriteLock();
/*--------------------------------------------------------------*/
/*---------------- Static Fields ----------------*/
/*--------------------------------------------------------------*/
/*--------------------------------------------------------------*/
/*---------------- Common Fields ----------------*/
/*--------------------------------------------------------------*/
/** Print status messages to this output stream */
private PrintStream outstream=System.err;
/** Print verbose messages */
public static boolean verbose=false;
/** True if an error was encountered */
public boolean errorState=false;
/** Overwrite existing output files */
private boolean overwrite=true;
/** Append to existing output files */
private boolean append=false;
}
|