Vector< Real > Class Template 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. 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 Floor (const VectorBase< Real > &v, Real floor_val, MatrixIndexT *floored_count=nullptr)
 Applies floor to all elements. More...
 
void Ceiling (const VectorBase< Real > &v, Real ceil_val, MatrixIndexT *ceiled_count=nullptr)
 Applies ceiling to all elements. More...
 
void Pow (const VectorBase< Real > &v, Real power)
 
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)
 Multiply element-by-element by another vector. More...
 
template<typename OtherReal >
void MulElements (const VectorBase< OtherReal > &v)
 Multiply 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 vectors: 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 matrix: *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>
class 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 406 of file kaldi-vector.h.

Constructor & Destructor Documentation

◆ Vector() [1/6]

Vector ( )
inline

Constructor that takes no arguments. Initializes to empty.

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

409 : VectorBase<Real>() {}

◆ Vector() [2/6]

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 413 of file kaldi-vector.h.

415  : VectorBase<Real>() { Resize(s, resize_type); }
void Resize(MatrixIndexT length, MatrixResizeType resize_type=kSetZero)
Set vector to a specified size (can be zero).

◆ Vector() [3/6]

Vector ( const CuVectorBase< OtherReal > &  cu)
explicit

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

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

398  {
399  Init(cu.Dim());
400  cu.CopyToVec(this);
401 }
void Init(const MatrixIndexT dim)
Init assumes the current contents of the class are invalid (i.e.

◆ Vector() [4/6]

Vector ( const Vector< Real > &  v)
inline

Copy constructor. The need for this is controversial.

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

423  : VectorBase<Real>() { // (cannot be explicit)
424  Resize(v.Dim(), kUndefined);
425  this->CopyFromVec(v);
426  }
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() [5/6]

Vector ( const VectorBase< Real > &  v)
inlineexplicit

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

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

429  : VectorBase<Real>() {
430  Resize(v.Dim(), kUndefined);
431  this->CopyFromVec(v);
432  }
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() [6/6]

Vector ( const VectorBase< OtherReal > &  v)
inlineexplicit

Type conversion constructor.

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

436  : VectorBase<Real>() {
437  Resize(v.Dim(), kUndefined);
438  this->CopyFromVec(v);
439  }
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()

~Vector ( )
inline

Destructor. Deallocates memory.

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

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

Member Function Documentation

◆ Destroy()

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.

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:397
#define KALDI_MEMALIGN_FREE(x)
Definition: kaldi-utils.h:60
Real * data_
data memory area
Definition: kaldi-vector.h:395

◆ Init()

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.

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:397
#define KALDI_MEMALIGN(align, size, pp_orig)
Definition: kaldi-utils.h:58
Real * data_
data memory area
Definition: kaldi-vector.h:395
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ operator=() [1/2]

Vector<Real>& operator= ( const Vector< Real > &  other)
inline

Assignment operator.

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

473  {
474  Resize(other.Dim(), kUndefined);
475  this->CopyFromVec(other);
476  return *this;
477  }
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).

◆ operator=() [2/2]

Vector<Real>& operator= ( const VectorBase< Real > &  other)
inline

Assignment operator that takes VectorBase.

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

480  {
481  Resize(other.Dim(), kUndefined);
482  this->CopyFromVec(other);
483  return *this;
484  }
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).

◆ Read()

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 1109 of file kaldi-vector.cc.

Referenced by FramePoolingComponent::InitData(), main(), kaldi::operator>>(), PdfPrior::PdfPrior(), AccumFullGmm::Read(), LdaEstimate::Read(), AccumDiagGmm::Read(), Plda::Read(), RestrictedAttentionComponent::Read(), CuVector< float >::Read(), VectorBase< float >::Read(), Vector< float >::Read(), IvectorExtractorStats::Read(), PermuteComponent::Read(), kaldi::nnet3::ReadVectorAsChar(), kaldi::UnitTestIo(), kaldi::UnitTestIoCross(), and UnitTestReadWave().

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

◆ RemoveElement()

void RemoveElement ( MatrixIndexT  i)

Remove one element and shifts later elements down.

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

Referenced by 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:397
Real * data_
data memory area
Definition: kaldi-vector.h:395
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ Resize()

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.

