From a74183ddb4ab8383bfe214b3745eb8a0a99ee47a Mon Sep 17 00:00:00 2001 From: Determinant Date: Thu, 25 Jun 2015 12:56:45 +0800 Subject: let HTK I/O implementation be a single package --- tnet_io/KaldiLib/Common.cc | 277 ------ tnet_io/KaldiLib/Common.h | 233 ----- tnet_io/KaldiLib/Error.h | 172 ---- tnet_io/KaldiLib/Features.cc | 1798 ------------------------------------- tnet_io/KaldiLib/Features.h | 597 ------------ tnet_io/KaldiLib/Labels.cc | 612 ------------- tnet_io/KaldiLib/Labels.h | 90 -- tnet_io/KaldiLib/Makefile | 28 - tnet_io/KaldiLib/MathAux.h | 117 --- tnet_io/KaldiLib/Matrix.cc | 295 ------ tnet_io/KaldiLib/Matrix.h | 677 -------------- tnet_io/KaldiLib/Matrix.tcc | 796 ---------------- tnet_io/KaldiLib/MlfStream.cc | 268 ------ tnet_io/KaldiLib/MlfStream.h | 639 ------------- tnet_io/KaldiLib/MlfStream.tcc | 517 ----------- tnet_io/KaldiLib/StkMatch.cc | 582 ------------ tnet_io/KaldiLib/StkMatch.h | 123 --- tnet_io/KaldiLib/StkStream.h | 526 ----------- tnet_io/KaldiLib/StkStream.tcc | 228 ----- tnet_io/KaldiLib/Timer.cc | 5 - tnet_io/KaldiLib/Timer.h | 103 --- tnet_io/KaldiLib/Tokenizer.cc | 53 -- tnet_io/KaldiLib/Tokenizer.h | 45 - tnet_io/KaldiLib/Types.h | 78 -- tnet_io/KaldiLib/UserInterface.cc | 669 -------------- tnet_io/KaldiLib/UserInterface.h | 166 ---- tnet_io/KaldiLib/Vector.cc | 110 --- tnet_io/KaldiLib/Vector.h | 496 ---------- tnet_io/KaldiLib/Vector.tcc | 638 ------------- tnet_io/KaldiLib/clapack.cc | 61 -- tnet_io/KaldiLib/clapack.h | 149 --- tnet_io/cwrapper.cpp | 148 --- tnet_io/cwrapper.h | 37 - tnet_io/init.c | 118 --- tnet_io/test.c | 40 - tnet_io/tnet.mk | 83 -- 36 files changed, 11574 deletions(-) delete mode 100644 tnet_io/KaldiLib/Common.cc delete mode 100644 tnet_io/KaldiLib/Common.h delete mode 100644 tnet_io/KaldiLib/Error.h delete mode 100644 tnet_io/KaldiLib/Features.cc delete mode 100644 tnet_io/KaldiLib/Features.h delete mode 100644 tnet_io/KaldiLib/Labels.cc delete mode 100644 tnet_io/KaldiLib/Labels.h delete mode 100644 tnet_io/KaldiLib/Makefile delete mode 100644 tnet_io/KaldiLib/MathAux.h delete mode 100644 tnet_io/KaldiLib/Matrix.cc delete mode 100644 tnet_io/KaldiLib/Matrix.h delete mode 100644 tnet_io/KaldiLib/Matrix.tcc delete mode 100644 tnet_io/KaldiLib/MlfStream.cc delete mode 100644 tnet_io/KaldiLib/MlfStream.h delete mode 100644 tnet_io/KaldiLib/MlfStream.tcc delete mode 100644 tnet_io/KaldiLib/StkMatch.cc delete mode 100644 tnet_io/KaldiLib/StkMatch.h delete mode 100644 tnet_io/KaldiLib/StkStream.h delete mode 100644 tnet_io/KaldiLib/StkStream.tcc delete mode 100644 tnet_io/KaldiLib/Timer.cc delete mode 100644 tnet_io/KaldiLib/Timer.h delete mode 100644 tnet_io/KaldiLib/Tokenizer.cc delete mode 100644 tnet_io/KaldiLib/Tokenizer.h delete mode 100644 tnet_io/KaldiLib/Types.h delete mode 100644 tnet_io/KaldiLib/UserInterface.cc delete mode 100644 tnet_io/KaldiLib/UserInterface.h delete mode 100644 tnet_io/KaldiLib/Vector.cc delete mode 100644 tnet_io/KaldiLib/Vector.h delete mode 100644 tnet_io/KaldiLib/Vector.tcc delete mode 100644 tnet_io/KaldiLib/clapack.cc delete mode 100644 tnet_io/KaldiLib/clapack.h delete mode 100644 tnet_io/cwrapper.cpp delete mode 100644 tnet_io/cwrapper.h delete mode 100644 tnet_io/init.c delete mode 100644 tnet_io/test.c delete mode 100644 tnet_io/tnet.mk (limited to 'tnet_io') diff --git a/tnet_io/KaldiLib/Common.cc b/tnet_io/KaldiLib/Common.cc deleted file mode 100644 index 40909ee..0000000 --- a/tnet_io/KaldiLib/Common.cc +++ /dev/null @@ -1,277 +0,0 @@ -#include -#include -#include -#include -#include - -#include "Common.h" -#include "MathAux.h" - - -/// Defines the white chars for string trimming -#if !defined(WHITE_CHARS) -# define WHITE_CHARS " \t" -#endif - -namespace TNet { - -#include - - // Allocating stream variable used by stream modifier MatrixVectorIostreamControl - const int MATRIX_IOS_FORMAT_IWORD = std::ios_base::xalloc(); - - //*************************************************************************** - //*************************************************************************** - int getHTKstr(char *str) - { - char termChar = '\0'; - char *chrptr = str; - - while (std::isspace(*chrptr)) ++chrptr; - - if (*chrptr == '\'' || *chrptr == '"') { - termChar = *chrptr; - chrptr++; - } - - for (; *chrptr; chrptr++) { - if (*chrptr == '\'' || *chrptr == '"') { - if (termChar == *chrptr) { - termChar = '\0'; - chrptr++; - break; - } - } - - if (std::isspace(*chrptr) && !termChar) { - break; - } - - if (*chrptr == '\\') { - ++chrptr; - if (*chrptr == '\0' || (*chrptr >= '0' && *chrptr <= '7' && - (*++chrptr < '0' || *chrptr > '7' || - *++chrptr < '0' || *chrptr > '7'))) { - return -1; - } - - if (*chrptr >= '0' && *chrptr <= '7') { - *chrptr = (char)((*chrptr - '0') + (chrptr[-1] - '0') * 8 + (chrptr[-2] - '0') * 64); - } - } - *str++ = *chrptr; - } - - if (termChar) { - return -2; - } - - *str = '\0'; - - return 0; - } - - - //***************************************************************************** - //***************************************************************************** - void - ParseHTKString(const std::string & rIn, std::string & rOut) - { - int ret_val; - - // the new string will be at most as long as the original, so we allocate - // space - char* new_str = new char[rIn.size() + 1]; - - char* p_htk_str = new_str; - - strcpy(p_htk_str, rIn.c_str()); - ret_val = getHTKstr(p_htk_str); - - // call the function - if (!ret_val) { - rOut = p_htk_str; - } - - delete [] new_str; - - if (ret_val) { - throw std::runtime_error("Error parsing HTK string"); - } - } - - - - //*************************************************************************** - //*************************************************************************** - bool - IsBigEndian() - { - int a = 1; - return (bool) ((char *) &a)[0] != 1; - } - - - //*************************************************************************** - //*************************************************************************** - void - MakeHtkFileName(char* pOutFileName, const char* inFileName, - const char* out_dir, const char* out_ext) - { - const char* base_name; - const char* bname_end = NULL; - const char* chrptr; - - // if (*inFileName == '*' && *++inFileName == '/') ++inFileName; - - // we don't do anything if file is stdin/out - if (!strcmp(inFileName, "-")) - { - pOutFileName[0] = '-'; - pOutFileName[1] = '\0'; - return; - } - - base_name = strrchr(inFileName, '/'); - base_name = base_name != NULL ? base_name + 1 : inFileName; - - if (out_ext) bname_end = strrchr(base_name, '.'); - if (!bname_end) bname_end = base_name + strlen(base_name); - - - if ((chrptr = strstr(inFileName, "/./")) != NULL) - { - // what is in path after /./ serve as base name - base_name = chrptr + 3; - } - /* else if (*inFileName != '/') - { - // if inFileName isn't absolut path, don't forget directory structure - base_name = inFileName; - }*/ - - *pOutFileName = '\0'; - if (out_dir) - { - if (*out_dir) - { - strcat(pOutFileName, out_dir); - strcat(pOutFileName, "/"); - } - strncat(pOutFileName, base_name, bname_end-base_name); - } - else - { - strncat(pOutFileName, inFileName, bname_end-inFileName); - } - - if (out_ext && *out_ext) - { - strcat(pOutFileName, "."); - strcat(pOutFileName, out_ext); - } - } - - - //**************************************************************************** - //**************************************************************************** - bool - CloseEnough(const float f1, const float f2, const float nRounds) - { - bool ret_val = (_ABS((f1 - f2) / (f2 == 0.0f ? 1.0f : f2)) - < (nRounds * FLT_EPSILON)); - - return ret_val; - } - - - //**************************************************************************** - //**************************************************************************** - bool - CloseEnough(const double f1, const double f2, const double nRounds) - { - bool ret_val = (_ABS((f1 - f2) / (f2 == 0.0 ? 1.0 : f2)) - < (nRounds * DBL_EPSILON)); - - return ret_val; - } - - - //**************************************************************************** - //**************************************************************************** - char* - ExpandHtkFilterCmd(const char *command, const char *filename, const char* pFilter) - { - - char *out, *outend; - const char *chrptr = command; - int ndollars = 0; - int fnlen = strlen(filename); - - while (*chrptr++) ndollars += (*chrptr == *pFilter); - - out = (char*) malloc(strlen(command) - ndollars + ndollars * fnlen + 1); - - outend = out; - - for (chrptr = command; *chrptr; chrptr++) { - if (*chrptr == *pFilter) { - strcpy(outend, filename); - outend += fnlen; - } else { - *outend++ = *chrptr; - } - } - *outend = '\0'; - return out; - } - - //*************************************************************************** - //*************************************************************************** - char * - StrToUpper(char *str) - { - char *chptr; - for (chptr = str; *chptr; chptr++) { - *chptr = (char)toupper(*chptr); - } - return str; - } - - - //**************************************************************************** - //**************************************************************************** - std::string& - Trim(std::string& rStr) - { - // WHITE_CHARS is defined in common.h - std::string::size_type pos = rStr.find_last_not_of(WHITE_CHARS); - if(pos != std::string::npos) - { - rStr.erase(pos + 1); - pos = rStr.find_first_not_of(WHITE_CHARS); - if(pos != std::string::npos) rStr.erase(0, pos); - } - else - rStr.erase(rStr.begin(), rStr.end()); - - return rStr; - } - - -} // namespace TNet - -//#ifdef CYGWIN - -void assertf(const char *c, int i, const char *msg){ - printf("Assertion \"%s\" failed: file \"%s\", line %d\n", msg?msg:"(null)", c?c:"(null)", i); - abort(); -} - - -void assertf_throw(const char *c, int i, const char *msg){ - char buf[2000]; - snprintf(buf, 1999, "Assertion \"%s\" failed, throwing exception: file \"%s\", line %d\n", msg?msg:"(null)", c?c:"(null)", i); - throw std::runtime_error((std::string)buf); -} -//#endif diff --git a/tnet_io/KaldiLib/Common.h b/tnet_io/KaldiLib/Common.h deleted file mode 100644 index 9cd9658..0000000 --- a/tnet_io/KaldiLib/Common.h +++ /dev/null @@ -1,233 +0,0 @@ -#ifndef TNet_Common_h -#define TNet_Common_h - -#include -#include // C string stuff like strcpy -#include -#include -#include - -/* Alignment of critical dynamic data structure - * - * Not all platforms support memalign so we provide a stk_memalign wrapper - * void *stk_memalign( size_t align, size_t size, void **pp_orig ) - * *pp_orig is the pointer that has to be freed afterwards. - */ -#ifdef HAVE_POSIX_MEMALIGN -# define stk_memalign(align,size,pp_orig) \ - ( !posix_memalign( pp_orig, align, size ) ? *(pp_orig) : NULL ) -# ifdef STK_MEMALIGN_MANUAL -# undef STK_MEMALIGN_MANUAL -# endif -#elif defined(HAVE_MEMALIGN) - /* Some systems have memalign() but no declaration for it */ - //void * memalign( size_t align, size_t size ); -# define stk_memalign(align,size,pp_orig) \ - ( *(pp_orig) = memalign( align, size ) ) -# ifdef STK_MEMALIGN_MANUAL -# undef STK_MEMALIGN_MANUAL -# endif -#else /* We don't have any choice but to align manually */ -# define stk_memalign(align,size,pp_orig) \ - (( *(pp_orig) = malloc( size + align - 1 )) ? \ - (void *)( (((unsigned long)*(pp_orig)) + 15) & ~0xFUL ) : NULL ) -# define STK_MEMALIGN_MANUAL -#endif - - -#define swap8(a) { \ - char t=((char*)&a)[0]; ((char*)&a)[0]=((char*)&a)[7]; ((char*)&a)[7]=t;\ - t=((char*)&a)[1]; ((char*)&a)[1]=((char*)&a)[6]; ((char*)&a)[6]=t;\ - t=((char*)&a)[2]; ((char*)&a)[2]=((char*)&a)[5]; ((char*)&a)[5]=t;\ - t=((char*)&a)[3]; ((char*)&a)[3]=((char*)&a)[4]; ((char*)&a)[4]=t;} -#define swap4(a) { \ - char t=((char*)&a)[0]; ((char*)&a)[0]=((char*)&a)[3]; ((char*)&a)[3]=t;\ - t=((char*)&a)[1]; ((char*)&a)[1]=((char*)&a)[2]; ((char*)&a)[2]=t;} -#define swap2(a) { \ - char t=((char*)&a)[0]; ((char*)&a)[0]=((char*)&a)[1]; ((char*)&a)[1]=t;} - - -namespace TNet -{ - /** ************************************************************************** - ** ************************************************************************** - * @brief Aligns a number to a specified base - * @param n Number of type @c _T to align - * @return Aligned value of type @c _T - */ - template - inline _T - align(const _T n) - { - const _T x(_align - 1); - return (n + x) & ~(x); - } - - - /** - * @brief Returns true if architecture is big endian - */ - bool - IsBigEndian(); - - - /** - * @brief Returns true if two numbers are close enough to each other - * - * @param f1 First operand - * @param f2 Second operand - * @param nRounds Expected number of operations prior to this comparison - */ - bool - CloseEnough(const float f1, const float f2, const float nRounds); - - - /** - * @brief Returns true if two numbers are close enough to each other - * - * @param f1 First operand - * @param f2 Second operand - * @param nRounds Expected number of operations prior to this comparison - */ - bool - CloseEnough(const double f1, const double f2, const double nRounds); - - - /** - * @brief Parses a HTK-style string into a C++ std::string readable - * - * @param rIn HTK input string - * @param rOut output parsed string - */ - void - ParseHTKString(const std::string & rIn, std::string & rOut); - - - /** - * @brief Synthesize new file name based on name, path, and extension - * - * @param pOutFileName full ouptut file name - * @param pInFileName file name - * @param pOutDir directory - * @param pOutExt extension - */ - void - MakeHtkFileName(char *pOutFileName, const char* pInFileName, const char *pOutDir, - const char *pOutExt); - - - /** - * @brief Removes the leading and trailing white chars - * - * @param rStr Refference to the string to be processed - * @return Refference to the original string - * - * The white characters are determined by the @c WHITE_CHARS macro defined - * above. - */ - std::string& - Trim(std::string& rStr); - - - char* - StrToUpper(char* pStr); - - char* - ExpandHtkFilterCmd(const char *command, const char *filename, const char* pFilter); - - - template - std::string to_string(const T& val) - { - std::stringstream ss; - ss << val; - return ss.str(); - } - - inline void - ExpectKeyword(std::istream &i_stream, const char *kwd) - { - std::string token; - i_stream >> token; - if (token != kwd) { - throw std::runtime_error(std::string(kwd) + " expected"); - } - } - - extern const int MATRIX_IOS_FORMAT_IWORD; - - enum MatrixVectorIostreamControlBits { - ACCUMULATE_INPUT = 1, -// BINARY_OUTPUT = 2 - }; - - class MatrixVectorIostreamControl - { - public: - MatrixVectorIostreamControl(enum MatrixVectorIostreamControlBits bitsToBeSet, bool valueToBeSet) - : mBitsToBeSet(bitsToBeSet), mValueToBeSet(valueToBeSet) {} - - static long Flags(std::ios_base &rIos, enum MatrixVectorIostreamControlBits bits) - { return rIos.iword(MATRIX_IOS_FORMAT_IWORD); } - - long mBitsToBeSet; - bool mValueToBeSet; - - friend std::ostream & operator <<(std::ostream &rOs, const MatrixVectorIostreamControl modifier) - { - if(modifier.mValueToBeSet) { - rOs.iword(MATRIX_IOS_FORMAT_IWORD) |= modifier.mBitsToBeSet; - } else { - rOs.iword(MATRIX_IOS_FORMAT_IWORD) &= ~modifier.mBitsToBeSet; - } - return rOs; - } - - friend std::istream & operator >>(std::istream &rIs, const MatrixVectorIostreamControl modifier) - { - if(modifier.mValueToBeSet) { - rIs.iword(MATRIX_IOS_FORMAT_IWORD) |= modifier.mBitsToBeSet; - } else { - rIs.iword(MATRIX_IOS_FORMAT_IWORD) &= ~modifier.mBitsToBeSet; - } - return rIs; - } - }; - - - - -} // namespace TNet - -#ifdef __ICC -#pragma warning (disable: 383) // ICPC remark we don't want. -#pragma warning (disable: 810) // ICPC remark we don't want. -#pragma warning (disable: 981) // ICPC remark we don't want. -#pragma warning (disable: 1418) // ICPC remark we don't want. -#pragma warning (disable: 444) // ICPC remark we don't want. -#pragma warning (disable: 869) // ICPC remark we don't want. -#pragma warning (disable: 1287) // ICPC remark we don't want. -#pragma warning (disable: 279) // ICPC remark we don't want. -#pragma warning (disable: 981) // ICPC remark we don't want. -#endif - -//#ifdef CYGWIN -#if 1 -#undef assert -#ifndef NDEBUG -#define assert(e) ((e) ? (void)0 : assertf(__FILE__, __LINE__, #e)) -#else -#define assert(e) ((void)0) -#endif -void assertf(const char *c, int i, const char *msg); // Just make it possible to break into assert on gdb-- has some kind of bug on cygwin. -#else -#include -#endif - -#define assert_throw(e) ((e) ? (void)0 : assertf_throw(__FILE__, __LINE__, #e)) -void assertf_throw(const char *c, int i, const char *msg); - -#define DAN_STYLE_IO - -#endif // ifndef TNet_Common_h - diff --git a/tnet_io/KaldiLib/Error.h b/tnet_io/KaldiLib/Error.h deleted file mode 100644 index 2228dde..0000000 --- a/tnet_io/KaldiLib/Error.h +++ /dev/null @@ -1,172 +0,0 @@ -// -// C++ Interface: %{MODULE} -// -// Description: -// -// -// Author: %{AUTHOR} <%{EMAIL}>, (C) %{YEAR} -// -// Copyright: See COPYING file that comes with this distribution -// -// - -/** @file Error.h - * This header defines several types and functions relating to the - * handling of exceptions in STK. - */ - -#ifndef TNET_Error_h -#define TNET_Error_h - -#include -#include -#include -#include - -#include -#include -#include -#include - -// THESE MACROS TERRIBLY CLASH WITH STK!!!! -// WE MUST USE SAME MACROS! -// -//#define Error(msg) _Error_(__func__, __FILE__, __LINE__, msg) -//#define Warning(msg) _Warning_(__func__, __FILE__, __LINE__, msg) -//#define TraceLog(msg) _TraceLog_(__func__, __FILE__, __LINE__, msg) -// - -#ifndef Error - #define Error(...) _Error_(__func__, __FILE__, __LINE__, __VA_ARGS__) -#endif -#ifndef PError - #define PError(...) _PError_(__func__, __FILE__, __LINE__, __VA_ARGS__) -#endif -#ifndef Warning - #define Warning(...) _Warning_(__func__, __FILE__, __LINE__, __VA_ARGS__) -#endif -#ifndef TraceLog - #define TraceLog(...) _TraceLog_(__func__, __FILE__, __LINE__, __VA_ARGS__) -#endif - -namespace TNet { - - - - /** MyException - * Custom exception class, gets the stacktrace - */ - class MyException - : public std::runtime_error - { - public: - explicit MyException(const std::string& what_arg) throw(); - virtual ~MyException() throw(); - - const char* what() const throw() - { return mWhat.c_str(); } - - private: - std::string mWhat; - }; - - /** - * MyException:: implemenatation - */ - inline - MyException:: - MyException(const std::string& what_arg) throw() - : std::runtime_error(what_arg) - { - mWhat = what_arg; - mWhat += "\nTHE STACKTRACE INSIDE MyException OBJECT IS:\n"; - - void *array[10]; - size_t size; - char **strings; - size_t i; - - size = backtrace (array, 10); - strings = backtrace_symbols (array, size); - - //<< 0th string is the MyException ctor, so ignore and start by 1 - for (i = 1; i < size; i++) { - mWhat += strings[i]; - mWhat += "\n"; - } - - free (strings); - } - - - inline - MyException:: - ~MyException() throw() - { } - - - /** - * @brief Error throwing function (with backtrace) - */ - inline void - _Error_(const char *func, const char *file, int line, const std::string &msg) - { - std::stringstream ss; - ss << "ERROR (" << func << ':' << file << ':' << line << ") " << msg; - throw MyException(ss.str()); - } - - /** - * @brief Throw a formatted error - */ - inline void _PError_(const char *func, const char *file, int line, const char *fmt, ...) { - va_list ap; - char msg[256]; - va_start(ap, fmt); - vsnprintf(msg, sizeof msg, fmt, ap); - va_end(ap); - _Error_(func, file, line, msg); - } - - /** - * @brief Warning handling function - */ - inline void - _Warning_(const char *func, const char *file, int line, const std::string &msg) - { - std::cout << "WARNING (" << func << ':' << file << ':' << line << ") " << msg << std::endl; - } - - inline void - _TraceLog_(const char *func, const char *file, int line, const std::string &msg) - { - std::cout << "INFO (" << func << ':' << file << ':' << line << ") " << msg << std::endl; - std::cout.flush(); - } - - /** - * New kaldi error handling: - * - * class KaldiErrorMessage is invoked from the KALDI_ERROR macro. - * The destructor throws an exception. - */ - class KaldiErrorMessage { - public: - KaldiErrorMessage(const char *func, const char *file, int line) { - this->stream() << "ERROR (" - << func << "():" - << file << ':' << line << ") "; - } - inline std::ostream &stream() { return ss; } - ~KaldiErrorMessage() { throw MyException(ss.str()); } - private: - std::ostringstream ss; - }; - #define KALDI_ERR TNet::KaldiErrorMessage(__func__, __FILE__, __LINE__).stream() - - - -} // namespace TNet - -//#define TNET_Error_h -#endif diff --git a/tnet_io/KaldiLib/Features.cc b/tnet_io/KaldiLib/Features.cc deleted file mode 100644 index 64b63e8..0000000 --- a/tnet_io/KaldiLib/Features.cc +++ /dev/null @@ -1,1798 +0,0 @@ - -//enable feature repository profiling -#define PROFILING 1 - -#include -#include -#include -#include - -#include "Features.h" -#include "Tokenizer.h" -#include "StkMatch.h" -#include "Types.h" - - - -namespace TNet -{ - const char - FeatureRepository:: - mpParmKindNames[13][16] = - { - {"WAVEFORM"}, - {"LPC"}, - {"LPREFC"}, - {"LPCEPSTRA"}, - {"LPDELCEP"}, - {"IREFC"}, - {"MFCC"}, - {"FBANK"}, - {"MELSPEC"}, - {"USER"}, - {"DISCRETE"}, - {"PLP"}, - {"ANON"} - }; - - //*************************************************************************** - //*************************************************************************** - - FileListElem:: - FileListElem(const std::string & rFileName) - { - std::string::size_type pos; - - mLogical = rFileName; - mWeight = 1.0; - - // some slash-backslash replacement hack - for (size_t i = 0; i < mLogical.size(); i++) { - if (mLogical[i] == '\\') { - mLogical[i] = '/'; - } - } - - // read sentence weight definition if any ( physical_file.fea[s,e]{weight} ) - if ((pos = mLogical.find('{')) != std::string::npos) - { - std::string tmp_weight(mLogical.begin() + pos + 1, mLogical.end()); - std::stringstream tmp_ss(tmp_weight); - - tmp_ss >> mWeight; - mLogical.erase(pos); - } - - // look for "=" symbol and if found, split it - if ((pos = mLogical.find('=')) != std::string::npos) - { - // copy all from mLogical[pos+1] till the end to mPhysical - mPhysical.assign(mLogical.begin() + pos + 1, mLogical.end()); - // erase all from pos + 1 till the end from mLogical - mLogical.erase(pos); - // trim the leading and trailing spaces - Trim(mPhysical); - Trim(mLogical); - } - else - { - // trim the leading and trailing spaces - Trim(mLogical); - - mPhysical = mLogical; - } - } - - - //########################################################################### - //########################################################################### - // FeatureRepository section - //########################################################################### - //########################################################################### - - //*************************************************************************** - //*************************************************************************** - void - FeatureRepository:: - ReadCepsNormFile( - const char * pFileName, - char ** pLastFileName, - BaseFloat ** vec_buff, - int sampleKind, - CNFileType type, - int coefs) - { - FILE* fp; - int i; - char s1[64]; - char s2[64]; - const char* typeStr = (type == CNF_Mean ? "MEAN" : - type == CNF_Variance ? "VARIANCE" : "VARSCALE"); - - const char* typeStr2 = (type == CNF_Mean ? "CMN" : - type == CNF_Variance ? "CVN" : "VarScale"); - - if (*pLastFileName != NULL && !strcmp(*pLastFileName, pFileName)) { - return; - } - free(*pLastFileName); - *pLastFileName=strdup(pFileName); - *vec_buff = (BaseFloat*) realloc(*vec_buff, coefs * sizeof(BaseFloat)); - - if (*pLastFileName == NULL || *vec_buff== NULL) - throw std::runtime_error("Insufficient memory"); - - if ((fp = fopen(pFileName, "r")) == NULL) { - throw std::runtime_error(std::string("Cannot open ") + typeStr2 - + " pFileName: '" + pFileName + "'"); - } - - if ((type != CNF_VarScale - && (fscanf(fp, " <%64[^>]> <%64[^>]>", s1, s2) != 2 - || strcmp(StrToUpper(s1), "CEPSNORM") - || ReadParmKind(s2, false) != sampleKind)) - || fscanf(fp, " <%64[^>]> %d", s1, &i) != 2 - || strcmp(StrToUpper(s1), typeStr) - || i != coefs) - { - ParmKind2Str(sampleKind, s2); - - //std::cout << "[[[TADY!!!!]]]" << pFileName << "\n" << std::flush; - - throw std::runtime_error(std::string("") - + (type == CNF_VarScale ? "" : " <") - + (type == CNF_VarScale ? "" : s2) - + (type == CNF_VarScale ? "" : ">") - + " <" + typeStr + " ... expected in " + typeStr2 - + " file " + pFileName); - } - - for (i = 0; i < coefs; i++) { - if (fscanf(fp, " "FLOAT_FMT, *vec_buff+i) != 1) { - if (fscanf(fp, "%64s", s2) == 1) { - throw std::runtime_error(std::string("Decimal number expected but '") - + s2 + "' found in " + typeStr2 + " file " + pFileName); - } - else if (feof(fp)) { - throw std::runtime_error(std::string("Unexpected end of ") - + typeStr2 + " file "+ pFileName); - } - else { - throw std::runtime_error(std::string("Cannot read ") + typeStr2 - + " file " + pFileName); - } - } - - if (type == CNF_Variance) - (*vec_buff)[i] = BaseFloat(1 / sqrt((*vec_buff)[i])); - else if (type == CNF_VarScale) - (*vec_buff)[i] = BaseFloat(sqrt((*vec_buff)[i])); - } - - if (fscanf(fp, "%64s", s2) == 1) - { - throw std::runtime_error(std::string("End of file expected but '") - + s2 + "' found in " + typeStr2 + " file " + pFileName); - } - - fclose(fp); - } // ReadCepsNormFile(...) - - - //*************************************************************************** - //*************************************************************************** - void - FeatureRepository:: - HtkFilter(const char* pFilter, const char* pValue, FeatureRepository& rOut) - { - std::list::iterator it; - std::string str; - - rOut.mSwapFeatures = mSwapFeatures; - rOut.mStartFrameExt = mStartFrameExt; - rOut.mEndFrameExt = mEndFrameExt; - rOut.mTargetKind = mTargetKind; - rOut.mDerivOrder = mDerivOrder; - rOut.mDerivWinLengths = mDerivWinLengths; - - rOut.mpCvgFile = mpCvgFile; - rOut.mpCmnPath = mpCmnPath; - rOut.mpCmnMask = mpCmnMask; - rOut.mpCvnPath = mpCvnPath; - rOut.mpCvnMask = mpCvnMask; - - rOut.mInputQueue.clear(); - - // go through all records and check the mask - for (it=mInputQueue.begin(); it!= mInputQueue.end(); ++it) { - if (pFilter == NULL - || (ProcessMask(it->Logical(), pFilter, str) && (str == pValue))) { - rOut.mInputQueue.push_back(*it); - } - } - - // set the queue position to the begining - rOut.mInputQueueIterator = mInputQueue.end(); - - rOut.mCurrentIndexFileName = ""; - rOut.mCurrentIndexFileDir = ""; - rOut.mCurrentIndexFileExt = ""; - - mStream.close(); - mStream.clear(); - - rOut.mpLastFileName = NULL; - rOut.mLastFileName = ""; - rOut.mpLastCmnFile = NULL; - rOut.mpLastCvnFile = NULL; - rOut.mpLastCvgFile = NULL; - rOut.mpCmn = NULL; - rOut.mpCvn = NULL; - rOut.mpCvg = NULL; - rOut.mpA = NULL; - rOut.mpB = NULL; - - } - - - //*************************************************************************** - //*************************************************************************** - void - FeatureRepository:: - HtkSelection(const char* pFilter, std::list< std::string >& rOut) - { - std::map< std::string, bool> aux_map; - std::map< std::string, bool>::iterator map_it; - std::list::iterator it; - std::string str; - - rOut.clear(); - - if(pFilter != NULL) { - // go through all records and check the mask - for (it=mInputQueue.begin(); it!= mInputQueue.end(); ++it) { - if (ProcessMask(it->Logical(), pFilter, str)) { - aux_map[str] = true; - } - } - } else { - aux_map[std::string("default speaker")] = true; - } - - for (map_it = aux_map.begin(); map_it != aux_map.end(); ++map_it) { - rOut.push_back(map_it->first); - } - } - - - //*************************************************************************** - //*************************************************************************** - int - FeatureRepository:: - ParmKind2Str(unsigned parmKind, char *pOutString) - { - // :KLUDGE: Absolutely no idea what this is... - if ((parmKind & 0x003F) >= sizeof(mpParmKindNames)/sizeof(mpParmKindNames[0])) - return 0; - - strcpy(pOutString, mpParmKindNames[parmKind & 0x003F]); - - if (parmKind & PARAMKIND_E) strcat(pOutString, "_E"); - if (parmKind & PARAMKIND_N) strcat(pOutString, "_N"); - if (parmKind & PARAMKIND_D) strcat(pOutString, "_D"); - if (parmKind & PARAMKIND_A) strcat(pOutString, "_A"); - if (parmKind & PARAMKIND_C) strcat(pOutString, "_C"); - if (parmKind & PARAMKIND_Z) strcat(pOutString, "_Z"); - if (parmKind & PARAMKIND_K) strcat(pOutString, "_K"); - if (parmKind & PARAMKIND_0) strcat(pOutString, "_0"); - if (parmKind & PARAMKIND_V) strcat(pOutString, "_V"); - if (parmKind & PARAMKIND_T) strcat(pOutString, "_T"); - - return 1; - } - - - // //*************************************************************************** - // //*************************************************************************** - // void - // AddFileListToFeatureRepositories( - // const char* pFileName, - // const char* pFilter, - // std::queue &featureRepositoryList) - // { - // IStkStream l_stream; - // std::string file_name; - // Tokenizer file_list(pFileName, ","); - // Tokenizer::iterator p_file_name; - - // //:TODO: error if empty featureRepositoryList - // - // for (p_file_name = file_list.begin(); p_file_name != file_list.end(); ++p_file_name) - // { - // // get rid of initial and trailing blanks - // Trim(*p_file_name); - - // // open file name - // l_stream.open(p_file_name->c_str(), std::ios::in, pFilter); - // - // if (!l_stream.good()) { - // //:TODO: - // // Warning or error ... Why warning? -Lukas - // throw std::runtime_error(std::string("Cannot not open list file ") + - // *p_file_name); - // } - - // // read all lines and parse them - // for(;;) - // { - // l_stream >> file_name; - // //:TODO: if(l_stream.badl()) Error() - // // Reading after last token set the fail bit - // if(l_stream.fail()) - // break; - // // we can push_back a std::string as new FileListElem object - // // is created using FileListElem(const std::string&) constructor - // // and logical and physical names are correctly extracted - // featureRepositoryList.front()->mInputQueue.push_back(file_name); - // - // //cycle in the featureRepositoryList - // featureRepositoryList.push(featureRepositoryList.front()); - // featureRepositoryList.pop(); - // } - // l_stream.close(); - // } - // } // AddFileList(const std::string & rFileName) - - - //*************************************************************************** - //*************************************************************************** - void - FeatureRepository:: - Init( - bool swap, - int extLeft, - int extRight, - int targetKind, - int derivOrder, - int* pDerivWinLen, - const char* pCmnPath, - const char* pCmnMask, - const char* pCvnPath, - const char* pCvnMask, - const char* pCvgFile) - { - mSwapFeatures = swap; - mStartFrameExt = extLeft; - mEndFrameExt = extRight; - mTargetKind = targetKind; - mDerivOrder = derivOrder; - mDerivWinLengths = pDerivWinLen; - mpCmnPath = pCmnPath; - mpCmnMask = pCmnMask; - mpCvnPath = pCvnPath; - mpCvnMask = pCvnMask; - mpCvgFile = pCvgFile; - } // Init() - - - //*************************************************************************** - //*************************************************************************** - void - FeatureRepository:: - AddFile(const std::string & rFileName) - { - mInputQueue.push_back(rFileName); - } // AddFile(const std::string & rFileName) - - - //*************************************************************************** - //*************************************************************************** - void - FeatureRepository:: - AddFileList(const char* pFileName, const char* pFilter) - { - IStkStream l_stream; - std::string file_name; - Tokenizer file_list(pFileName, ","); - Tokenizer::iterator p_file_name; - - for (p_file_name = file_list.begin(); p_file_name != file_list.end(); ++p_file_name) - { - // get rid of spaces - Trim(*p_file_name); - - // open the file - l_stream.open(p_file_name->c_str(), std::ios::in, pFilter); - - if (!l_stream.good()) - { - //:TODO: - // Warning or error ... Why warning? -Lukas - throw std::runtime_error(std::string("Cannot not open list file ") + - *p_file_name); - } - // read all lines and parse them - for(;;) - { - l_stream >> file_name; - //:TODO: if(l_stream.badl()) Error() - // Reading after last token set the fail bit - if(l_stream.fail()) - break; - // we can push_back a std::string as new FileListElem object - // is created using FileListElem(const std::string&) constructor - // and logical and physical names are correctly extracted - mInputQueue.push_back(file_name); - } - l_stream.close(); - } - } // AddFileList(const std::string & rFileName) - - - //*************************************************************************** - //*************************************************************************** - void - FeatureRepository:: - MoveNext() - { - assert (mInputQueueIterator != mInputQueue.end()); - mInputQueueIterator++; - } // ReadFullMatrix(Matrix& rMatrix) - - - //*************************************************************************** - //*************************************************************************** - bool - FeatureRepository:: - ReadFullMatrix(Matrix& rMatrix) - { - // clear the matrix - rMatrix.Destroy(); - - // extract index file name - if (!mCurrentIndexFileDir.empty()) - { - char tmp_name[mCurrentIndexFileDir.length() + - mCurrentIndexFileExt.length() + - mInputQueueIterator->Physical().length()]; - - MakeHtkFileName(tmp_name, mInputQueueIterator->Physical().c_str(), - mCurrentIndexFileDir.c_str(), mCurrentIndexFileExt.c_str()); - - mCurrentIndexFileName = tmp_name; - } - else - mCurrentIndexFileName = ""; - - //get the 3-letter suffix - int pos_last_three_chars = mInputQueueIterator->Physical().size() - 3; - if (pos_last_three_chars < 0) pos_last_three_chars = 0; - //read the gzipped ascii features - if (mInputQueueIterator->Physical().substr(pos_last_three_chars) == ".gz") { - return ReadGzipAsciiFeatures(*mInputQueueIterator, rMatrix); - } - - // read the matrix and return the result - return ReadHTKFeatures(*mInputQueueIterator, rMatrix); - } // ReadFullMatrix(Matrix& rMatrix) - - - - //*************************************************************************** - //*************************************************************************** - bool - FeatureRepository:: - WriteFeatureMatrix(const Matrix& rMatrix, const std::string& filename, int targetKind, int samplePeriod) - { - FILE* fp = fopen(filename.c_str(),"w"); - if(NULL == fp) { Error(std::string("Cannot create file:") + filename); return false; } - - WriteHTKFeatures(fp, samplePeriod, targetKind, mSwapFeatures, const_cast&>(rMatrix)); - - fclose(fp); - - return true; - } - - - //*************************************************************************** - //*************************************************************************** - // private: - int - FeatureRepository:: - ReadHTKHeader() - { - // TODO - // Change this... We should read from StkStream - FILE* fp = mStream.fp(); - - if (!fread(&mHeader.mNSamples, sizeof(INT_32), 1, fp)) return -1; - if (!fread(&mHeader.mSamplePeriod, sizeof(INT_32), 1, fp)) return -1; - if (!fread(&mHeader.mSampleSize, sizeof(INT_16), 1, fp)) return -1; - if (!fread(&mHeader.mSampleKind, sizeof(UINT_16), 1, fp)) return -1; - - if (mSwapFeatures) - { - swap4(mHeader.mNSamples); - swap4(mHeader.mSamplePeriod); - swap2(mHeader.mSampleSize); - swap2(mHeader.mSampleKind); - } - - if (mHeader.mSamplePeriod < 0 - || mHeader.mSamplePeriod > 1000000 - || mHeader.mNSamples < 0 - || mHeader.mSampleSize < 0) - { - return -1; - } - - return 0; - } - - - //*************************************************************************** - //*************************************************************************** - // private: - int - FeatureRepository:: - ReadHTKFeature( - BaseFloat* pIn, - size_t feaLen, - bool decompress, - BaseFloat* pScale, - BaseFloat* pBias) - { - FILE* fp = mStream.fp(); - - size_t i; - - if (decompress) - { - INT_16 s; - // BaseFloat pScale = (xmax - xmin) / (2*32767); - // BaseFloat pBias = (xmax + xmin) / 2; - - for (i = 0; i < feaLen; i++) - { - if (fread(&s, sizeof(INT_16), 1, fp) != 1) - return -1; - - if (mSwapFeatures) swap2(s); - pIn[i] = ((BaseFloat)s + pBias[i]) / pScale[i]; - } - - return 0; - } - -#if !DOUBLEPRECISION - if (fread(pIn, sizeof(FLOAT_32), feaLen, fp) != feaLen) - return -1; - - if (mSwapFeatures) - for (i = 0; i < feaLen; i++) - swap4(pIn[i]); -#else - float f; - - for (i = 0; i < feaLen; i++) - { - if (fread(&f, sizeof(FLOAT_32), 1, fp) != 1) - return -1; - - if (mSwapFeatures) - swap4(f); - - pIn[i] = f; - } -#endif - return 0; - } // int ReadHTKFeature - - - - //*************************************************************************** - //*************************************************************************** -/* bool - FeatureRepository:: - ReadHTKFeatures(const std::string& rFileName, Matrix& rFeatureMatrix) - { - std::string file_name(rFileName); - std::string cmn_file_name; - std::string cvn_file_name; - - int ext_left = mStartFrameExt; - int ext_right = mEndFrameExt; - int from_frame; - int to_frame; - int tot_frames; - int trg_vec_size; - int src_vec_size; - int src_deriv_order; - int lo_src_tgz_deriv_order; - int i; - int j; - int k; - int e; - int coefs; - int trg_E; - int trg_0; - int trg_N; - int src_E; - int src_0; - int src_N; - int comp; - int coef_size; - char* chptr; - - - - // read frame range definition if any ( physical_file.fea[s,e] ) - if ((chptr = strrchr(file_name.c_str(), '[')) == NULL || - ((i=0), sscanf(chptr, "[%d,%d]%n", &from_frame, &to_frame, &i), - chptr[i] != '\0')) - { - chptr = NULL; - } - - if (chptr != NULL) - *chptr = '\0'; - - // Experimental changes... - // if ((strcmp(file_name.c_str(), "-")) - // && (mpLastFileName != NULL) - // && (!strcmp(mpLastFileName, file_name.c_str()))) - // { - // mHeader = mLastHeader; - // } - // else - // { - // if (mpLastFileName) - // { - // //if (mpFp != stdin) - // // fclose(mpFp); - // mStream.close(); - // - // free(mpLastFileName); - // mpLastFileName = NULL; - // } - - if ((file_name != "-" ) - && (!mLastFileName.empty()) - && (mLastFileName == file_name)) - { - mHeader = mLastHeader; - } - else - { - if (!mLastFileName.empty()) - { - mStream.close(); - mLastFileName = ""; - } - - - // open the feature file - mStream.open(file_name.c_str(), ios::binary); - if (!mStream.good()) - { - Error("Cannot open feature file: '%s'", file_name.c_str()); - } - - - if (ReadHTKHeader()) - Error("Invalid HTK header in feature file: '%s'", file_name.c_str()); - - if (mHeader.mSampleKind & PARAMKIND_C) - { - // File is in compressed form, scale and pBias vectors - // are appended after HTK header. - - int coefs = mHeader.mSampleSize/sizeof(INT_16); - mpA = (BaseFloat*) realloc(mpA, coefs * sizeof(BaseFloat)); - mpB = (BaseFloat*) realloc(mpB, coefs * sizeof(BaseFloat)); - if (mpA == NULL || mpB == NULL) Error("Insufficient memory"); - - e = ReadHTKFeature(mpA, coefs, 0, 0, 0); - e |= ReadHTKFeature(mpB, coefs, 0, 0, 0); - - if (e) - Error("Cannot read feature file: '%s'", file_name.c_str()); - - mHeader.mNSamples -= 2 * sizeof(FLOAT_32) / sizeof(INT_16); - } - - // remember current settings - mLastFileName = file_name; - mLastHeader = mHeader; - } - - if (chptr != NULL) - *chptr = '['; - - if (chptr == NULL) - { // Range [s,e] was not specified - from_frame = 0; - to_frame = mHeader.mNSamples-1; - } - - src_deriv_order = PARAMKIND_T & mHeader.mSampleKind ? 3 : - PARAMKIND_A & mHeader.mSampleKind ? 2 : - PARAMKIND_D & mHeader.mSampleKind ? 1 : 0; - src_E = (PARAMKIND_E & mHeader.mSampleKind) != 0; - src_0 = (PARAMKIND_0 & mHeader.mSampleKind) != 0; - src_N = ((PARAMKIND_N & mHeader.mSampleKind) != 0) * (src_E + src_0); - comp = PARAMKIND_C & mHeader.mSampleKind; - - mHeader.mSampleKind &= ~PARAMKIND_C; - - if (mTargetKind == PARAMKIND_ANON) - { - mTargetKind = mHeader.mSampleKind; - } - else if ((mTargetKind & 077) == PARAMKIND_ANON) - { - mTargetKind &= ~077; - mTargetKind |= mHeader.mSampleKind & 077; - } - - trg_E = (PARAMKIND_E & mTargetKind) != 0; - trg_0 = (PARAMKIND_0 & mTargetKind) != 0; - trg_N =((PARAMKIND_N & mTargetKind) != 0) * (trg_E + trg_0); - - coef_size = comp ? sizeof(INT_16) : sizeof(FLOAT_32); - coefs = (mHeader.mSampleSize/coef_size + src_N) / - (src_deriv_order+1) - src_E - src_0; - src_vec_size = (coefs + src_E + src_0) * (src_deriv_order+1) - src_N; - - //Is coefs dividable by 1 + number of derivatives specified in header - if (src_vec_size * coef_size != mHeader.mSampleSize) - { - Error("Invalid HTK header in feature file: '%s'. " - "mSampleSize do not match with parmKind", file_name.c_str()); - } - - if (mDerivOrder < 0) - mDerivOrder = src_deriv_order; - - - if ((!src_E && trg_E) || (!src_0 && trg_0) || (src_N && !trg_N) || - (trg_N && !trg_E && !trg_0) || (trg_N && !mDerivOrder) || - (src_N && !src_deriv_order && mDerivOrder) || - ((mHeader.mSampleKind & 077) != (mTargetKind & 077) && - (mHeader.mSampleKind & 077) != PARAMKIND_ANON)) - { - char srcParmKind[64]; - char trgParmKind[64]; - - ParmKind2Str(mHeader.mSampleKind, srcParmKind); - ParmKind2Str(mTargetKind, trgParmKind); - Error("Cannot convert %s to %s", srcParmKind, trgParmKind); - } - - lo_src_tgz_deriv_order = LOWER_OF(src_deriv_order, mDerivOrder); - trg_vec_size = (coefs + trg_E + trg_0) * (mDerivOrder+1) - trg_N; - - i = LOWER_OF(from_frame, mStartFrameExt); - from_frame -= i; - ext_left -= i; - - i = LOWER_OF(mHeader.mNSamples-to_frame-1, mEndFrameExt); - to_frame += i; - ext_right -= i; - - if (from_frame > to_frame || from_frame >= mHeader.mNSamples || to_frame< 0) - Error("Invalid frame range for feature file: '%s'", file_name.c_str()); - - tot_frames = to_frame - from_frame + 1 + ext_left + ext_right; - - // initialize matrix - rFeatureMatrix.Init(tot_frames, trg_vec_size); - - // fill the matrix with features - for (i = 0; i <= to_frame - from_frame; i++) - { - BaseFloat* A = mpA; - BaseFloat* B = mpB; - BaseFloat* mxPtr = rFeatureMatrix[i+ext_left]; - - // seek to the desired position - fseek(mStream.fp(), - sizeof(HtkHeader) + (comp ? src_vec_size * 2 * sizeof(FLOAT_32) : 0) - + (from_frame + i) * src_vec_size * coef_size, - SEEK_SET); - - e = ReadHTKFeature(mxPtr, coefs, comp, A, B); - - mxPtr += coefs; - A += coefs; - B += coefs; - - if (src_0 && !src_N) e |= ReadHTKFeature(mxPtr, 1, comp, A++, B++); - if (trg_0 && !trg_N) mxPtr++; - if (src_E && !src_N) e |= ReadHTKFeature(mxPtr, 1, comp, A++, B++); - if (trg_E && !trg_N) mxPtr++; - - for (j = 0; j < lo_src_tgz_deriv_order; j++) - { - e |= ReadHTKFeature(mxPtr, coefs, comp, A, B); - mxPtr += coefs; - A += coefs; - B += coefs; - - if (src_0) e |= ReadHTKFeature(mxPtr, 1, comp, A++, B++); - if (trg_0) mxPtr++; - if (src_E) e |= ReadHTKFeature(mxPtr, 1, comp, A++, B++); - if (trg_E) mxPtr++; - } - - if (e) - Error("Cannot read feature file: '%s' frame %d/%d", file_name.c_str(), - i, to_frame - from_frame + 1); - } - - // From now, coefs includes also trg_0 + trg_E ! - coefs += trg_0 + trg_E; - - // If extension of the matrix to the left or to the right is required, - // perform it here - for (i = 0; i < ext_left; i++) - { - memcpy(rFeatureMatrix[i], - rFeatureMatrix[ext_left], - (coefs * (1+lo_src_tgz_deriv_order) - trg_N) * sizeof(BaseFloat)); - } - - for (i = tot_frames - ext_right; i < tot_frames; i++) - { - memcpy(rFeatureMatrix[i], - rFeatureMatrix[tot_frames - ext_right - 1], - (coefs * (1+lo_src_tgz_deriv_order) - trg_N) * sizeof(BaseFloat)); - } - - // Sentence cepstral mean normalization - if( (mpCmnPath == NULL) - && !(PARAMKIND_Z & mHeader.mSampleKind) - && (PARAMKIND_Z & mTargetKind)) - { - // for each coefficient - for(j=0; j < coefs; j++) - { - BaseFloat norm = 0.0; - for(i=0; i < tot_frames; i++) // for each frame - { - norm += rFeatureMatrix[i][j - trg_N]; - //norm += fea_mx[i*trg_vec_size - trg_N + j]; - } - - norm /= tot_frames; - - for(i=0; i < tot_frames; i++) // for each frame - rFeatureMatrix[i][j - trg_N] -= norm; - //fea_mx[i*trg_vec_size - trg_N + j] -= norm; - } - } - - // Compute missing derivatives - for (; src_deriv_order < mDerivOrder; src_deriv_order++) - { - int winLen = mDerivWinLengths[src_deriv_order]; - BaseFloat norm = 0.0; - - for (k = 1; k <= winLen; k++) - { - norm += 2 * k * k; - } - - // for each frame - for (i=0; i < tot_frames; i++) - { - // for each coefficient - for (j=0; j < coefs; j++) - { - //BaseFloat* src = fea_mx + i*trg_vec_size + src_deriv_order*coefs - trg_N + j; - BaseFloat* src = &rFeatureMatrix[i][src_deriv_order*coefs - trg_N + j]; - - *(src + coefs) = 0.0; - - if (i < winLen || i >= tot_frames-winLen) - { // boundaries need special treatment - for (k = 1; k <= winLen; k++) - { - *(src+coefs) += k*(src[ LOWER_OF(tot_frames-1-i,k)*rFeatureMatrix.Stride()] - -src[-LOWER_OF(i, k)*rFeatureMatrix.Stride()]); - } - } - else - { // otherwise use more efficient code - for (k = 1; k <= winLen; k++) - { - *(src+coefs) += k*(src[ k * rFeatureMatrix.Stride()] - -src[-k * rFeatureMatrix.Stride()]); - } - } - *(src + coefs) /= norm; - } - } - } - - mHeader.mNSamples = tot_frames; - mHeader.mSampleSize = trg_vec_size * sizeof(FLOAT_32); - mHeader.mSampleKind = mTargetKind & ~(PARAMKIND_D | PARAMKIND_A | PARAMKIND_T); - - - //////////////////////////////////////////////////////////////////////////// - /////////////// Cepstral mean and variance normalization /////////////////// - //////////////////////////////////////////////////////////////////////////// - //......................................................................... - if (mpCmnPath != NULL - && mpCmnMask != NULL) - { - // retrieve file name - ProcessMask(file_name, mpCmnMask, cmn_file_name); - // add the path correctly - cmn_file_name.insert(0, "/"); - cmn_file_name.insert(0, mpCmnPath); - - // read the file - ReadCepsNormFile(cmn_file_name.c_str(), &mpLastCmnFile, &mpCmn, - mHeader.mSampleKind & ~PARAMKIND_Z, CNF_Mean, coefs); - - // recompute feature values - for (i=0; i < tot_frames; i++) - { - for (j=trg_N; j < coefs; j++) - { - rFeatureMatrix[i][j - trg_N] -= mpCmn[j]; - } - } - } - - mHeader.mSampleKind |= mDerivOrder==3 ? PARAMKIND_D | PARAMKIND_A | PARAMKIND_T : - mDerivOrder==2 ? PARAMKIND_D | PARAMKIND_A : - mDerivOrder==1 ? PARAMKIND_D : 0; - - //......................................................................... - if (mpCvnPath != NULL - && mpCvnMask != NULL) - { - // retrieve file name - ProcessMask(file_name, mpCvnMask, cvn_file_name); - // add the path correctly - cvn_file_name.insert(0, "/"); - cvn_file_name.insert(0, mpCvnPath); - - // read the file - ReadCepsNormFile(cvn_file_name.c_str(), &mpLastCvnFile, &mpCvn, - mHeader.mSampleKind, CNF_Variance, trg_vec_size); - - // recompute feature values - for (i=0; i < tot_frames; i++) - { - for (j=trg_N; j < trg_vec_size; j++) - { - rFeatureMatrix[i][j - trg_N] *= mpCvn[j]; - } - } - } - - //......................................................................... - // process the global covariance file - if (mpCvgFile != NULL) - { - ReadCepsNormFile(mpCvgFile, &mpLastCvgFile, &mpCvg, - -1, CNF_VarScale, trg_vec_size); - - // recompute feature values - for (i=0; i < tot_frames; i++) - { - for (j=trg_N; j < trg_vec_size; j++) - { - rFeatureMatrix[i][j - trg_N] *= mpCvg[j]; - } - } - } - - return true; - } -*/ - - //*************************************************************************** - //*************************************************************************** - - - - - - //*************************************************************************** - //*************************************************************************** - bool - FeatureRepository:: - ReadHTKFeatures(const FileListElem& rFileNameRecord, - Matrix& rFeatureMatrix) - { - std::string file_name(rFileNameRecord.Physical()); - std::string cmn_file_name; - std::string cvn_file_name; - - int ext_left = mStartFrameExt; - int ext_right = mEndFrameExt; - int from_frame; - int to_frame; - int tot_frames; - int trg_vec_size; - int src_vec_size; - int src_deriv_order; - int lo_src_tgz_deriv_order; - int i; - int j; - int k; - int e; - int coefs; - int trg_E; - int trg_0; - int trg_N; - int src_E; - int src_0; - int src_N; - int comp; - int coef_size; - char* chptr; - - - TIMER_START(mTim); - - // read frame range definition if any ( physical_file.fea[s,e] ) - if ((chptr = strrchr((char*)file_name.c_str(), '[')) == NULL || - ((i=0), sscanf(chptr, "[%d,%d]%n", &from_frame, &to_frame, &i), - chptr[i] != '\0')) - { - chptr = NULL; - } - - if (chptr != NULL) - *chptr = '\0'; - - - if ((file_name != "-" ) - && (!mLastFileName.empty()) - && (mLastFileName == file_name)) - { - mHeader = mLastHeader; - } - else - { - if (!mLastFileName.empty()) - { - mStream.close(); - mLastFileName = ""; - } - - - // open the feature file - mStream.open(file_name.c_str(), std::ios::binary); - if (!mStream.good()) - { - throw std::runtime_error(std::string("Cannot open feature file: '") - + file_name.c_str() + "'"); - } - - - if (ReadHTKHeader()) { - throw std::runtime_error(std::string("Invalid HTK header in feature file: '") - + file_name.c_str() + "'"); - } - - if (mHeader.mSampleKind & PARAMKIND_C) - { - // File is in compressed form, scale and pBias vectors - // are appended after HTK header. - coefs = mHeader.mSampleSize/sizeof(INT_16); - - mpA = (BaseFloat*) realloc(mpA, coefs * sizeof(BaseFloat)); - mpB = (BaseFloat*) realloc(mpB, coefs * sizeof(BaseFloat)); - - if (mpA == NULL || mpB == NULL) { - throw std::runtime_error("Insufficient memory"); - } - - e = ReadHTKFeature(mpA, coefs, 0, 0, 0); - e |= ReadHTKFeature(mpB, coefs, 0, 0, 0); - - if (e) { - throw std::runtime_error(std::string("Cannot read feature file: '") - + file_name.c_str() + "'"); - } - - mHeader.mNSamples -= 2 * sizeof(FLOAT_32) / sizeof(INT_16); - } - - // remember current settings - mLastFileName = file_name; - mLastHeader = mHeader; - } - - if (chptr != NULL) { - *chptr = '['; - } - - if (chptr == NULL) { - // Range [s,e] was not specified - from_frame = 0; - to_frame = mHeader.mNSamples-1; - } - - src_deriv_order = PARAMKIND_T & mHeader.mSampleKind ? 3 : - PARAMKIND_A & mHeader.mSampleKind ? 2 : - PARAMKIND_D & mHeader.mSampleKind ? 1 : 0; - src_E = (PARAMKIND_E & mHeader.mSampleKind) != 0; - src_0 = (PARAMKIND_0 & mHeader.mSampleKind) != 0; - src_N = ((PARAMKIND_N & mHeader.mSampleKind) != 0) * (src_E + src_0); - comp = PARAMKIND_C & mHeader.mSampleKind; - - mHeader.mSampleKind &= ~PARAMKIND_C; - - if (mTargetKind == PARAMKIND_ANON) - { - mTargetKind = mHeader.mSampleKind; - } - else if ((mTargetKind & 077) == PARAMKIND_ANON) - { - mTargetKind &= ~077; - mTargetKind |= mHeader.mSampleKind & 077; - } - - trg_E = (PARAMKIND_E & mTargetKind) != 0; - trg_0 = (PARAMKIND_0 & mTargetKind) != 0; - trg_N =((PARAMKIND_N & mTargetKind) != 0) * (trg_E + trg_0); - - coef_size = comp ? sizeof(INT_16) : sizeof(FLOAT_32); - coefs = (mHeader.mSampleSize/coef_size + src_N) / - (src_deriv_order+1) - src_E - src_0; - src_vec_size = (coefs + src_E + src_0) * (src_deriv_order+1) - src_N; - - //Is coefs dividable by 1 + number of derivatives specified in header - if (src_vec_size * coef_size != mHeader.mSampleSize) - { - throw std::runtime_error(std::string("Invalid HTK header in feature file: '") - + file_name + "' mSampleSize do not match with parmKind"); - } - - if (mDerivOrder < 0) - mDerivOrder = src_deriv_order; - - - if ((!src_E && trg_E) || (!src_0 && trg_0) || (src_N && !trg_N) || - (trg_N && !trg_E && !trg_0) || (trg_N && !mDerivOrder) || - (src_N && !src_deriv_order && mDerivOrder) || - ((mHeader.mSampleKind & 077) != (mTargetKind & 077) && - (mHeader.mSampleKind & 077) != PARAMKIND_ANON)) - { - char srcParmKind[64]; - char trgParmKind[64]; - memset(srcParmKind,0,64); - memset(trgParmKind,0,64); - - ParmKind2Str(mHeader.mSampleKind, srcParmKind); - ParmKind2Str(mTargetKind, trgParmKind); - throw std::runtime_error(std::string("Cannot convert ") + srcParmKind - + " to " + trgParmKind); - } - - lo_src_tgz_deriv_order = std::min(src_deriv_order, mDerivOrder); - trg_vec_size = (coefs + trg_E + trg_0) * (mDerivOrder+1) - trg_N; - - i = std::min(from_frame, mStartFrameExt); - from_frame -= i; - ext_left -= i; - - i = std::min(mHeader.mNSamples-to_frame-1, mEndFrameExt); - to_frame += i; - ext_right -= i; - - if (from_frame > to_frame || from_frame >= mHeader.mNSamples || to_frame< 0) - throw std::runtime_error(std::string("Invalid frame range for feature file: '") - + file_name.c_str() + "'"); - - tot_frames = to_frame - from_frame + 1 + ext_left + ext_right; - - - TIMER_END(mTim,mTimeOpen); - - - // initialize matrix - rFeatureMatrix.Init(tot_frames, trg_vec_size, false); - - // fill the matrix with features - for (i = 0; i <= to_frame - from_frame; i++) - { - BaseFloat* A = mpA; - BaseFloat* B = mpB; - BaseFloat* mxPtr = rFeatureMatrix.pRowData(i+ext_left); - - TIMER_START(mTim); - // seek to the desired position - fseek(mStream.fp(), - sizeof(HtkHeader) + (comp ? src_vec_size * 2 * sizeof(FLOAT_32) : 0) - + (from_frame + i) * src_vec_size * coef_size, - SEEK_SET); - TIMER_END(mTim,mTimeSeek); - - TIMER_START(mTim); - // read - e = ReadHTKFeature(mxPtr, coefs, comp, A, B); - TIMER_END(mTim,mTimeRead); - - mxPtr += coefs; - A += coefs; - B += coefs; - - if (src_0 && !src_N) e |= ReadHTKFeature(mxPtr, 1, comp, A++, B++); - if (trg_0 && !trg_N) mxPtr++; - if (src_E && !src_N) e |= ReadHTKFeature(mxPtr, 1, comp, A++, B++); - if (trg_E && !trg_N) mxPtr++; - - for (j = 0; j < lo_src_tgz_deriv_order; j++) - { - e |= ReadHTKFeature(mxPtr, coefs, comp, A, B); - mxPtr += coefs; - A += coefs; - B += coefs; - - if (src_0) e |= ReadHTKFeature(mxPtr, 1, comp, A++, B++); - if (trg_0) mxPtr++; - if (src_E) e |= ReadHTKFeature(mxPtr, 1, comp, A++, B++); - if (trg_E) mxPtr++; - } - - if (e) { - std::cout << mHeader.mNSamples << "\n"; - std::cout << 2 * sizeof(FLOAT_32) / sizeof(INT_16) << "\n"; - std::cout << "from" << from_frame << "to" << to_frame << "i" << i << "\n"; - - std::ostringstream s; - s << i << "/" << to_frame - from_frame + 1, s.str(); - throw std::runtime_error(std::string("Cannot read feature file: '") - + file_name + "' frame " + s.str()); - } - } - - // From now, coefs includes also trg_0 + trg_E ! - coefs += trg_0 + trg_E; - - // If extension of the matrix to the left or to the right is required, - // perform it here - for (i = 0; i < ext_left; i++) - { - memcpy(rFeatureMatrix.pRowData(i), - rFeatureMatrix.pRowData(ext_left), - (coefs * (1+lo_src_tgz_deriv_order) - trg_N) * sizeof(BaseFloat)); - } - - for (i = tot_frames - ext_right; i < tot_frames; i++) - { - memcpy(rFeatureMatrix.pRowData(i), - rFeatureMatrix.pRowData(tot_frames - ext_right - 1), - (coefs * (1+lo_src_tgz_deriv_order) - trg_N) * sizeof(BaseFloat)); - } - - // Sentence cepstral mean normalization - if( (mpCmnPath == NULL) - && !(PARAMKIND_Z & mHeader.mSampleKind) - && (PARAMKIND_Z & mTargetKind)) - { - // for each coefficient - for(j=0; j < coefs; j++) - { - BaseFloat norm = 0.0; - for(i=0; i < tot_frames; i++) // for each frame - { - norm += rFeatureMatrix[i][j - trg_N]; - //norm += fea_mx[i*trg_vec_size - trg_N + j]; - } -