30 #include <sys/types.h> 58 #if __cplusplus >= 201103L 77 struct timeval st_time;
78 gettimeofday(&st_time,0);
79 return (
unsigned long)(st_time.tv_usec/1000 + st_time.tv_sec*1000);
82 GetSystemTime(&st_time);
83 return (
unsigned long)(st_time.wMilliseconds + 1000*(st_time.wSecond + 60*(st_time.wMinute + 60*st_time.wHour)));
91 TicToc(
const bool is_tic, std::ostream& os=std::cout)
93 static unsigned long t0 = 0;
94 const unsigned long t =
Time();
95 if (is_tic)
return (t0 = t);
98 edays = (
unsigned int)(dt/86400000.0),
99 ehours = (
unsigned int)((dt - edays*86400000.0)/3600000.0),
100 emin = (
unsigned int)((dt - edays*86400000.0 - ehours*3600000.0)/60000.0),
101 esec = (
unsigned int)((dt - edays*86400000.0 - ehours*3600000.0 - emin*60000.0)/1000.0),
102 ems = (
unsigned int)(dt - edays*86400000.0 - ehours*3600000.0 - emin*60000.0 - esec*1000.0);
103 if (!edays && !ehours && !emin && !esec)
104 os <<
"[UTL] Elapsed time: " << ems <<
" ms" << std::endl << std::flush;
106 if (!edays && !ehours && !emin)
107 os <<
"[UTL] Elapsed time: " << esec <<
" sec "<< ems <<
" ms" << std::endl << std::flush;
109 if (!edays && !ehours)
110 os <<
"[UTL] Elapsed time: " << emin <<
" min " << esec <<
" sec "<< ems <<
" ms" << std::endl << std::flush;
113 os <<
"[UTL] Elapsed time: " << ehours <<
" hours "<< emin <<
" min " << esec <<
" sec "<< ems <<
"ms" << std::endl << std::flush;
115 os <<
"[UTL] Elapsed time: " << edays <<
" dats " << ehours <<
" hours "<< emin <<
" min " << esec <<
" sec "<< ems <<
"ms" << std::endl << std::flush;
128 Tic(std::ostream& os=std::cout)
138 Toc(std::ostream& os=std::cout)
143 template<
class Parent>
152 Help(
const void*
object) : is(false) { }
153 Help(
const T*
object) : is(true) { }
155 operator bool() {
return is; }
161 template<
class Object>
164 operator bool() {
return is; }
167 template<
class Parent,
class Object>
176 SwapBytes(
void *ptr,
const int sizePerElement,
const int count)
178 char minibuf[32], *buffer=(
char *)ptr;
179 for (
int y=0; y<count; y++)
181 for (
int x=0; x<sizePerElement; x++)
182 minibuf[x] = *(buffer++);
183 for (
int x=0; x<sizePerElement; x++)
184 *(--buffer) = minibuf[x];
185 buffer+=sizePerElement;
189 template <
typename T>
193 const unsigned int N = values.size();
194 std::nth_element(values.begin(),values.begin()+N/2,values.end());
211 template <
class Iterator>
212 inline unsigned int argmin(Iterator i1, Iterator i2)
216 for ( Iterator ii = i1; ii!=iter; ++ii )
221 template <
class Iterator>
222 inline unsigned int argmax(Iterator i1, Iterator i2)
226 for ( Iterator ii = i1; ii!=iter; ++ii )
232 template <
class VectorType>
234 argmax2(
const VectorType& vec,
int size,
int& index0,
int& index1)
239 for (
int i = 0; i < size; ++i )
248 else if (vec[i] > max1)
257 template<
typename T>
inline const T&
min(
const T& a,
const T& b) {
return a<=b?a:b; }
259 template<
typename T>
inline const T&
min(
const T& a,
const T& b,
const T& c) {
return min(
min(a,b),c); }
261 template<
typename T>
inline const T&
min(
const T& a,
const T& b,
const T& c,
const T& d) {
return min(
min(
min(a,b),c),d); }
263 template<
typename T>
inline const T&
max(
const T& a,
const T& b) {
return a>=b?a:b; }
265 template<
typename T>
inline const T&
max(
const T& a,
const T& b,
const T& c) {
return max(
max(a,b),c); }
267 template<
typename T>
inline const T&
max(
const T& a,
const T& b,
const T& c,
const T& d) {
return max(
max(a,b,c),d); }
269 #define __utl_minmax(T0_, T1_, T2_) \ 270 inline const T0_ min(const T1_ a, const T2_ b) {return a<=b?a:b; } \ 271 inline const T0_ min(const T2_ a, const T1_ b) {return a<=b?a:b; } \ 272 inline const T0_ max(const T1_ a, const T2_ b) {return a>=b?a:b; } \ 273 inline const T0_ max(const T2_ a, const T1_ b) {return a>=b?a:b; } 285 template<
typename T>
inline int sign(
const T& x) {
return (x<0)?-1:(x==0?0:1); }
287 template<
typename T>
inline T
square(
const T& x) {
return x*x; }
289 template<
typename T>
inline T
cube(
const T& x) {
return x*x*x; }
294 std::string result(str);
295 for (std::string::iterator c = result.begin(); c != result.end(); ++c)
303 std::string result(str);
304 for (std::string::iterator c = result.begin(); c != result.end(); ++c)
321 const char *src = source.c_str();
322 char *searchPos =
const_cast<char *
>(strstr(src,replace));
331 size_t replaceSize = strlen(replace);
337 char *orig = strdup(src);
338 char *currentPos = orig;
339 searchPos = searchPos - src + orig;
342 source.erase(source.begin(),source.end());
346 source += currentPos;
347 currentPos = searchPos + replaceSize;
350 searchPos = strstr(currentPos,replace);
355 source += currentPos;
365 ret.reserve(strlen(path)+3);
369 std::string::size_type pos = 0;
371 while((pos = ret.find(
'/', pos)) != std::string::npos)
393 while((pos = ret.find(
"\\\\", pos)) != std::string::npos)
399 if(ret.find(
' ') != std::string::npos
402 ret.insert(static_cast<std::string::size_type>(0),
403 static_cast<std::string::size_type>(1),
'\"');
413 std::string ret = path;
416 std::string::size_type pos=1;
417 while((pos = ret.find(
"//", pos)) != std::string::npos)
422 if(ret.find_first_of(
" ") != std::string::npos)
424 std::string result =
"";
426 for(
const char* ch = ret.c_str(); *ch !=
'\0'; ++ch)
429 if((*ch ==
' ') && lastch !=
'\\')
444 const char* pathCString = path.c_str();
445 bool hasDoubleSlash =
false;
447 const char* pos0 = pathCString;
448 const char* pos1 = pathCString+1;
449 for (std::string::size_type pos = 0; *pos0; ++ pos )
452 if ( *pos0 ==
'\\' && *pos1 !=
' ' )
458 if (*pos1 ==
'/' && *(pos1+1) ==
'/' && !hasDoubleSlash)
465 hasDoubleSlash =
true;
468 hasDoubleSlash =
true;
476 if ( hasDoubleSlash )
485 pathCString = path.c_str();
486 if(pathCString[0] ==
'~' && (pathCString[1] ==
'/' || pathCString[1] ==
'\0'))
488 const char* homeEnv = getenv(
"HOME");
491 path.replace(0,1,homeEnv);
496 pathCString = path.c_str();
497 if(path.size() > 1 && *(pathCString+(path.size()-1)) ==
'/')
500 if(!((path.size() == 3 && pathCString[1] ==
':')))
502 path = path.substr(0, path.size()-1);
517 std::string result(path);
531 std::ifstream ii(file.c_str());
537 IsEndingWith(
const std::string& fullString,
const std::string& ending )
539 if (fullString.length() >= ending.length())
540 return (0 == fullString.compare (fullString.length() - ending.length(), ending.length(), ending));
550 GetPath(
const std::string& fileNameAbsolute, std::string& path, std::string& file)
552 size_t found = fileNameAbsolute.find_last_of(
"/\\");
553 path = fileNameAbsolute.substr( 0, found + 1);
554 file = fileNameAbsolute.substr( found + 1);
559 GetFileExtension(
const std::string& fileNameAbsolute, std::string& ext, std::string& fileNoExt)
561 size_t found = fileNameAbsolute.find_last_of(
".");
562 ext = fileNameAbsolute.substr(found + 1);
563 fileNoExt = fileNameAbsolute.substr(0,found);
572 size_t found2 = fileNoExt.find_last_of(
".");
573 std::string ext2 = fileNoExt.substr(found2 + 1);
577 fileNoExt = fileNoExt.substr(0,found2);
586 ZeroPad(
const unsigned int number,
const unsigned int paddedLength)
588 std::stringstream padded;
589 padded << std::setfill(
'0') << std::setw(paddedLength) << number;
595 GetSequentialFileName(
const std::string& filePrefix,
const unsigned int iteration,
const std::string& fileExtension,
const unsigned int paddedLength=6)
597 std::stringstream padded;
598 padded << filePrefix <<
"_" <<
ZeroPad(iteration, paddedLength) <<
"." << fileExtension;
604 inline std::vector<std::string>
607 std::vector<std::string> vec;
608 for (
int i = 0; i < N; ++i )
610 std::string ss(arr[i]);
621 for (
int i = 0; i < N; ++i )
625 strcpy(arr[i], vec[i].c_str());
635 template<
class VectorType>
643 for(
unsigned int i = 0; i < nSize; i++)
651 for(
unsigned int i = 0; i < v.size(); i++)
654 norm[i] = ((v[i]-min)/(max-
min));
663 inline std::vector<T>
666 return NormalizeMinMax<std::vector<T> >(v, v.size());
670 template<
class VectorType>
676 for(
unsigned int i = 0; i < nSize; i++)
680 double normsqrt = std::sqrt(norm);
681 for (
int i = 0; i < v.size(); i += 1 )
688 inline std::vector<T>
691 return NormalizeUnitNorm<std::vector<T> >(v, v.size());
695 template<
class VectorType>
702 for(
unsigned int i = 0; i < nSize; i++)
708 for(
unsigned int i = 0; i < nSize; i++)
718 inline std::vector<T>
721 return NormalizeMax<std::vector<T> >(v, v.size());
731 double number = strtod(input.c_str(),&pend);
742 std::ostringstream strs;
743 strs.precision(precision);
761 std::istringstream ss(input);
769 template <
class VectorType>
773 std::ostringstream ss;
774 for (
int i = 0; i < N; ++i )
787 return x>=0 ? std::floor(x+0.5) : std::ceil(x-0.5);
792 IsInt(
const std::string& input,
const double epss=1e-10)
797 double dd = strtod(input.c_str(),&pend);
800 double diff = dd - (long)(dd);
801 return diff<epss && diff>-epss;
805 IsInt(
const double dd,
const double epss=1e-10)
807 double diff = dd - (long)(dd);
808 return diff<epss && diff>-epss;
812 IsInt(
const float dd,
const double epss=1e-10)
814 double diff = dd - (long)(dd);
815 return diff<epss && diff>-epss;
821 return (value % 2 == 0);
831 template <
class VectorType>
835 for(
unsigned int i = 0; i < size; ++i)
845 SplitString (
const std::string& str, std::vector<std::string>& strVec,
const char* cc=
" ")
848 char str2[str.size()+1];
849 for (
int i = 0; i < str.size(); i += 1 )
851 str2[str.size()]=
'\0';
852 char *pch = strtok(str2, cc);
855 strVec.push_back(std::string(pch));
856 pch = strtok(NULL, cc);
862 ReadLines (
const std::string& filename, std::vector < std::vector<std::string> >& strVec,
const char* cc=
" ")
867 std::ifstream infile(filename.c_str(), std::ios_base::in);
869 while (std::getline(infile, line,
'\n'))
871 std::vector<std::string> tmp;
881 strVec.push_back(tmp);
893 if (strVec.size()>0 && strVec[0].size()==1 &&
IsInt(strVec[0][0]))
896 std::istringstream ( strVec[0][0] ) >> nSize;
897 if (nSize+1==strVec.size())
899 std::vector<std::vector<std::string> > strVec_back(strVec);
901 for (
int i = 1; i < strVec_back.size(); i += 1 )
902 strVec.push_back(strVec_back[i]);
907 template <
class TVectorType>
912 for (
int i = 0; i < NSize; i += 1 )
919 template <
class IteratorType>
920 inline std::vector<double>
924 return std::vector<double>(4,0);
926 double m = *v1, M = m;
927 double S = 0, S2 = 0;
929 for ( IteratorType ptr=v1; ptr!=v2; ++ptr )
931 const double val = *ptr;
940 double mean = S/(double)n;
941 double variance = n>1?(S2 - S*S/n)/(n-1):0;
942 variance = std::sqrt(variance);
944 std::vector<double> result(4);
945 result[0]=m, result[1]=M, result[2]=mean, result[3]=variance;
950 inline std::vector<double>
951 GetContainerStats<const std::complex<double>*> (
const std::complex<double>* v1,
const std::complex<double>* v2 )
953 return std::vector<double>(4,0);
957 inline std::vector<double>
958 GetContainerStats<std::complex<double>*> ( std::complex<double>* v1, std::complex<double>* v2 )
960 return std::vector<double>(4,0);
964 inline std::vector<double>
965 GetContainerStats<std::complex<float>*> ( std::complex<float>* v1, std::complex<float>* v2 )
967 return std::vector<double>(4,0);
971 inline std::vector<double>
972 GetContainerStats<const std::complex<float>*> (
const std::complex<float>* v1,
const std::complex<float>* v2 )
974 return std::vector<double>(4,0);
978 inline std::vector<double>
979 GetContainerStats<const std::string*> (
const std::string* v1,
const std::string* v2 )
981 return std::vector<double>(4,0);
984 template <
class IteratorType>
992 for ( IteratorType ptr=v; ptr != v2; ++ptr )
1000 template <
typename T>
1002 PrintVector (
const std::vector<T>& vec,
const std::string& str=
"",
const char* separate=
" ", std::ostream& os=std::cout,
bool showStats=
true)
1008 sprintf(tmp,
"%-8s(%p): size = %lu, stat = { %g, %g [%g], %g } : ", str==
""?
"vector":str.c_str(), &vec, vec.size(), st[0], st[2], st[3], st[1] );
1011 sprintf(tmp,
"%-8s(%p): size = %lu : ", str==
""?
"vector":str.c_str(), &vec, vec.size() );
1012 std::string strr(tmp);
1015 os << strr <<
" = [ ";
1016 for (
int i = 0; i < vec.size(); i += 1 )
1017 os << vec[i] << separate;
1018 os <<
"];\n" << std::flush;
1021 os << strr <<
" is an empty vector" << std::endl;
1026 PrintVector<std::string> (
const std::vector<std::string>& vec,
const std::string& str,
const char* separate, std::ostream& os,
bool showStats)
1029 sprintf(tmp,
"%-8s(%p): size = %lu, : ", str==
""?
"vector":str.c_str(), &vec, vec.size());
1030 std::string strr=tmp;
1033 os << strr <<
" = [ ";
1034 for (
int i = 0; i < vec.size(); i += 1 )
1035 os << vec[i] << separate;
1036 os <<
"];\n" << std::flush;
1039 os << strr <<
" is an empty vector" << std::endl;
1042 template <
class VectorType>
1044 PrintVector (
const VectorType& vec,
const int NSize,
const std::string& str=
"",
const char* separate=
" ", std::ostream& os=std::cout,
bool showStats=
true)
1050 sprintf(tmp,
"%-8s(%p): size = %lu, stat = { %g, %g [%g], %g } : ", str==
""?
"vector":str.c_str(), &vec, (
long unsigned int)NSize, st[0], st[2], st[3], st[1] );
1053 sprintf(tmp,
"%-8s(%p): size = %lu : ", str==
""?
"vector":str.c_str(), &vec, (
long unsigned int)NSize );
1054 std::string strr(tmp);
1057 os << strr <<
" = [ ";
1058 for (
int i = 0; i < NSize; i += 1 )
1059 os << vec[i] << separate;
1060 os <<
"];\n" << std::flush;
1063 os << strr <<
" is an empty vector" << std::endl;
1066 template <
class IteratorType>
1068 PrintContainer ( IteratorType v1, IteratorType v2,
const std::string& str=
"",
const char* separate=
" ", std::ostream& os=std::cout,
bool showStats=
true)
1070 long unsigned int NSize=0;
1071 IteratorType q = v1;
1072 for ( ; q!=v2; ++q )
1079 sprintf(tmp,
"%-8s(%p): size = %lu, stat = { %g, %g [%g], %g } : ", str==
""?
"vector":str.c_str(), v1, NSize, st[0], st[2], st[3], st[1] );
1082 sprintf(tmp,
"%-8s(%p): size = %lu : ", str==
""?
"vector":str.c_str(), v1, NSize );
1084 std::string strr(tmp);
1087 os << strr <<
" = [ ";
1088 IteratorType q = v1;
1089 for ( ; q!=v2; ++q )
1090 os << (*q) << separate;
1091 os <<
"];\n" << std::flush;
1094 os << strr <<
" is an empty container" << std::endl;
1103 for (l=0; l<=strlen(s) && s[l]!=c; l++)
1113 template <
typename T>
1115 SetVector(
const char *s, std::vector<T>& vec,
const int least_num=0,
const char& c=
',')
1126 for (l=0; l<=strlen(s); l++)
1128 if (s[l]==c || s[l]==
'\0')
1132 T ftmp = (T)atof(temp);
1133 vec.push_back(ftmp);
1143 utlAssert(least_num==0 || vec.size()>=least_num,
"no enough numbers were imported in vector");
1146 utlAssert(least_num==0 || vec.size()>=least_num,
"no enough numbers were imported in vector");
1150 template <
typename T>
1152 SetVector(
const std::string& s, std::vector<T>& vec,
const int least_num=0,
const char& c=
',')
1154 return SetVector(s.c_str(), vec, least_num, c);
1157 template <
class T >
1159 ReadVector (
const std::string& vectorStr, std::vector<T>& vec,
const char* cc=
" ")
1164 std::vector<std::vector<std::string> > strVec;
1168 bool isRowVector = strVec.size()==1;
1171 for (
int i = 0; i < strVec[0].size(); i += 1 )
1172 vec.push_back(ConvertStringToNumber<T>(strVec[0][i]));
1176 for (
int i = 0; i < strVec.size(); i += 1 )
1178 utlException(strVec[i].size()!=1,
"should keep one float number in one line");
1179 vec.push_back(ConvertStringToNumber<T>(strVec[i][0]));
1186 ReadVector<std::string> (
const std::string& vectorStr, std::vector<std::string>& vec,
const char* cc)
1191 std::vector<std::vector<std::string> > strVec;
1195 bool isRowVector = strVec.size()==1;
1198 for (
int i = 0; i < strVec[0].size(); i += 1 )
1199 vec.push_back(strVec[0][i]);
1203 for (
int i = 0; i < strVec.size(); i += 1 )
1205 utlException(strVec[i].size()!=1,
"should keep one float number in one line");
1206 vec.push_back(strVec[i][0]);
1211 template <
typename VectorType>
1213 SaveVector (
const VectorType& vv,
const int NSize,
const std::string& vectorStr,
const bool is_save_number=
false)
1216 out.open ( vectorStr.c_str() );
1217 utlException(!out,
"\nERROR : failed to open output file " << vectorStr );
1220 out << NSize <<
"\n";
1221 for (
int i = 0; i < NSize; i += 1 )
1222 out << vv[i] <<
"\n";
1226 template <
typename T>
1228 SaveVector (
const std::vector<T>& vv,
const std::string& vectorStr,
const bool is_save_number=
false)
1230 int NSize = vv.size();
1231 SaveVector<std::vector<T> >(vv, NSize, vectorStr, is_save_number);
1234 template <
typename T>
1235 inline std::vector<int>
1238 std::vector<int> index;
1239 for (
int i = 0; i < vec.size(); i += 1 )
1241 if (std::fabs(elem-vec[i])<gap)
1248 inline std::vector<int>
1249 FindVector<std::string> (
const std::vector<std::string>& vec,
const std::string& elem,
const double )
1251 std::vector<int> index;
1252 for (
int i = 0; i < vec.size(); i += 1 )
1260 template <
typename T>
1261 std::vector<std::vector<int> >
1264 std::vector<std::vector<int> > index;
1267 for (
int i = 0; i < vec.size(); i += 1 )
1269 bool is_test =
false;
1270 for (
int i_ind = 0; i_ind < index.size(); i_ind += 1 )
1272 for (
int j_ind = 0; j_ind < index[i_ind].size(); j_ind += 1 )
1274 if (i==index[i_ind][j_ind])
1286 vec_sep.push_back(vec[i]);
1287 std::vector<int> index_tmp =
FindVector(vec, vec[i], gap);
1288 index.push_back(index_tmp);
1292 for (
int m = 0; m < index.size(); m += 1 )
1295 for (
int n = 0; n < index[m].size(); n += 1 )
1296 sum += vec[index[m][n]];
1297 vec_sep[m] = sum/(double)index[m].size();
1302 template <
typename T>
1306 for (
int i = 0; i < vec2.size(); i += 1 )
1307 vec1.push_back(vec2[i]);
1310 template <
typename T>
1314 std::vector<T> select;
1315 for (
int i = 0; i < index.size(); i += 1 )
1317 select.push_back( vec[index[i]] );
1322 template <
typename T>
1324 SelectVector (
const std::vector<T>& vec,
const int startIndex,
const int numberOfElement )
1326 std::vector<T> select;
1327 for (
int i = 0; i < numberOfElement; i += 1 )
1329 if (startIndex+i<vec.size())
1330 select.push_back( vec[startIndex+i] );
1337 IsSame (
const T& value,
const T& v0,
const double eps=1e-10 )
1339 return std::fabs(value-v0)<eps;
1351 IsSame<std::string>(
const std::string& value,
const std::string& v0,
const double)
1365 IsSameVector(
const std::vector<T>& vec1,
const std::vector<T>& vec2,
const double eps=1e-10)
1367 if (vec1.size()!=vec2.size())
1369 for (
int i = 0; i < vec1.size(); ++i )
1371 if (!IsSame<T>(vec1[i], vec2[i], eps))
1378 template <
class T,
size_t N1,
size_t N2 >
1380 IsSameArray (
const T (&a1)[N1],
const T (&a2)[N2],
const double eps=1e-10 )
1384 for (
int i = 0; i < N1; ++i )
1386 if (!IsSame<T>(a1[i], a2[i], eps))
1392 template <
class VectorType,
class T>
1394 IsInVector (
const VectorType& vec,
const int size,
const T& num,
const double eps=1e-10 )
1396 for (
int i = 0; i < size; i += 1 )
1398 if (IsSame<T>(vec[i], num, eps))
1404 template <
typename T>
1406 IsInVector (
const std::vector<T>& vec,
const T& num,
const double eps=1e-10 )
1408 return IsInVector<std::vector<T>, T>(vec, vec.size(), num, eps);
1413 template <
typename T >
1415 Random(
const T d1 = T(0.0),
const T d2 = T(1.0) )
1418 static bool first_time =
true;
1421 std::srand(std::time(NULL));
1424 T ra = 1e-10 + (1-2e-10) * std::rand() / RAND_MAX;
1425 return (d2 - d1)*ra + d1;
1434 utlAssert(d2>d1,
"wrong setting, d1="<<d1 <<
", d2="<<d2);
1435 static bool first_time =
true;
1438 std::srand(std::time(NULL));
1442 int rand_tmp = std::rand() % (tmp+1);
1443 return rand_tmp + d1;
1446 template <
typename T >
1447 inline std::vector<T>
1448 RandomVec(
const std::vector<T>& vec,
const int num, std::vector<int>& result_index)
1450 utlAssert(vec.size()>num && num>0,
"wrong size, vec.size()="<<vec.size() <<
", num="<<num);
1451 result_index.clear();
1452 std::vector<T> result;
1453 static bool first_time =
true;
1456 std::srand(std::time(NULL));
1459 for (
int nn = 0; nn < num; nn += 1 )
1461 int i =
RandomInt(0, vec.size()-num+nn);
1462 bool is_choose =
false;
1463 for (
int n_i = 0; n_i < result_index.size(); n_i += 1 )
1465 if (i==result_index[n_i])
1473 result_index.push_back(i);
1474 result.push_back(vec[i]);
1478 result_index.push_back(vec.size()-num+nn);
1479 result.push_back(vec[vec.size()-num+nn]);
1488 inline std::vector<double>
1491 std::vector<double> result(3);
1494 result[0] = std::sqrt(1-u*u)*std::cos(theta);
1495 result[1] = std::sqrt(1-u*u)*std::sin(theta);
1502 template <
typename T >
1508 static bool first_time =
true;
1511 std::srand(std::time(NULL));
1516 U1 = 1e-10 + (1-2e-10) * std::rand() / RAND_MAX;
1517 U2 = 1e-10 + (1-2e-10) * std::rand() / RAND_MAX;
1518 A = std::sqrt(-2*std::log(U1))*std::cos(2*
M_PI*U2);
1519 return (value + sigma*A);
1524 template <
typename T >
1530 static bool first_time =
true;
1533 std::srand(std::time(NULL));
1537 T real_part = value;
1543 T noise_real = real_part + n1;
1544 T noise_imag = imag_part + n2;
1546 T noise = std::sqrt(noise_real*noise_real + noise_imag*noise_imag);
1550 template <
typename VectorType>
1552 AddNoise(
const VectorType& signal,
const int size,
const double sigma,
const bool is_rician=
true)
1557 VectorType result(signal);
1558 for (
int i = 0; i < size; i += 1 )
1568 template <
typename T >
1569 inline std::vector<T>
1570 AddNoise(
const std::vector<T>& signal,
const double sigma,
const bool is_rician=
true)
1572 return AddNoise(signal, signal.size(), sigma, is_rician);
1577 template <
typename T >
1581 r = sqrt(x*x + y*y + z*z);
1584 theta = std::acos( z / r );
1585 phi = std::atan2( y, x );
1591 template <
typename T >
1600 template <
typename T >
1604 x = r * std::sin(theta) * std::cos(phi);
1605 y = r * std::sin(theta) * std::sin(phi);
1606 z = r * std::cos(theta);
1609 template <
typename T >
1617 template <
class IteratorType>
1621 for ( IteratorType ptr=v1; ptr != v2; ++ptr )
1622 *ptr = std::pow(*ptr, poww);
1625 template <
class VectorType>
1629 VectorType result(num);
1631 result[0] = valueMin;
1634 double step = (valueMax-valueMin)/(
double)(num-1);
1635 for (
int i = 0; i < num; i += 1 )
1636 result[i] = valueMin+step*i;
1641 inline std::vector<int>
1642 GetRange (
const int start,
const int end,
const int space=1)
1644 std::vector<int> result;
1648 result.push_back(val);
1650 }
while ( val < end );
1654 template <
class VectorType>
1658 for (
int i = 0; i < N; i += 1 )
1659 vec[i] = (vec[i]>=kappa) ? (vec[i]-kappa) : ( (vec[i]<=-kappa) ? (vec[i]+kappa) : 0.0 );
1662 template <
class VectorType>
1666 VectorType result(vec);
1671 template <
class VectorType>
1675 for (
int i = 0; i < N; i += 1 )
1679 template <
class VectorType>
1683 VectorType result(vec);
1688 template <
class T1,
class T2>
1692 for (
int i = 0; i < N; i += 1 )
1693 vec[i] = flip[i]? -vec[i] : vec[i];
1697 template <
class T1,
class T2>
1701 for (
int i = 0; i < N; i += 1 )
1706 template <
class T1,
class T2>
1710 for (
int i = 0; i < NRows; i += 1 )
1711 for (
int j = 0; j < NColumns; j += 1 )
1712 mat2(i,j) = mat1(i,j);
1716 template <
class TMatrixType>
1718 PrintMatrixStats (
const TMatrixType& matrix,
const int NumberRows,
const int NumberColumns,
const std::string& str=
"",
const char* separate=
" ", std::ostream& os=std::cout )
1721 std::vector<double> st = NumberRows*NumberColumns>0 ?
GetContainerStats(&matrix(0,0), &matrix(0,0)+NumberRows*NumberColumns) : std::vector<double>(4,0);
1722 sprintf(tmp,
"%-8s(%p): size = (%d, %d), stat = { %g, %g [%g], %g } : ", str==
""?
"matrix":str.c_str(), &matrix, NumberRows, NumberColumns, st[0], st[2], st[3], st[1] );
1723 std::string strr(tmp);
1724 if (NumberRows>0 && NumberColumns>0)
1725 os << strr << std::endl;
1728 template <
class TMatrixType>
1730 PrintMatrix (
const TMatrixType& matrix,
const int NumberRows,
const int NumberColumns,
const std::string& str=
"",
const char* separate=
" ", std::ostream& os=std::cout,
bool showStats=
true )
1735 std::vector<double> st = NumberRows*NumberColumns>0 ?
GetContainerStats(&matrix(0,0), &matrix(0,0)+NumberRows*NumberColumns) : std::vector<double>(4,0);
1736 sprintf(tmp,
"%-8s(%p): size = (%d, %d), stat = { %g, %g [%g], %g } : ", str==
""?
"matrix":str.c_str(), &matrix, NumberRows, NumberColumns, st[0], st[2], st[3], st[1] );
1739 sprintf(tmp,
"%-8s(%p): size = (%d, %d) : ", str==
""?
"matrix":str.c_str(), &matrix, NumberRows, NumberColumns );
1740 std::string strr(tmp);
1742 if (NumberRows>0 && NumberColumns>0)
1744 os << strr <<
" = [ ";
1745 for (
int i = 0; i < NumberRows-1; i += 1 )
1747 for (
int j = 0; j < NumberColumns-1; j += 1 )
1748 os << matrix(i,j)<< separate;
1749 os << matrix(i,NumberColumns-1) <<
"; ";
1751 for (
int j = 0; j < NumberColumns-1; j += 1 )
1752 os << matrix(NumberRows-1,j)<< separate;
1753 os << matrix(NumberRows-1,NumberColumns-1) <<
"];\n" << std::flush;
1756 os << strr <<
" is an empty matrix" << std::endl;
1760 template <
class TMatrixType>
1762 ArgmaxSymmetricMatrix(
const TMatrixType matrix,
const int size,
int& row,
int& colomn,
const bool includeDiagonalElements)
1766 for (
unsigned int i = 0; i < size; i += 1 )
1768 for (
unsigned int j = 0; (includeDiagonalElements?(j<=i):(j<i)) ; j += 1 )
1770 value = matrix(i,j);
1771 if (value > maxValue)
1782 template <
class TMatrixType>
1784 ArgminSymmetricMatrix(
const TMatrixType& matrix,
const int size,
int& row,
int& colomn,
const bool includeDiagonalElements)
1788 for (
unsigned int i = 0; i < size; i += 1 )
1790 for (
unsigned int j = 0; (includeDiagonalElements?(j<=i):(j<i)) ; j += 1 )
1792 value = matrix(i,j);
1793 if (value < minValue)
1804 template <
class TMatrixType>
1806 ArgmaxMatrix(
const TMatrixType& matrix,
const int rows,
const int columns,
int& row,
int& colomn)
1810 for (
unsigned int i = 0; i < rows; i += 1 )
1812 for (
unsigned int j = 0; j < columns; j += 1 )
1814 value = matrix(i,j);
1815 if (value > maxValue)
1826 template <
class TMatrixType>
1828 ArgminMatrix(
const TMatrixType matrix,
const int rows,
const int columns,
int& row,
int& colomn)
1832 for (
unsigned int i = 0; i < rows; i += 1 )
1834 for (
unsigned int j = 0; j < columns; j += 1 )
1836 value = matrix(i,j);
1837 if (value < minValue)
1848 template <
typename Vector2D>
1852 for (
int i = 0; i < vv.size(); i += 1 )
1854 if (vv[i].size()==0)
1856 out<<
"\n" << std::flush;
1859 for (
int j = 0; j < vv[i].size()-1; j += 1 )
1860 out << vv[i][j]<<
" ";
1861 out << vv[i][vv[i].size()-1] <<
"\n" << std::flush;
1866 template <
typename Vector2D>
1871 out.open ( file.c_str() );
1872 utlException (!out,
"\nERROR : failed to open output file " << file );
1878 template <
class TMatrixType>
1880 SaveMatrix (
const TMatrixType& matrix,
const int NumberRows,
const int NumberColumns,
const std::string& file )
1883 out.open ( file.c_str() );
1884 utlException (!out,
"\nERROR : failed to open output file " << file );
1885 for (
int i = 0; i < NumberRows; i += 1 )
1887 for (
int j = 0; j < NumberColumns-1; j += 1 )
1888 out << matrix(i,j)<<
" ";
1889 out << matrix(i,NumberColumns-1) <<
"\n";
1895 template <
class TMatrixType>
1899 std::vector<std::vector<std::string> > matrixStr;
1901 int NumberRows = matrixStr.size();
1903 int NumberColumns = matrixStr[0].size();
1904 matrix = TMatrixType(NumberRows, NumberColumns);
1905 for (
int i = 0; i < NumberRows; i += 1 )
1907 utlException(NumberColumns!=matrixStr[i].size(),
"wrong size");
1908 for (
int j = 0; j < NumberColumns; j += 1 )
1909 std::istringstream ( matrixStr[i][j] ) >> matrix(i,j);
1917 int Dim = size.size();
1920 offsetTable.resize(Dim);
1921 for (
int i = Dim-1; i >= 0; i-- )
1924 offsetTable[i]=size[i];
1926 offsetTable[i]=size[i]*offsetTable[i+1];
1931 offsetTable.resize(Dim+1);
1933 int numberOfSamples = 1;
1934 for (
int i = 0; i < Dim; ++i )
1936 numberOfSamples *= size[i];
1937 offsetTable[i+1] = numberOfSamples;
1946 ComputeNDArrayOffset(
const std::vector<int>& multiIndex,
const std::vector<int>& size,
const int storedWay, std::vector<int> offsetTable=std::vector<int>())
1948 int Dim = multiIndex.size();
1950 return multiIndex[0];
1952 if (offsetTable.size()==0)
1959 for (
int i = 0; i < Dim-1; ++i )
1960 offset += multiIndex[i]*offsetTable[i+1];
1961 offset += multiIndex[Dim-1];
1966 for (
int i = Dim-1; i > 0; i-- )
1967 offset += multiIndex[i] * offsetTable[i];
1968 offset += multiIndex[0];
1977 ComputeNDArrayIndex(
const int offset, std::vector<int>& index,
const std::vector<int>& size,
const int storedWay, std::vector<int> offsetTable=std::vector<int>())
1979 int Dim = size.size();
1987 if (offsetTable.size()==0)
1994 for (
int i = 1; i < Dim; i++ )
1996 index[i-1] = nn / offsetTable[i] ;
1997 nn -= index[i-1] * offsetTable[i];
2004 for (
int i = Dim-1; i > 0; i-- )
2006 index[i] = nn / offsetTable[i] ;
2007 nn -= index[i] * offsetTable[i];
2021 template <
typename T>
2023 operator<<(std::ostream& out, const std::vector<T>& vec )
2027 for (
int i = 0; i < vec.size()-1; i += 1 )
2029 out << vec[i] <<
" ";
2031 out << vec[vec.size()-1];
2034 out <<
"(empty vector)";
2038 template <
typename T>
2040 operator<<(std::ostream& out, const std::complex<T>& val )
2042 T a = val.real(), b = val.imag();
2052 out <<
"+" << b <<
"i";
void SwapBytes(void *ptr, const int sizePerElement, const int count)
void PrintContainer(IteratorType v1, IteratorType v2, const std::string &str="", const char *separate=" ", std::ostream &os=std::cout, bool showStats=true)
double ArgminMatrix(const TMatrixType matrix, const int rows, const int columns, int &row, int &colomn)
void ReadMatrix(const std::string &file, TMatrixType &matrix)
unsigned int argmin(Iterator i1, Iterator i2)
bool IsOdd(const int value)
void argmax2(const VectorType &vec, int size, int &index0, int &index1)
void SaveVector(const VectorType &vv, const int NSize, const std::string &vectorStr, const bool is_save_number=false)
T min_element(const std::vector< T > &v)
VectorType GetVectorShrinkage(const VectorType &vec, const int N, const double kappa)
int GetNumberOfNonZeroValues(IteratorType v, IteratorType v2, const double threshold=1e-6)
void VectorToVector(const T1 &v1, T2 &v2, const int N)
bool IsNumber(const std::string &input)
int strfind(const char *s, const char c)
std::string ConvertToWindowsOutputPath(const char *path)
void SplitString(const std::string &str, std::vector< std::string > &strVec, const char *cc=" ")
VectorType GetAbsoluteVector(const VectorType &vec, const int N)
void PrintMatrix(const TMatrixType &matrix, const int NumberRows, const int NumberColumns, const std::string &str="", const char *separate=" ", std::ostream &os=std::cout, bool showStats=true)
VectorType AddNoise(const VectorType &signal, const int size, const double sigma, const bool is_rician=true)
bool IsEven(const int value)
std::vector< double > GetContainerStats(IteratorType v1, IteratorType v2)
double ArgmaxMatrix(const TMatrixType &matrix, const int rows, const int columns, int &row, int &colomn)
#define __utl_minmax(T0_, T1_, T2_)
void ReplaceString(std::string &source, const char *replace, const char *with)
std::vector< T > RandomVec(const std::vector< T > &vec, const int num, std::vector< int > &result_index)
std::string ConvertNumberToString(const T value, const int precision=6)
void ConnectVector(std::vector< T > &vec1, const std::vector< T > &vec2)
#define utlException(cond, expout)
bool IsFileExist(const std::string &file)
void spherical2Cartesian(const T r, const T theta, const T phi, T &x, T &y, T &z)
std::vector< std::vector< int > > SeparateVector(const std::vector< T > &vec, std::vector< T > &vec_sep, const double gap=1e-9)
void ReadLinesFirstlineCheck(const std::string &filename, std::vector< std::vector< std::string > > &strVec, const char *cc=" ")
bool IsSame< char >(const char &value, const char &v0, const double)
std::string StringToLowerCase(const std::string &str)
const T & max(const T &a, const T &b)
Return the maximum between a and b.
void ConvertToUnixSlashes(std::string &path)
unsigned long TicToc(const bool is_tic, std::ostream &os=std::cout)
void PowerVector(IteratorType v1, IteratorType v2, const double poww)
unsigned int argmax(Iterator i1, Iterator i2)
std::vector< int > FindVector(const std::vector< T > &vec, const T &elem, const double gap=1e-9)
void FlipVector(T1 &vec, const T2 &flip, const int N)
void Save2DVector(const Vector2D &vv, std::ostream &out=std::cout)
std::string GetSequentialFileName(const std::string &filePrefix, const unsigned int iteration, const std::string &fileExtension, const unsigned int paddedLength=6)
std::string StringToUpperCase(const std::string &str)
const T & min(const T &a, const T &b)
Return the minimum between a and b.
void SaveMatrix(const TMatrixType &matrix, const int NumberRows, const int NumberColumns, const std::string &file)
std::string CreateExpandedPath(const std::string &path)
void ComputeOffsetTable(const std::vector< int > &size, std::vector< int > &offsetTable, const int storedWay)
bool IsInstanceOf(const Object &o)
std::string ConvertToUnixOutputPath(const char *path)
bool IsContainsNaN(const VectorType &a, const int size)
T abs(const T x)
template version of the fabs function
std::string ZeroPad(const unsigned int number, const unsigned int paddedLength)
std::vector< std::string > CovertChar2DArrayToStringArray(const char arr[][M], int N)
bool IsSame< int >(const int &value, const int &v0, const double)
T median_element(std::vector< T > values)
#define utlGlobalAssert(cond, expout)
int ComputeNDArrayOffset(const std::vector< int > &multiIndex, const std::vector< int > &size, const int storedWay, std::vector< int > offsetTable=std::vector< int >())
bool IsInt(const std::string &input, const double epss=1e-10)
unsigned long Toc(std::ostream &os=std::cout)
End tic/toc timer and displays elapsed time from last call to tic().
int RoundNumber(const T x)
std::vector< double > RandomPointInSphere(const bool hemis)
void CovertStringArrayToChar2DArray(const std::vector< std::string > &vec, char arr[][M], int N)
T Random(const T d1=T(0.0), const T d2=T(1.0))
void AbsoluteVector(VectorType &vec, const int N)
bool IsSameVector(const std::vector< T > &vec1, const std::vector< T > &vec2, const double eps=1e-10)
void ComputeNDArrayIndex(const int offset, std::vector< int > &index, const std::vector< int > &size, const int storedWay, std::vector< int > offsetTable=std::vector< int >())
double ArgminSymmetricMatrix(const TMatrixType &matrix, const int size, int &row, int &colomn, const bool includeDiagonalElements)
unsigned long Time()
Return the value of a system timer, with a millisecond precision.
utl functions using c++11 Created "07-02-2016
void ReadVector(const std::string &vectorStr, std::vector< T > &vec, const char *cc=" ")
void PrintVector(const std::vector< T > &vec, const std::string &str="", const char *separate=" ", std::ostream &os=std::cout, bool showStats=true)
std::vector< T > SelectVector(const std::vector< T > &vec, const std::vector< int > &index)
VectorType GetVectorLinspace(const double valueMin, const double valueMax, const int num)
bool IsSameArray(const T(&a1)[N1], const T(&a2)[N2], const double eps=1e-10)
long RandomInt(const long d1=0, const long d2=1)
__InstanceOf(const Object &o)
bool IsInVector(const VectorType &vec, const int size, const T &num, const double eps=1e-10)
bool IsSame(const T &value, const T &v0, const double eps=1e-10)
void ReadLines(const std::string &filename, std::vector< std::vector< std::string > > &strVec, const char *cc=" ")
#define utlAssert(cond, expout)
bool IsEndingWith(const std::string &fullString, const std::string &ending)
VectorType NormalizeMinMax(const VectorType &v, const int nSize)
std::string ConvertVectorToString(VectorType vec, const int N, const char *separate=" ")
bool StringCompareCaseIgnored(const std::string &str1, const std::string &str2)
void MatrixToMatrix(const T1 &mat1, T2 &mat2, const int NRows, const int NColumns)
void cartesian2Spherical(const T x, const T y, const T z, T &r, T &theta, T &phi)
T RicianRand(const T value, const double sigma)
VectorType NormalizeUnitNorm(const VectorType &v, const int nSize)
void GetPath(const std::string &fileNameAbsolute, std::string &path, std::string &file)
int SetVector(const char *s, std::vector< T > &vec, const int least_num=0, const char &c=',')
T ConvertStringToNumber(const std::string &input)
std::vector< int > GetRange(const int start, const int end, const int space=1)
double GetSumOfVector(const TVectorType &vec, const int NSize)
int sign(const T &x)
Return the sign of x.
void PrintMatrixStats(const TMatrixType &matrix, const int NumberRows, const int NumberColumns, const std::string &str="", const char *separate=" ", std::ostream &os=std::cout)
T max_element(const std::vector< T > &v)
void GetFileExtension(const std::string &fileNameAbsolute, std::string &ext, std::string &fileNoExt)
unsigned long Tic(std::ostream &os=std::cout)
Start tic/toc timer for time measurement between code instructions.
void VectorShrinkage(VectorType &vec, const int N, const double kappa)
small but powerful CMD parser, borrowed from CImg, http://cimg.sourceforge.net/
double ArgmaxSymmetricMatrix(const TMatrixType matrix, const int size, int &row, int &colomn, const bool includeDiagonalElements)
VectorType NormalizeMax(const VectorType &v, const int nSize)
const double max(const int a, const float b)
T GaussRand(const T value, const double sigma)