1 /* -*- mode: c; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
3 /*********************************************************************
4 * Clustal Omega - Multiple sequence alignment
6 * Copyright (C) 2010 University College Dublin
8 * Clustal-Omega is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU General Public License as
10 * published by the Free Software Foundation; either version 2 of the
11 * License, or (at your option) any later version.
13 * This file is part of Clustal-Omega.
15 ********************************************************************/
18 * RCS $Id: util-C.h 155 2010-11-17 12:18:47Z fabian $
21 // Utility subroutines
25 #include <iostream> // cin, cout, cerr
26 #include <fstream> // ofstream, ifstream
27 #include <cstdio> // printf
28 #include <stdlib.h> // exit
29 #include <time.h> // clock
33 /////////////////////////////////////////////////////////////////////////////////////
35 /////////////////////////////////////////////////////////////////////////////////////
38 inline double dmax(double x, double y) { return (x>y? x : y);}
39 inline double dmin(double x, double y) { return (x<y? x : y);}
40 inline int imax(int x, int y) { return (x>y? x : y);}
41 inline int imin(int x, int y) { return (x<y? x : y);}
42 inline int iabs(int x) { return (x>=0? x : -x);}
44 // Rounding up, rounding down and rounding to nearest integer
45 inline int iceil(double x) {return int(ceil(x));}
46 inline int ifloor(double x) {return int(floor(x));}
47 inline int iround(double x) {return int(floor(x+0.5));}
49 //// Generalized mean: d=0: sqrt(x*y) d=1: (x+y)/2 d->-inf: min(x,y) d->+inf: max(x,y)
50 inline double fmean(double x, double y, double d) { return pow( (pow(x,d)+pow(y,d))/2 ,1./d);}
53 inline float log2(float x) {return (x<=0? (float)(-100000):1.442695041*log(x));}
54 inline float log10(float x) {return (x<=0? (float)(-100000):0.434294481*log(x));}
57 /////////////////////////////////////////////////////////////////////////////////////
59 /////////////////////////////////////////////////////////////////////////////////////
61 // This function returns log2 with a max abolute deviation of +/- 1.5E-5 (typically 0.8E-5).
62 // It takes 1.42E-8 s whereas log2(x) takes 9.5E-7 s. It is hence 9.4 times faster.
63 // It makes use of the representation of 4-byte floating point numbers:
64 // seee eeee emmm mmmm mmmm mmmm mmmm mmmm
66 // the following 8 bits, eee eee e, give the exponent + 127 (in hex: 0x7f).
67 // The following 23 bits, m, give the mantisse, the binary digits behind the decimal point.
68 // In summary: x = (-1)^s * 1.mmmmmmmmmmmmmmmmmmmmmm * 2^(eeeeeee-127)
69 // The expression (((*(int *)&x) & 0x7f800000 ) >>23 )-0x7f is the exponent eeeeeeee, i.e.
70 // the largest integer that is smaller than log2(x) (e.g. -1 for 0.9). *(int *)&x is an integer which
71 // contains the bytes as the floating point variable x is represented in memory.
72 // Check: assert( sizeof(f) == sizeof(int) );
73 // Check: assert( sizeof(f) == 4 );
74 inline float fast_log2(float x)
76 static float lg2[1025]; // lg2[i] = log2[1+x/1024]
77 static float diff[1025]; // diff[i]= (lg2[i+1]-lg2[i])/8096 (for interpolation)
78 static char initialized;
79 if (x<=0) return -100000;
80 if (!initialized) //First fill in the arrays lg2[i] and diff[i]
84 for (int i=1; i<=1024; ++i)
86 lg2[i] = log(float(1024+i))*1.442695041-10.0f;
87 diff[i-1] = (lg2[i]-prev)*1.2352E-4;
92 int a = (((*((int *)&x)) & 0x7F800000) >>23 )-0x7f;
93 int b = ((*((int *)&x)) & 0x007FE000) >>13;
94 int c = ((*((int *)&x)) & 0x00001FFF);
95 return a + lg2[b] + diff[b]*(float)(c);
98 /////////////////////////////////////////////////////////////////////////////////////
100 // ATTENTION: need to compile with g++ -fno-strict-aliasing when using -O2 or -O3!!!
101 // Relative deviation < 1.5E-4
102 /////////////////////////////////////////////////////////////////////////////////////
103 inline float fpow2(float x)
105 if (x>=128) return FLT_MAX;
106 if (x<=-128) return FLT_MIN;
107 int *px = (int*)(&x); // store address of float as pointer to long
108 float tx = (x-0.5f) + (3<<22); // temporary value for truncation: x-0.5 is added to a large integer (3<<22)
109 int lx = *((int*)&tx) - 0x4b400000; // integer value of x
110 float dx = x-(float)(lx); // float remainder of x
111 x = 1.0f + dx*(0.6960656421638072f // cubic apporoximation of 2^x
112 + dx*(0.224494337302845f // for x in the range [0, 1]
113 + dx*(0.07944023841053369f)));
114 *px += (lx<<23); // add integer power of 2 to exponent
118 /////////////////////////////////////////////////////////////////////////////////////
120 // Can't be used with -O2/-O3 optimization on some compilers !
121 // Works with g++ version 4.1, but not with 3.4, in which case it returns values
122 // that are a factor 1.002179942 too low
124 // Fast pow2 routine (Johannes Soeding)
125 // Same speed as fpow2(), but *relative* deviation < 1.2E-7
126 // Makes use of the binary representation of floats in memory:
127 // x = (-1)^s * 1.mmmmmmmmmmmmmmmmmmmmmm * 2^(eeeeeee-127)
130 // seee eeee emmm mmmm mmmm mmmm mmmm mmmm
131 // s is the sign, the 8 bits eee eee e are the exponent + 127 (in hex: 0x7f),
132 // and the following 23 bits m give the mantisse.
133 // We decompose the argument x = a + b, with integer a and 0 <= b < 1
134 // Therefore 2^x = 2^a * 2^b where a is the binary exponent of 2^x
135 // and 1 <= 2^b < 2, i.e. 2^b determines the mantisse uniquely.
136 // To calculate 2^b, we split b into the first 10 bits and the last 13 bits,
137 // b = b' + c, and then look up the mantisse of 2^b' in a precomputed table.
138 // We use the residual c to interpolate between the mantisse for 2^b' and 2(b'+1/1024)
139 /////////////////////////////////////////////////////////////////////////////////////
140 inline float fast_pow2(float x)
142 if (x<=-127) return 5.9E-39;
143 if (x>=128) return 3.4E38;
144 static char initialized=0;
145 static unsigned int pow2[1025];
146 static unsigned int diff[1025];
148 if (!initialized) //First fill in the pow2-vector
151 unsigned int prev = 0;
153 for (int b=1; b<1024; b++)
155 f=pow(2.0,float(b)/1024.0);
156 pow2[b]=(*((unsigned int *)(&f)) & 0x7FFFFF); // store the mantisse of 2^(1+b/1024)
157 diff[b-1]=pow2[b]-prev;
161 diff[1023]=pow2[1024]-prev;
165 int *px = (int *)(&x); // store address of float as pointer to int
166 int E = ((*px & 0x7F800000)>>23)-127; // E is exponent of x and is <=6
167 unsigned int M=(*px & 0x007FFFFF) | 0x00800000; // M is the mantisse 1.mmm mmmm mmmm mmmm mmmm mmmm
172 a = 0x3F800000 + ((M<<E) & 0x7F800000); // a is exponent of 2^x, beginning at bit 23
173 b = ((M<<E) & 0x007FE000)>>13;
174 c = ((M<<E) & 0x00001FFF);
176 a = 0x3F800000; // a = exponent of 2^x = 0
177 b = ((M>>(-E)) & 0x007FE000)>>13;
178 c = ((M>>(-E)) & 0x00001FFF);
184 a = 0x3F000000 - ((M<<E) & 0x7F800000); // a is exponent of 2^x
185 b = (0x00800000-(int)((M<<E) & 0x007FFFFF)) >>13;
186 c = (0x00800000-(int)((M<<E) & 0x007FFFFF)) & 0x00001FFF;
188 a = 0x3F000000; // a = exponent of 2^x = -1
189 b = (0x00800000-(int)((M>>(-E)) & 0x007FFFFF)) >>13;
190 c = (0x00800000-(int)((M>>(-E)) & 0x007FFFFF)) & 0x00001FFF;
193 /* printf("x=%0X\n",*px); */
194 /* printf("E=%0X\n",E); */
195 /* printf("M=%0X\n",M); */
196 /* printf("a=%0X\n",a); */
197 /* printf("b=%0X\n",b); */
198 y = a | (pow2[b] + ((diff[b]*c)>>13) );
199 /* printf("2^x=%0X\n",*px); */
200 return *((float*)&y);
205 // Normalize a float array such that it sums to one
206 // If it sums to 0 then assign def_array elements to array (optional)
207 inline float NormalizeTo1(float* array, int length, float* def_array=NULL)
211 for (k=0; k<length; k++) sum+=array[k];
215 for (k=0; k<length; k++) array[k]*=fac;
218 for (k=0; k<length; k++) array[k]=def_array[k];
222 // Normalize a float array such that it sums to x
223 // If it sums to 0 then assign def_array elements to array (optional)
224 inline float NormalizeToX(float* array, int length, float x, float* def_array=NULL)
228 for (k=0; k<length; k++) sum+=array[k];
232 for (k=0; k<length; k++) array[k]*=fac;
235 for (k=0; k<length; k++) array[k]=def_array[k];
239 /////////////////////////////////////////////////////////////////////////////////////
240 // Similar to spintf("%*g,w,val), but displays maximum number of digits within width w
241 /////////////////////////////////////////////////////////////////////////////////////
242 inline char* sprintg(float val, int w)
244 static char str[100];
245 float log10val = log10(fabs(val));
246 int neg = (val<0? 1: 0);
247 if (log10val >= w-neg-1 || -log10val > 3)
249 // positive exponential 1.234E+06
250 // negative exponential 1.234E-06
252 sprintf(str,"%*.*e",w,d<1?1:d,val);
256 int d = log10val>0? w-2-neg-int(log10val): w-2-neg;
257 sprintf(str,"%#*.*f",w,d,val);
262 /////////////////////////////////////////////////////////////////////////////////////
264 /////////////////////////////////////////////////////////////////////////////////////
266 //the integer. If no integer is found, returns INT_MIN and sets ptr to NULL /* MR1 */
267 inline int strtoi(const char*& ptr)
270 const char* ptr0=ptr;
271 if (!ptr) return INT_MIN;
272 while (*ptr!='\0' && !(*ptr>='0' && *ptr<='9')) ptr++;
277 if (*(ptr-1)=='-' && ptr>ptr0) i=-atoi(ptr); else i=atoi(ptr);
278 while (*ptr>='0' && *ptr<='9') ptr++;
283 //Same as strint, but interpretes '*' as default /* MR1 */
284 inline int strtoi_(const char*& ptr, int deflt=INT_MAX)
287 if (!ptr) return INT_MIN;
288 while (*ptr!='\0' && !(*ptr>='0' && *ptr<='9') && *ptr!='*') ptr++;
297 if (*(ptr-1)=='-') i=atoi(ptr-1);
299 while (*ptr>='0' && *ptr<='9') ptr++;
304 // Returns leftmost integer in ptr and sets the pointer to first char after
305 // the integer. If no integer is found, returns INT_MIN and sets pt to NULL
306 int strint(char*& ptr)
310 if (!ptr) return INT_MIN;
311 while (*ptr!='\0' && !(*ptr>='0' && *ptr<='9')) ptr++;
317 if (*(ptr-1)=='-' && ptr>ptr0) i=-atoi(ptr); else i=atoi(ptr);
318 while (*ptr>='0' && *ptr<='9') ptr++;
322 // Same as strint, but interpretes '*' as default
323 int strinta(char*& ptr, int deflt=99999)
326 if (!ptr) return INT_MIN;
327 while (*ptr!='\0' && !(*ptr>='0' && *ptr<='9') && *ptr!='*') ptr++;
338 if (*(ptr-1)=='-') i=atoi(ptr-1);
340 while (*ptr>='0' && *ptr<='9') ptr++;
344 // Returns leftmost float in ptr and sets the pointer to first char after
345 // the float. If no float is found, returns FLT_MIN and sets pt to NULL /* MR1 */
346 float strflt(char*& ptr)
350 if (!ptr) return FLT_MIN;
351 while (*ptr!='\0' && !(*ptr>='0' && *ptr<='9')) ptr++;
357 if (ptr>ptr0 && *(ptr-1)=='-') i=-atof(ptr); else i=atof(ptr);
358 while ((*ptr>='0' && *ptr<='9') || *ptr=='.') ptr++;
362 // Same as strint, but interpretes '*' as default /* MR1 */
363 float strflta(char*& ptr, float deflt=99999)
366 if (!ptr) return FLT_MIN;
367 while (*ptr!='\0' && !(*ptr>='0' && *ptr<='9') && *ptr!='*') ptr++;
378 if (*(ptr-1)=='-') i=-atof(ptr);
380 while ((*ptr>='0' && *ptr<='9') || *ptr=='.') ptr++;
385 // Removes the newline and other control characters at the end of a string (if present)
386 // and returns the new length of the string (-1 if str is NULL)
387 inline int chomp(char str[])
391 for (l=strlen(str)-1; l>=0 && str[l]<32; l--);
396 // Emulates the ifstream::getline method; similar to fgets(str,maxlen,FILE*),
397 // but removes the newline at the end and returns NULL if at end of file or read error
398 inline char* fgetline(char str[], const int maxlen, FILE* file)
400 if (!fgets(str,maxlen,file)) return NULL;
401 if (chomp(str)+1>=maxlen) // if line is cut after maxlen characters...
402 while (fgetc(file)!='\n'); // ... read in rest of line
406 // copies substring str[a,b] into substr and returns substr
407 char *substr(char* substr, char* str, int a, int b)
409 if (b<a) {int i=b; b=a; a=i;}
411 {printf("Function substr: >1000 chars to copy. Exiting.\n"); exit(6);}
415 while (*source!='\0' && source<=send) *(dest++) = *(source++);
421 // Returns pointer to first non-white-space character in str OR to NULL if none found
422 inline char* strscn(char* str)
424 if (!str) return NULL;
426 while (*ptr!='\0' && *ptr<=32) ptr++;
427 return (*ptr=='\0')? NULL: ptr;
430 // Returns pointer to first white-space character in str OR to NULL if none found /* MR1 */
431 inline char* strscn_ws(char* str)
433 if (!str) return NULL;
435 while (*ptr!='\0' && *ptr>32) ptr++;
436 return (*ptr=='\0')? NULL: ptr;
439 //Returns pointer to first non-white-space character in str OR to NULL if none found /* MR1 */
440 inline const char* strscn_c(const char* str)
442 if (!str) return NULL;
444 while (*ptr!='\0' && isspace(*ptr)) ptr++;
445 return (*ptr=='\0') ? NULL : ptr;
448 // Returns pointer to first non-white-space character in str OR to end of string '\0' if none found
449 inline char* strscn_(char* str)
451 if (!str) return NULL;
453 while (*ptr!='\0' && *ptr<=32) ptr++;
457 // Returns pointer to first non-c character in str OR to NULL if none found
458 inline char* strscn(char* str, const char c)
460 if (!str) return NULL;
462 while (*ptr!='\0' && *ptr==c) ptr++;
463 return (*ptr=='\0')? NULL: ptr;
466 // Returns pointer to first non-c character in str OR to end of string '\0' if none found
467 inline char* strscn_(char* str, const char c)
469 if (!str) return NULL;
471 while (*ptr!='\0' && *ptr==c) ptr++;
475 // Cuts string at first white space character found by overwriting it with '\0'.
476 // Returns pointer to next non-white-space char OR to NULL if no such char found
477 inline char* strcut(char* str)
479 if (!str) return NULL;
481 while (*ptr!='\0' && *ptr>32) ptr++;
482 if (*ptr=='\0') return NULL;
485 while (*ptr!='\0' && *ptr<=32) ptr++;
486 return (*ptr=='\0')? NULL:ptr;
489 // Cuts string at first white space character found by overwriting it with '\0'.
490 // Returns pointer to next non-white-space char OR to end of string '\0' if none found
491 inline char* strcut_(char* str)
493 if (!str) return NULL;
495 while (*ptr!='\0' && *ptr>32) ptr++;
496 if (*ptr=='\0') return ptr;
499 while (*ptr!='\0' && *ptr<=32) ptr++;
503 // Cuts string at first occurence of charcter c, by overwriting it with '\0'.
504 // Returns pointer to next char not equal c, OR to NULL if none found
505 inline char* strcut(char* str, const char c)
507 if (!str) return NULL;
509 while (*ptr!='\0' && *ptr!=c) ptr++;
510 if (*ptr=='\0') return NULL;
513 while (*ptr!='\0' && *ptr==c) ptr++;
514 return (*ptr=='\0')? NULL:ptr;
517 // Cuts string at first occurence of charcter c, by overwriting it with '\0'.
518 // Returns pointer to next char not equal c, OR to end of string '\0' if none found
519 inline char* strcut_(char* str, const char c)
521 if (!str) return NULL;
523 while (*ptr!='\0' && *ptr!=c) ptr++;
524 if (*ptr=='\0') return ptr;
527 while (*ptr!='\0' && *ptr==c) ptr++;
531 // Cuts string at first occurence of substr, by overwriting the first letter with '\0'.
532 // Returns pointer to next char after occurence of substr, OR to NULL if no such char found
533 inline char* strcut(char* str, const char* substr)
535 char* ptr; //present location in str being compared to substr
536 const char* sptr=substr; //present location in substr being compared to substr
537 // while not at end of str and not all of substr is matched yet
540 for (ptr=str, sptr=substr; *ptr==*sptr && *ptr!='\0'; ptr++, sptr++) ;
541 if (*sptr=='\0') {*str='\0'; return ptr;}
542 if (*ptr=='\0') return NULL;
547 // Cuts string at first occurence of substr, by overwriting the first letter with '\0'.
548 // Returns pointer to next char after occurence of substr, OR to end of string '\0' if no such char found
549 inline char* strcut_(char* str, const char* substr)
551 char* ptr; //present location in str being compared to substr
552 const char* sptr=substr; //present location in substr being compared to str
553 // while not at end of str and not all of substr is matched yet
556 for (ptr=str, sptr=substr; *ptr==*sptr && *ptr!='\0'; ptr++, sptr++) ;
557 if (*sptr=='\0') {*str='\0'; return ptr;}
558 if (*ptr=='\0') return ptr;
563 // Copies first word in ptr to str. In other words, copies first block of non whitespace characters,
564 // beginning at ptr, to str. If a word is found, returns address of second word in ptr or, if no second
565 // word is found, returns address to end of word ('\0' character) in ptr string. If no word is found
566 // in ptr NULL is returned.
567 inline char* strwrd(char* str, char* ptr)
569 ptr=strscn(ptr); // advance to beginning of next word
572 while (*ptr!='\0' && *ptr>32) *(str++) = *(ptr++);
574 while (*ptr!='\0' && *ptr<=32) ptr++;
580 // Copies first word ***delimited by char c*** in ptr to str. In other words, copies first block of non-c characters,
581 // beginning at ptr, to str. If a word is found, returns address of second word in ptr or, if no second
582 // word is found, returns address to end of word ('\0' character) in ptr string. If no word is found
583 // in ptr NULL is returned.
584 inline char* strwrd(char* str, char* ptr, const char c)
586 ptr=strscn(ptr,c); // advance to beginning of next word
589 while (*ptr!='\0' && *ptr!=c) *(str++) = *(ptr++);
591 while (*ptr!='\0' && *ptr==c) ptr++;
597 // Similar to Perl's tr/abc/ABC/: Replaces all chars in str found in one list with characters from the second list
598 // Returns the number of replaced charactrs
599 int strtr(char* str, const char oldchars[], const char newchars[])
604 for (ptr=str; *ptr!='\0'; ptr++)
605 for (plist=oldchars; *plist!='\0'; plist++)
608 *ptr=newchars[plist-oldchars];
615 // Similar to Perl's tr/abc//d: deletes all chars in str found in the list
616 // Returns number of removed characters
617 int strtrd(char* str, const char chars[])
624 for (plist=chars; *plist!='\0'; plist++)
625 if (*ptr1==*plist) break;
626 if (*plist=='\0') {*ptr0=*ptr1; ptr0++;}
632 // Similar to Perl's tr/a-z//d: deletes all chars in str found in the list
633 // Returns number of removed characters
634 int strtrd(char* str, char char1, char char2)
640 if (*ptr1>=char1 && *ptr1<=char2) {*ptr0=*ptr1; ptr0++;}
646 // transforms str into an all uppercase string
647 char* uprstr(char* str)
650 while (*s !='\0') {if (*s>='a' && *s<='z') *s+='A'-'a';s++;}
654 // transforms str into an all uppercase string
655 char* lwrstr(char* str)
658 while (*s !='\0') {if (*s>='A' && *s<='Z') *s+='a'-'A'; s++;}
662 // transforms chr into an uppercase character
663 inline char uprchr(char chr)
665 return (chr>='a' && chr<='z')? chr+'A'-'a' : chr;
668 // transforms chr into an lowercase character
669 inline char lwrchr(char chr)
671 return (chr>='A' && chr<='Z')? chr-'A'+'a' : chr;
675 // Replaces first occurence of str1 by str2 in str. Returns pointer to first occurence or NULL if not found
676 // ATTENTION: if str2 is longer than str1, allocated memory of str must be long enough!!
677 inline char* strsubst(char* str, const char str1[], const char str2[])
679 char* ptr = strstr(str,str1);
684 // Gives elapsed time since first call to this function
685 inline void ElapsedTimeSinceFirstCall(const char str[])
688 static double tfirst=0;
691 gettimeofday(&t, NULL);
692 tfirst = 1E-6*t.tv_usec + t.tv_sec;
694 gettimeofday(&t, NULL);
695 printf("Elapsed time since first call:%12.3fs %s\n",1E-6*t.tv_usec + t.tv_sec - tfirst,str);
698 // Gives elapsed time since last call to this function
699 inline void ElapsedTimeSinceLastCall(const char str[])
702 static double tlast=0.0;
705 gettimeofday(&t, NULL);
706 tlast = 1.0E-6*t.tv_usec + t.tv_sec;
708 gettimeofday(&t, NULL);
709 printf("Elapsed time since last call:%12.3fs %s\n",1.0E-6*t.tv_usec + t.tv_sec - tlast,str);
710 tlast = 1.0E-6*t.tv_usec + t.tv_sec;
713 inline char* RemovePath(char outname[], char filename[])
717 ptr=strrchr(filename,92); //return adress for LAST \ (backslash) in name
719 ptr=strrchr(filename,'/'); //return adress for LAST / in name
721 if (!ptr) ptr=filename; else ptr++;
726 inline char* RemoveExtension(char outname[], char filename[])
729 ptr1=strrchr(filename,'.'); //return adress for LAST '.' in name
730 if (ptr1) {*ptr1='\0'; strcpy(outname,filename); *ptr1='.';} else strcpy(outname,filename);
734 inline char* RemovePathAndExtension(char outname[], char filename[])
738 ptr=strrchr(filename,92); //return adress for LAST \ (backslash) in name
740 ptr=strrchr(filename,'/'); //return adress for LAST / in name
742 if (!ptr) ptr=filename; else ptr++;
743 ptr1=strrchr(filename,'.'); //return adress for LAST '.' in name
744 if (ptr1) {*ptr1='\0'; strcpy(outname,ptr); *ptr1='.';} else strcpy(outname,ptr);
748 inline char* Extension(char extension[], char filename[])
751 ptr=strrchr(filename,'.'); //return adress for LAST '.' in name
752 if (ptr) strcpy(extension,ptr+1); else *extension='\0';
756 // Path includes last '/'
757 inline char* Pathname(char pathname[], char filename[])
762 ptr=strrchr(filename,92); //return adress for LAST \ (backslash) in name
764 ptr=strrchr(filename,'/'); //return adress for LAST / in name
766 if (ptr) {chr=*(++ptr); *ptr='\0'; strcpy(pathname,filename); *ptr=chr;} else *pathname='\0';
770 // Swaps two integer elements in array k
771 inline void swapi(int k[], int i, int j)
774 temp=k[i]; k[i]=k[j]; k[j]=temp;
777 // QSort sorting routine. time complexity of O(N ln(N)) on average
778 // Sorts the index array k between elements i='left' and i='right' in such a way that afterwards
779 // v[k[i]] is sorted downwards (up=-1) or upwards (up=+1)
780 void QSortInt(int v[], int k[], int left, int right, int up=+1)
783 int last; // last element to have been swapped
785 if (left>=right) return; // do nothing if less then 2 elements to sort
786 // Put pivot element in the middle of the sort range to the side (to position 'left') ...
787 swapi(k,left,(left+right)/2);
789 // ... and swap all elements i SMALLER than the pivot
790 // with an element that is LARGER than the pivot (element last+1):
793 for (i=left+1; i<=right; i++)
794 if (v[k[i]]<v[k[left]]) swapi(k,++last,i);
797 for (i=left+1; i<=right; i++)
798 if (v[k[i]]>v[k[left]]) swapi(k,++last,i);
800 // Put the pivot to the right of the elements which are SMALLER, left to elements which are LARGER
803 // Sort the elements left from the pivot and right from the pivot
804 QSortInt(v,k,left,last-1,up);
805 QSortInt(v,k,last+1,right,up);
808 // QSort sorting routine. time complexity of O(N ln(N)) on average
809 // Sorts the index array k between elements i='left' and i='right' in such a way that afterwards
810 // v[k[i]] is sorted downwards (up=-1) or upwards (up=+1)
811 void QSortFloat(float v[], int k[], int left, int right, int up=+1)
814 int last; // last element to have been swapped
815 void swapi(int k[], int i, int j);
817 if (left>=right) return; // do nothing if less then 2 elements to sort
818 // Put pivot element in the middle of the sort range to the side (to position 'left') ...
819 swapi(k,left,(left+right)/2);
821 // ... and swap all elements i SMALLER than the pivot
822 // with an element that is LARGER than the pivot (element last+1):
825 for (i=left+1; i<=right; i++)
826 if (v[k[i]]<v[k[left]]) swapi(k,++last,i);
829 for (i=left+1; i<=right; i++)
830 if (v[k[i]]>v[k[left]]) swapi(k,++last,i);
832 // Put the pivot to the right of the elements which are SMALLER, left to elements which are LARGER
835 // Sort the elements left from the pivot and right from the pivot
836 QSortFloat(v,k,left,last-1,up);
837 QSortFloat(v,k,last+1,right,up);
841 * @brief comparison function for qsort,
842 * sorts floating point numbers ascendingly
844 * @param cv1 ponter to 1st entry to be sorted
845 * @param cv2 ponter to 2nd entry to be sorted
847 * @return 0 if entries are equal,
848 * +/-1 if 1st greater/smaller than 2nd
850 int CompFltAsc(const void *cv1, const void *cv2){
852 float f1 = *(float *)cv1;
853 float f2 = *(float *)cv2;
855 if (f1 > f2) { return +1; }
856 else if (f1 < f2) { return -1; }
859 } /* this is the end of CompFltAsc() */
861 //Return random number in the range [0,1]
862 inline float frand() { return rand()/(RAND_MAX+1.0); }
865 /////////////////////////////////////////////////////////////////////////////////////
866 //// Execute system command
867 /////////////////////////////////////////////////////////////////////////////////////
868 void runSystem(std::string cmd, int v = 2)
871 cout << "Command: " << cmd << "!\n";
872 int res = system(cmd.c_str());
875 cerr << endl << "ERROR when executing: " << cmd << "!\n";