All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Modules Pages
Vector< Real > Singleton Reference

A class representing a vector. More...

#include <kaldi-vector.h>

Inheritance diagram for Vector< Real >:
Collaboration diagram for Vector< Real >:

Public Member Functions

 Vector ()
 Constructor that takes no arguments. Initializes to empty. More...
 
 Vector (const MatrixIndexT s, MatrixResizeType resize_type=kSetZero)
 Constructor with specific size. More...
 
template<typename OtherReal >
 Vector (const CuVectorBase< OtherReal > &cu)
 Copy constructor from CUDA vector This is defined in ../cudamatrix/cu-vector.h. More...
 
 Vector (const Vector< Real > &v)
 Copy constructor. The need for this is controversial. More...
 
 Vector (const VectorBase< Real > &v)
 Copy-constructor from base-class, needed to copy from SubVector. More...
 
template<typename OtherReal >
 Vector (const VectorBase< OtherReal > &v)
 Type conversion constructor. More...
 
void Swap (Vector< Real > *other)
 Swaps the contents of *this and *other. Shallow swap. More...
 
 ~Vector ()
 Destructor. Deallocates memory. More...
 
void Read (std::istream &in, bool binary, bool add=false)
 Read function using C++ streams. More...
 
void Resize (MatrixIndexT length, MatrixResizeType resize_type=kSetZero)
 Set vector to a specified size (can be zero). More...
 
void RemoveElement (MatrixIndexT i)
 Remove one element and shifts later elements down. More...
 
Vector< Real > & operator= (const Vector< Real > &other)
 Assignment operator, protected so it can only be used by std::vector. More...
 
Vector< Real > & operator= (const VectorBase< Real > &other)
 Assignment operator that takes VectorBase. More...
 
- Public Member Functions inherited from VectorBase< Real >
void SetZero ()
 Set vector to all zeros. More...
 
bool IsZero (Real cutoff=1.0e-06) const
 Returns true if matrix is all zeros. More...
 
void Set (Real f)
 Set all members of a vector to a specified value. More...
 
void SetRandn ()
 Set vector to random normally-distributed noise. More...
 
void SetRandUniform ()
 Sets to numbers uniformly distributed on (0,1) More...
 
MatrixIndexT RandCategorical () const
 This function returns a random index into this vector, chosen with probability proportional to the corresponding element. More...
 
MatrixIndexT Dim () const
 Returns the dimension of the vector. More...
 
MatrixIndexT SizeInBytes () const
 Returns the size in memory of the vector, in bytes. More...
 
Real * Data ()
 Returns a pointer to the start of the vector's data. More...
 
const Real * Data () const
 Returns a pointer to the start of the vector's data (const). More...
 
Real operator() (MatrixIndexT i) const
 Indexing operator (const). More...
 
Real & operator() (MatrixIndexT i)
 Indexing operator (non-const). More...
 
SubVector< Real > Range (const MatrixIndexT o, const MatrixIndexT l)
 Returns a sub-vector of a vector (a range of elements). More...
 
const SubVector< Real > Range (const MatrixIndexT o, const MatrixIndexT l) const
 Returns a const sub-vector of a vector (a range of elements). More...
 
void CopyFromVec (const VectorBase< Real > &v)
 Copy data from another vector (must match own size). More...
 
template<typename OtherReal >
void CopyFromPacked (const PackedMatrix< OtherReal > &M)
 Copy data from a SpMatrix or TpMatrix (must match own size). More...
 
template<typename OtherReal >
void CopyFromVec (const VectorBase< OtherReal > &v)
 Copy data from another vector of different type (double vs. float) More...
 
template<typename OtherReal >
void CopyFromVec (const CuVectorBase< OtherReal > &v)
 Copy from CuVector. This is defined in ../cudamatrix/cu-vector.h. More...
 
void ApplyLog ()
 Apply natural log to all elements. More...
 
void ApplyLogAndCopy (const VectorBase< Real > &v)
 Apply natural log to another vector and put result in *this. More...
 
void ApplyExp ()
 Apply exponential to each value in vector. More...
 
void ApplyAbs ()
 Take absolute value of each of the elements. More...
 
void ApplyFloor (Real floor_val, MatrixIndexT *floored_count=nullptr)
 Applies floor to all elements. More...
 
void ApplyCeiling (Real ceil_val, MatrixIndexT *ceiled_count=nullptr)
 Applies ceiling to all elements. More...
 
MatrixIndexT ApplyFloor (const VectorBase< Real > &floor_vec)
 Applies floor to all elements. Returns number of elements floored. More...
 
Real ApplySoftMax ()
 Apply soft-max to vector and return normalizer (log sum of exponentials). More...
 
