Example #1
0
void SprsArray<Dtype>::Create(const Array<Dtype>& array) {
  // verify the array
  if (array.GetDimCnt() != 2) {
    std::cout << "[ERROR] the input array must be 2-dimensional" << std::endl;
    exit(-1);
  } // ENDIF: array

  // obtain basic variables
  rowCnt_ = array.GetDimLen(0);
  colCnt_ = array.GetDimLen(1);
  nnzCnt_ = 0;
  std::size_t eleCnt = array.GetEleCnt();
  const Dtype* pData = array.GetDataPtr();
  for (std::size_t eleIdx = 0; eleIdx < eleCnt; ++eleIdx) {
    if (ABS(pData[eleIdx]) > kEpsilon) {
      nnzCnt_++;
    } // ENDIF: ABS
  } // ENDFOR: eleIdx

  // release space occupied by previous pointers (if any)
  Delete();

  // allocate space for pointers
  val_ = new Dtype[nnzCnt_];
  idx_ = new MKL_INT[nnzCnt_];
  ptrb_ = new MKL_INT[rowCnt_];
  ptre_ = new MKL_INT[rowCnt_];

  // convert the dense array to CSR format, zero-based indexing)
  std::size_t nnzIdx = 0;
  for (std::size_t rowIdx = 0; rowIdx < rowCnt_; ++rowIdx) {
    // initialize variables for the current row
    const Dtype* pData = array.GetDataPtr() + rowIdx * colCnt_;
    bool isFirst = true;

    // scan through the current row
    for (std::size_t colIdx = 0; colIdx < colCnt_; ++colIdx) {
      if (ABS(pData[colIdx]) > kEpsilon) {
        val_[nnzIdx] = pData[colIdx];
        idx_[nnzIdx] = colIdx;
        if (isFirst) {
          isFirst = false;
          ptrb_[rowIdx] = nnzIdx;
        } // ENDIF: isFirst
        ptre_[rowIdx] = ++nnzIdx;
      } // ENDIF: ABS
    } // ENDFOR: colIdx
  } // ENDFOR: rowIdx
}