File: ClumpList.java

package info (click to toggle)
bbmap 39.20%2Bdfsg-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 26,024 kB
  • sloc: java: 312,743; sh: 18,099; python: 5,247; ansic: 2,074; perl: 96; makefile: 39; xml: 38
file content (468 lines) | stat: -rwxr-xr-x 12,492 bytes parent folder | download | duplicates (2)
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
package clump;

import java.io.PrintStream;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.Map.Entry;
import java.util.concurrent.atomic.AtomicInteger;

import dna.AminoAcid;
import shared.Shared;
import shared.Tools;
import stream.Read;
import structures.LongM;

/**
 * A list of clumps, meaning a list of lists of reads.
 * Allows adding reads by streaming and generating new clumps as needed.
 * The input reads must be correctly ordered.
 * @author Brian Bushnell
 * @date Nov 9, 2015
 *
 */
public class ClumpList extends ArrayList<Clump> {

	public ClumpList(int k_){
		this(null, k_, false);
	}
	
	//TODO: Add flag to remove duplicates, and remove optical duplicates
	public ClumpList(ArrayList<Read> list, int k_, boolean makeSimpleConsensus_){
		k=k_;
		makeSimpleConsensus=makeSimpleConsensus_;
		if(list!=null){addReads(list);}
//		Shared.sort(this);//Does nothing since reads are already sorted by kmer.
	}
	
	public void addReads(ArrayList<Read> list){
		assert(list.getClass()!=Clump.class) : list.getClass();
		if(list.size()<100000 || Shared.threads()<2){addReadsST(list);}
		else{addReadsMT(list);}
		
//		System.err.println(addedR+", "+addedC+", "+list.size());
	}
	
	public void reorderPaired(){//More efficient but requires unpair and repair, and paired reads.
		ArrayList<Clump> temp=new ArrayList<Clump>(size());
		for(Clump c : this){
			if(!c.added){
				temp.add(c);
				c.added=true;
				addFriends(c, temp, 0);
			}
		}
		assert(temp.size()==size());
		super.clear();
		this.addAll(temp);
	}
	
	private void addFriends(Clump c, ArrayList<Clump> temp, int depth){
		LinkedList<Clump> q=(depth<100 ? new LinkedList<Clump>() : null);
		for(Read r : c){
			Read r2=r.mate;
			if(r2!=null){
				ReadKey rk=(ReadKey)r2.obj;
				Clump c2=rk.clump;
				if(!c2.added){
					temp.add(c2);
					c2.added=true;
					if(q!=null){
						q.addFirst(c2);
//						addFriends(c2, temp, depth+1);//Not as good.
					}
				}
			}
		}
		while(q!=null && !q.isEmpty()){
			addFriends(q.pollLast(), temp, depth+1);
		}
	}
	
	public void reorder(){//Less efficient but works with unpaired reads
		ArrayList<Clump> temp=new ArrayList<Clump>(size());
//		temp.addAll(this);
		LinkedHashMap<LongM, ArrayList<Clump>> map=map();
		LinkedList<Clump> q=new LinkedList<Clump>();
		
		final LongM key=new LongM();
		for(Entry<LongM, ArrayList<Clump>> e : map.entrySet()){
			ArrayList<Clump> list=e.getValue();
			if(list.size()>1){
				Clump c0=list.get(0);
				if(!c0.added){
					temp.add(c0);
					c0.added=true;
				}
				for(int i=1; i<list.size(); i++){
					Clump c=list.get(i);
					if(!c.added){
						q.addFirst(c);
						c.added=true;
					}
				}
				while(!q.isEmpty()){
					Clump c=q.pollLast();
					temp.add(c);
					key.set(c.kmer);
					ArrayList<Clump> list2=map.get(key);
					if(list2.size()>1){
						for(int i=1; i<list2.size(); i++){
							Clump c2=list2.get(i);
							if(!c2.added){
								c2.added=true;
								q.addFirst(c2);
							}
						}
					}
				}
			}
		}
		for(Clump c : this){
			if(!c.added){
				c.added=true;
				temp.add(c);
			}
		}
		assert(temp.size()==size()) : temp.size()+", "+this.size();
		this.clear();
		this.addAll(temp);
	}
	
