Source

optiCall / opticall / filtering.cpp

Full commit
  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
/*
 *  filtering.cpp
 *  
 *
 *  Created by Tejas Shah on 15/11/2011.
 *  Copyright 2011 WTSI. 
 *
 */


#include <algorithm>
#include "inclusions.h"


using namespace std;
using namespace boost;
using namespace Eigen;

/*********Counting the lines in a file********/


unsigned int fileRead( istream & is, vector <char> & buff ) {
	is.read( &buff[0], buff.size() );
	return is.gcount();
}

unsigned int countLines( const vector <char> & buff, int sz ) {
	int newlines = 0;
	const char * p = &buff[0];
	for ( int i = 0; i < sz; i++ ) {
		if ( p[i] == '\n' ) {
			newlines++;
		}
	}
	return newlines;
}

unsigned int snpCount(const char * filename, bool header) {
    time_t now = time(0);
	
	//cout << "buffer\n";
	const int SZ = 1024 * 1024;
	vector <char> buff( SZ );
	ifstream ifs( filename );
	int n = 0;
	while( int cc = fileRead( ifs, buff ) ) {
		n += countLines( buff, cc );
	}
	//cout << n << endl;
    //cout << time(0) - now << endl;
	
	if (header) {
		return n - 1;
	}
	return n;
	
}



/***********************Parse a line to get the intensities***************/





vector<string> intensitiesFromLine(string line, vector < vector <string>  > &snpinfo){
	
	
	vector<string> linedata;
	linedata.reserve(6000);    // make room for 10 elements
	
	trim(line);
	
	split(linedata, line, boost::is_any_of("\t "), token_compress_on);
	
	//cout << "bits of line data " << linedata[5] << " " << linedata[linedata.size()-1] << " " << linedata.size()  << endl;
	
	//cout << linedata.size() << "\n";
	vector<string> individs(&linedata[0]+3,&linedata[0]+linedata.size());
	vector<string> snpdesc(&linedata[0],&linedata[0]+3);
	snpinfo.push_back(snpdesc);
	return individs;
	
}




/*****************Get Header Info**************/

vector<string> readHeaderInfoFromIntFile(const char * fname) {
	
	//declare a vector to hold the data
	vector<string> individualsx2;
	vector< vector<string> > junkheaderdetail;
	
	string header;
	ifstream myfile (fname);
	if (myfile.is_open())
	{
		if ( myfile.good() )
		{
			getline (myfile,header);
			//cout << line << endl;
			individualsx2 = intensitiesFromLine(header,junkheaderdetail);
		}
		myfile.close();
	}
	else cout << "Unable to open file";
	
	vector<string> individuals;
	
	for(vector< string >::iterator ind_iter = individualsx2.begin();
		ind_iter != individualsx2.end(); ++++ind_iter){
		individuals.push_back((*ind_iter).substr(0,(*ind_iter).length()-1));
	}
	
	
	/*
	 for(vector< string >::iterator ind_iter = individuals.begin();
	 ind_iter != individuals.end(); ++ind_iter){
	 cout << *ind_iter << "\n";
	 }	
	 
	 cout << individuals.size() << "\n";
	 */
	return individuals;
	
	//provide the header info
}





/*********************Read a vblock from file and return *****************/

MatrixXd readVblockFromIntFile(ifstream & myfile, int vertical_block_size, int numsamples, vector < vector <string>  > &snpinfo, int offset) {
	string line;
	//vector<vector<string>> flat_intensities
	MatrixXd vblock(vertical_block_size,(numsamples)*2); 
	vector<string> intensities;
	
	//ifstream myfile (fname);
	if (myfile.is_open())
	{
		int snpcounter = 0;
		while ( myfile.good() && snpcounter < vertical_block_size)
		{
			getline (myfile,line);
			//cout << line << endl;
			intensities = intensitiesFromLine(line,snpinfo);
			//now set the part of the matrix with the intensities
			for (int j = 0+2*offset; j < (offset+numsamples)*2; j = j+2 ) {
				
				//cout << "starting next step of loop for offset " << offset << "with counter " << snpcounter << "and j " << j << endl;
				//cout << intensities.size() << endl;
				
				//cout << vblock(snpcounter,j - 2*offset) << endl;
				
				//cout << "didn't crap out" << endl;
				
				if (intensities[j] == "NaN")
				{
					//cout << "have an NaN in the dataset" << endl;
					vblock(snpcounter,j - 2*offset) = numeric_limits<double>::quiet_NaN();
					vblock(snpcounter,j+1 - 2*offset) = numeric_limits<double>::quiet_NaN();
				}
				
				vblock(snpcounter,j - 2*offset) = atof( intensities[j].c_str() );
				vblock(snpcounter,j+1 -2*offset) = atof( intensities[j+1].c_str() );
				
				//cout << "ccounter" << snpcounter << " vblock is " << vblock(snpcounter,j - 2*offset) << " " << vblock(snpcounter,j+1 -2*offset) << endl;
				
			}
			snpcounter++;
		}
		//myfile.close();
	}
	
	//cout << "\nblock:\n" << vblock.row(2) << endl;
	return vblock;
	//MatrixXi Vblock(vertical_block_size,numsamples); 	
	
	
	//else cout << "Unable to open file";
}