Real ApplyLogSoftMax ()
 Applies log soft-max to vector and returns normalizer (log sum of exponentials). More...
 
void Tanh (const VectorBase< Real > &src)
 Sets each element of *this to the tanh of the corresponding element of "src". More...
 
void Sigmoid (const VectorBase< Real > &src)
 Sets each element of *this to the sigmoid function of the corresponding element of "src". More...
 
void ApplyPow (Real power)
 Take all elements of vector to a power. More...
 
void ApplyPowAbs (Real power, bool include_sign=false)
 Take the absolute value of all elements of a vector to a power. More...
 
Real Norm (Real p) const
 Compute the p-th norm of the vector. More...
 
bool ApproxEqual (const VectorBase< Real > &other, float tol=0.01) const
 Returns true if ((*this)-other).Norm(2.0) <= tol * (*this).Norm(2.0). More...
 
void InvertElements ()
 Invert all elements. More...
 
template<typename OtherReal >
void AddVec (const Real alpha, const VectorBase< OtherReal > &v)
 Add vector : *this = *this + alpha * rv (with casting between floats and doubles) More...
 
void AddVec2 (const Real alpha, const VectorBase< Real > &v)
 Add vector : *this = *this + alpha * rv^2 [element-wise squaring]. More...
 
template<typename OtherReal >
void AddVec2 (const Real alpha, const VectorBase< OtherReal > &v)
 Add vector : *this = *this + alpha * rv^2 [element-wise squaring], with casting between floats and doubles. More...
 
void AddMatVec (const Real alpha, const MatrixBase< Real > &M, const MatrixTransposeType trans, const VectorBase< Real > &v, const Real beta)
 Add matrix times vector : this <– beta*this + alpha*M*v. More...
 
void AddMatSvec (const Real alpha, const MatrixBase< Real > &M, const MatrixTransposeType trans, const VectorBase< Real > &v, const Real beta)
 This is as AddMatVec, except optimized for where v contains a lot of zeros. More...
 
void AddSpVec (const Real alpha, const SpMatrix< Real > &M, const VectorBase< Real > &v, const Real beta)
 Add symmetric positive definite matrix times vector: this <– beta*this + alpha*M*v. More...
 
void AddTpVec (const Real alpha, const TpMatrix< Real > &M, const MatrixTransposeType trans, const VectorBase< Real > &v, const Real beta)
 Add triangular matrix times vector: this <– beta*this + alpha*M*v. More...
 
void ReplaceValue (Real orig, Real changed)
 Set each element to y = (x == orig ? changed : x). More...
 
void MulElements (const VectorBase< Real > &v)
 Multipy element-by-element by another vector. More...
 
template<typename OtherReal >
void MulElements (const VectorBase< OtherReal > &v)
 Multipy element-by-element by another vector of different type. More...
 
void DivElements (const VectorBase< Real > &v)
 Divide element-by-element by a vector. More...
 
template<typename OtherReal >
void DivElements (const VectorBase< OtherReal > &v)
 Divide element-by-element by a vector of different type. More...
 
void Add (Real c)
 Add a constant to each element of a vector. More...
 
void AddVecVec (Real alpha, const VectorBase< Real > &v, const VectorBase< Real > &r, Real beta)
 Add element-by-element product of vectlrs: More...
 
void AddVecDivVec (Real alpha, const VectorBase< Real > &v, const VectorBase< Real > &r, Real beta)
 Add element-by-element quotient of two vectors. More...
 
void Scale (Real alpha)
 Multiplies all elements by this constant. More...
 
void MulTp (const TpMatrix< Real > &M, const MatrixTransposeType trans)
 Multiplies this vector by lower-triangular marix: *this <– *this *M. More...
 
void Solve (const TpMatrix< Real > &M, const MatrixTransposeType trans)
 If trans == kNoTrans, solves M x = b, where b is the value of *this at input and x is the value of *this at output. More...
 
void CopyRowsFromMat (const MatrixBase< Real > &M)
 Performs a row stack of the matrix M. More...
 
template<typename OtherReal >
void CopyRowsFromMat (const MatrixBase< OtherReal > &M)
 
void CopyRowsFromMat (const CuMatrixBase< Real > &M)
 The following is implemented in ../cudamatrix/cu-matrix.cc. More...
 
void CopyColsFromMat (const MatrixBase< Real > &M)
 Performs a column stack of the matrix M. More...
 
void CopyRowFromMat (const MatrixBase< Real > &M, MatrixIndexT row)
 Extracts a row of the matrix M. More...
 
template<typename OtherReal >
void CopyRowFromMat (const MatrixBase< OtherReal > &M, MatrixIndexT row)
 Extracts a row of the matrix M with type conversion. More...
 
