File: Mathematics.cpp

package info (click to toggle)
shogun 0.6.3-1
  • links: PTS, VCS
  • area: main
  • in suites: lenny
  • size: 8,688 kB
  • ctags: 6,563
  • sloc: cpp: 61,677; python: 5,233; sh: 2,767; makefile: 555; objc: 37
file content (538 lines) | stat: -rw-r--r-- 11,947 bytes parent folder | download
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
525
526
527
528
529
530
531
532
533
534
535
536
537
538
/*
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * Written (W) 1999-2008 Soeren Sonnenburg
 * Written (W) 1999-2008 Gunnar Raetsch
 * Copyright (C) 1999-2008 Fraunhofer Institute FIRST and Max-Planck-Society
 */

// Math.cpp: implementation of the CMath class.
//
//////////////////////////////////////////////////////////////////////


#include "lib/common.h"
#include "lib/Mathematics.h"
#include "lib/lapack.h"
#include "lib/io.h"

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

#ifdef USE_LOGCACHE
//gene/math specific constants
#ifdef USE_HMMDEBUG
#define MAX_LOG_TABLE_SIZE 10*1024*1024
#define LOG_TABLE_PRECISION 1e-6
#else
#define MAX_LOG_TABLE_SIZE 123*1024*1024
#define LOG_TABLE_PRECISION 1e-15
#endif

INT CMath::LOGACCURACY         = 0; // 100000 steps per integer
#endif

INT CMath::LOGRANGE            = 0; // range for logtable: log(1+exp(x))  -25 <= x <= 0

const DREAL CMath::INFTY            =  -log(0.0);	// infinity
const DREAL CMath::ALMOST_INFTY		=  +1e+20;		//a large number
const DREAL CMath::ALMOST_NEG_INFTY =  -1000;	
#ifdef USE_LOGCACHE
DREAL* CMath::logtable = NULL;
#endif
CHAR* CMath::rand_state = NULL;
UINT CMath::seed = 0;

CMath::CMath()
: CSGObject()
{
#ifndef HAVE_SWIG
	CSGObject::version.print_version();
#endif
	CMath::rand_state=new CHAR[256];
	init_random();
#ifndef HAVE_SWIG
	SG_PRINT( "( seeding random number generator with %u, ", seed);
#endif

#ifdef USE_LOGCACHE
    LOGRANGE=CMath::determine_logrange();
    LOGACCURACY=CMath::determine_logaccuracy(LOGRANGE);
#ifndef HAVE_SWIG
    SG_PRINT( "initializing log-table (size=%i*%i*%i=%2.1fMB) ... ) ",LOGRANGE,LOGACCURACY,sizeof(DREAL),LOGRANGE*LOGACCURACY*sizeof(DREAL)/(1024.0*1024.0)) ;
#endif 
   
    CMath::logtable=new DREAL[LOGRANGE*LOGACCURACY];
    init_log_table();
#else
	INT i=0;
	while ((DREAL)log(1+((DREAL)exp(-DREAL(i)))))
		i++;
#ifndef HAVE_SWIG
    SG_PRINT("determined range for x in log(1+exp(-x)) is:%d )\n", i);
#endif 
	LOGRANGE=i;
#endif 
}

CMath::~CMath()
{
	delete[] CMath::rand_state;
	CMath::rand_state=NULL;
#ifdef USE_LOGCACHE
	delete[] CMath::logtable;
	CMath::logtable=NULL;
#endif
}

#ifdef USE_LOGCACHE
INT CMath::determine_logrange()
{
    INT i;
    DREAL acc=0;
    for (i=0; i<50; i++)
    {
	acc=((DREAL)log(1+((DREAL)exp(-DREAL(i)))));
	if (acc<=(DREAL)LOG_TABLE_PRECISION)
	    break;
    }

    SG_INFO( "determined range for x in table log(1+exp(-x)) is:%d (error:%G)\n",i,acc);
    return i;
}

INT CMath::determine_logaccuracy(INT range)
{
    range=MAX_LOG_TABLE_SIZE/range/((int)sizeof(DREAL));
    SG_INFO( "determined accuracy for x in table log(1+exp(-x)) is:%d (error:%G)\n",range,1.0/(double) range);
    return range;
}