/********************* Read gender file ******************************/

vector<int> readInfoFile(string fname, vector<string> allsamples, MatrixXi &samplegenders) {

	string line;
	
	vector<string> infosampleids;
	vector<int> infosamplegender;
	vector<int> infosampleexclude;
	
	ifstream myfile (fname.c_str());
	
	if (myfile.is_open())
	{
		int samplecounter = 0;
		while ( myfile.is_open()  && myfile.good() )
		{
			getline (myfile,line);
			//split the file up and save it

			
			vector<string> linedata;
			linedata.reserve(3000);    // make room for 5 elements
			trim(line);
			split(linedata, line, boost::is_any_of("\t "), token_compress_on);
			
			//cout << "gotten line " << linedata.size() << endl;
			
			if (linedata.size() < 3) 
			{
				continue;
			}
			
			//linedata[0] is the sampleid, linedata[1] is the sex, linedata[2] is the exclusion flag
			infosampleids.push_back(linedata[0]);
			infosamplegender.push_back(atoi(linedata[1].c_str()));
			infosampleexclude.push_back(atoi(linedata[2].c_str()));
			
			
		}
	}
	
	myfile.close();
	
	//cout << "gotten lines" << endl;
	
	vector<int> exclusion_indices;
			
	//then compare with the sample list
	for (int i = 0; i < allsamples.size(); i++)
	{
		samplegenders(i,0) = 0;
		for (int j = 0; j < infosampleids.size(); j++ )
		{
			if ( allsamples[i] == infosampleids[j] && infosampleexclude[j] == 1 &&  find (exclusion_indices.begin(), exclusion_indices.end(), i)  ==   exclusion_indices.end()  ) {
				exclusion_indices.push_back(i);
			}
			if ( allsamples[i] == infosampleids[j]  ) {
				samplegenders(i,0) = infosamplegender[j];
			}
		}
	}
	
	//so exclusion list has been populated
	return exclusion_indices;
	
}


/********************* Combine two lists of indices to be excluded into one *************/

vector<int> combineExclusionLists(vector<int> list1, vector<int> list2)
{	
	vector<int> outputlist = list1;
	for (int i = 0; i < list2.size() ; i++)
	{
		if (outputlist.size() == 0  ||  find (outputlist.begin(), outputlist.end(), list2[i])  ==   outputlist.end() )
		{
			outputlist.push_back(list2[i]);
		}
	}
	return outputlist;
}


/************************ returns a list of individualstobecalled i.e. individuals who have not been excluded  ***********************************/

vector<string> individualsForCalling(vector<string> individuals, vector<int> excluded)
{
	vector<string> newindlist;
	for (int i = 0; i < individuals.size() ; i++)
	{
		if (excluded.size() == 0 ||  find (excluded.begin(), excluded.end(), i)  ==   excluded.end()  )
		{
			newindlist.push_back(individuals[i]);
		}
	}
	return newindlist;
	
}




/********************* Sorting function for random numbers*******/

bool lessthanfunction (int i,int j) { return (i<j); }




/*************Find samples with mean intensities more than numsds away from the mean ******/