template<typename OtherReal >
void CopyRowFromSp (const SpMatrix< OtherReal > &S, MatrixIndexT row)
 Extracts a row of the symmetric matrix S. More...
 
template<typename OtherReal >
void CopyColFromMat (const MatrixBase< OtherReal > &M, MatrixIndexT col)
 Extracts a column of the matrix M. More...
 
void CopyDiagFromMat (const MatrixBase< Real > &M)
 Extracts the diagonal of the matrix M. More...
 
void CopyDiagFromPacked (const PackedMatrix< Real > &M)
 Extracts the diagonal of a packed matrix M; works for Sp or Tp. More...
 
void CopyDiagFromSp (const SpMatrix< Real > &M)
 Extracts the diagonal of a symmetric matrix. More...
 
void CopyDiagFromTp (const TpMatrix< Real > &M)
 Extracts the diagonal of a triangular matrix. More...
 
Real Max () const
 Returns the maximum value of any element, or -infinity for the empty vector. More...
 
Real Max (MatrixIndexT *index) const
 Returns the maximum value of any element, and the associated index. More...
 
Real Min () const
 Returns the minimum value of any element, or +infinity for the empty vector. More...
 
Real Min (MatrixIndexT *index) const
 Returns the minimum value of any element, and the associated index. More...
 
Real Sum () const
 Returns sum of the elements. More...
 
Real SumLog () const
 Returns sum of the logs of the elements. More...
 
void AddRowSumMat (Real alpha, const MatrixBase< Real > &M, Real beta=1.0)
 Does *this = alpha * (sum of rows of M) + beta * *this. More...
 
void AddColSumMat (Real alpha, const MatrixBase< Real > &M, Real beta=1.0)
 Does *this = alpha * (sum of columns of M) + beta * *this. More...
 
void AddDiagMat2 (Real alpha, const MatrixBase< Real > &M, MatrixTransposeType trans=kNoTrans, Real beta=1.0)
 Add the diagonal of a matrix times itself: *this = diag(M M^T) + beta * *this (if trans == kNoTrans), or *this = diag(M^T M) + beta * *this (if trans == kTrans). More...
 
void AddDiagMatMat (Real alpha, const MatrixBase< Real > &M, MatrixTransposeType transM, const MatrixBase< Real > &N, MatrixTransposeType transN, Real beta=1.0)
 Add the diagonal of a matrix product: *this = diag(M N), assuming the "trans" arguments are both kNoTrans; for transpose arguments, it behaves as you would expect. More...
 
Real LogSumExp (Real prune=-1.0) const
 Returns log(sum(exp())) without exp overflow If prune > 0.0, ignores terms less than the max - prune. More...
 
void Read (std::istream &in, bool binary, bool add=false)
 Reads from C++ stream (option to add to existing contents). More...
 
void Write (std::ostream &Out, bool binary) const
 Writes to C++ stream (option to write in binary). More...
 
template<>
void AddVec (const float alpha, const VectorBase< float > &rv)
 
template<>
void AddVec (const double alpha, const VectorBase< double > &rv)
 
template<>
void AddVec (const float alpha, const VectorBase< float > &v)
 
template<>
void AddVec (const double alpha, const VectorBase< double > &v)
 

Private Member Functions