Referenced by OnlineSpeexEncoder::AcceptWaveform(), OnlineGenericBaseFeature< C >::AcceptWaveform(), RestrictedAttentionComponent::Add(), kaldi::AppendVector(), ApplyFmllrXform(), Plda::ApplyTransform(), kaldi::ComplexFftRecursive(), AmSgmm2::ComponentLogLikes(), DiagGmm::ComponentPosteriors(), kaldi::ComputeAndSubtractMean(), Plda::ComputeDerivedVars(), IvectorExtractor::ComputeDerivedVars(), AmSgmm2::ComputeFmllrPreXform(), AmSgmm2::ComputeGammaI(), kaldi::ComputePca(), BasisFmllrEstimate::ComputeTransform(), kaldi::ComputeVadEnergy(), FmllrRawAccs::ConvertToSimpleStats(), kaldi::ConvolveSignals(), OnlineSpeexDecoder::Decode(), kaldi::EstPca(), Xent::Eval(), kaldi::ExtractObjectRange(), kaldi::ExtractWindow(), kaldi::FFTbasedBlockConvolveSignals(), kaldi::FFTbasedConvolveSignals(), FmllrRawAccs::FmllrRawAccs(), TcpServer::GetChunk(), kaldi::GetEqualLoudnessVector(), kaldi::GetFeatureMeanAndVariance(), Nnet::GetGradient(), kaldi::nnet2::GetInitialScaleParams(), LogisticRegression::GetLogPosteriors(), kaldi::GetOccs(), Nnet::GetParams(), SingleUtteranceNnet2DecoderThreaded::GetRemainingWaveform(), MleAmSgmm2Accs::GetStateOccupancies(), LdaEstimate::GetStats(), OnlineSpeexDecoder::GetWaveform(), LdaEstimate::Init(), OnlinePreconditionerSimple::InitDefault(), OnlineNaturalGradientSimple::InitDefault(), TransitionModel::InitStats(), OnlineGenericBaseFeature< C >::InputFinished(), IvectorExtractor::IvectorExtractor(), IvectorExtractorStats::IvectorExtractorStats(), AffineComponent::LimitRank(), FullGmm::LogLikelihoods(), DiagGmm::LogLikelihoods(), FullGmm::LogLikelihoodsPreselect(), DiagGmm::LogLikelihoodsPreselect(), main(), MleSgmm2SpeakerAccs::MleSgmm2SpeakerAccs(), OnlineIvectorFeature::OnlineIvectorFeature(), LimitRankClass::operator()(), IvectorExtractTask::operator()(), OnlinePaSource::Read(), MleAmSgmm2Accs::Read(), kaldi::ReadData(), kaldi::nnet3::ReadVectorAsChar(), LinearResample::Resample(), DiagGmmNormal::Resize(), FullGmmNormal::Resize(), AccumFullGmm::Resize(), AccumDiagGmm::Resize(), Sgmm2PerFrameDerivedVars::Resize(), MleAmSgmm2Accs::ResizeAccumulators(), kaldi::nnet3::RunNnetComputation(), kaldi::SelectLags(), RestrictedAttentionComponent::StoreStats(), CuVector< float >::Swap(), kaldi::TypeThreeUsage(), UnitTestEstimateLda(), kaldi::UnitTestIo(), UnitTestLinearResample(), UnitTestReadWave(), kaldi::UnitTestRegtreeFmllrDiagGmm(), kaldi::UnitTestResize(), kaldi::nnet3::UnitTestSummarizeVector(), MleSgmm2SpeakerAccs::UpdateNoU(), MleSgmm2SpeakerAccs::UpdateWithU(), 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:397
Real * data_
data memory area
Definition: kaldi-vector.h:395
void SetZero()
Set vector to all zeros.
void Init(const MatrixIndexT dim)
Init assumes the current contents of the class are invalid (i.e.

◆ Swap()

void Swap ( Vector< Real > *  other)

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

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

Referenced by BatchedXvectorComputer::OutputXvector(), kaldi::nnet3::PrintParameterStats(), Vector< float >::Resize(), and CuVector< float >::Swap().

1297  {
1298  std::swap(this->data_, other->data_);
1299  std::swap(this->dim_, other->dim_);
1300 }
void swap(basic_filebuf< CharT, Traits > &x, basic_filebuf< CharT, Traits > &y)
MatrixIndexT dim_
dimension of vector
Definition: kaldi-vector.h:397
Real * data_
data memory area
Definition: kaldi-vector.h:395

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