vector<int> findIntensityOutliers(string fname, int snpcount, vector<string> individuals,double numsds, vector<int> exclude_list) {
	
	
	
	MatrixXd sumdistances = MatrixXd::Zero(individuals.size(),1);
	MatrixXd countdistances = MatrixXd::Zero(individuals.size(),1);

	//figure out the number of individuals to get on a run through the file assuming 500MB of RAM
	int indsperrun = floor( 1000000 / (2*snpcount)  );
	int indsdone = 0;
	
	cout << "removing outliers based on mean intensity" << endl;
	

	
	while (indsdone < individuals.size())
	{
	
		ifstream intensityfile (fname.c_str());
		if (intensityfile.is_open()  && intensityfile.good())
		{
			string header;
			getline(intensityfile,header);
		}
		

		
		int numsamples = min( (int) indsperrun, (int) individuals.size() - indsdone );  //minimum of indsperrun and (individuals.size() - indsdone)
		int offset = indsdone;
		
		vector < vector< string > > snpinfo;
		MatrixXd block = readVblockFromIntFile(intensityfile,snpcount,numsamples,snpinfo, offset   );	//get intensity data from the file
		
		//cout << block << endl;
		//cout << block.rows() << " " << block.cols() << endl;
		
		intensityfile.close();

		
		for (int snpt = 0; snpt < snpcount; snpt++)
		{
			for(int ind = 0; ind < numsamples; ind++)
			{
				double distance = sqrt( block(snpt, 2*ind)*block(snpt, 2*ind) + block(snpt, 2*ind+1)*block(snpt, 2*ind+1)  );
				if (!isnan(distance) && !isinf(distance)  )
				{
					sumdistances(ind+offset,0) = sumdistances(ind+offset,0) + distance;
					countdistances(ind+offset,0)++;
				}
			}
		}
		

		
		indsdone = indsdone + numsamples;
		
		
	}
	
	

	MatrixXd meandistances = sumdistances.array() / countdistances.array();
	//Next need to account for NANs - before calculating Stdev
	double sumofmeandists = 0;
	double sumofmeandistssq = 0;
	int count = 0;
	
	for (int i = 0; i < meandistances.rows(); i++)
	{
		double mdist = meandistances(i,0);
		if (!isnan(mdist) && !isinf(mdist)  && (exclude_list.size() == 0 || find (exclude_list.begin(), exclude_list.end(), i)  ==   exclude_list.end() )  )
		{
			count++;
			sumofmeandists = sumofmeandists + mdist;
			sumofmeandistssq = sumofmeandistssq + mdist*mdist;
		}
	}
	
	double meandist = sumofmeandists/count;
	double sddist = sqrt( sumofmeandistssq/count - meandist*meandist );
	
	double lower_bound = meandist  - numsds*sddist;
	double upper_bound = meandist + numsds*sddist;
	
	vector<int> outlying_samples;
	
	
	cout << meandist << " " << sddist << endl;
	cout << "end mean distances" << endl;
	
	for (int i = 0; i < meandistances.rows(); i++)
	{
		double mdist = meandistances(i,0);
		if (  ( isnan(mdist) || isinf(mdist) || mdist < lower_bound || mdist > upper_bound )  && (exclude_list.size() == 0 || find (exclude_list.begin(), exclude_list.end(), i)  ==   exclude_list.end() )   )
		{
			outlying_samples.push_back(i);
			cout << "excluding mean intensity outlier " << i << " with mdist " << mdist << endl;
		}
	}
	
	
	
	return outlying_samples;
}






/***********Create a random sample from the intensity data**********/

MatrixXd fetchRandomIntensities(string fname, int sample_block_size, int snpcount, vector<string> individuals, vector<int> initial_outliers) {
	
	vector < vector< string > > snpinfo;
	
	ifstream intensityfile (fname.c_str());
	if (intensityfile.is_open()  && intensityfile.good())
	{
		string header;
		getline(intensityfile,header);
	}


	/**
	 * STEP 1: Create one block mixture model - by sampling the file once
	 */
	//collect data
	MatrixXd sample(min<int>(sample_block_size,snpcount*individuals.size()),2);
	vector<int> sampling_indices;

	//cout << "getting ready to smaple" << endl;

	//first check if there's actually enough points to take a big sample
	if (sample_block_size >= snpcount*individuals.size())
	{
		//cout << " not enough points for sample " << endl;
		for (int i = 0; i < snpcount*individuals.size(); i++) {
			//TODO: Need to consider the excluded sample indices
			bool excluded = false;
			for (int outlind = 0; outlind < initial_outliers.size(); outlind++ )
			{
				if ((i - initial_outliers[outlind])%individuals.size() == 0 ) 
				{
					excluded = true;
				}
			}
			
			if (!excluded)
			{
				sampling_indices.push_back(i);
			}
			
		}
		
		
	}
	else {
		//cout << " enough points for random sample " << endl;
		//select a bunch of random numbers
		srand(time(0));
		while (sampling_indices.size() < sample_block_size) {
			float randnum = (float)rand()/(float)RAND_MAX;
			int val = floor(randnum*snpcount*individuals.size());
			if (val == snpcount*individuals.size()) {
				//slight fudge if the random number chosen is exactly 1.0
				val = val -1 ;
			}
			
			//TODO: Need to consider the excluded sample indices
			bool excluded = false;
			for (int outlind = 0; outlind < initial_outliers.size(); outlind++ )
			{
				if ((val - initial_outliers[outlind])%individuals.size() == 0 ) 
				{
					excluded = true;
				}
			}
			
			//our random value is not in the list - add it
			if (!excluded && find (sampling_indices.begin(), sampling_indices.end(), val)  ==   sampling_indices.end() ) {
				sampling_indices.push_back(val);
			}
		}
		//ok so now we have the required number of random values - sort them
		sort (sampling_indices.begin(), sampling_indices.end(), lessthanfunction);
	}

	//cout << sampling_indices[0] << " " << sampling_indices[1] << endl;

	//and now finally we fetch the sampled file
	int counter = 0;
	for (int snpt = 0; snpt < snpcount; snpt++)
	{
		//cout << "getting into loop" << endl;
		MatrixXd block = readVblockFromIntFile(intensityfile,1,individuals.size(),snpinfo,0);	//read one line from the file
		//now put the block into a sample
	
		//cout << snpinfo[snpt][0] << endl;
	
		for (int ind = 0; ind < individuals.size(); ind++)
		{
			if (snpt*individuals.size() + ind == sampling_indices[0])
			{
				sampling_indices.erase(sampling_indices.begin());
				sample(counter,0) = block(0,ind*2);
				sample(counter,1) = block(0,ind*2+1);
				counter = counter + 1;
			}
		}
	}


	intensityfile.close();
	return sample;

}