CUDA Networks
matrix_read_csv_limited.cu
Go to the documentation of this file.
1 /**
2  * @file matrix_read_csv_limited.cu
3  * @brief Implementation of the Matrix::read_csv_limited method.
4  */
5 #include "matrix.h"
6 #include <cuda_runtime.h>
7 #include <fstream>
8 #include <sstream>
9 #include <stdexcept>
10 #include <vector>
11 
12 void Matrix::read_csv_limited(const char* filename,
13  int startRow,
14  int endRow,
15  int fileRows,
16  int fileCols) {
17  // Open the CSV file
18  std::ifstream file(filename);
19  if (!file.is_open()) {
20  throw std::runtime_error("Error opening file");
21  }
22 
23  // Check if the specified range is valid
24  if (startRow < 0 || endRow > fileRows || startRow >= endRow) {
25  throw std::runtime_error("Invalid row range specified");
26  }
27 
28  // Check if the matrix dimensions match the specified range and file columns
29  if (rows != endRow - startRow || cols != fileCols) {
30  throw std::runtime_error("Matrix dimensions do not match the specified range and file columns");
31  }
32 
33  // Vector to temporarily store the data read from the CSV
34  std::vector<double> temp_data(rows * cols);
35  std::string line, value;
36  int currentRow = 0;
37 
38  // Read the CSV file line by line
39  while (std::getline(file, line) && currentRow < fileRows) {
40  // Process only the rows within the specified range
41  if (currentRow >= startRow && currentRow < endRow) {
42  std::istringstream s(line);
43  for (int col = 0; col < fileCols; ++col) {
44  // Parse each value in the line, separated by commas
45  if (!std::getline(s, value, ',')) {
46  throw std::runtime_error("Insufficient columns in CSV file");
47  }
48  // Convert the string value to double and store it in the temporary vector
49  temp_data[(currentRow - startRow) * cols + col] = std::stod(value);
50  }
51  }
52  currentRow++;
53  }
54 
55  // Check if we read enough rows
56  if (currentRow < endRow) {
57  throw std::runtime_error("Insufficient rows in CSV file");
58  }
59 
60  // Copy data from the temporary vector to the device (GPU) memory
61  cudaMemcpy(d_data, temp_data.data(), rows * cols * sizeof(double), cudaMemcpyHostToDevice);
62 }
void read_csv_limited(const char *filename, int startRow, int endRow, int fileRows, int fileCols)
Read a subset of data from a CSV file into the matrix.
Defines the Matrix class for GPU-accelerated matrix operations.