//init log table of form log(1+exp(x))
void CMath::init_log_table()
{
  for (INT i=0; i< LOGACCURACY*LOGRANGE; i++)
    logtable[i]=log(1+exp(DREAL(-i)/DREAL(LOGACCURACY)));
}
#endif

void CMath::sort(INT *a, INT cols, INT sort_col)
{
  INT changed=1;
  if (a[0]==-1) return ;
  while (changed)
  {
      changed=0; INT i=0 ;
      while ((a[(i+1)*cols]!=-1) && (a[(i+1)*cols+1]!=-1)) // to be sure
	  {
		  if (a[i*cols+sort_col]>a[(i+1)*cols+sort_col])
		  {
			  for (INT j=0; j<cols; j++)
				  CMath::swap(a[i*cols+j],a[(i+1)*cols+j]) ;
			  changed=1 ;
		  } ;
		  i++ ;
	  } ;
  } ;
} 

void CMath::sort(DREAL *a, INT* idx, INT N) 
{

	INT changed=1;
	while (changed)
	{
		changed=0;
		for (INT i=0; i<N-1; i++)
		{
			if (a[i]>a[i+1])
			{
				swap(a[i],a[i+1]) ;
				swap(idx[i],idx[i+1]) ;
				changed=1 ;
			} ;
		} ;
	} ;
	 
} 

DREAL CMath::Align(CHAR * seq1, CHAR* seq2, INT l1, INT l2, DREAL gapCost)
{
  DREAL actCost=0 ;
  INT i1, i2 ;
  DREAL* const gapCosts1 = new DREAL[ l1 ];
  DREAL* const gapCosts2 = new DREAL[ l2 ];
  DREAL* costs2_0 = new DREAL[ l2 + 1 ];
  DREAL* costs2_1 = new DREAL[ l2 + 1 ];

  // initialize borders
  for( i1 = 0; i1 < l1; ++i1 ) {
    gapCosts1[ i1 ] = gapCost * i1;
  }
  costs2_1[ 0 ] = 0;
  for( i2 = 0; i2 < l2; ++i2 ) {
    gapCosts2[ i2 ] = gapCost * i2;
    costs2_1[ i2+1 ] = costs2_1[ i2 ] + gapCosts2[ i2 ];
  }
  // compute alignment
  for( i1 = 0; i1 < l1; ++i1 ) {
    swap( costs2_0, costs2_1 );
    actCost = costs2_0[ 0 ] + gapCosts1[ i1 ];
    costs2_1[ 0 ] = actCost;
    for( i2 = 0; i2 < l2; ++i2 ) {
      const DREAL actMatch = costs2_0[ i2 ] + ( seq1[i1] == seq2[i2] );
      const DREAL actGap1 = costs2_0[ i2+1 ] + gapCosts1[ i1 ];
      const DREAL actGap2 = actCost + gapCosts2[ i2 ];
      const DREAL actGap = min( actGap1, actGap2 );
      actCost = min( actMatch, actGap );
      costs2_1[ i2+1 ] = actCost;
    }
  }

  delete [] gapCosts1;
  delete [] gapCosts2;
  delete [] costs2_0;
  delete [] costs2_1;
  
  // return the final cost
  return actCost;
}

