-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.cpp
More file actions
92 lines (86 loc) · 2.91 KB
/
utils.cpp
File metadata and controls
92 lines (86 loc) · 2.91 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
#include "utils.h"
fplll::ZZ_mat<mpz_t> std_vector_to_fplll_ZZ_mat(std::vector<std::vector<int>> matrix) {
if (matrix.empty()) {
throw std::invalid_argument("Provided matrix must be non-empty");
}
int rows = matrix.size();
int cols = matrix.at(0).size();
fplll::ZZ_mat<mpz_t> fplll_matrix(rows, cols);
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
fplll_matrix(i, j) = matrix.at(i).at(j);
}
}
return fplll_matrix;
}
MatrixXm std_vector_to_Eigen_mat(std::vector<std::vector<int>> matrix) {
if (matrix.empty()) {
throw std::invalid_argument("Provided matrix must be non-empty");
}
int cols = matrix.size();
int rows = matrix.at(0).size();
MatrixXm eigen_matrix(rows, cols);
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
eigen_matrix(i, j) = matrix.at(j).at(i);
}
}
return eigen_matrix;
}
MatrixXm fplll_ZZ_mat_to_Eigen_mat(fplll::ZZ_mat<mpz_t> fplll_matrix) {
if (fplll_matrix.empty()) {
throw std::invalid_argument("Provided matrix must be non-empty");
}
// fplll runs row-based LLL, but the rest of the code is column-based, so we take the transpose when converting
// back from fplll
int rows = fplll_matrix.c;
int cols = fplll_matrix.r;
MatrixXm eigen_matrix(rows, cols);
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
eigen_matrix(i, j) = fplll_matrix(j, i).get_si();
}
}
return eigen_matrix;
}
fplll::ZZ_mat<mpz_t> eigen_mat_to_fplll_ZZ_mat(MatrixXm matrix) {
if (matrix.size() <= 0) {
throw std::invalid_argument("Provided matrix must be non-empty");
}
// fplll runs row-based LLL, but the rest of the code is column-based, so we take the transpose when converting
// back from fplll
int rows = matrix.cols();
int cols = matrix.rows();
fplll::ZZ_mat<mpz_t> fplll_matrix(rows, cols);
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
mpz_t val;
mpz_init(val);
mpfr_get_z(val, matrix(j,i).mpfr_srcptr(), MPFR_RNDN);
fplll_matrix(i,j) = val;
}
}
return fplll_matrix;
}
MatrixXm read_matrix_from_file(std::string file, int rows, int cols) {
MatrixXm matrix(rows, cols);
std::fstream f(file);
if (!f.is_open()) {
throw std::runtime_error("Could not open file");
}
std::string line;
for (int i = 0; i < rows; i++) {
if (!getline(f, line)) {
throw std::runtime_error("Not enough rows in matrix file");
}
std::istringstream sstream(line);
mpfr::mpreal val;
for (int j = 0; j < cols; j++) {
if (!(sstream >> val)) {
throw std::runtime_error("Not enough columns in matrix file");
}
matrix(i, j) = val;
}
}
return matrix;
}