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...
 
MatrixIndexT ApplyFloor (Real floor_val)
 Applies floor to all elements. Returns number of elements floored. More...
 
MatrixIndexT ApplyCeiling (Real ceil_val)
 Applies ceiling to all elements. Returns number of elements changed. 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 387 of file kaldi-vector.h.

Constructor & Destructor Documentation

Vector ( )
inline

Constructor that takes no arguments. Initializes to empty.

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

390 : 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 394 of file kaldi-vector.h.

396  : 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 364 of file cu-vector.h.

364  {
365  Init(cu.Dim());
366  cu.CopyToVec(this);
367 }
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 404 of file kaldi-vector.h.

404  : VectorBase<Real>() { // (cannot be explicit)
405  Resize(v.Dim(), kUndefined);
406  this->CopyFromVec(v);
407  }
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 410 of file kaldi-vector.h.

410  : VectorBase<Real>() {
411  Resize(v.Dim(), kUndefined);
412  this->CopyFromVec(v);
413  }
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 417 of file kaldi-vector.h.

417  : VectorBase<Real>() {
418  Resize(v.Dim(), kUndefined);
419  this->CopyFromVec(v);
420  }
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 435 of file kaldi-vector.h.

435 { 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 278 of file kaldi-vector.cc.

References data_, and KALDI_MEMALIGN_FREE.

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

278  {
280  if (this->data_ != NULL)
281  KALDI_MEMALIGN_FREE(this->data_);
282  this->data_ = NULL;
283  this->dim_ = 0;
284 }
MatrixIndexT dim_
dimension of vector
Definition: kaldi-vector.h:378
#define KALDI_MEMALIGN_FREE(x)
Definition: kaldi-utils.h:56
Real * data_
data memory area
Definition: kaldi-vector.h:376
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 166 of file kaldi-vector.cc.

References data_, KALDI_ASSERT, and KALDI_MEMALIGN.

166  {
167  KALDI_ASSERT(dim >= 0);
168  if (dim == 0) {
169  this->dim_ = 0;
170  this->data_ = NULL;
171  return;
172  }
173  MatrixIndexT size;
174  void *data;
175  void *free_data;
176 
177  size = dim * sizeof(Real);
178 
179  if ((data = KALDI_MEMALIGN(16, size, &free_data)) != NULL) {
180  this->data_ = static_cast<Real*> (data);
181  this->dim_ = dim;
182  } else {
183  throw std::bad_alloc();
184  }
185 }
int32 MatrixIndexT
Definition: matrix-common.h:96
MatrixIndexT dim_
dimension of vector
Definition: kaldi-vector.h:378
#define KALDI_MEMALIGN(align, size, pp_orig)
Definition: kaldi-utils.h:54
Real * data_
data memory area
Definition: kaldi-vector.h:376
#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 454 of file kaldi-vector.h.

454  {
455  Resize(other.Dim(), kUndefined);
456  this->CopyFromVec(other);
457  return *this;
458  }
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 461 of file kaldi-vector.h.

461  {
462  Resize(other.Dim(), kUndefined);
463  this->CopyFromVec(other);
464  return *this;
465  }
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 1094 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(), Plda::Read(), TransitionModel::Read(), FullGmm::Read(), VectorClusterable::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::UnitTestIo(), kaldi::UnitTestIoCross(), and UnitTestReadWave().

1094  {
1095  if (add) {
1096  Vector<Real> tmp(this->Dim());
1097  tmp.Read(is, binary, false); // read without adding.
1098  if (this->Dim() == 0) this->Resize(tmp.Dim());
1099  if (this->Dim() != tmp.Dim()) {
1100  KALDI_ERR << "Vector<Real>::Read, adding but dimensions mismatch "
1101  << this->Dim() << " vs. " << tmp.Dim();
1102  }
1103  this->AddVec(1.0, tmp);
1104  return;
1105  } // now assume add == false.
1106 
1107  std::ostringstream specific_error;
1108  MatrixIndexT pos_at_start = is.tellg();
1109 
1110  if (binary) {
1111  int peekval = Peek(is, binary);
1112  const char *my_token = (sizeof(Real) == 4 ? "FV" : "DV");
1113  char other_token_start = (sizeof(Real) == 4 ? 'D' : 'F');
1114  if (peekval == other_token_start) { // need to instantiate the other type to read it.
1115  typedef typename OtherReal<Real>::Real OtherType; // if Real == float, OtherType == double, and vice versa.
1116  Vector<OtherType> other(this->Dim());
1117  other.Read(is, binary, false); // add is false at this point.
1118  if (this->Dim() != other.Dim()) this->Resize(other.Dim());
1119  this->CopyFromVec(other);
1120  return;
1121  }
1122  std::string token;
1123  ReadToken(is, binary, &token);
1124  if (token != my_token) {
1125  specific_error << ": Expected token " << my_token << ", got " << token;
1126  goto bad;
1127  }
1128  int32 size;
1129  ReadBasicType(is, binary, &size); // throws on error.
1130  if ((MatrixIndexT)size != this->Dim()) this->Resize(size);
1131  if (size > 0)
1132  is.read(reinterpret_cast<char*>(this->data_), sizeof(Real)*size);
1133  if (is.fail()) {
1134  specific_error << "Error reading vector data (binary mode); truncated "
1135  "stream? (size = " << size << ")";
1136  goto bad;
1137  }
1138  return;
1139  } else { // Text mode reading; format is " [ 1.1 2.0 3.4 ]\n"
1140  std::string s;
1141  is >> s;
1142  // if ((s.compare("DV") == 0) || (s.compare("FV") == 0)) { // Back compatibility.
1143  // is >> s; // get dimension
1144  // is >> s; // get "["
1145  // }
1146  if (is.fail()) { specific_error << "EOF while trying to read vector."; goto bad; }
1147  if (s.compare("[]") == 0) { Resize(0); return; } // tolerate this variant.
1148  if (s.compare("[")) { specific_error << "Expected \"[\" but got " << s; goto bad; }
1149  std::vector<Real> data;
1150  while (1) {
1151  int i = is.peek();
1152  if (i == '-' || (i >= '0' && i <= '9')) { // common cases first.
1153  Real r;
1154  is >> r;
1155  if (is.fail()) { specific_error << "Failed to read number."; goto bad; }
1156  if (! std::isspace(is.peek()) && is.peek() != ']') {
1157  specific_error << "Expected whitespace after number."; goto bad;
1158  }
1159  data.push_back(r);
1160  // But don't eat whitespace... we want to check that it's not newlines
1161  // which would be valid only for a matrix.
1162  } else if (i == ' ' || i == '\t') {
1163  is.get();
1164  } else if (i == ']') {
1165  is.get(); // eat the ']'
1166  this->Resize(data.size());
1167  for (size_t j = 0; j < data.size(); j++)
1168  this->data_[j] = data[j];
1169  i = is.peek();
1170  if (static_cast<char>(i) == '\r') {
1171  is.get();
1172  is.get(); // get \r\n (must eat what we wrote)
1173  } else if (static_cast<char>(i) == '\n') { is.get(); } // get \n (must eat what we wrote)
1174  if (is.fail()) {
1175  KALDI_WARN << "After end of vector data, read error.";
1176  // we got the data we needed, so just warn for this error.
1177  }
1178  return; // success.
1179  } else if (i == -1) {
1180  specific_error << "EOF while reading vector data.";
1181  goto bad;
1182  } else if (i == '\n' || i == '\r') {
1183  specific_error << "Newline found while reading vector (maybe it's a matrix?)";
1184  goto bad;
1185  } else {
1186  is >> s; // read string.
1187  if (!KALDI_STRCASECMP(s.c_str(), "inf") ||
1188  !KALDI_STRCASECMP(s.c_str(), "infinity")) {
1189  data.push_back(std::numeric_limits<Real>::infinity());
1190  KALDI_WARN << "Reading infinite value into vector.";
1191  } else if (!KALDI_STRCASECMP(s.c_str(), "nan")) {
1192  data.push_back(std::numeric_limits<Real>::quiet_NaN());
1193  KALDI_WARN << "Reading NaN value into vector.";
1194  } else {
1195  specific_error << "Expecting numeric vector data, got " << s;
1196  goto bad;
1197  }
1198  }
1199  }
1200  }
1201  // we never reach this line (the while loop returns directly).
1202 bad:
1203  KALDI_ERR << "Failed to read vector from stream. " << specific_error.str()
1204  << " File position at start is "
1205  << pos_at_start<<", currently "<<is.tellg();
1206 }
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:96
#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:376
#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:62
void RemoveElement ( MatrixIndexT  i)

Remove one element and shifts later elements down.

Definition at line 268 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().

268  {
269  KALDI_ASSERT(i < this->dim_ && "Access out of vector");
270  for (MatrixIndexT j = i + 1; j < this->dim_; j++)
271  this->data_[j-1] = this->data_[j];
272  this->dim_--;
273 }
int32 MatrixIndexT
Definition: matrix-common.h:96
MatrixIndexT dim_
dimension of vector
Definition: kaldi-vector.h:378
Real * data_
data memory area
Definition: kaldi-vector.h:376
#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 189 of file kaldi-vector.cc.

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

Referenced by VectorRandomizer::AddData(), PldaUnsupervisedAdaptor::AddStats(), kaldi::nnet2::AppendDiscriminativeExamples(), kaldi::AppendVector(), ApplyFmllrXform(), 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(), Xent::Eval(), 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(), OnlineNaturalGradient::InitDefault(), OnlinePreconditioner::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(), MleAmSgmm2Accs::Read(), kaldi::ReadData(), kaldi::nnet3::ReadVectorAsChar(), LinearResample::Resample(), LinearResample::Reset(), FullGmm::Resize(), FullGmmNormal::Resize(), DiagGmmNormal::Resize(), DiagGmm::Resize(), AccumFullGmm::Resize(), AccumDiagGmm::Resize(), Sgmm2PerFrameDerivedVars::Resize(), MleAmSgmm2Accs::ResizeAccumulators(), AmNnet::ResizeOutputLayer(), kaldi::SelectLags(), AmNnetSimple::SetNnet(), AmNnet::SetPriors(), LinearResample::SetRemainder(), Sgmm2PerSpkDerivedVars::SetSpeakerVector(), ShiftedDeltaFeatures::ShiftedDeltaFeatures(), FullGmm::Split(), DiagGmm::Split(), 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().

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

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

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

1276  {
1277  std::swap(this->data_, other->data_);
1278  std::swap(this->dim_, other->dim_);
1279 }
void swap(basic_filebuf< CharT, Traits > &x, basic_filebuf< CharT, Traits > &y)
MatrixIndexT dim_
dimension of vector
Definition: kaldi-vector.h:378
Real * data_
data memory area
Definition: kaldi-vector.h:376

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