Source

sleipnir / src / seekwriter.h

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
/*****************************************************************************
* This file is provided under the Creative Commons Attribution 3.0 license.
*
* You are free to share, copy, distribute, transmit, or adapt this work
* PROVIDED THAT you attribute the work to the authors listed below.
* For more information, please see the following web page:
* http://creativecommons.org/licenses/by/3.0/
*
* This file is a component of the Sleipnir library for functional genomics,
* authored by:
* Curtis Huttenhower (chuttenh@princeton.edu)
* Mark Schroeder
* Maria D. Chikina
* Olga G. Troyanskaya (ogt@princeton.edu, primary contact)
*
* If you use this library, the included executable tools, or any related
* code in your work, please cite the following publication:
* Curtis Huttenhower, Mark Schroeder, Maria D. Chikina, and
* Olga G. Troyanskaya.
* "The Sleipnir library for computational functional genomics"
*****************************************************************************/
#ifndef SEEKWRITER_H
#define SEEKWRITER_H

#include "seekbasic.h"
#include "seekmap.h"
#include "seekevaluate.h"
#include "sparsematrix.h"
#include "datapair.h"
#include "seekreader.h"

namespace Sleipnir {

class CSeekWriter{
public:

	//should be either unsigned short or utype
	template<class tType>
	static bool ReadSeekSparseMatrixHeader(const char *fileName,
	CSeekIntIntMap &m){
		FILE *f = fopen(fileName, "rb");
		if(f==NULL){
			cerr << "File not found" << endl;
			return false;
		}
		size_t j;
		tType val, numPresent;
		int ret;

		//m need to be initialized to size vecstrGenes.size() first!
		ret = fread((char*) (&numPresent), 1, sizeof(numPresent), f);
		for(j=0; j<numPresent; j++){
			ret = fread((char*)(&val), 1, sizeof(val), f); //val stores the present gene
			m.Add((utype) val);
		}
		fclose(f);
		return true;
	}

	//compatibility
	template<class tType>
	static bool ReadSeekSparseMatrix(const char *fileName,
	CSparseFlatMatrix<float> &mat, CSeekIntIntMap &m, const int maxRank, 
	const float rbp_p, const vector<string> &vecstrGenes){
	
		FILE *f = fopen(fileName, "rb");
		if(f==NULL){
			cerr << "File not found" << endl;
			return false;
		}

		size_t i, j;
		tType numGenes, numPresent, val;
		int ret;

		mat.Initialize(vecstrGenes.size());
		ret = fread((char*) (&numPresent), 1, sizeof(numPresent), f);
		for(j=0; j<numPresent; j++){
			ret = fread((char*)(&val), 1, sizeof(val), f); //val = gene ID
			m.Add((utype) val);
			mat.InitializeRow(val, maxRank*2); //initial capacity
		}
		ret = fread((char*) (&numGenes), 1, sizeof(numGenes), f);

		vector<float> rbp_score;
		rbp_score.resize(maxRank);
		for(i=0; i<maxRank; i++)
			rbp_score[i] = (1.0 - rbp_p) * pow(rbp_p, i);

		for(i=0; i<numGenes; i++){
			tType id, id2;  //gene ID
			unsigned short numEntries, val; //rank
			ret = fread((char*)(&id), 1, sizeof(id), f);
			ret = fread((char*)(&numEntries), 1, sizeof(numEntries), f);
			for(j=0; j<numEntries; j++){
				ret = fread((char*)(&id2),1,sizeof(id2),f);
				ret = fread((char*)(&val),1,sizeof(val),f);
				tType first = id;
				tType second = id2;
				//mat looks like a full matrix
				mat.Add(first, second, rbp_score[val]);
				mat.Add(second, first, rbp_score[val]);
			}
		}
		fclose(f);

		mat.Organize();
		size_t ii, jj;
		const vector<utype> &allRGenes = m.GetAllReverse();
		fprintf(stderr, "Begin calculating row sum\n");

		vector<float> vecSum;
		CSeekTools::InitVector(vecSum, vecstrGenes.size(), (float) 0);
		for(ii=0; ii<m.GetNumSet(); ii++){
			i = (size_t) allRGenes[ii];
			const vector<CPair<float> > &row = mat.GetRow(i);
			for(jj=0; jj<row.size(); jj++)
				vecSum[i] += row[jj].v;
		}

		vector<float> vecSqrtSum;
		CSeekTools::InitVector(vecSqrtSum, vecstrGenes.size(), (float) 0);

		for(ii=0; ii<m.GetNumSet(); ii++){
			i = (size_t) allRGenes[ii];
			if(vecSum[i]==0) continue;
			vecSqrtSum[i] = sqrtf(vecSum[i]);
		}

		fprintf(stderr, "Begin normalization using row sum\n");
		float rv;
		for(ii=0; ii<m.GetNumSet(); ii++){
			i = (size_t) allRGenes[ii];
			vector<CPair<float> >::iterator row_it;
			for(row_it = mat.RowBegin(i); row_it!=mat.RowEnd(i); row_it++){
				j = (size_t) row_it->i;
				rv = row_it->v;
				if(vecSqrtSum[i]==0 || vecSqrtSum[j]==0) continue;
				row_it->v = rv / vecSqrtSum[i] / vecSqrtSum[j];
			}
		}
		return true;
	}