void Init (const MatrixIndexT dim)
 Init assumes the current contents of the class are invalid (i.e. More...
 
void Destroy ()
 Destroy function, called internally. More...
 

Additional Inherited Members

- Protected Member Functions inherited from VectorBase< Real >
 ~VectorBase ()
 Destructor; does not deallocate memory, this is handled by child classes. More...
 
 VectorBase ()
 Empty initializer, corresponds to vector of zero size. More...
 
void CopyFromPtr (const Real *Data, MatrixIndexT sz)
 Load data into the vector: sz must match own size. More...
 
 KALDI_DISALLOW_COPY_AND_ASSIGN (VectorBase)
 
- Protected Attributes inherited from VectorBase< Real >
Real * data_
 data memory area More...
 
MatrixIndexT dim_
 dimension of vector More...
 

Detailed Description

template<typename Real>
singleton kaldi::Vector< Real >

A class representing a vector.

This class provides a way to work with vectors in kaldi. It encapsulates basic operations and memory optimizations.

Definition at line 390 of file kaldi-vector.h.

Constructor & Destructor Documentation

Vector ( )
inline

Constructor that takes no arguments. Initializes to empty.

Definition at line 393 of file kaldi-vector.h.

393 : VectorBase<Real>() {}
Vector ( const MatrixIndexT  s,
MatrixResizeType  resize_type = kSetZero 
)
inlineexplicit

Constructor with specific size.

Sets to all-zero by default if set_zero == false, memory contents are undefined.

Definition at line 397 of file kaldi-vector.h.

399  : VectorBase<Real>() { Resize(s, resize_type); }
void Resize(MatrixIndexT length, MatrixResizeType resize_type=kSetZero)
Set vector to a specified size (can be zero).
Vector ( const CuVectorBase< OtherReal > &  cu)
explicit

Copy constructor from CUDA vector This is defined in ../cudamatrix/cu-vector.h.

Definition at line 383 of file cu-vector.h.

383  {
384  Init(cu.Dim());
385  cu.CopyToVec(this);
386 }
void Init(const MatrixIndexT dim)
Init assumes the current contents of the class are invalid (i.e.
Vector ( const Vector< Real > &  v)
inline

Copy constructor. The need for this is controversial.

Definition at line 407 of file kaldi-vector.h.

407  : VectorBase<Real>() { // (cannot be explicit)
408  Resize(v.Dim(), kUndefined);
409  this->CopyFromVec(v);
410  }
void Resize(MatrixIndexT length, MatrixResizeType resize_type=kSetZero)
Set vector to a specified size (can be zero).
void CopyFromVec(const VectorBase< Real > &v)
Copy data from another vector (must match own size).
Vector ( const VectorBase< Real > &  v)
inlineexplicit

Copy-constructor from base-class, needed to copy from SubVector.

Definition at line 413 of file kaldi-vector.h.

413  : VectorBase<Real>() {
414  Resize(v.Dim(), kUndefined);
415  this->CopyFromVec(v);
416  }
void Resize(MatrixIndexT length, MatrixResizeType resize_type=kSetZero)
Set vector to a specified size (can be zero).
void CopyFromVec(const VectorBase< Real > &v)
Copy data from another vector (must match own size).
Vector ( const VectorBase< OtherReal > &  v)
inlineexplicit

Type conversion constructor.

Definition at line 420 of file kaldi-vector.h.

420  : VectorBase<Real>() {
421  Resize(v.Dim(), kUndefined);
422  this->CopyFromVec(v);
423  }
void Resize(MatrixIndexT length, MatrixResizeType resize_type=kSetZero)
Set vector to a specified size (can be zero).
void CopyFromVec(const VectorBase< Real > &v)
Copy data from another vector (must match own size).
~Vector ( )
inline

Destructor. Deallocates memory.

Definition at line 438 of file kaldi-vector.h.

438 { Destroy(); }
void Destroy()
Destroy function, called internally.

Member Function Documentation

void Destroy ( )
private

Destroy function, called internally.

Deallocates memory and sets object to empty vector.

we need to free the data block if it was defined

Definition at line 279 of file kaldi-vector.cc.

References data_, and KALDI_MEMALIGN_FREE.

Referenced by Vector< BaseFloat >::~Vector().

279  {
281  if (this->data_ != NULL)
282  KALDI_MEMALIGN_FREE(this->data_);
283  this->data_ = NULL;
284  this->dim_ = 0;
285 }
MatrixIndexT dim_
dimension of vector
Definition: kaldi-vector.h:381
#define KALDI_MEMALIGN_FREE(x)
Definition: kaldi-utils.h:56
Real * data_
data memory area
Definition: kaldi-vector.h:379
void Init ( const MatrixIndexT  dim)
inlineprivate

Init assumes the current contents of the class are invalid (i.e.

junk or has already been freed), and it sets the vector to newly allocated memory with the specified dimension. dim == 0 is acceptable. The memory contents pointed to by data_ will be undefined.

Definition at line 167 of file kaldi-vector.cc.

References data_, KALDI_ASSERT, and KALDI_MEMALIGN.

167  {
168  KALDI_ASSERT(dim >= 0);
169  if (dim == 0) {
170  this->dim_ = 0;
171  this->data_ = NULL;
172  return;
173  }
174  MatrixIndexT size;
175  void *data;
176  void *free_data;
177 
178  size = dim * sizeof(Real);
179 
180  if ((data = KALDI_MEMALIGN(16, size, &free_data)) != NULL) {
181  this->data_ = static_cast<Real*> (data);
182  this->dim_ = dim;
183  } else {
184  throw std::bad_alloc();
185  }
186 }
int32 MatrixIndexT
Definition: matrix-common.h:98
MatrixIndexT dim_
dimension of vector
Definition: kaldi-vector.h:381
#define KALDI_MEMALIGN(align, size, pp_orig)
Definition: kaldi-utils.h:54
Real * data_
data memory area
Definition: kaldi-vector.h:379
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:169
Vector<Real>& operator= ( const Vector< Real > &  other)
inline

Assignment operator, protected so it can only be used by std::vector.

Definition at line 457 of file kaldi-vector.h.

457  {
458  Resize(other.Dim(), kUndefined);
459  this->CopyFromVec(other);
460  return *this;
461  }
void Resize(MatrixIndexT length, MatrixResizeType resize_type=kSetZero)
Set vector to a specified size (can be zero).
void CopyFromVec(const VectorBase< Real > &v)
Copy data from another vector (must match own size).
Vector<Real>& operator= ( const VectorBase< Real > &  other)
inline

Assignment operator that takes VectorBase.

Definition at line 464 of file kaldi-vector.h.

464  {
465  Resize(other.Dim(), kUndefined);
466  this->CopyFromVec(other);
467  return *this;
468  }
void Resize(MatrixIndexT length, MatrixResizeType resize_type=kSetZero)
Set vector to a specified size (can be zero).
void CopyFromVec(const VectorBase< Real > &v)
Copy data from another vector (must match own size).
void Read ( std::istream &  in,
bool  binary,
bool  add = false 
)

Read function using C++ streams.

Can also add to existing contents of matrix.

Definition at line 1106 of file kaldi-vector.cc.

References data_, VectorBase< Real >::Dim(), rnnlm::i, rnnlm::j, KALDI_ERR, KALDI_STRCASECMP, KALDI_WARN, kaldi::Peek(), Vector< Real >::Read(), kaldi::ReadBasicType(), and kaldi::ReadToken().

Referenced by FramePoolingComponent::InitData(), main(), kaldi::operator>>(), PdfPrior::PdfPrior(), AmNnet::Read(), NnetExample::Read(), AmNnetSimple::Read(), AccumFullGmm::Read(), LdaEstimate::Read(), Sgmm2FmllrGlobalParams::Read(), AccumDiagGmm::Read(), TransitionModel::Read(), FullGmm::Read(), Plda::Read(), VectorClusterable::Read(), RestrictedAttentionComponent::Read(), DiagGmm::Read(), DiscriminativeNnetExample::Read(), IvectorExtractor::Read(), CuVector< Real >::Read(), VectorBase< Real >::Read(), OnlineIvectorEstimationStats::Read(), Vector< Real >::Read(), IvectorExtractorStats::Read(), PermuteComponent::Read(), kaldi::nnet3::ReadVectorAsChar(), kaldi::TypeThreeUsage(), kaldi::UnitTestIo(), kaldi::UnitTestIoCross(), and UnitTestReadWave().

1106  {
1107  if (add) {
1108  Vector<Real> tmp(this->Dim());
1109  tmp.Read(is, binary, false); // read without adding.
1110  if (this->Dim() == 0) this->Resize(tmp.Dim());
1111  if (this->Dim() != tmp.Dim()) {
1112  KALDI_ERR << "Vector<Real>::Read, adding but dimensions mismatch "
1113  << this->Dim() << " vs. " << tmp.Dim();
1114  }
1115  this->AddVec(1.0, tmp);
1116  return;
1117  } // now assume add == false.
1118 
1119  std::ostringstream specific_error;
1120  MatrixIndexT pos_at_start = is.tellg();
1121 
1122  if (binary) {
1123  int peekval = Peek(is, binary);
1124  const char *my_token = (sizeof(Real) == 4 ? "FV" : "DV");
1125  char other_token_start = (sizeof(Real) == 4 ? 'D' : 'F');
1126  if (peekval == other_token_start) { // need to instantiate the other type to read it.
1127  typedef typename OtherReal<Real>::Real OtherType; // if Real == float, OtherType == double, and vice versa.
1128  Vector<OtherType> other(this->Dim());
1129  other.Read(is, binary, false); // add is false at this point.
1130  if (this->Dim() != other.Dim()) this->Resize(other.Dim());
1131  this->CopyFromVec(other);
1132  return;
1133  }
1134  std::string token;
1135  ReadToken(is, binary, &token);
1136  if (token != my_token) {
1137  if (token.length() > 20) token = token.substr(0, 17) + "...";
1138  specific_error << ": Expected token " << my_token << ", got " << token;
1139  goto bad;
1140  }
1141  int32 size;
1142  ReadBasicType(is, binary, &size); // throws on error.
1143  if ((MatrixIndexT)size != this->Dim()) this->Resize(size);
1144  if (size > 0)
1145  is.read(reinterpret_cast<char*>(this->data_), sizeof(Real)*size);
1146  if (is.fail()) {
1147  specific_error << "Error reading vector data (binary mode); truncated "
1148  "stream? (size = " << size << ")";
1149  goto bad;
1150  }
1151  return;
1152  } else { // Text mode reading; format is " [ 1.1 2.0 3.4 ]\n"
1153  std::string s;
1154  is >> s;
1155  // if ((s.compare("DV") == 0) || (s.compare("FV") == 0)) { // Back compatibility.
1156  // is >> s; // get dimension
1157  // is >> s; // get "["
1158  // }
1159  if (is.fail()) { specific_error << "EOF while trying to read vector."; goto bad; }
1160  if (s.compare("[]") == 0) { Resize(0); return; } // tolerate this variant.
1161  if (s.compare("[")) {
1162  if (s.length() > 20) s = s.substr(0, 17) + "...";
1163  specific_error << "Expected \"[\" but got " << s;
1164  goto bad;
1165  }
1166  std::vector<Real> data;
1167  while (1) {
1168  int i = is.peek();
1169  if (i == '-' || (i >= '0' && i <= '9')) { // common cases first.
1170  Real r;
1171  is >> r;
1172  if (is.fail()) { specific_error << "Failed to read number."; goto bad; }
1173  if (! std::isspace(is.peek()) && is.peek() != ']') {
1174  specific_error << "Expected whitespace after number."; goto bad;
1175  }
1176  data.push_back(r);
1177  // But don't eat whitespace... we want to check that it's not newlines
1178  // which would be valid only for a matrix.
1179  } else if (i == ' ' || i == '\t') {
1180  is.get();
1181  } else if (i == ']') {
1182  is.get(); // eat the ']'
1183  this->Resize(data.size());
1184  for (size_t j = 0; j < data.size(); j++)
1185  this->data_[j] = data[j];
1186  i = is.peek();
1187  if (static_cast<char>(i) == '\r') {
1188  is.get();
1189  is.get(); // get \r\n (must eat what we wrote)
1190  } else if (static_cast<char>(i) == '\n') { is.get(); } // get \n (must eat what we wrote)
1191  if (is.fail()) {
1192  KALDI_WARN << "After end of vector data, read error.";
1193  // we got the data we needed, so just warn for this error.
1194  }
1195  return; // success.
1196  } else if (i == -1) {
1197  specific_error << "EOF while reading vector data.";
1198  goto bad;
1199  } else if (i == '\n' || i == '\r') {
1200  specific_error << "Newline found while reading vector (maybe it's a matrix?)";
1201  goto bad;
1202  } else {
1203  is >> s; // read string.
1204  if (!KALDI_STRCASECMP(s.c_str(), "inf") ||
1205  !KALDI_STRCASECMP(s.c_str(), "infinity")) {
1206  data.push_back(std::numeric_limits<Real>::infinity());
1207  KALDI_WARN << "Reading infinite value into vector.";
1208  } else if (!KALDI_STRCASECMP(s.c_str(), "nan")) {
1209  data.push_back(std::numeric_limits<Real>::quiet_NaN());
1210  KALDI_WARN << "Reading NaN value into vector.";
1211  } else {
1212  if (s.length() > 20) s = s.substr(0, 17) + "...";
1213  specific_error << "Expecting numeric vector data, got " << s;
1214  goto bad;
1215  }
1216  }
1217  }
1218  }
1219  // we never reach this line (the while loop returns directly).
1220 bad:
1221  KALDI_ERR << "Failed to read vector from stream. " << specific_error.str()
1222  << " File position at start is "
1223  << pos_at_start<<", currently "<<is.tellg();
1224 }
void ReadBasicType(std::istream &is, bool binary, T *t)
ReadBasicType is the name of the read function for bool, integer types, and floating-point types...
Definition: io-funcs-inl.h:55
void ReadToken(std::istream &is, bool binary, std::string *str)
ReadToken gets the next token and puts it in str (exception on failure).
Definition: io-funcs.cc:154
void Resize(MatrixIndexT length, MatrixResizeType resize_type=kSetZero)
Set vector to a specified size (can be zero).
int Peek(std::istream &is, bool binary)
Peek consumes whitespace (if binary == false) and then returns the peek() value of the stream...
Definition: io-funcs.cc:145
void CopyFromVec(const VectorBase< Real > &v)
Copy data from another vector (must match own size).
int32 MatrixIndexT
Definition: matrix-common.h:98
#define KALDI_ERR
Definition: kaldi-error.h:127
#define KALDI_WARN
Definition: kaldi-error.h:130
Real * data_
data memory area
Definition: kaldi-vector.h:379
#define KALDI_STRCASECMP
Definition: kaldi-utils.h:140
void AddVec(const Real alpha, const VectorBase< OtherReal > &v)
Add vector : *this = *this + alpha * rv (with casting between floats and doubles) ...
MatrixIndexT Dim() const
Returns the dimension of the vector.
Definition: kaldi-vector.h:63
void RemoveElement ( MatrixIndexT  i)

Remove one element and shifts later elements down.

Definition at line 269 of file kaldi-vector.cc.

References data_, rnnlm::j, and KALDI_ASSERT.

Referenced by FullGmm::Merge(), DiagGmm::Merge(), DiagGmm::RemoveComponent(), FullGmm::RemoveComponent(), and kaldi::UnitTestRemoveRow().

269  {
270  KALDI_ASSERT(i < this->dim_ && "Access out of vector");
271  for (MatrixIndexT j = i + 1; j < this->dim_; j++)
272  this->data_[j-1] = this->data_[j];
273  this->dim_--;
274 }
int32 MatrixIndexT
Definition: matrix-common.h:98
MatrixIndexT dim_
dimension of vector
Definition: kaldi-vector.h:381
Real * data_
data memory area
Definition: kaldi-vector.h:379
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:169
void Resize ( MatrixIndexT  length,
MatrixResizeType  resize_type = kSetZero 
)

Set vector to a specified size (can be zero).

The value of the new data depends on resize_type: -if kSetZero, the new data will be zero -if kUndefined, the new data will be undefined -if kCopyData, the new data will be the same as the old data in any shared positions, and zero elsewhere. This function takes time proportional to the number of data elements.

Definition at line 190 of file kaldi-vector.cc.

References data_, VectorBase< Real >::data_, kaldi::kCopyData, kaldi::kSetZero, kaldi::kUndefined, and Vector< Real >::Swap().

Referenced by RestrictedAttentionComponent::Add(), VectorRandomizer::AddData(), PldaUnsupervisedAdaptor::AddStats(), kaldi::nnet2::AppendDiscriminativeExamples(), kaldi::AppendVector(), ApplyFmllrXform(), Plda::ApplyTransform(), kaldi::nnet2::AverageConstPart(), Sgmm2PerSpkDerivedVars::Clear(), kaldi::ComplexFftRecursive(), AmSgmm2::ComponentLogLikes(), DiagGmm::ComponentPosteriors(), kaldi::ComputeAndSubtractMean(), TransitionModel::ComputeDerivedOfProbs(), Plda::ComputeDerivedVars(), IvectorExtractor::ComputeDerivedVars(), AmSgmm2::ComputeFmllrPreXform(), AmSgmm2::ComputeGammaI(), FullGmm::ComputeGconsts(), DiagGmm::ComputeGconsts(), RegtreeFmllrDiagGmm::ComputeLogDets(), kaldi::ComputePca(), AmSgmm2::ComputePerSpkDerivedVars(), BasisFmllrEstimate::ComputeTransform(), kaldi::ComputeVadEnergy(), FmllrRawAccs::ConvertToSimpleStats(), kaldi::ConvolveSignals(), SvdApplier::DecomposeComponent(), kaldi::EstPca(), Xent::Eval(), kaldi::ExtractObjectRange(), kaldi::ExtractWaveformRemainder(), kaldi::ExtractWindow(), FeatureWindowFunction::FeatureWindowFunction(), kaldi::FFTbasedBlockConvolveSignals(), kaldi::FFTbasedConvolveSignals(), FmllrRawAccs::FmllrRawAccs(), PitchInterpolator::Forward(), kaldi::GetEqualLoudnessVector(), kaldi::GetFeatureMeanAndVariance(), Nnet::GetGradient(), kaldi::nnet2::GetInitialScaleParams(), LogisticRegression::GetLogPosteriors(), kaldi::GetOccs(), Nnet::GetParams(), MleAmSgmm2Accs::GetStateOccupancies(), LdaEstimate::GetStats(), AmNnet::Init(), LdaEstimate::Init(), RegtreeFmllrDiagGmm::Init(), FmllrDiagGmmAccs::SingleFrameStats::Init(), PldaStats::Init(), OnlinePreconditionerSimple::InitDefault(), OnlineNaturalGradientSimple::InitDefault(), OnlinePreconditioner::InitDefault(), OnlineNaturalGradient::InitDefault(), TransitionModel::InitializeProbs(), TransitionModel::InitStats(), IvectorExtractor::IvectorExtractor(), IvectorExtractorStats::IvectorExtractorStats(), AffineComponent::LimitRank(), AmSgmm2::LogLikelihood(), FullGmm::LogLikelihoods(), DiagGmm::LogLikelihoods(), FullGmm::LogLikelihoodsPreselect(), DiagGmm::LogLikelihoodsPreselect(), DecodableAmDiagGmmRegtreeFmllr::LogLikelihoodZeroBased(), main(), MelBanks::MelBanks(), FullGmm::Merge(), DiagGmm::Merge(), FullGmm::MergePreselect(), kaldi::nnet3::MergeSupervision(), MfccComputer::MfccComputer(), MleSgmm2SpeakerAccs::MleSgmm2SpeakerAccs(), OnlinePitchFeatureImpl::OnlinePitchFeatureImpl(), OnlineTransform::OnlineTransform(), LimitRankClass::operator()(), IvectorExtractTask::operator()(), Vector< BaseFloat >::operator=(), PlpComputer::PlpComputer(), kaldi::nnet2::ProcessFile(), NnetComputeProb::ProcessOutputs(), MleAmSgmm2Accs::Read(), kaldi::ReadData(), kaldi::nnet3::ReadVectorAsChar(), LinearResample::Resample(), LinearResample::Reset(), FullGmmNormal::Resize(), FullGmm::Resize(), DiagGmmNormal::Resize(), DiagGmm::Resize(), AccumFullGmm::Resize(), AccumDiagGmm::Resize(), Sgmm2PerFrameDerivedVars::Resize(), MleAmSgmm2Accs::ResizeAccumulators(), AmNnet::ResizeOutputLayer(), kaldi::nnet3::RunNnetComputation(), kaldi::SelectLags(), AmNnetSimple::SetNnet(), AmNnet::SetPriors(), LinearResample::SetRemainder(), Sgmm2PerSpkDerivedVars::SetSpeakerVector(), ShiftedDeltaFeatures::ShiftedDeltaFeatures(), FullGmm::Split(), DiagGmm::Split(), RestrictedAttentionComponent::StoreStats(), CuVector< Real >::Swap(), UnitTestEstimateLda(), kaldi::UnitTestIo(), UnitTestLinearResample(), UnitTestReadWave(), kaldi::UnitTestRegtreeFmllrDiagGmm(), kaldi::UnitTestResize(), kaldi::nnet3::UnitTestSummarizeVector(), MleSgmm2SpeakerAccs::UpdateNoU(), OnlinePitchFeatureImpl::UpdateRemainder(), MleSgmm2SpeakerAccs::UpdateWithU(), VectorRandomizer::Value(), Vector< BaseFloat >::Vector(), and NonlinearComponent::Write().

190  {
191 
192  // the next block uses recursion to handle what we have to do if
193  // resize_type == kCopyData.
194  if (resize_type == kCopyData) {
195  if (this->data_ == NULL || dim == 0) resize_type = kSetZero; // nothing to copy.
196  else if (this->dim_ == dim) { return; } // nothing to do.
197  else {
198  // set tmp to a vector of the desired size.
199  Vector<Real> tmp(dim, kUndefined);
200  if (dim > this->dim_) {
201  memcpy(tmp.data_, this->data_, sizeof(Real)*this->dim_);
202  memset(tmp.data_+this->dim_, 0, sizeof(Real)*(dim-this->dim_));
203  } else {
204  memcpy(tmp.data_, this->data_, sizeof(Real)*dim);
205  }
206  tmp.Swap(this);
207  // and now let tmp go out of scope, deleting what was in *this.
208  return;
209  }
210  }
211  // At this point, resize_type == kSetZero or kUndefined.
212 
213  if (this->data_ != NULL) {
214  if (this->dim_ == dim) {
215  if (resize_type == kSetZero) this->SetZero();
216  return;
217  } else {
218  Destroy();
219  }
220  }
221  Init(dim);
222  if (resize_type == kSetZero) this->SetZero();
223 }
void Destroy()
Destroy function, called internally.
MatrixIndexT dim_
dimension of vector
Definition: kaldi-vector.h:381
Real * data_
data memory area
Definition: kaldi-vector.h:379
void SetZero()
Set vector to all zeros.
void Init(const MatrixIndexT dim)
Init assumes the current contents of the class are invalid (i.e.
void Swap ( Vector< Real > *  other)

Swaps the contents of *this and *other. Shallow swap.

Definition at line 1294 of file kaldi-vector.cc.

References data_, VectorBase< Real >::data_, VectorBase< Real >::dim_, and kaldi::swap().

Referenced by PitchInterpolator::Forward(), OnlinePreconditioner::Init(), OnlineNaturalGradient::Init(), kaldi::nnet3::PrintParameterStats(), OnlinePitchFeatureImpl::RecomputeBacktraces(), Vector< Real >::Resize(), NnetDiscriminativeSupervision::Swap(), NnetChainSupervision::Swap(), CuVector< Real >::Swap(), and OnlinePitchFeatureImpl::UpdateRemainder().

1294  {
1295  std::swap(this->data_, other->data_);
1296  std::swap(this->dim_, other->dim_);
1297 }
void swap(basic_filebuf< CharT, Traits > &x, basic_filebuf< CharT, Traits > &y)
MatrixIndexT dim_
dimension of vector
Definition: kaldi-vector.h:381
Real * data_
data memory area
Definition: kaldi-vector.h:379

The documentation for this singleton was generated from the following files: