File: StandardDeviator.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 (453 lines) | stat: -rwxr-xr-x 13,963 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
package structures;

import java.util.ArrayList;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

import dna.Scaffold;
import shared.Timer;
import shared.Tools;
import template.Accumulator;
import template.ThreadWaiter;

public class StandardDeviator implements Accumulator<StandardDeviator.ProcessThread> {

	public StandardDeviator(boolean stranded_, int strand_) {
		stranded=stranded_;
		strand=strand_;
	}
	
	//This one is to slow, maybe because short contigs need too much locking.
	//They would have to be put into lists of contigs.
//	public boolean calculateStuffQueued(int threads0, Collection<Scaffold> scaffolds, 
//			boolean calcStd, boolean calcMedian, double windowAvg, int window) {
//
//		final int threads=Tools.mid(1, threads0, scaffolds.size());
//		Timer t=new Timer();
//		
//		System.err.println("threads="+threads);
//		
//		{//First pass to sum depth
//			totalSum=0;
//			bins=0;
//			ArrayBlockingQueue<Scaffold> queue=new ArrayBlockingQueue<Scaffold>(threads*2);
//			//Fill a list with ProcessThreads
//			ArrayList<ProcessThread> alpt=new ArrayList<ProcessThread>(threads);
//			for(int i=0; i<threads; i++){
//				alpt.add(new ProcessThread(i, queue, false, false, -1, -1, -1));
//			}//TODO: For some reason this is running singlethreaded... 97% CPU.
//			//Start the threads and wait for them to finish
//			ThreadWaiter.startThreads(alpt);
//			for(Scaffold s : scaffolds) {addToQueue(queue, s);}
//			addToQueue(queue, POISON);
//			boolean success=ThreadWaiter.waitForThreads(alpt, this);
//			errorState&=!success;
//			t.stopAndStart("calcSumMT:");
//		}
//		
//		final double globalMean=totalSum/(double)bins;
//		{//Second pass for statistics
//			totalSum=0;
//			bins=0;
//			ArrayBlockingQueue<Scaffold> queue=new ArrayBlockingQueue<Scaffold>(threads*2);
//			//Fill a list with ProcessThreads
//			ArrayList<ProcessThread> alpt=new ArrayList<ProcessThread>(threads);
//			for(int i=0; i<threads; i++){
//				alpt.add(new ProcessThread(i, queue, calcStd, calcMedian, globalMean, windowAvg, window));
//			}//This part only uses 150% CPU
//			//Start the threads and wait for them to finish
//			ThreadWaiter.startThreads(alpt);
//			for(Scaffold s : scaffolds) {addToQueue(queue, s);}
//			addToQueue(queue, POISON);
//			boolean success=ThreadWaiter.waitForThreads(alpt, this);
//			errorState&=!success;
//			t.stopAndStart("calcStdMT:");
//		}
//		
//		return errorState;
//	}
	
	public boolean calculateStuff(int threads0, ArrayList<Scaffold> scaffolds, 
			boolean calcStd, boolean calcMedian, boolean calcHist, 
			int minDepth, int histMax, double windowAvg, int window) {

		final int threads=Tools.mid(1, threads0, scaffolds.size());
		Timer t=new Timer();
		
//		if(verbose) {System.err.println("threads="+threads);}
		
		{//First pass to sum depth for global stdev
			totalSum=0;
			bins=0;
			//Fill a list with ProcessThreads
			ArrayList<ProcessThread> alpt=new ArrayList<ProcessThread>(threads);
			for(int i=0; i<threads; i++){
				alpt.add(new ProcessThread(i, threads, scaffolds, false, false, false, minDepth, -1, -1, -1, -1));
			}
			//Start the threads and wait for them to finish
			ThreadWaiter.startThreads(alpt);
			boolean success=ThreadWaiter.waitForThreadsToFinish(alpt, this);
			errorState&=!success;
			if(verbose) {t.stopAndStart("calcSumMT:");}
		}
		
		final double globalMean=totalSum/(double)bins;
		{//Second pass for statistics
			totalSum=0;
			bins=0;
			//Fill a list with ProcessThreads
			ArrayList<ProcessThread> alpt=new ArrayList<ProcessThread>(threads);
			for(int i=0; i<threads; i++){
				alpt.add(new ProcessThread(i, threads, scaffolds,
						calcStd, calcMedian, calcHist, minDepth, histMax, globalMean, windowAvg, window));
			}
			//Start the threads and wait for them to finish
			ThreadWaiter.startThreads(alpt);
			boolean success=ThreadWaiter.waitForThreadsToFinish(alpt, this);
			errorState&=!success;
			if(verbose) {t.stopAndStart("calcStdMT:");}
		}
		
		return errorState;
	}