	//compatibility
	template<class tType>
	static bool RemoveDominant(CSparseFlatMatrix<float> &mat, 
	CSeekIntIntMap &m, const vector<string> &vecstrGenes){
	
		size_t i, j;
		vector<vector<float> > tmp_mat, tmp2;
		tmp_mat.resize(vecstrGenes.size());
		tmp2.resize(vecstrGenes.size());
		for(i=0; i<vecstrGenes.size(); i++){
			tmp_mat[i].resize(vecstrGenes.size());
			tmp2[i].resize(vecstrGenes.size());
			for(j=0; j<vecstrGenes.size(); j++){
				tmp_mat[i][j] = 0;
				tmp2[i][j] = 0;
			}
		}

		size_t ii, jj;
		const vector<utype> &allRGenes = m.GetAllReverse();
		for(ii=0; ii<m.GetNumSet(); ii++){
			i = (size_t) allRGenes[ii];
			vector<CPair<float> >::iterator row_it;
			for(row_it=mat.RowBegin(i); row_it!=mat.RowEnd(i); row_it++){
				j = (size_t) row_it->i;
				tmp_mat[i][j] = row_it->v;
			}
		}

		int TOP = 100;
		fprintf(stderr, "Started removing dominant...\n");
		for(ii=0; ii<m.GetNumSet(); ii++){
			i = (size_t) allRGenes[ii];
			vector<CPair<float> > vp;
			vp.resize(m.GetNumSet());
			for(jj=0; jj<m.GetNumSet(); jj++){
				j = (size_t) allRGenes[jj];
				vp[jj].i = (utype) j;
				vp[jj].v = tmp_mat[i][j];
			}
			nth_element(vp.begin(), vp.begin()+TOP, vp.end(), CDescendingValue<float>());
			sort(vp.begin(), vp.begin()+TOP, CDescendingValue<float>());

			//top 100
			size_t k, l;
			size_t max_ind = 0;
			float max_val = -1;
			for(k=0; k<TOP; k++){
				size_t this_g = vp[k].i;
				float v = 0;
				for(l=0; l<TOP; l++){
					size_t other_g = vp[l].i;
					if(this_g==other_g) continue;
					v+=tmp_mat[this_g][other_g];
				}
				if(v>max_val){
					max_val = v;
					max_ind = k;
				}
			}
			for(jj=0; jj<m.GetNumSet(); jj++){
				j = (size_t) allRGenes[jj];
				tmp2[i][j] = tmp_mat[i][j] - tmp_mat[j][max_ind];
				if(tmp2[i][j]<0)	
					tmp2[i][j] = 0;
			}
		}

		fprintf(stderr, "Started re-normalizing matrix...\n");

		for(ii=0; ii<m.GetNumSet(); ii++){
			i = (size_t) allRGenes[ii];
			for(jj=ii+1; jj<m.GetNumSet(); jj++){
				j = (size_t) allRGenes[jj];
				float m = max(tmp2[i][j], tmp2[j][i]);
				tmp2[i][j] = m;
				tmp2[j][i] = m;
			}
		}

		vector<float> vecSum;
		CSeekTools::InitVector(vecSum, vecstrGenes.size(), (float) 0);
		for(ii=0; ii<m.GetNumSet(); ii++){
			i = (size_t) allRGenes[ii];
			for(jj=0; jj<m.GetNumSet(); jj++){
				j = (size_t) allRGenes[jj];
				vecSum[i] += tmp2[i][j];
			}
		}

		vector<float> vecSqrtSum;
		CSeekTools::InitVector(vecSqrtSum, vecstrGenes.size(), (float) 0);
		for(ii=0; ii<m.GetNumSet(); ii++){
			i = (size_t) allRGenes[ii];
			if(vecSum[i]==0) continue;
			vecSqrtSum[i] = sqrtf(vecSum[i]);
		}

		for(ii=0; ii<m.GetNumSet(); ii++){
			i = (size_t) allRGenes[ii];
			vector<CPair<float> >::iterator row_it;
			for(row_it=mat.RowBegin(i); row_it!=mat.RowEnd(i); row_it++){
				j = (size_t) row_it->i;
				if(vecSqrtSum[i]==0 || vecSqrtSum[j]==0) continue;
				row_it->v = tmp2[i][j] / vecSqrtSum[i] / vecSqrtSum[j];
				//fprintf(stderr, "%d %d %.3e\n", i, j, row_it->v);
			}
		}
		return true;
	}

