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 316 2016-12-16 16:14:39Z 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
32 //#include "new_new.h" /* memory tracking */
33 #include "../config.h"
35 /////////////////////////////////////////////////////////////////////////////////////
37 /////////////////////////////////////////////////////////////////////////////////////
40 inline double dmax(double x, double y) { return (x>y? x : y);}
41 inline double dmin(double x, double y) { return (x<y? x : y);}
42 inline int imax(int x, int y) { return (x>y? x : y);}
43 inline int imin(int x, int y) { return (x<y? x : y);}
44 inline int iabs(int x) { return (x>=0? x : -x);}
46 // Rounding up, rounding down and rounding to nearest integer
47 inline int iceil(double x) {return int(ceil(x));}
48 inline int ifloor(double x) {return int(floor(x));}
49 inline int iround(double x) {return int(floor(x+0.5));}
51 //// Generalized mean: d=0: sqrt(x*y) d=1: (x+y)/2 d->-inf: min(x,y) d->+inf: max(x,y)
52 inline double fmean(double x, double y, double d) { return pow( (pow(x,d)+pow(y,d))/2 ,1./d);}
55 //#ifndef CLUSTAL_OMEGA_HAVE_LOG2
57 inline float Log2(float x) {return (x<=0? (float)(-100000):1.442695041*log(x));}
58 inline float Log10(float x) {return (x<=0? (float)(-100000):0.434294481*log(x));}
62 /////////////////////////////////////////////////////////////////////////////////////
64 /////////////////////////////////////////////////////////////////////////////////////
66 // This function returns log2 with a max abolute deviation of +/- 1.5E-5 (typically 0.8E-5).
67 // It takes 1.42E-8 s whereas log2(x) takes 9.5E-7 s. It is hence 9.4 times faster.
68 // It makes use of the representation of 4-byte floating point numbers:
69 // seee eeee emmm mmmm mmmm mmmm mmmm mmmm
71 // the following 8 bits, eee eee e, give the exponent + 127 (in hex: 0x7f).
72 // The following 23 bits, m, give the mantisse, the binary digits behind the decimal point.
73 // In summary: x = (-1)^s * 1.mmmmmmmmmmmmmmmmmmmmmm * 2^(eeeeeee-127)
74 // The expression (((*(int *)&x) & 0x7f800000 ) >>23 )-0x7f is the exponent eeeeeeee, i.e.
75 // the largest integer that is smaller than log2(x) (e.g. -1 for 0.9). *(int *)&x is an integer which
76 // contains the bytes as the floating point variable x is represented in memory.
77 // Check: assert( sizeof(f) == sizeof(int) );
78 // Check: assert( sizeof(f) == 4 );
79 inline float fast_log2(float x)
81 static float lg2[1025]; // lg2[i] = log2[1+x/1024]
82 static float diff[1025]; // diff[i]= (lg2[i+1]-lg2[i])/8096 (for interpolation)
83 static char initialized;
84 if (x<=0) return -100000;
85 if (!initialized) //First fill in the arrays lg2[i] and diff[i]
89 for (int i=1; i<=1024; ++i)
91 lg2[i] = log(float(1024+i))*1.442695041-10.0f;
92 diff[i-1] = (lg2[i]-prev)*1.2352E-4;
97 int a = (((*((int *)&x)) & 0x7F800000) >>23 )-0x7f;
98 int b = ((*((int *)&x)) & 0x007FE000) >>13;
99 int c = ((*((int *)&x)) & 0x00001FFF);
100 return a + lg2[b] + diff[b]*(float)(c);
103 /////////////////////////////////////////////////////////////////////////////////////
105 // ATTENTION: need to compile with g++ -fno-strict-aliasing when using -O2 or -O3!!!
106 // Relative deviation < 1.5E-4
107 /////////////////////////////////////////////////////////////////////////////////////
108 inline float fpow2(float x)
110 if (x>=128) return FLT_MAX;
111 if (x<=-128) return FLT_MIN;
112 int *px = (int*)(&x); // store address of float as pointer to long
113 float tx = (x-0.5f) + (3<<22); // temporary value for truncation: x-0.5 is added to a large integer (3<<22)
114 int lx = *((int*)&tx) - 0x4b400000; // integer value of x
115 float dx = x-(float)(lx); // float remainder of x
116 x = 1.0f + dx*(0.6960656421638072f // cubic apporoximation of 2^x
117 + dx*(0.224494337302845f // for x in the range [0, 1]
118 + dx*(0.07944023841053369f)));
119 *px += (lx<<23); // add integer power of 2 to exponent
123 /////////////////////////////////////////////////////////////////////////////////////
125 // Can't be used with -O2/-O3 optimization on some compilers !
126 // Works with g++ version 4.1, but not with 3.4, in which case it returns values
127 // that are a factor 1.002179942 too low
129 // Fast pow2 routine (Johannes Soeding)
130 // Same speed as fpow2(), but *relative* deviation < 1.2E-7
131 // Makes use of the binary representation of floats in memory:
132 // x = (-1)^s * 1.mmmmmmmmmmmmmmmmmmmmmm * 2^(eeeeeee-127)
135 // seee eeee emmm mmmm mmmm mmmm mmmm mmmm
136 // s is the sign, the 8 bits eee eee e are the exponent + 127 (in hex: 0x7f),
137 // and the following 23 bits m give the mantisse.
138 // We decompose the argument x = a + b, with integer a and 0 <= b < 1
139 // Therefore 2^x = 2^a * 2^b where a is the binary exponent of 2^x
140 // and 1 <= 2^b < 2, i.e. 2^b determines the mantisse uniquely.
141 // To calculate 2^b, we split b into the first 10 bits and the last 13 bits,
142 // b = b' + c, and then look up the mantisse of 2^b' in a precomputed table.
143 // We use the residual c to interpolate between the mantisse for 2^b' and 2(b'+1/1024)
144 /////////////////////////////////////////////////////////////////////////////////////
145 inline float fast_pow2(float x)
147 if (x<=-127) return 5.9E-39;
148 if (x>=128) return 3.4E38;
149 static char initialized=0;
150 static unsigned int pow2[1025];
151 static unsigned int diff[1025];
153 if (!initialized) //First fill in the pow2-vector
156 unsigned int prev = 0;
158 for (int b=1; b<1024; b++)
160 f=pow(2.0,float(b)/1024.0);
161 pow2[b]=(*((unsigned int *)(&f)) & 0x7FFFFF); // store the mantisse of 2^(1+b/1024)
162 diff[b-1]=pow2[b]-prev;
166 diff[1023]=pow2[1024]-prev;
170 int *px = (int *)(&x); // store address of float as pointer to int
171 int E = ((*px & 0x7F800000)>>23)-127; // E is exponent of x and is <=6
172 unsigned int M=(*px & 0x007FFFFF) | 0x00800000; // M is the mantisse 1.mmm mmmm mmmm mmmm mmmm mmmm
177 a = 0x3F800000 + ((M<<E) & 0x7F800000); // a is exponent of 2^x, beginning at bit 23
178 b = ((M<<E) & 0x007FE000)>>13;
179 c = ((M<<E) & 0x00001FFF);
181 a = 0x3F800000; // a = exponent of 2^x = 0
182 b = ((M>>(-E)) & 0x007FE000)>>13;
183 c = ((M>>(-E)) & 0x00001FFF);
189 a = 0x3F000000 - ((M<<E) & 0x7F800000); // a is exponent of 2^x
190 b = (0x00800000-(int)((M<<E) & 0x007FFFFF)) >>13;
191 c = (0x00800000-(int)((M<<E) & 0x007FFFFF)) & 0x00001FFF;
193 a = 0x3F000000; // a = exponent of 2^x = -1
194 b = (0x00800000-(int)((M>>(-E)) & 0x007FFFFF)) >>13;
195 c = (0x00800000-(int)((M>>(-E)) & 0x007FFFFF)) & 0x00001FFF;
198 /* printf("x=%0X\n",*px); */
199 /* printf("E=%0X\n",E); */
200 /* printf("M=%0X\n",M); */
201 /* printf("a=%0X\n",a); */
202 /* printf("b=%0X\n",b); */
203 y = a | (pow2[b] + ((diff[b]*c)>>13) );
204 /* printf("2^x=%0X\n",*px); */
205 return *((float*)&y);
210 // Normalize a float array such that it sums to one
211 // If it sums to 0 then assign def_array elements to array (optional)
212 inline float NormalizeTo1(float* array, int length, float* def_array=NULL)
216 for (k=0; k<length; k++) sum+=array[k];
220 for (k=0; k<length; k++) array[k]*=fac;
223 for (k=0; k<length; k++) array[k]=def_array[k];
227 // Normalize a float array such that it sums to x
228 // If it sums to 0 then assign def_array elements to array (optional)
229 inline float NormalizeToX(float* array, int length, float x, float* def_array=NULL)
233 for (k=0; k<length; k++) sum+=array[k];
237 for (k=0; k<length; k++) array[k]*=fac;
240 for (k=0; k<length; k++) array[k]=def_array[k];
244 /////////////////////////////////////////////////////////////////////////////////////
245 // Similar to spintf("%*g,w,val), but displays maximum number of digits within width w
246 /////////////////////////////////////////////////////////////////////////////////////
247 inline char* sprintg(float val, int w)
249 static char str[100];
250 float log10val = Log10(fabs(val));
251 int neg = (val<0? 1: 0);
252 if (log10val >= w-neg-1 || -log10val > 3)
254 // positive exponential 1.234E+06
255 // negative exponential 1.234E-06
257 sprintf(str,"%*.*e",w,d<1?1:d,val);
261 int d = log10val>0? w-2-neg-int(log10val): w-2-neg;
262 sprintf(str,"%#*.*f",w,d,val);
267 /////////////////////////////////////////////////////////////////////////////////////
269 /////////////////////////////////////////////////////////////////////////////////////
271 //the integer. If no integer is found, returns INT_MIN and sets ptr to NULL /* MR1 */
272 inline int strtoi(const char*& ptr)
275 const char* ptr0=ptr;
276 if (!ptr) return INT_MIN;
277 while (*ptr!='\0' && !(*ptr>='0' && *ptr<='9')) ptr++;
282 if (*(ptr-1)=='-' && ptr>ptr0) i=-atoi(ptr); else i=atoi(ptr);
283 while (*ptr>='0' && *ptr<='9') ptr++;
288 //Same as strint, but interpretes '*' as default /* MR1 */
289 inline int strtoi_(const char*& ptr, int deflt=INT_MAX)
292 if (!ptr) return INT_MIN;
293 while (*ptr!='\0' && !(*ptr>='0' && *ptr<='9') && *ptr!='*') ptr++;
302 if (*(ptr-1)=='-') i=atoi(ptr-1);
304 while (*ptr>='0' && *ptr<='9') ptr++;
309 // Returns leftmost integer in ptr and sets the pointer to first char after
310 // the integer. If no integer is found, returns INT_MIN and sets pt to NULL
311 int strint(char*& ptr)
315 if (!ptr) return INT_MIN;
316 while (*ptr!='\0' && !(*ptr>='0' && *ptr<='9')) ptr++;
322 if (*(ptr-1)=='-' && ptr>ptr0) i=-atoi(ptr); else i=atoi(ptr);
323 while (*ptr>='0' && *ptr<='9') ptr++;
327 // Same as strint, but interpretes '*' as default
328 int strinta(char*& ptr, int deflt=99999)
331 if (!ptr) return INT_MIN;
332 while (*ptr!='\0' && !(*ptr>='0' && *ptr<='9') && *ptr!='*') ptr++;
343 if (*(ptr-1)=='-') i=atoi(ptr-1);
345 while (*ptr>='0' && *ptr<='9') ptr++;
349 // Returns leftmost float in ptr and sets the pointer to first char after
350 // the float. If no float is found, returns FLT_MIN and sets pt to NULL /* MR1 */
351 float strflt(char*& ptr)
355 if (!ptr) return FLT_MIN;
356 while (*ptr!='\0' && !(*ptr>='0' && *ptr<='9')) ptr++;
362 if (ptr>ptr0 && *(ptr-1)=='-') i=-atof(ptr); else i=atof(ptr);
363 while ((*ptr>='0' && *ptr<='9') || *ptr=='.') ptr++;
367 // Same as strint, but interpretes '*' as default /* MR1 */
368 float strflta(char*& ptr, float deflt=99999)
371 if (!ptr) return FLT_MIN;
372 while (*ptr!='\0' && !(*ptr>='0' && *ptr<='9') && *ptr!='*') ptr++;
383 if (*(ptr-1)=='-') i=-atof(ptr);
385 while ((*ptr>='0' && *ptr<='9') || *ptr=='.') ptr++;
390 // Removes the newline and other control characters at the end of a string (if present)
391 // and returns the new length of the string (-1 if str is NULL)
392 inline int chomp(char str[])
396 for (l=strlen(str)-1; l>=0 && str[l]<32; l--);
401 // Emulates the ifstream::getline method; similar to fgets(str,maxlen,FILE*),
402 // but removes the newline at the end and returns NULL if at end of file or read error
403 inline char* fgetline(char str[], const int maxlen, FILE* file)
405 if (!fgets(str,maxlen,file)) return NULL;
406 if (chomp(str)+1>=maxlen) // if line is cut after maxlen characters...
407 while (fgetc(file)!='\n'); // ... read in rest of line
411 // copies substring str[a,b] into substr and returns substr
412 char *substr(char* substr, char* str, int a, int b)
414 if (b<a) {int i=b; b=a; a=i;}
416 {printf("Function substr: >1000 chars to copy. Exiting.\n"); exit(6);}
420 while (*source!='\0' && source<=send) *(dest++) = *(source++);
426 // Returns pointer to first non-white-space character in str OR to NULL if none found
427 inline char* strscn(char* str)
429 if (!str) return NULL;
431 while (*ptr!='\0' && *ptr<=32) ptr++;
432 return (*ptr=='\0')? NULL: ptr;
435 // Returns pointer to first white-space character in str OR to NULL if none found /* MR1 */
436 inline char* strscn_ws(char* str)
438 if (!str) return NULL;
440 while (*ptr!='\0' && *ptr>32) ptr++;
441 return (*ptr=='\0')? NULL: ptr;
444 //Returns pointer to first non-white-space character in str OR to NULL if none found /* MR1 */
445 inline const char* strscn_c(const char* str)
447 if (!str) return NULL;
449 while (*ptr!='\0' && isspace(*ptr)) ptr++;
450 return (*ptr=='\0') ? NULL : ptr;
453 // Returns pointer to first non-white-space character in str OR to end of string '\0' if none found
454 inline char* strscn_(char* str)
456 if (!str) return NULL;
458 while (*ptr!='\0' && *ptr<=32) ptr++;
462 // Returns pointer to first non-c character in str OR to NULL if none found
463 inline char* strscn(char* str, const char c)
465 if (!str) return NULL;
467 while (*ptr!='\0' && *ptr==c) ptr++;
468 return (*ptr=='\0')? NULL: ptr;
471 // Returns pointer to first non-c character in str OR to end of string '\0' if none found
472 inline char* strscn_(char* str, const char c)
474 if (!str) return NULL;
476 while (*ptr!='\0' && *ptr==c) ptr++;
480 // Cuts string at first white space character found by overwriting it with '\0'.
481 // Returns pointer to next non-white-space char OR to NULL if no such char found
482 inline char* strcut(char* str)
484 if (!str) return NULL;
486 while (*ptr!='\0' && *ptr>32) ptr++;
487 if (*ptr=='\0') return NULL;
490 while (*ptr!='\0' && *ptr<=32) ptr++;
491 return (*ptr=='\0')? NULL:ptr;
494 // Cuts string at first white space character found by overwriting it with '\0'.
495 // Returns pointer to next non-white-space char OR to end of string '\0' if none found
496 inline char* strcut_(char* str)
498 if (!str) return NULL;
500 while (*ptr!='\0' && *ptr>32) ptr++;
501 if (*ptr=='\0') return ptr;
504 while (*ptr!='\0' && *ptr<=32) ptr++;
508 // Cuts string at first occurence of charcter c, by overwriting it with '\0'.
509 // Returns pointer to next char not equal c, OR to NULL if none found
510 inline char* strcut(char* str, const char c)
512 if (!str) return NULL;
514 while (*ptr!='\0' && *ptr!=c) ptr++;
515 if (*ptr=='\0') return NULL;
518 while (*ptr!='\0' && *ptr==c) ptr++;
519 return (*ptr=='\0')? NULL:ptr;
522 // Cuts string at first occurence of charcter c, by overwriting it with '\0'.
523 // Returns pointer to next char not equal c, OR to end of string '\0' if none found
524 inline char* strcut_(char* str, const char c)
526 if (!str) return NULL;
528 while (*ptr!='\0' && *ptr!=c) ptr++;
529 if (*ptr=='\0') return ptr;
532 while (*ptr!='\0' && *ptr==c) ptr++;
536 // Cuts string at first occurence of substr, by overwriting the first letter with '\0'.
537 // Returns pointer to next char after occurence of substr, OR to NULL if no such char found
538 inline char* strcut(char* str, const char* substr)
540 char* ptr; //present location in str being compared to substr
541 const char* sptr=substr; //present location in substr being compared to substr
542 // while not at end of str and not all of substr is matched yet
545 for (ptr=str, sptr=substr; *ptr==*sptr && *ptr!='\0'; ptr++, sptr++) ;
546 if (*sptr=='\0') {*str='\0'; return ptr;}
547 if (*ptr=='\0') return NULL;
552 // Cuts string at first occurence of substr, by overwriting the first letter with '\0'.
553 // Returns pointer to next char after occurence of substr, OR to end of string '\0' if no such char found
554 inline char* strcut_(char* str, const char* substr)
556 char* ptr; //present location in str being compared to substr
557 const char* sptr=substr; //present location in substr being compared to str
558 // while not at end of str and not all of substr is matched yet
561 for (ptr=str, sptr=substr; *ptr==*sptr && *ptr!='\0'; ptr++, sptr++) ;
562 if (*sptr=='\0') {*str='\0'; return ptr;}
563 if (*ptr=='\0') return ptr;
568 // Copies first word in ptr to str. In other words, copies first block of non whitespace characters,
569 // beginning at ptr, to str. If a word is found, returns address of second word in ptr or, if no second
570 // word is found, returns address to end of word ('\0' character) in ptr string. If no word is found
571 // in ptr NULL is returned.
572 inline char* strwrd(char* str, char* ptr)
574 ptr=strscn(ptr); // advance to beginning of next word
577 while (*ptr!='\0' && *ptr>32) *(str++) = *(ptr++);
579 while (*ptr!='\0' && *ptr<=32) ptr++;
585 // Copies first word ***delimited by char c*** in ptr to str. In other words, copies first block of non-c characters,
586 // beginning at ptr, to str. If a word is found, returns address of second word in ptr or, if no second
587 // word is found, returns address to end of word ('\0' character) in ptr string. If no word is found
588 // in ptr NULL is returned.
589 inline char* strwrd(char* str, char* ptr, const char c)
591 ptr=strscn(ptr,c); // advance to beginning of next word
594 while (*ptr!='\0' && *ptr!=c) *(str++) = *(ptr++);
596 while (*ptr!='\0' && *ptr==c) ptr++;
602 // Similar to Perl's tr/abc/ABC/: Replaces all chars in str found in one list with characters from the second list
603 // Returns the number of replaced charactrs
604 int strtr(char* str, const char oldchars[], const char newchars[])
609 for (ptr=str; *ptr!='\0'; ptr++)
610 for (plist=oldchars; *plist!='\0'; plist++)
613 *ptr=newchars[plist-oldchars];
620 // Similar to Perl's tr/abc//d: deletes all chars in str found in the list
621 // Returns number of removed characters
622 int strtrd(char* str, const char chars[])
629 for (plist=chars; *plist!='\0'; plist++)
630 if (*ptr1==*plist) break;
631 if (*plist=='\0') {*ptr0=*ptr1; ptr0++;}
637 // Similar to Perl's tr/a-z//d: deletes all chars in str found in the list
638 // Returns number of removed characters
639 int strtrd(char* str, char char1, char char2)
645 if (*ptr1>=char1 && *ptr1<=char2) {*ptr0=*ptr1; ptr0++;}
651 // transforms str into an all uppercase string
652 char* uprstr(char* str)
655 while (*s !='\0') {if (*s>='a' && *s<='z') *s+='A'-'a';s++;}
659 // transforms str into an all uppercase string
660 char* lwrstr(char* str)
663 while (*s !='\0') {if (*s>='A' && *s<='Z') *s+='a'-'A'; s++;}
667 // transforms chr into an uppercase character
668 inline char uprchr(char chr)
670 return (chr>='a' && chr<='z')? chr+'A'-'a' : chr;
673 // transforms chr into an lowercase character
674 inline char lwrchr(char chr)
676 return (chr>='A' && chr<='Z')? chr-'A'+'a' : chr;
680 // Replaces first occurence of str1 by str2 in str. Returns pointer to first occurence or NULL if not found
681 // ATTENTION: if str2 is longer than str1, allocated memory of str must be long enough!!
682 inline char* strsubst(char* str, const char str1[], const char str2[])
684 char* ptr = strstr(str,str1);
689 // Gives elapsed time since first call to this function
690 inline void ElapsedTimeSinceFirstCall(const char str[])
693 static double tfirst=0;
696 gettimeofday(&t, NULL);
697 tfirst = 1E-6*t.tv_usec + t.tv_sec;
699 gettimeofday(&t, NULL);
700 printf("Elapsed time since first call:%12.3fs %s\n",1E-6*t.tv_usec + t.tv_sec - tfirst,str);
703 // Gives elapsed time since last call to this function
704 inline void ElapsedTimeSinceLastCall(const char str[])
707 static double tlast=0.0;
710 gettimeofday(&t, NULL);
711 tlast = 1.0E-6*t.tv_usec + t.tv_sec;
713 gettimeofday(&t, NULL);
714 printf("Elapsed time since last call:%12.3fs %s\n",1.0E-6*t.tv_usec + t.tv_sec - tlast,str);
715 tlast = 1.0E-6*t.tv_usec + t.tv_sec;
718 inline char* RemovePath(char outname[], char filename[])
722 ptr=strrchr(filename,92); //return adress for LAST \ (backslash) in name
724 ptr=strrchr(filename,'/'); //return adress for LAST / in name
726 if (!ptr) ptr=filename; else ptr++;
731 inline char* RemoveExtension(char outname[], char filename[])
734 ptr1=strrchr(filename,'.'); //return adress for LAST '.' in name
735 if (ptr1) {*ptr1='\0'; strcpy(outname,filename); *ptr1='.';} else strcpy(outname,filename);
739 inline char* RemovePathAndExtension(char outname[], char filename[])
743 ptr=strrchr(filename,92); //return adress for LAST \ (backslash) in name
745 ptr=strrchr(filename,'/'); //return adress for LAST / in name
747 if (!ptr) ptr=filename; else ptr++;
748 ptr1=strrchr(filename,'.'); //return adress for LAST '.' in name
749 if (ptr1) {*ptr1='\0'; strcpy(outname,ptr); *ptr1='.';} else strcpy(outname,ptr);
753 inline char* Extension(char extension[], char filename[])
756 ptr=strrchr(filename,'.'); //return adress for LAST '.' in name
757 if (ptr) strcpy(extension,ptr+1); else *extension='\0';
761 // Path includes last '/'
762 inline char* Pathname(char pathname[], char filename[])
767 ptr=strrchr(filename,92); //return adress for LAST \ (backslash) in name
769 ptr=strrchr(filename,'/'); //return adress for LAST / in name
771 if (ptr) {chr=*(++ptr); *ptr='\0'; strcpy(pathname,filename); *ptr=chr;} else *pathname='\0';
775 // Swaps two integer elements in array k
776 inline void swapi(int k[], int i, int j)
779 temp=k[i]; k[i]=k[j]; k[j]=temp;
782 // QSort sorting routine. time complexity of O(N ln(N)) on average
783 // Sorts the index array k between elements i='left' and i='right' in such a way that afterwards
784 // v[k[i]] is sorted downwards (up=-1) or upwards (up=+1)
785 void QSortInt(int v[], int k[], int left, int right, int up=+1)
788 int last; // last element to have been swapped
790 if (left>=right) return; // do nothing if less then 2 elements to sort
791 // Put pivot element in the middle of the sort range to the side (to position 'left') ...
792 swapi(k,left,(left+right)/2);
794 // ... and swap all elements i SMALLER than the pivot
795 // with an element that is LARGER than the pivot (element last+1):
798 for (i=left+1; i<=right; i++)
799 if (v[k[i]]<v[k[left]]) swapi(k,++last,i);
802 for (i=left+1; i<=right; i++)
803 if (v[k[i]]>v[k[left]]) swapi(k,++last,i);
805 // Put the pivot to the right of the elements which are SMALLER, left to elements which are LARGER
808 // Sort the elements left from the pivot and right from the pivot
809 QSortInt(v,k,left,last-1,up);
810 QSortInt(v,k,last+1,right,up);
813 // QSort sorting routine. time complexity of O(N ln(N)) on average
814 // Sorts the index array k between elements i='left' and i='right' in such a way that afterwards
815 // v[k[i]] is sorted downwards (up=-1) or upwards (up=+1)
816 void QSortFloat(float v[], int k[], int left, int right, int up=+1)
819 int last; // last element to have been swapped
820 void swapi(int k[], int i, int j);
822 if (left>=right) return; // do nothing if less then 2 elements to sort
823 // Put pivot element in the middle of the sort range to the side (to position 'left') ...
824 swapi(k,left,(left+right)/2);
826 // ... and swap all elements i SMALLER than the pivot
827 // with an element that is LARGER than the pivot (element last+1):
830 for (i=left+1; i<=right; i++)
831 if (v[k[i]]<v[k[left]]) swapi(k,++last,i);
834 for (i=left+1; i<=right; i++)
835 if (v[k[i]]>v[k[left]]) swapi(k,++last,i);
837 // Put the pivot to the right of the elements which are SMALLER, left to elements which are LARGER
840 // Sort the elements left from the pivot and right from the pivot
841 QSortFloat(v,k,left,last-1,up);
842 QSortFloat(v,k,last+1,right,up);
846 * @brief comparison function for qsort,
847 * sorts floating point numbers ascendingly
849 * @param cv1 ponter to 1st entry to be sorted
850 * @param cv2 ponter to 2nd entry to be sorted
852 * @return 0 if entries are equal,
853 * +/-1 if 1st greater/smaller than 2nd
855 int CompFltAsc(const void *cv1, const void *cv2){
857 float f1 = *(float *)cv1;
858 float f2 = *(float *)cv2;
860 if (f1 > f2) { return +1; }
861 else if (f1 < f2) { return -1; }
864 } /* this is the end of CompFltAsc() */
866 //Return random number in the range [0,1]
867 inline float frand() { return rand()/(RAND_MAX+1.0); }
870 /////////////////////////////////////////////////////////////////////////////////////
871 //// Execute system command
872 /////////////////////////////////////////////////////////////////////////////////////
873 void runSystem(std::string cmd, int v = 2)
876 cout << "Command: " << cmd << "!\n";
877 int res = system(cmd.c_str());
880 cerr << endl << "ERROR when executing: " << cmd << "!\n";