	public double[] standardDeviation(ArrayList<Scaffold> scaffolds, int minscaf0){
		totalSum=bins=0;
		mean=stdev=0;
		long scafsCounted=0;
		final int minscaf=Tools.max(minscaf0, 1);
		
		for(Scaffold scaf : scaffolds){
			if(scaf.length>=minscaf){
				final CoverageArray ca=(CoverageArray)(strand==1 ? scaf.obj1 : scaf.obj0);
				bins+=scaf.length;
				totalSum+=(ca==null ? 0 : ca.sum());
				scafsCounted++;
			}
		}
		
		if(bins<1){return new double[] {mean, stdev};}
		mean=totalSum/(double)bins;
//		System.err.println("sum="+totalSum+", bins="+bins+", mean="+mean+", scaffolds="+scafsCounted);
		double sumdev2=0;
		for(Scaffold scaf : scaffolds){
			if(scaf.length>=minscaf){
				final CoverageArray ca=(CoverageArray)(strand==1 ? scaf.obj1 : scaf.obj0);
				if(ca==null) {
					sumdev2+=(mean*mean*scaf.length);
				}else {
					sumdev2+=ca.devSum(mean);
				}
			}
		}

		stdev=Math.sqrt(sumdev2/bins);
//		System.err.println("sumdev2="+sumdev2+", stdev="+stdev);
		return new double[] {mean, stdev};
	}

	/** This works but is slow.  Just use unbinned std. */
	@Deprecated
	public double[] standardDeviationBinned(ArrayList<Scaffold> scaffolds, int binsize, int minscaf0){
		totalSumBinned=binsBinned=0;
		meanBinned=stdevBinned=0;
		final int minscaf=Tools.max(minscaf0, 1);
		
		for(Scaffold scaf : scaffolds){
			if(scaf.length>=minscaf){
				CoverageArray ca=(CoverageArray)(strand==1 ? scaf.obj1 : scaf.obj0);
				int bins=(int)((scaf.length+(long)binsize-1L)/binsize);
				assert(bins>0) : scaf.length+", "+binsize+", "+minscaf;
				binsBinned+=bins;
				if(ca==null) {
					totalSumBinned+=0;
				}else {
					totalSumBinned+=ca.sum()/bins;
				}
			}
		}
		
		if(binsBinned<1){return new double[] {meanBinned, stdevBinned};}
		meanBinned=totalSumBinned/(double)binsBinned;
		double sumdev2=0;
		
		for(Scaffold scaf : scaffolds){
			if(scaf.length>=minscaf){
				CoverageArray ca=(CoverageArray)(strand==1 ? scaf.obj1 : scaf.obj0);
				int lastPos=-1, nextPos=binsize-1;
				long tempSum=0;
				final int lim=scaf.length-1;
				for(int i=0; i<scaf.length; i++){
					int x=(ca==null ? 0 : ca.get(i));
					tempSum+=x;
					if(i>=nextPos || i==lim){
						int bin=(i-lastPos);
						double depth=(tempSum/(double)bin);
						double dev=meanBinned-depth;
						sumdev2+=(dev*dev);
						nextPos+=binsize;
						lastPos=i;
						tempSum=0;
					}
				}
			}
		}
		
		stdevBinned=Math.sqrt(sumdev2/binsBinned);
		return new double[] {meanBinned, stdevBinned};
	}