	//compatibility
	template<class tType>
	static bool WriteSparseMatrix(CDataPair &Dat, 
	vector<map<tType,unsigned short> > &umat, 
	const vector<string> &vecstrGenes, const char *fileName){

		FILE *f = fopen(fileName, "wb");
		if(f==NULL){
			fprintf(stderr, "File not found %s\n", fileName);
			return false;
		}

		size_t i, j;
		vector<tType> veciGenes;
		veciGenes.resize(vecstrGenes.size());
		for(i=0; i<vecstrGenes.size(); i++)
			veciGenes[i] = (tType) Dat.GetGeneIndex(vecstrGenes[i]);

		CSeekIntIntMap mm(vecstrGenes.size());
		for(i=0; i<vecstrGenes.size(); i++)
			if(veciGenes[i]!=(tType)-1)
				mm.Add((utype)i);

		tType numPresent = (tType) mm.GetNumSet();	
		//1 tType
		fwrite((char*)(&numPresent), 1, sizeof(numPresent), f);
		const vector<utype> &allR = mm.GetAllReverse();
		//numPresent tType
		for(i=0; i<numPresent; i++){
			tType pr = (tType) allR[i];
			fwrite((char*)(&pr), 1, sizeof(pr), f);
		}

		tType numGenes = 0;
		for(i=0; i<vecstrGenes.size(); i++){
			if(umat[i].size()==0) continue;
			numGenes++;
		}
		//1 tType
		fwrite((char*) (&numGenes), 1, sizeof(numGenes), f);

		for(i=0; i<vecstrGenes.size(); i++){
			unsigned short numEntries = umat[i].size(); //should be 1000
			if(numEntries==0) 
				continue;
			//1 tType
			tType gi = (tType) i;
			fwrite((char*) (&gi), 1, sizeof(gi), f);
			//1 unsigned short
			fwrite((char*) (&numEntries), 1, sizeof(numEntries), f);
			typename map<tType,unsigned short>::iterator it;
			for(it=umat[i].begin(); it!=umat[i].end(); it++){
				tType first = it->first;
				unsigned short second = it->second;
				//1 tType
				fwrite((char*) (&first), 1, sizeof(first), f);
				//1 unsigned short
				fwrite((char*) (&second), 1, sizeof(second), f);
			}
		}
		fclose(f);
		return true;
	}

	//compatiblity
	template<class tType>
	static bool GetSparseRankMatrix(CDataPair &Dat, 
	vector<map<tType,unsigned short> > &umat, int maxRank, 
	const vector<string> &vecstrGenes){
	
		size_t i, j;
		vector<tType> veciGenes;
		veciGenes.resize(vecstrGenes.size());
		for( i = 0; i < vecstrGenes.size( ); ++i )
			veciGenes[ i ] = (tType) Dat.GetGeneIndex( vecstrGenes[i] );
		umat.resize(vecstrGenes.size());
		for(i=0; i<vecstrGenes.size(); i++)
			umat[i] = map<tType, unsigned short>();

		fprintf(stderr, "Start reading DAB...\n");
		tType s, t;
		for(i=0; i<vecstrGenes.size(); i++){
			if((s=veciGenes[i])==(tType)-1) continue;
			if(i%1000==0) fprintf(stderr, "Start reading gene %d...\n", i);

			float *v = Dat.GetFullRow(s);
			vector<AResultFloat> vv;
			vv.resize(vecstrGenes.size());

			for(j=0; j<vecstrGenes.size(); j++){
				vv[j].i = (utype) j;
				vv[j].f = -9999;
				if((t=veciGenes[j])==(tType)-1) continue;
				if(CMeta::IsNaN(v[t])) continue;
				vv[j].f = v[t];
			}
			nth_element(vv.begin(), vv.begin()+maxRank, vv.end());
			sort(vv.begin(), vv.begin()+maxRank);

			for(j=0; j<vecstrGenes.size(); j++){
				if(j<maxRank){
					tType first = (tType) i;
					tType second = (tType) vv[j].i;
					if((tType) i >= (tType) vv[j].i){
						first = (tType) vv[j].i;
						second = (tType) i;
					}
					typename map<tType,unsigned short>::iterator it;
					if((it=umat[first].find(second))==umat[first].end())
						umat[first][second] = (unsigned short) j;
					else
						umat[first][second] = std::min(it->second, (unsigned short) j);
				}
			}
			delete[] v;
		}
		fprintf(stderr, "Finished reading DAB\n");
		return true;
	}

