C++ 并行计算物种矩阵的相对丰度 - 按列计算
"#include "iostream"\n#include "fstream"\n#include "vector"\n#include "string"\n#include "sstream"\n#include "algorithm"\n#include "numeric"\n#include "cmath"\n#include "omp.h"\n\nusing namespace std;\n\n// Function to split a string based on a delimiter\nvector<string> splitString(const string& str, char delimiter) {\n vector<string> tokens;\n stringstream ss(str);\n string token;\n while (getline(ss, token, delimiter)) {\n tokens.push_back(token);\n }\n return tokens;\n}\n\n// Function to calculate relative abundance in parallel\nvector<vector<double>> calculateRelativeAbundance(const vector<vector<double>>& matrix) {\n int numCols = matrix[0].size();\n vector<vector<double>> relativeAbundance(matrix.size(), vector<double>(numCols));\n\n #pragma omp parallel for\n for (int j = 0; j < numCols; j++) {\n double colSum = 0.0;\n for (int i = 0; i < matrix.size(); i++) {\n colSum += matrix[i][j];\n }\n for (int i = 0; i < matrix.size(); i++) {\n relativeAbundance[i][j] = matrix[i][j] / colSum;\n }\n }\n\n return relativeAbundance;\n}\n\nint main() {\n string filename = "species_matrix.csv";\n\n // Read the species matrix from file\n ifstream file(filename);\n if (!file) {\n cerr << "Error opening file." << endl;\n return 1;\n }\n\n string line;\n vector<vector<double>> matrix;\n vector<string> rowNames;\n vector<string> colNames;\n\n // Read the column names from the first line\n if (getline(file, line)) {\n colNames = splitString(line, ',');\n }\n\n // Read the remaining rows of the matrix\n while (getline(file, line)) {\n vector<double> row;\n vector<string> tokens = splitString(line, ',');\n\n // The first token is the row name\n rowNames.push_back(tokens[0]);\n\n // Convert the remaining tokens to doubles\n for (int i = 1; i < tokens.size(); i++) {\n row.push_back(stod(tokens[i]));\n }\n\n matrix.push_back(row);\n }\n\n file.close();\n\n // Calculate relative abundance\n vector<vector<double>> relativeAbundance = calculateRelativeAbundance(matrix);\n\n // Output the relative abundance matrix with row and column names\n cout << " ";\n for (const auto& colName : colNames) {\n cout << colName << "\t";\n }\n cout << endl;\n\n for (int i = 0; i < matrix.size(); i++) {\n cout << rowNames[i] << " ";\n for (int j = 0; j < matrix[i].size(); j++) {\n cout << relativeAbundance[i][j] << "\t";\n }\n cout << endl;\n }\n\n return 0;\n}\n"
原文地址: https://www.cveoy.top/t/topic/p0af 著作权归作者所有。请勿转载和采集!