	//Unsafe because it will fail if there are over 2 billion bins
	public double[] standardDeviationBinnedUnsafe(String fname, ArrayList<Scaffold> scaffolds, int binsize, int minscaf0){
		final int minscaf=Tools.max(minscaf0, 1);
		
		LongList list=new LongList();
		for(Scaffold scaf : scaffolds){
			CoverageArray ca=(CoverageArray)(strand==1 ? scaf.obj1 : scaf.obj0);
			int lastPos=-1, nextPos=binsize-1;
			long sum=0;
			final int lim=scaf.length-1;
			for(int i=0; i<scaf.length; i++){
				int x=(ca==null ? 0 : ca.get(i));
				sum+=x;
				if(i>=nextPos || i==lim){
					int bin=(i-lastPos);
					if(scaf.length>=minscaf){
						list.add((int)(10*(sum/(double)bin)));
					}
					nextPos+=binsize;
					lastPos=i;
					sum=0;
				}
			}
		}
		list.sort();
		
		mean=0.1*list.mean();
		double median=0.1*list.median();
		double mode=0.1*list.mode();
		stdev=0.1*list.stdev();
		return new double[] {mean, median, mode, stdev};
	}
	
	/*--------------------------------------------------------------*/
	/*----------------          Threading           ----------------*/
	/*--------------------------------------------------------------*/
	
//	static class ProcessThreadQueued extends Thread {
//		
//		ProcessThreadQueued(int tid_, ArrayBlockingQueue<Scaffold> queue_, boolean calcStd_, 
//				boolean calcMedian_, double globalMean_, double windowAvg_, int window_){
//			tid=tid_;
//			queue=queue_;
//			
//			calcStd=calcStd_;
//			calcMedian=calcMedian_;
//			globalMean=globalMean_;
//			windowAvg=windowAvg_;
//			window=window_;
//		}
//		
//		@Override
//		public void run() {
////			synchronized(this) {
//				for(Scaffold next=getNext(queue); next!=POISON; next=getNext(queue)){
////					synchronized(next) {
//						binsT+=next.length;
//						processCA((CoverageArray)next.obj1);
//						processCA((CoverageArray)next.obj2);
////					}
//				}
//				addToQueue(queue, POISON);//Send it to the next one
////			}
//		}
//		
//		private void processCA(CoverageArray ca) {
//			if(ca==null) {return;}
//			totalSumT+=ca.sum();
//			if(calcStd) {ca.standardDeviation();}
//			if(calcMedian) {ca.median();}
//			if(globalMean>-1) {ca.devSum(globalMean);}
//			if(windowAvg>0) {ca.basesUnderAverageCoverage(windowAvg, window);}
//		}
//		
//		long totalSumT=0;
//		long binsT=0;
//		
//		final int tid;
//		final ArrayBlockingQueue<Scaffold> queue;
//		
//		final boolean calcStd;
//		final boolean calcMedian;
//		final double globalMean;
//		final double windowAvg;
//		final int window;
//	}
	
	class ProcessThread extends Thread {
		
		ProcessThread(int tid_, int threads_, ArrayList<Scaffold> list_, 
				boolean calcStd_, boolean calcMedian_, boolean calcHist_, int minDepth_, int histMax_, 
				double globalMean_, double windowAvg_, int window_){
//			System.err.println(calcHist_);
			tid=tid_;
			threads=threads_;
			list=list_;
			
			calcStd=calcStd_;
			calcMedian=calcMedian_;
			calcHist=calcHist_;
			minDepth=minDepth_;
			histMax=histMax_;
			globalMean=globalMean_;
			windowAvg=windowAvg_;
			window=window_;
			if(calcHist) {
				assert(histMax>0) : histMax;
				hist0=new LongList(Tools.min(histMax+1, Character.MAX_VALUE+1));
				if(stranded) {hist1=new LongList(Tools.min(histMax+1, Character.MAX_VALUE+1));}
			}
		}
		