//plot x- axis false positives (fp) 1-Specificity
//plot y- axis true positives (tp) Sensitivity
INT CMath::calcroc(DREAL* fp, DREAL* tp, DREAL* output, INT* label, INT& size, INT& possize, INT& negsize, DREAL& tresh, FILE* rocfile)
{
	INT left=0;
	INT right=size-1;
	INT i;

	for (i=0; i<size; i++)
	{
		if (!(label[i]== -1 || label[i]==1))
			return -1;
	}

	//sort data such that -1 labels first +1 behind
	while (left<right)
	{
		while ((label[left] < 0) && (left<right))
			left++;
		while ((label[right] > 0) && (left<right))	//warning: label must be either -1 or +1
			right--;

		swap(output[left],output[right]);
		swap(label[left], label[right]);
	}

	// neg/pos sizes
	negsize=left;
	possize=size-left;
	DREAL* negout=output;
	DREAL* posout=&output[left];

	// sort the pos and neg outputs separately
	qsort(negout, negsize);
	qsort(posout, possize);

	// set minimum+maximum values for decision-treshhold
	DREAL minimum=min(negout[0], posout[0]);
	DREAL maximum=minimum;
	if (negsize>0)
		maximum=max(maximum,negout[negsize-1]);
	if (possize>0)
		maximum=max(maximum,posout[possize-1]);

	DREAL treshhold=minimum;
	DREAL old_treshhold=treshhold;

	//clear array.
	for (i=0; i<size; i++)
	{
		fp[i]=1.0;
		tp[i]=1.0;
	}

	//start with fp=1.0 tp=1.0 which is posidx=0, negidx=0
	//everything right of {pos,neg}idx is considered to beLONG to +1
	INT posidx=0;
	INT negidx=0;
	INT iteration=1;
	INT returnidx=-1;

	DREAL minerr=10;

	while (iteration < size && treshhold<=maximum)
	{
		old_treshhold=treshhold;

		while (treshhold==old_treshhold && treshhold<=maximum)
		{
			if (posidx<possize && negidx<negsize)
			{
				if (posout[posidx]<negout[negidx])
				{
					if (posout[posidx]==treshhold)
						posidx++;
					else
						treshhold=posout[posidx];
				}
				else
				{
					if (negout[negidx]==treshhold)
						negidx++;
					else
						treshhold=negout[negidx];
				}
			}
			else
			{
				if (posidx>=possize && negidx<negsize-1)
				{
					negidx++;
					treshhold=negout[negidx];
				}
				else if (negidx>=negsize && posidx<possize-1)
				{
					posidx++;
					treshhold=posout[posidx];
				}
				else if (negidx<negsize && treshhold!=negout[negidx])
					treshhold=negout[negidx];
				else if (posidx<possize && treshhold!=posout[posidx])
					treshhold=posout[posidx];
				else
				{
					treshhold=2*(maximum+100); // force termination
					posidx=possize;
					negidx=negsize;
					break;
				}
			}
		}

		//calc tp,fp
		tp[iteration]=(possize-posidx)/(DREAL (possize));
		fp[iteration]=(negsize-negidx)/(DREAL (negsize));

		//choose poINT with minimal error
		if (minerr > negsize*fp[iteration]/size+(1-tp[iteration])*possize/size )
		{
			minerr=negsize*fp[iteration]/size+(1-tp[iteration])*possize/size;
			tresh=(old_treshhold+treshhold)/2;
			returnidx=iteration;
		}

		iteration++;
	}

	// set new size
	size=iteration;

	if (rocfile)
	{
		const CHAR id[]="ROC";
		fwrite(id, sizeof(char), sizeof(id), rocfile);
		fwrite(fp, sizeof(DREAL), size, rocfile);
		fwrite(tp, sizeof(DREAL), size, rocfile);
	}

	return returnidx;
}

UINT CMath::crc32(BYTE *data, INT len)
{
    UINT        result;
    INT                 i,j;
    BYTE       octet;

    result = 0-1;

    for (i=0; i<len; i++)
    {
	octet = *(data++);
	for (j=0; j<8; j++)
	{
	    if ((octet >> 7) ^ (result >> 31))
	    {
		result = (result << 1) ^ 0x04c11db7;
	    }
	    else
	    {
		result = (result << 1);
	    }
	    octet <<= 1;
	}
    }

    return ~result; 
}

double CMath::mutual_info(DREAL* p1, DREAL* p2, INT len)
{
	double e=0;

	for (INT i=0; i<len; i++)
		for (INT j=0; j<len; j++)
			e+=exp(p2[j*len+i])*(p2[j*len+i]-p1[i]-p1[j]);

	return e;
}

double CMath::relative_entropy(DREAL* p, DREAL* q, INT len)
{
	double e=0;

	for (INT i=0; i<len; i++)
		e+=exp(p[i])*(p[i]-q[i]);

	return e;
}

double CMath::entropy(DREAL* p, INT len)
{
	double e=0;

	for (INT i=0; i<len; i++)
		e-=exp(p[i])*p[i];

	return e;
}