	public void addReadsMT(ArrayList<Read> list){
		int threads=Tools.mid(2, Shared.threads()/2, 16);
//		assert(false) : threads;
		final ArrayList<ClumpThread> alct=new ArrayList<ClumpThread>(threads);
		int incr=((list.size()+threads-1)/threads);
		if(incr*threads<list.size()-1){incr++;}
		assert(threads*incr>=list.size()) : threads+", "+incr+", "+list.size();
		for(int i=0; i<threads; i++){
			alct.add(new ClumpThread(list, i*incr, (i+1)*incr, k, makeSimpleConsensus));
		}
		
		if(verbose){outstream.println("Starting clump threads.");}
		for(ClumpThread ct : alct){ct.start();}
		
		if(verbose){outstream.println("Waiting for threads.");}
		/* Wait for threads to die */
		for(ClumpThread ct : alct){
			
			/* Wait for a thread to die */
			while(ct.getState()!=Thread.State.TERMINATED){
				try {
					ct.join();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			addAll(ct.storage);
			cAdded+=ct.cAddedT;
			rAdded+=ct.rAddedT;
		}
		assert(list.size()==rAdded) : list.size()+"!="+rAdded;
//		for(int i=0; i<list.size(); i++){assert(list.get(i).doscarded()) : i;}
	}
	
//	long addedR=0, addedC=0;
//
//	@Override
//	public boolean add(Clump c){
//		assert(c!=null && c.size()>0);
//		synchronized(this){
//			addedR+=c.size();
//			addedC++;
//		}
//		return super.add(c);
//	}
//
//	@Override
//	public boolean addAll(Collection<? extends Clump> cc){
//		for(Clump c : cc){add(c);}
//		return true;
//	}
	
	public void addReadsST(ArrayList<Read> list){
		Clump currentClump=null;
		long currentKmer=-1;
		for(final Read r : list){
			final ReadKey key=(ReadKey)r.obj;
			if(key.kmer!=currentKmer){
				if(currentClump!=null){
					if(makeSimpleConsensus){
						currentClump.consensusRead();
						currentClump.clearCounts();
					}
					add(currentClump);
				}
				currentKmer=key.kmer;
				currentClump=Clump.makeClump(key.kmer);
			}
			currentClump.add(r);
//			assert(!r.doscarded());
//			r.setDoscarded(true);
//			assert(r.doscarded());
		}
		if(currentClump!=null && !currentClump.isEmpty()){
			if(makeSimpleConsensus){
				currentClump.consensusRead();
				currentClump.clearCounts();
			}
			add(currentClump);
		}
//		for(int i=0; i<list.size(); i++){assert(list.get(i).doscarded()) : i;}
	}
	
	public ArrayList<Read> process(final int threads, final int mode, final long[] rvector){
		final ArrayList<ProcessThread> alct=new ArrayList<ProcessThread>(threads);
		for(int i=0; i<threads; i++){alct.add(new ProcessThread(mode));}
		
		if(verbose){outstream.println("Starting condense/correction threads.");}
		for(ProcessThread ct : alct){ct.start();}
		
		if(verbose){outstream.println("Waiting for threads.");}
		long readsThisPass=0;
		long corrections=0;
		long duplicates=0;
		/* Wait for threads to die */
		for(ProcessThread ct : alct){
			
			/* Wait for a thread to die */
			while(ct.getState()!=Thread.State.TERMINATED){
				try {
					ct.join();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			readsThisPass+=ct.storage.size();
			corrections+=ct.corrections;
			duplicates+=ct.duplicates;
		}
		
		if(verbose){outstream.println("Gathering reads.");}
		ArrayList<Read> list=new ArrayList<Read>((int)readsThisPass);
		for(int i=0; i<threads; i++){
			ProcessThread ct=alct.set(i, null);
			list.addAll(ct.storage);
		}

		rvector[0]+=corrections;
		rvector[1]+=duplicates;
//		assert(false) : duplicates+", "+Arrays.toString(rvector);
		assert(list.size()==readsThisPass);
		return list;
	}
	
	@Override
	public void clear(){
		super.clear();
		ptr.set(0);
		map=null;
	}
	
	public LinkedHashMap<LongM, ArrayList<Clump>> map(){
		LinkedHashMap<LongM, ArrayList<Clump>> temp=map;
		if(temp==null){
			synchronized(this){
				if(map==null){
					temp=makeMap();
				}
				assert(map==null);
				map=temp;
			}
		}
		return map;
	}
	
	private synchronized LinkedHashMap<LongM, ArrayList<Clump>> makeMap(){
		assert(this.map==null);
		LinkedHashMap<LongM, ArrayList<Clump>> map=new LinkedHashMap<LongM, ArrayList<Clump>>(this.size());
		for(Clump c : this){
			ArrayList<Clump> list=new ArrayList<Clump>(4);
			list.add(c);
			map.put(new LongM(c.kmer), list);
		}
		fillMap(map);
		assert(this.map==null);
		return map;
	}
	
	private void fillMap(LinkedHashMap<LongM, ArrayList<Clump>> map){
		final int shift=2*k;
		final int shift2=shift-2;
		final long mask=(shift>63 ? -1L : ~((-1L)<<shift));
		final LongM key=new LongM();
		
		for(Clump c : this){
			Read r=c.consensusRead();
			byte[] bases=r.bases;
			long kmer=0, rkmer=0;
			int len=0;
			for(int i=0; i<bases.length; i++){
				byte b=bases[i];
				long x=AminoAcid.baseToNumber[b];
				long x2=AminoAcid.baseToComplementNumber[b];
				kmer=((kmer<<2)|x)&mask;
				rkmer=((rkmer>>>2)|(x2<<shift2))&mask;

				if(x<0){
					len=0;
					kmer=rkmer=0;
				}else{len++;}

				if(len>=k){
					final long kmax=Tools.max(kmer, rkmer);
					key.set(kmax);
					if(kmax!=c.kmer){
						//This assertion should be fine, but it fails on nt.
//						assert(kmer!=c.kmer && rkmer!=c.kmer) : kmax+", "+kmer+", "+rkmer+", "+c.kmer+", "+r.length()+", "+(r.length()<10000 ? r.toString() : "");
					}
					ArrayList<Clump> list=map.get(key);
					if(list!=null && !list.contains(c)){list.add(c);}
				}
			}
		}
	}
	
	private class ProcessThread extends Thread{
		
		public ProcessThread(int mode_){
			mode=mode_;
		}
		
		@Override
		public void run(){
			final int size=size();
			for(int i=ptr.getAndIncrement(); i<size; i=ptr.getAndIncrement()){
				Clump c=get(i);
				if(mode==CONDENSE){
					ArrayList<Read> list=c.makeConsensus();
					storage.addAll(list);
				}else if(mode==CORRECT){
					corrections+=c.splitAndErrorCorrect();
					if(UNRCOMP){
						for(Read r : c){
							if(r.swapped()){
								ReadKey key=(ReadKey)r.obj;
								key.flip(r, k);
//								r.reverseComplement();
//								r.setSwapped(false);
//								key.position=r.length()-key.position+k-2;
							}
						}
					}
					storage.addAll(c);
				}else if(mode==DEDUPE){
					duplicates+=c.removeDuplicates();
					storage.addAll(c);
				}else{
					throw new RuntimeException("Unknown mode "+mode);
				}
				c.clear();
				set(i, null);
			}
		}
		
		public long corrections=0;
		public long duplicates=0;
		ArrayList<Read> storage=new ArrayList<Read>();
		private final int mode;
	}
	
	private static class ClumpThread extends Thread {
		
		public ClumpThread(ArrayList<Read> input_, int startIndex_, int stopIndex_, int k, boolean makeSimpleConsensus_){
			input=input_;
			startIndex=startIndex_;
			stopIndex=Tools.min(input.size(), stopIndex_);
//			outstream.println("Processing "+startIndex_+"-"+stopIndex_);
			storage=new ClumpList(k);
			makeSimpleConsensusT=makeSimpleConsensus_;
		}
		
		@Override
		public void run(){
			if(startIndex>=input.size()){return;}
			int i=startIndex;

			long currentKmer=-1;
			if(startIndex>0){
				Read r=input.get(i-1);
				final ReadKey key=(ReadKey)r.obj;
				currentKmer=key.kmer;
			}
			while(i<stopIndex){
				Read r=input.get(i);
				final ReadKey key=(ReadKey)r.obj;
				if(key.kmer!=currentKmer){
					if(currentClump!=null){
						storage.add(currentClump);
						cAddedT++;
						rAddedT+=currentClump.size();
					}
					currentKmer=key.kmer;
					currentClump=Clump.makeClump(key.kmer);
				}
				if(currentClump!=null){
					currentClump.add(r);
//					assert(!r.doscarded()) : +i+", "+startIndex;
//					r.setDoscarded(true);
				}
//				if(i==0){assert(r.doscarded()) : currentClump;}
				i++;
			}
			while(currentClump!=null && i<input.size()){
				Read r=input.get(i);
				final ReadKey key=(ReadKey)r.obj;
				if(key.kmer!=currentKmer){
					storage.add(currentClump);
					cAddedT++;
					rAddedT+=currentClump.size();
					currentClump=null;
					break;
				}else{
					currentClump.add(r);
//					assert(!r.doscarded()) : +i+", "+startIndex;
//					r.setDoscarded(true);
				}
				i++;
			}
			if(currentClump!=null && currentClump.size()>0){
				cAddedT++;
				rAddedT+=currentClump.size();
				storage.add(currentClump);
			}
			if(makeSimpleConsensusT){
				for(Clump c : storage){
					c.consensusRead();
					c.clearCounts();
				}
			}
			currentClump=null;
		}
		
		final boolean makeSimpleConsensusT;
		final ArrayList<Read> input;
		final int startIndex;
		final int stopIndex;
		ClumpList storage;
		Clump currentClump;
		long cAddedT=0, rAddedT=0;
	}
	
	static final int CONDENSE=1, CORRECT=2, DEDUPE=3;
	
	private final boolean makeSimpleConsensus;
	long cAdded=0, rAdded=0;
	
	final int k;
	final AtomicInteger ptr=new AtomicInteger(0);
	private LinkedHashMap<LongM, ArrayList<Clump>> map;

	public static boolean UNRCOMP=true;
	private static boolean verbose=false;
	
	private static final long serialVersionUID = 1L;
	private static final PrintStream outstream=System.err;
	
}