Debian Codegraph @

current/jasper/KmerPosition3.java

raw symbols SCIP
1 package jasper;
2
3 import java.util.ArrayList;
4
5 import dna.AminoAcid;
6 import fileIO.ByteStreamWriter;
7 import fileIO.FileFormat;
8 import fileIO.ReadWrite;
9 import shared.Parse;
10 import shared.Parser;
11 import shared.PreParser;
12 import shared.Shared;
13 import shared.Timer;
14 import shared.Tools;
15 import stream.ConcurrentReadInputStream;
16 import stream.Read;
17 import structures.ListNum;
18 import structures.LongHashSet;
19 import structures.LongList;
20
21 /**
22 * Read in file of high-throughput reads sequences and a reference sequence file
23 * report the positions in the reads that are the start of a matching kmer sequence
24 * between the read and the reference sequence.
25 * This is useful for identifying over-representation of kmers at a particular position in reads. <br>
26 *
27 * read = ACGTA <br>
28 * reference = ATGTACC <br>
29 * kmer length = 3 <br>
30 * match = GTA, beginning in the read at position 2 (zero indexed). <br>
31 * returned info = #positions, #number of kmers beginning at that position,
32 * #percentage of reads with kmers beginning at that positons. <br>
33 *
34 *
35 * @author Jasper Toscani Field
36 * @date Jun 4, 2020
37 *
38 */
39 public class KmerPosition3 {
40
41 /*--------------------------------------------------------------*/
42 /*---------------- Initialization ----------------*/
43 /*--------------------------------------------------------------*/
44
45 public static void main(String[] args){
46 //Start a timer immediately upon code entrance.
47 Timer t=new Timer();
48
49 //Create an instance of this class
50 KmerPosition3 x=new KmerPosition3(args);
51
52 //Run the object
53 x.process(t);
54
55 //Close the print stream if it was redirected
56 Shared.closeStream(x.outstream);
57 }
58
59 /**
60 * Handles pre-parsing and parsing of user flags.
61 * Reads in the read file(s) and the reference files.
62 * Sets the maximum number of reads to be processed.
63 *
64 * @param args string of the arguments input at the commandline.
65 *
66 */
67 public KmerPosition3(String[] args){
68
69 {//Preparse block for help, config files, and outstream
70 PreParser pp=new PreParser(args, getClass(), false);
71 args=pp.args;
72 outstream=pp.outstream;
73 }
74
75 //Primary parsing of standard arguments found in all bbmap programs (maxReads, parseSam, parseZip, etc).
76 Parser parser=new Parser();
77
78 //Loop through arguments up to the maximum number of arguments input.
79 //process all remaining arguments.
80 for(int i=0; i<args.length; i++){
81
82 //Grab argument string at index.
83 String arg=args[i];
84
85 //Split argument string on "=".
86 String[] split=arg.split("=");
87
88 //Convert the left side to lowercase.
89 String a=split[0].toLowerCase();
90
91 //Ternary conditional statement: is the length of the split greater than 1 (thus, an actual input)?
92 //if so, the right side of the split is the b variable, if not, b is null.
93 String b=split.length>1 ? split[1] : null;
94
95 //If b isn't null but a string "null" was input, convert b to null.
96 if(b!=null && b.equalsIgnoreCase("null")){b=null;}
97
98 //Unused example statement. does nothing currently. start here for adding new flag parsing.
99 if(a.equals("parse_flag_goes_here")){
100
101 //Handle reference variable assignment.
102 }else if(a.equals("ref")){
103 ref=b;
104
105 //Handle kmer variable assignment.
106 }else if(a.equals("k")){
107 k=Integer.parseInt(b);
108
109 //Parses in and out flags, handles all flags not recognized earlier in class.
110 }else if(a.equals("rcomp")){
111 rcomp=Parse.parseBoolean(b);
112
113 //Parses in and out flags, handles all flags not recognized earlier in class.
114 }else if(parser.parse(arg, a, b)){
115
116 //If not one of the known parameters, let the user know they made a mistake.
117 }else{
118 assert(false) : "Unknown parameter "+args[i];
119 outstream.println("Unknown parameter "+args[i]);
120 }
121 }
122
123 {//Handle quality scoring by identifying quality scoring method.
124 Parser.processQuality();
125
126 //appropriate argument passing
127 maxReads=parser.maxReads;
128 in1=parser.in1;
129 in2=parser.in2;
130 out1=parser.out1;
131 }
132
133 assert(in1!=null) : "Please specify an input file.";
134 assert(ref!=null) : "Please specify a reference file.";
135
136 //File format handling for each file.
137 ffout1=FileFormat.testOutput(out1, FileFormat.TXT, null, true, true, false, false);
138 ffin1=FileFormat.testInput(in1, FileFormat.FASTQ, null, true, true);
139 ffin2=FileFormat.testInput(in2, FileFormat.FASTQ, null, true, true);
140 ffref=FileFormat.testInput(ref, FileFormat.FASTA, null, true, true);
141 }
142
143 /*--------------------------------------------------------------*/
144 /*---------------- Outer Methods ----------------*/
145 /*--------------------------------------------------------------*/
146
147 /**
148 * Primary processing function. Begins the read stream on a thread,
149 * passes reads to kmer production and bit-shifting methods.
150 * Completes after writing kmer statistics to file, halting and
151 * reporting the timer and reporting any error states.
152 *
153 * @param t Timer object for the program. The timer has already been started and is non-null.
154 */
155 void process(Timer t){
156
157 //Creates a empty LongHashSet.
158 //This hash set will eventually hold kmers found in the reference of length k,
159 //advancing 1 position each step.
160 LongHashSet refKmerSet=loadReference();
161
162 //Instantiate the input stream
163 final ConcurrentReadInputStream cris;
164 {
165 cris=ConcurrentReadInputStream.getReadInputStream(maxReads, true, ffin1, ffin2);
166 cris.start();
167 }
168 //Paired indicates whether input stream is processing the data as paired.
169 boolean paired=cris.paired();
170
171
172 long readsProcessed=0, basesProcessed=0;
173 {
174 //Returns listNum of 200 reads,
175 //minimize function calling to reduce inter-thread communication.
176 ListNum<Read> ln=cris.nextList();
177
178 //Prevents null pointer exception if ListNum is null
179 //meaning file was empty.
180 ArrayList<Read> reads=(ln!=null ? ln.list : null);
181
182 //Pulls first read in list, checks if paired input was selected and
183 //determines if this is correct.
184 if(reads!=null && !reads.isEmpty()){
185 Read r=reads.get(0);
186
187 assert((ffin1==null || ffin1.samOrBam()) || (r.mate!=null)==cris.paired());
188 }
189
190 //Loop while more reads available.
191 while(ln!=null && reads!=null && reads.size()>0){//ln!=null prevents a compiler potential null access warning
192 if(verbose){outstream.println("Fetched "+reads.size()+" reads.");}
193
194 //Loop through every read in list.
195 for(int idx=0; idx<reads.size(); idx++){
196 final Read r1=reads.get(idx);
197 final Read r2=r1.mate;
198
199 //Handles incrementing the number of reads processed if paired or unpaired.
200 readsProcessed+=r1.pairCount();
201 basesProcessed+=r1.pairLength();
202
203 // ********* Process reads here *********
204 //Pass read 1 (and 2 if paired) and the reference kmer set, with the positional count list.
205 processRead(r1, refKmerSet, matchCounts1, totalCounts1);
206 if(r1.mate!=null) {
207 processRead(r2, refKmerSet, matchCounts2, totalCounts2);
208 }
209 }
210
211 //When done processing list, return to input stream to
212 //notify we're ready for new list of reads.
213 cris.returnList(ln);
214
215 if(verbose){outstream.println("Returned a list.");}
216
217 //Grab next list.
218 ln=cris.nextList();
219
220 //Prevent null pointer exception if list of reads is empty.
221 reads=(ln!=null ? ln.list : null);
222 }
223
224 //If no list returned on line 176, return list now.
225 if(ln!=null){
226 cris.returnList(ln.id, ln.list==null || ln.list.isEmpty());
227 }
228 }
229
230 //Close stream after processing file, collect error if encountered.
231 errorState=ReadWrite.closeStreams(cris) | errorState;
232 if(verbose){outstream.println("Finished reading data.");}
233
234 //Writes output to file indicated by user.
235 outputResults(matchCounts1, totalCounts1, matchCounts2, totalCounts2);
236
237 //Stop timer after all processes have competed and before printing runtime.
238 t.stop();
239 outstream.println("Time: \t"+t);
240 outstream.println("Reads Processed: "+readsProcessed+" \t"+Tools.format("%.2fk reads/sec", (readsProcessed/(double)(t.elapsed))*1000000));
241 outstream.println("Bases Processed: "+basesProcessed+" \t"+Tools.format("%.2fk bases/sec", (basesProcessed/(double)(t.elapsed))*1000000));
242
243 //If an error statement was encountered, report this and crash program (exit with 1, not 0).
244 assert(!errorState) : "An error was encountered.";
245 }
246
247 /*--------------------------------------------------------------*/
248 /*---------------- Inner Methods Fields ----------------*/
249 /*--------------------------------------------------------------*/
250
251 /**
252 * This function converts the list of counts for kmers found at each position in both read sets and
253 * the positions that have reads of length reaching that position, to arrays.
254 * The statistics of the analyses are written to the output file.
255 *
256 * @param posCounts1 list of length of the reads, tracking the number of kmers found beginning at each position for readset 1.
257 * @param readCounts1 list of max length of the reads, tracking the number of reads with nucleotides at that position for readset 1.
258 * @param posCounts2 Same for readset 2.
259 * @param readCounts2 Same for readset 2.
260 */
261 private void outputResults(LongList posCounts1, LongList readCounts1, LongList posCounts2, LongList readCounts2){
262 //Makes sure a valid output file name exists.
263 if(ffout1==null) {return;}
264
265 //Begins output writer method.
266 ByteStreamWriter bsw=new ByteStreamWriter(ffout1);
267 bsw.start();
268
269 //Converts count lists to arrays for indexing.
270 long[] readArray1 = readCounts1.toArray();
271 long[] countArray1 = posCounts1.toArray();
272 long[] readArray2 = readCounts2.toArray();
273 long[] countArray2 = posCounts2.toArray();
274
275 //Writes the header line to the output file.
276 bsw.println("#pos\tread1_count\tread1_perc\tread2_count\tread2_perc");
277
278 //Finds the maximum of both read set lengths.
279 //This handles if one read set is longer than the other.
280 //Its important to use the longer length to avoid iterating out of bounds.
281 int maxLen = Tools.max(readArray1.length, readArray2.length);
282
283 //Iterate to the length of the longest read (if the value exists, otherwise report 0) and
284 //write counts to output file.
285 for(int i=0; i<maxLen; i++) {
286
287 //Write to file the position in reads
288 bsw.print(i);
289 bsw.print('\t');
290
291 //Write to file the number of kmers found at position i.
292 bsw.print(countArray1.length>i ? countArray1[i] : 0);
293 bsw.print('\t');
294
295 //Write to file the percentage of reads with a kmer at this particular position.
296 bsw.print(countArray1.length>i ? (countArray1[i] / (float) readArray1[i]) * 100 : 0, 3);
297 bsw.print('\t');
298
299 //Same statistics as above for the read 2 counts.
300 bsw.print(countArray2.length>i ? countArray2[i] : 0);
301 bsw.print('\t');
302
303 //Same percentage statistic as above for read 2 kmers at this position.
304 bsw.print(countArray2.length>i ? (countArray2[i] / (float) readArray2[i]) * 100 : 0, 3);
305 bsw.println();
306 }
307
308 //Stop the output stream by telling separate thread no more data is incoming
309 //but to finish writing already passed data.
310 errorState=bsw.poisonAndWait() | errorState;
311 }
312
313 /**
314 * This method produces a LongHashSet containing all forward kmers of length k found in the reference file
315 * reference kmers are converted to bytes for faster, memory efficient comparison to read kmers
316 *
317 * @return A set of reference kmers
318 */
319 private LongHashSet loadReference(){
320 //Initialize empty LongHashSet to accept reference kmers.
321 LongHashSet hs=new LongHashSet();
322
323 //Get the reference sequences from the ref file.
324 ArrayList<Read> readArray=ConcurrentReadInputStream.getReads(maxReads, false, ffref, null, null, null);
325
326 //iterate over sequences pulled from reference file,
327 //and pass the sequence to the byte conversion method
328 for(Read r : readArray) {
329 addToSet(hs, r);
330 }
331
332 return hs;
333 }
334
335 /**
336 * This method separates the reference sequence into kmers before converting each kmer to bytes
337 * The converted kmers are added to the hashset and returned to the main method for final comparison
338 *
339 * @param hs hashset that will hold the kmers after conversion to bytes
340 * @param r the reference sequence
341 * @return Number of kmers added to hashset
342 */
343 private int addToSet(LongHashSet hs, Read r) {
344 int proccessedKmers=0;
345 //This is the old string-based code. Useful for comparisons to the new code below.
346 /*for(int i=0, j=k; j<=r.length(); i++, j++) {
347 //String(byte[] bytes, int offset, int length)
348 String s=new String(r.bases, i, k);
349 hs.add(s);
350 countRead++;
351 }*/
352
353 //Convert kmer sequences to 2-bit notation, shifting each kmer by one nucleotide
354 final int shift=2*k;
355
356 //Make mask of 1's for the last k*2 bits
357 final long mask=(shift>63 ? -1L : ~((-1L)<<shift));
358 if(verbose) {System.out.println(Long.toBinaryString(mask));}
359
360 //number of consecutive, valid (non-degenerate) bases
361 int len=0;
362
363 //access read objects bases
364 byte[] bases=r.bases;
365
366 //binary representation of current kmer
367 long kmer=0;
368
369 //iterate over bases in read
370 for(int i=0; i<bases.length; i++){
371 byte b=bases[i];
372
373 //Fast nucleotide conversion from letter to 2-bit encoding
374 long x=AminoAcid.baseToNumber[b];
375
376 //Shift kmer to left, dropping oldest base, OR in new base on right
377 kmer=((kmer<<2)|x)&mask;
378
379
380 //ACGTTNTGCGC
381
382 //This section handles creating kmers without degenerate bases at any position
383 //Check new base is not degenerate (-1) and increment length of kmer
384 if(x>=0){
385 len++;
386 }else{
387 //If base is degenerate (-1), restart kmer construction by setting length to 0
388 len=0;
389 kmer=0;
390 }
391
392 //Once kmer reaches length k, add kmer to hashset and increment number of processed kmers
393 if(len>=k){
394 hs.add(kmer);
395 if(rcomp){hs.add(AminoAcid.reverseComplementBinaryFast(kmer, k));}
396 proccessedKmers++;
397 }
398 }
399
400 return proccessedKmers;
401 }
402
403 /**
404 * This method performs byte shifting to perform very fast comparison of kmers from the reads and
405 * compares read kmers to reference kmers. If identical byte-kmers are found, increment the appropriate counts.
406 * Also, increment the count if a valid nucleotide is at that position in the read.
407 *
408 * @param r read sequence
409 * @param hs set of kmer sequences from the reference
410 * @param matchCounts list of counts of the number of kmers found starting at each position
411 * @param totalCounts list of counts of reads with nucleotides at each position
412 */
413 private void processRead(Read r, LongHashSet hs, LongList matchCounts, LongList totalCounts) {
414
415 //This is the old string-based code. Do not uncomment. Useful for comparison.
416 /*for(int i=0, j=k; j<=r.length(); i++, j++) {
417 //String(byte[] bytes, int offset, int length)
418
419 //int x=5;
420 String s=new String(r.bases, i, k);
421 totalCounts.increment(i);
422 if(hs.contains(s)) {
423 matchCounts.increment(i);
424 }
425 }*/
426 //Convert kmer sequences to 2-bit notation, shifting each kmer by one nucleotide
427 final int shift=2*k;
428
429 //Make mask of 1's for the last k*2 bits
430 final long mask=(shift>63 ? -1L : ~((-1L)<<shift));
431 if(verbose) {System.out.println(Long.toBinaryString(mask));}
432
433 //number of consecutive, valid (non-degenerate) bases
434 int len=0;
435
436 //access read objects bases
437 byte[] bases=r.bases;
438
439 //binary representation of current kmer
440 long kmer=0;
441
442 //iterate over bases in read up to the length of the read
443 for(int i=0; i<bases.length; i++){
444 byte b=bases[i];
445
446 //Fast nucleotide conversion from letter to 2-bit encoding
447 long x=AminoAcid.baseToNumber[b];
448
449 //Shift kmer to left, dropping oldest base, OR in new base on right
450 kmer=((kmer<<2)|x)&mask;
451
452 //This section handles creating kmers without degenerate bases at any position
453 //Check new base is not degenerate (-1) and increment length of kmer
454 if(x>=0){
455 len++;
456 }else{
457
458 //If base is degenerate (-1), restart kmer construction by setting length to 0
459 len=0;
460 kmer=0;
461 }
462 if(len>=k){
463
464 //increment list of counts for reads containing nucleotides at each position
465 //i - k + 1 is the first base of kmer, i is last base in kmer
466 //we want start positions
467 totalCounts.increment(i - k + 1);
468
469 //if the read kmer is in the hashset of kmers from the reference,
470 //increment count of positions corresponding to the start of a kmer at that position
471 if(hs.contains(kmer)) {
472 matchCounts.increment(i - k + 1);
473 }
474 }
475 }
476
477 }
478
479
480
481 //A -> 0 -> 00
482 //C -> 1 -> 01
483 //G -> 2 -> 10
484 //T -> 3 -> 11
485 //N -> -1 -> 11111111111111111111111111111111111111111
486
487 //00110110 -> ATCG
488
489
490 //kmer=00000000
491 //Add T, 11 G A A A G A A A A
492 //left shift: kmer=kmer<<2 -> kmer=10000000<<2 -> 1000000000
493 //kmer=00000000 0011111111
494 //Or it with the new code 0000000000
495 //kmer=kmer|x -> kmer=00000000 | 11 -> 0000000011
496 //mask it with the mask:
497 //kmer=kmer&mask -> kmer=00000000 & 11111111 -> 00000011
498
499 //kmer=00000011
500 //Add C, 01
501 //left shift : -> 00001100
502 //Or it with the new code: A A T C
503 //kmer=kmer|x -> kmer=00001100 | 01 -> 00001101
504 //mask (does nothing)
505
506 // kmer= TATC = 11001101
507 //Add G, 10
508 // left-shift: 1100110100 (TATCA)
509 //Or with the new code: kmer=1100110100 | 10 = 1100110110 = TATCG
510 //Mask with 11111111 (TTTT): 1100110110
511 // 11111111
512 //yields 00110110 = ATCG
513
514 /*--------------------------------------------------------------*/
515 /*---------------- Fields ----------------*/
516 /*--------------------------------------------------------------*/
517
518 /**Primary input file for high-throughput read sequences.*/
519 private String in1=null;
520
521 /**Paired-end read input file. Only use if this file contains the mates of in1.*/
522 private String in2=null;
523
524 /**Output file name. This file will contain all output statistics of kmer positioning and counts.*/
525 private String out1=null;
526
527 /**Reference sequence file. This file should be .fasta format and
528 * contain reference sequences you wish to be identified in the read files. */
529 private String ref=null;
530
531 /**File format structure FileFormat for in1.
532 * This is used to parse the input file type if possible and provide methods.*/
533 private final FileFormat ffin1;
534
535 /**File format structure FileFormat for in2.
536 * This is used to parse the input file type if possible and provide methods.*/
537 private final FileFormat ffin2;
538
539 /**File format structure FileFormat for out1. This provides methods and structure to the output.*/
540 private final FileFormat ffout1;
541
542 /**File format structure of ref.
543 * This provides methods and structure for the reference file assuming its in FASTA format.*/
544 private final FileFormat ffref;
545
546 /*--------------------------------------------------------------*/
547
548 /**Variable for the number of reads to analyze. If set to -1, all reads will be used. */
549 private long maxReads=-1;
550
551 /**Boolean variable that changes to true if an error has occurred.
552 * This will cause the program to exit with 1 status. */
553 private boolean errorState=false;
554
555 /** Add reverse-complemented kmers to the hashset */
556 private boolean rcomp=true;
557
558 /**Variable for kmer length. Can be changed on the commandline with the k=# flag.*/
559 private int k=19;
560
561 /**List of long containing counts of kmers starting at each nucleotide in a read for read set 1. */
562 private LongList matchCounts1=new LongList();
563
564 /**List of Long containing counts of reads that have nucleotides at a each position for read set 1. */
565 private LongList totalCounts1=new LongList();
566
567 /**List of Long containing counts of kmers starting at each nucleotide in a read for read set 2. */
568 private LongList matchCounts2=new LongList();
569
570 /**List of Long containing counts of reads that have nucleotides at a each position for read set 2. */
571 private LongList totalCounts2=new LongList();
572
573 /*--------------------------------------------------------------*/
574
575 /**Output stream that output statistics are piped through to the output file. */
576 private java.io.PrintStream outstream=System.err;
577
578 /**Verbose commandline flag variable. If set to true, will print additional program information. */
579 public static boolean verbose=false;
580
581 }