		@Override
		public synchronized void run() {
			for(int i=tid; i<list.size(); i+=threads){
				Scaffold scaf=list.get(i);
				synchronized(scaf) {
					binsT+=scaf.length;
					processCA((CoverageArray)scaf.obj0, 0, scaf.length, scaf.basehits);
					if(stranded) {processCA((CoverageArray)scaf.obj1, 1, scaf.length, scaf.basehits);}
				}
			}
		}
		
		/** In the case of preallocated ca's with 0 mapped reads, this goes faster */
		private void processCA(CoverageArray ca, int strand, int length, long mappedBases) {
			if(mappedBases>0) {
				if(calcHist) {addToHist(ca, strand, length);}
				if(ca==null) {return;}
				totalSumT+=ca.calcSumAndCovered(minDepth);
				if(calcStd) {ca.standardDeviation();}
				if(calcMedian) {ca.median();}
				if(globalMean>-1) {ca.devSum(globalMean);}
				if(windowAvg>0) {ca.basesUnderAverageCoverage(windowAvg, window);}
			}else {
				if(calcHist) {addToHist(null, strand, length);}
				if(ca==null) {return;}
				totalSumT+=0;
				ca.setSum(0);
				ca.setCovered(0);
				ca.setStdev(0);
				ca.setMedian(0);
				ca.setDevSum(mappedBases);
				if(globalMean>-1) {ca.setDevSum((globalMean*globalMean)*length);}
				if(windowAvg>0) {ca.setUnderWindowAverage(length);}
			}
		}
		
		private void addToHist(CoverageArray ca, int strand, int length) {
			LongList hist=(strand==0 ? hist0 : hist1);
			assert(hist!=null) : stranded+", "+strand+", "+length;
			if(ca==null) {
				hist.increment(0, length);
				return;
			}
			assert(ca.length()==length) : ca.length()+", "+length+", "+ca.maxIndex;
			for(int i=0, len=ca.length(); i<len; i++) {
				int d=Tools.min(ca.get(i), histMax);
				hist.increment(d);
			}
		}
		
		long totalSumT=0;
		long binsT=0;
		
		final int tid;
		final int threads;
		final ArrayList<Scaffold> list;
		LongList hist0;
		LongList hist1;
		
		final boolean calcStd;
		final boolean calcMedian;
		final boolean calcHist;
		final int minDepth;
		final int histMax;
		final double globalMean;
		final double windowAvg;
		final int window;
	}
	
	private static Scaffold getNext(ArrayBlockingQueue<Scaffold> queue) {
		Scaffold next=null;
		while(next==null) {
			try {
				next=queue.take();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return next;
	}
	
	private static void addToQueue(ArrayBlockingQueue<Scaffold> queue, Scaffold s) {
		while(s!=null) {
			try {
				queue.put(s);
				s=null;
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	@Override
	public void accumulate(ProcessThread t) {
		synchronized(t) {
			totalSum+=t.totalSumT;
			bins+=t.binsT;
			if(hist0==null) {hist0=t.hist0;}
			else if(t.hist0!=null) {hist0.incrementBy(t.hist0);}
			if(hist1==null) {hist1=t.hist1;}
			else if(t.hist1!=null) {hist1.incrementBy(t.hist1);}
		}
	}

	@Override
	public boolean success() {
		// TODO Auto-generated method stub
		return false;
	}
	
	/*--------------------------------------------------------------*/
	/*----------------            Fields            ----------------*/
	/*--------------------------------------------------------------*/
	
	long totalSum;
	long bins;
	double mean;
	double stdev;
	
	long totalSumBinned;
	long binsBinned;
	double meanBinned;
	double stdevBinned;

	public LongList hist0;
	public LongList hist1;
	
	@Override
	public final ReadWriteLock rwlock() {return rwlock;}
	private final ReadWriteLock rwlock=new ReentrantReadWriteLock();

	public final int strand;
	public final boolean stranded;
	public boolean errorState=false;
	
	private static final Scaffold POISON=new Scaffold("POISON", null, -1);
	public static boolean verbose=false;
	
}