OpenFPM_pdata  4.1.0
Project that contain the implementation of distributed structures
 
Loading...
Searching...
No Matches
CSVReader.hpp
1//
2// Created by jstark on 23.12.21.
3//
4
5#ifndef OPENFPM_IO_CSVREADER_HPP
6#define OPENFPM_IO_CSVREADER_HPP
7
8#include <iostream>
9#include <sstream>
10#include <string>
11
12#include "Vector/map_vector.hpp"
14#include "VCluster/VCluster.hpp"
15
22template <typename T>
23T string_to_type(const std::string & string_to_convert)
24{
25 T x_new_type;
26 std::istringstream istream_string_to_convert(string_to_convert);
27 istream_string_to_convert >> x_new_type;
28 return x_new_type;
29}
30
31
41template <typename T>
42void read_csv_to_vector(const std::string & input_file, openfpm::vector<T> & output_vector, size_t & m, size_t & n)
43{
44 size_t total_size = 0;
45 m = 0;
46 n = 0;
47 auto & v_cl = create_vcluster();
48 // File is accessed and read only by one process
49 if (v_cl.rank() == 0)
50 {
51 if(!check_if_file_exists(input_file))
52 {
53 std::cout << "Cannot find < " << input_file << " >. Please check path specification. Aborting..."
54 << std::endl;
55 abort();
56 }
57 std::ifstream file(input_file); // Create file pointer and open file
58 std::string line, element;
59 while (getline(file, line)) // Read entire row and store as one string in line
60 {
61 std::stringstream stream_line(line); // Needed to break line into elements later one
62 while (getline(stream_line, element, ',')) // Read every column of line and store content as string in element
63 {
64 output_vector.add(string_to_type<T>(element)); // Convert element from string to type T and append to
65 // output_vector
66 total_size += 1; // Increase n by one for each element read
67 }
68 m += 1; // Increase m by one for each row read
69 }
70 if(m >= 1) n = total_size / m; // If at least one row present, divide number of elements read by number of rows to get
71 // the number of columns
72 }
73 // Distribute size of the lin. vector to all other processes s.t. their output_vector can be resized accordingly.
74 MPI_Bcast(&total_size,1,MPI_UNSIGNED,0,MPI_COMM_WORLD);
75 MPI_Bcast(&m,1,MPI_UNSIGNED,0,MPI_COMM_WORLD);
76 MPI_Bcast(&n,1,MPI_UNSIGNED,0,MPI_COMM_WORLD);
77
78 if (v_cl.rank() != 0)
79 {
80 output_vector.resize(total_size);
81 }
82 // After the output_vector has been resized to correct size, it can receive the content from process 0.
83 v_cl.Bcast(output_vector, 0);
84 v_cl.execute();
85}
86
87#endif //OPENFPM_IO_CSVREADER_HPP
Header file containing functions for creating files and folders.
static bool check_if_file_exists(std::string path)
Checks if a file already exists.
Implementation of 1-D std::vector like structure.