//Howto construct the pseudo inverse (from "The Matrix Cookbook")
//
//Assume A does not have full rank, i.e. A is n \times m and rank(A) = r < min(n;m).
//
//The matrix A+ known as the pseudo inverse is unique and does always exist.
//
//The pseudo inverse A+ can be constructed from the singular value
//decomposition A = UDV^T , by  A^+ = V(D+)U^T.

#ifdef HAVE_LAPACK
DREAL* CMath::pinv(DREAL* matrix, INT rows, INT cols, DREAL* target)
{
	if (!target)
		target=new DREAL[rows*cols];

	char jobu='A';
	char jobvt='A';
	int m=rows;
	int n=cols;
	int lda=m;
	int ldu=m;
	int ldvt=n;
	int info=-1;
	int lsize=CMath::min(m,n);
	double* s=new double[lsize];
	double* u=new double[m*m];
	double* vt=new double[n*n];

	wrap_dgesvd(jobu, jobvt, m, n, matrix, lda, s, u, ldu, vt, ldvt, &info);
	ASSERT(info==0);

	for (INT i=0; i<n; i++)
	{
		for (INT j=0; j<lsize; j++)
			vt[i*n+j]=vt[i*n+j]/s[j];
	}

	cblas_dgemm(CblasColMajor, CblasTrans, CblasTrans, m, n, m, 1.0, vt, ldvt, u, ldu, 0, target, m);

	delete[] u;
	delete[] vt;
	delete[] s;

	return target;
}
#endif

template <>
void CMath::display_vector(BYTE* vector, INT n, const char* name)
{
	ASSERT(n>=0);
	SG_SPRINT("%s=[", name);
	for (INT i=0; i<n; i++)
		SG_SPRINT("%d%s", vector[i], i==n-1? "" : ",");
	SG_SPRINT("]\n");
}

template <>
void CMath::display_vector(INT* vector, INT n, const char* name)
{
	ASSERT(n>=0);
	SG_SPRINT("%s=[", name);
	for (INT i=0; i<n; i++)
		SG_SPRINT("%d%s", vector[i], i==n-1? "" : ",");
	SG_SPRINT("]\n");
}

template <>
void CMath::display_vector(LONG* vector, INT n, const char* name)
{
	ASSERT(n>=0);
	SG_SPRINT("%s=[", name);
	for (INT i=0; i<n; i++)
		SG_SPRINT("%lld%s", vector[i], i==n-1? "" : ",");
	SG_SPRINT("]\n");
}

template <>
void CMath::display_vector(SHORTREAL* vector, INT n, const char* name)
{
	ASSERT(n>=0);
	SG_SPRINT("%s=[", name);
	for (INT i=0; i<n; i++)
		SG_SPRINT("%10.10f%s", vector[i], i==n-1? "" : ",");
	SG_SPRINT("]\n");
}

template <>
void CMath::display_vector(DREAL* vector, INT n, const char* name)
{
	ASSERT(n>=0);
	SG_SPRINT("%s=[", name);
	for (INT i=0; i<n; i++)
		SG_SPRINT("%10.10f%s", vector[i], i==n-1? "" : ",");
	SG_SPRINT("]\n");
}

template <>
void CMath::display_matrix(INT* matrix, INT rows, INT cols, const char* name)
{
	ASSERT(rows>=0 && cols>=0);
	SG_SPRINT("%s=[\n", name);
	for (INT i=0; i<rows; i++)
	{
		SG_SPRINT("[");
		for (INT j=0; j<cols; j++)
			SG_SPRINT("\t%d%s", matrix[j*rows+i],
				j==cols-1? "" : ",");
		SG_SPRINT("]%s\n", i==rows-1? "" : ",");
	}
	SG_SPRINT("]\n");
}

template <>
void CMath::display_matrix(DREAL* matrix, INT rows, INT cols, const char* name)
{
	ASSERT(rows>=0 && cols>=0);
	SG_SPRINT("%s=[\n", name);
	for (INT i=0; i<rows; i++)
	{
		SG_SPRINT("[");
		for (INT j=0; j<cols; j++)
			SG_SPRINT("\t%lf%s", (double) matrix[j*rows+i],
				j==cols-1? "" : ",");
		SG_SPRINT("]%s\n", i==rows-1? "" : ",");
	}
	SG_SPRINT("]\n");
}