	//To be used after NormalizeDAB
	template<class tType>
	static bool ConvertToSparseMatrix(CDataPair &Dat,
	vector<map<tType,unsigned short> > &umat,
	const vector<string> &vecstrGenes, const float cutoff_val){

		size_t i, j;
		vector<tType> veciGenes;
		veciGenes.resize(vecstrGenes.size());
		for( i = 0; i < vecstrGenes.size( ); ++i )
			veciGenes[ i ] = (tType) Dat.GetGeneIndex( vecstrGenes[i] );
		umat.resize(vecstrGenes.size());
		for(i=0; i<vecstrGenes.size(); i++)
			umat[i] = map<tType, unsigned short>();

		tType s,t;
		for(i=0; i<vecstrGenes.size(); i++){
			if((s=veciGenes[i])==(tType)-1) continue;
			if(i%1000==0) fprintf(stderr, "Start reading gene %d...\n", i);

			for(j=i+1; j<vecstrGenes.size(); j++){
				if((t=veciGenes[j])==(tType)-1) continue;
				float r = Dat.Get(s,t);
				if(CMeta::IsNaN(r)) continue;
				if(r > cutoff_val)
					umat[i][j] = (unsigned short) (r * 100.0);
			}
		}
		fprintf(stderr, "Finished reading DAB\n");
		return true;
	}

	//to be used for sparse matrix created from cutting-off z-scores
	template<class tType>
	static bool ReadSeekSparseMatrix(const char *fileName,
	CSparseFlatMatrix<float> &mat, CSeekIntIntMap &m, 
	const vector<string> &vecstrGenes, const int initialCapacity, 
	const float exponent){
	
		if(exponent<1.0){
			fprintf(stderr, "Exponent must be >=1.0\n");
			return false;
		}
	
		FILE *f = fopen(fileName, "rb");
		if(f==NULL){
			cerr << "File not found" << endl;
			return false;
		}

		size_t i, j;
		tType numGenes, numPresent, val;
		int ret;

		mat.Initialize(vecstrGenes.size());
		ret = fread((char*) (&numPresent), 1, sizeof(numPresent), f);
		for(j=0; j<numPresent; j++){
			ret = fread((char*)(&val), 1, sizeof(val), f); //val = gene ID
			m.Add((utype) val);
			mat.InitializeRow(val, initialCapacity); //initial capacity
		}
		ret = fread((char*) (&numGenes), 1, sizeof(numGenes), f);

		for(i=0; i<numGenes; i++){
			tType id, id2;  //gene ID
			unsigned short numEntries, val; //z-scores * 100.0
			ret = fread((char*)(&id), 1, sizeof(id), f);
			ret = fread((char*)(&numEntries), 1, sizeof(numEntries), f);
			for(j=0; j<numEntries; j++){
				ret = fread((char*)(&id2),1,sizeof(id2),f);
				ret = fread((char*)(&val),1,sizeof(val),f);
				tType first = id;
				tType second = id2;
				float fval = (float) val / 100.0;
				if(exponent>1.0)
					fval = pow(fval, exponent);
				mat.Add(first, second, fval);
				mat.Add(second, first, fval);
			}
		}
		fclose(f);

		mat.Organize();
		return true;
	}

	//===============================================================
	//not currently used
	static bool ReadSparseMatrix(const char *fileName, 
		vector<map<utype,float> > &mat, 
		CSeekIntIntMap &m, const int maxRank, const float rbp_p,
		const vector<string> &vecstrGenes);

	//not currently used
	static bool ProductNorm(const vector<map<utype,float> > &mat1,
		const vector<map<utype,float> > &mat2, const CSeekIntIntMap &m1, 
		const CSeekIntIntMap &m2, vector<map<utype,float> > &re);

	//================================================================
	static bool SumSparseMatrix(CSparseFlatMatrix<float> &mat1,
		CSparseFlatHalfMatrix<float> &res, const CSeekIntIntMap &mi, const float w);

	static bool SumSparseMatrix(CSparseFlatMatrix<float> &mat1,
		CHalfMatrix<float> &res, const CSeekIntIntMap &mi, const float w);

	static bool NormalizeDAB(CDataPair &Dat, const vector<string> &vecstrGenes,
		//bool cutoff, float cutoff_val, 
		bool expTransform, bool divideNorm, bool subtractNorm);

	static bool GetGeneAverage(CDataPair &Dat,
		const vector<string> &vecstrGenes,
		vector<float> &vecResult, bool logit=false, float top_percent=1.0);
	static bool GetGenePresence(CDataPair &Dat,
		const vector<string> &vecstrGenes,
		vector<char> &vecResult);
	static bool GetDatasetSinfo(CDataPair &Dat, float &mean,
		float &stdev);
};

}
#endif