v2.0.0
Loading...
Searching...
No Matches
fiff_sparse_matrix.cpp
Go to the documentation of this file.
1//=============================================================================================================
16
17//=============================================================================================================
18// INCLUDES
19//=============================================================================================================
20
21#include "fiff_sparse_matrix.h"
22#include <fiff/fiff_file.h>
23#include <fiff/fiff_types.h>
24
25#include <vector>
26#include <QDebug>
27
28//=============================================================================================================
29// USED NAMESPACES
30//=============================================================================================================
31
32using namespace Eigen;
33using namespace FIFFLIB;
34
35//============================= fiff_type_spec.h =============================
36
37/*
38 * These return information about a fiff type.
39 */
40
42{
43 return type & FIFFTS_BASE_MASK;
44}
45
50
55
56//============================= fiff_matrix.c =============================
57
58std::vector<int> fiff_get_matrix_dims(const FiffTag::UPtr& tag)
59/*
60 * Interpret dimensions from matrix data (dense and sparse)
61 */
62{
63 int ndim;
64 int* dims;
65 unsigned int tsize = tag->size();
66 /*
67 * Initial checks
68 */
69 if (tag->data() == nullptr) {
70 qCritical("fiff_get_matrix_dims: no data available!");
71 return {};
72 }
73 if (fiff_type_fundamental(tag->type) != FIFFTS_FS_MATRIX) {
74 qCritical("fiff_get_matrix_dims: tag does not contain a matrix!");
75 return {};
76 }
77 if (tsize < sizeof(fiff_int_t)) {
78 qCritical("fiff_get_matrix_dims: too small matrix data!");
79 return {};
80 }
81 /*
82 * Get the number of dimensions and check
83 */
84 ndim = *((fiff_int_t*)((fiff_byte_t*)(tag->data()) + tag->size() - sizeof(fiff_int_t)));
85 if (ndim <= 0 || ndim > FIFFC_MATRIX_MAX_DIM) {
86 qCritical("fiff_get_matrix_dims: unreasonable # of dimensions!");
87 return {};
88 }
89 if (fiff_type_matrix_coding(tag->type) == FIFFTS_MC_DENSE) {
90 if (tsize < (ndim + 1) * sizeof(fiff_int_t)) {
91 qCritical("fiff_get_matrix_dims: too small matrix data!");
92 return {};
93 }
94 std::vector<int> res(ndim + 1);
95 res[0] = ndim;
96 dims = ((fiff_int_t*)((fiff_byte_t*)(tag->data()) + tag->size())) - ndim - 1;
97 for (int k = 0; k < ndim; k++)
98 res[k + 1] = dims[k];
99 return res;
100 } else if (fiff_type_matrix_coding(tag->type) == FIFFTS_MC_CCS ||
102 if (tsize < (ndim + 2) * sizeof(fiff_int_t)) {
103 qCritical("fiff_get_matrix_sparse_dims: too small matrix data!");
104 return {};
105 }
106 std::vector<int> res(ndim + 2);
107 res[0] = ndim;
108 dims = ((fiff_int_t*)((fiff_byte_t*)(tag->data()) + tag->size())) - ndim - 1;
109 for (int k = 0; k < ndim; k++)
110 res[k + 1] = dims[k];
111 res[ndim + 1] = dims[-1];
112 return res;
113 } else {
114 qCritical("fiff_get_matrix_dims: unknown matrix coding.");
115 return {};
116 }
117}
118
119//=============================================================================================================
120// DEFINE MEMBER METHODS
121//=============================================================================================================
122
127
128//=============================================================================================================
129
130FiffSparseMatrix::FiffSparseMatrix(Eigen::SparseMatrix<float>&& mat,
132: coding(coding)
133, m_eigen(std::move(mat))
134{
135}
136
137//=============================================================================================================
138
140{
141 return fiff_get_matrix_dims(tag);
142}
143
144//=============================================================================================================
145
147{
148 int m, n, nz;
149 int cod, correct_size;
150
151 if (fiff_type_fundamental(tag->type) != FIFFT_MATRIX ||
152 fiff_type_base(tag->type) != FIFFT_FLOAT ||
153 (fiff_type_matrix_coding(tag->type) != FIFFTS_MC_CCS &&
154 fiff_type_matrix_coding(tag->type) != FIFFTS_MC_RCS)) {
155 qWarning("[FiffSparseMatrix::fiff_get_float_sparse_matrix] wrong data type!");
156 return nullptr;
157 }
158
159 auto dims = fiff_get_matrix_sparse_dims(tag);
160 if (dims.empty())
161 return nullptr;
162
163 if (dims[0] != 2) {
164 qWarning("[FiffSparseMatrix::fiff_get_float_sparse_matrix] wrong # of dimensions!");
165 return nullptr;
166 }
167
168 m = dims[1];
169 n = dims[2];
170 nz = dims[3];
171
172 cod = fiff_type_matrix_coding(tag->type);
173 if (cod == FIFFTS_MC_CCS)
174 correct_size = nz * (sizeof(fiff_float_t) + sizeof(fiff_int_t)) +
175 (n + 1 + dims[0] + 2) * (sizeof(fiff_int_t));
176 else if (cod == FIFFTS_MC_RCS)
177 correct_size = nz * (sizeof(fiff_float_t) + sizeof(fiff_int_t)) +
178 (m + 1 + dims[0] + 2) * (sizeof(fiff_int_t));
179 else {
180 qWarning("[FiffSparseMatrix::fiff_get_float_sparse_matrix] Incomprehensible sparse matrix coding");
181 return nullptr;
182 }
183 if (tag->size() != correct_size) {
184 qWarning("[FiffSparseMatrix::fiff_get_float_sparse_matrix] wrong data size!");
185 return nullptr;
186 }
187 /*
188 * Parse tag data into triplets and build Eigen sparse matrix directly
189 */
190 const float* src_data = reinterpret_cast<const float*>(tag->data());
191 const int* src_inds = reinterpret_cast<const int*>(src_data + nz);
192 const int* src_ptrs = src_inds + nz;
193
194 using T = Eigen::Triplet<float>;
195 std::vector<T> triplets;
196 triplets.reserve(nz);
197
198 if (cod == FIFFTS_MC_RCS) {
199 for (int row = 0; row < m; ++row) {
200 for (int j = src_ptrs[row]; j < src_ptrs[row + 1]; ++j) {
201 triplets.push_back(T(row, src_inds[j], src_data[j]));
202 }
203 }
204 } else { // CCS
205 for (int col = 0; col < n; ++col) {
206 for (int j = src_ptrs[col]; j < src_ptrs[col + 1]; ++j) {
207 triplets.push_back(T(src_inds[j], col, src_data[j]));
208 }
209 }
210 }
211
212 Eigen::SparseMatrix<float> eigenMat(m, n);
213 eigenMat.setFromTriplets(triplets.begin(), triplets.end());
214 eigenMat.makeCompressed();
215
216 auto res = std::make_unique<FiffSparseMatrix>(std::move(eigenMat), cod);
217 return res;
218}
219
220//=============================================================================================================
221
222FiffSparseMatrix::UPtr FiffSparseMatrix::create_sparse_rcs(int nrow, int ncol, int* nnz, int** colindex, float** vals)
223{
224 int j, k, totalNz;
225
226 for (j = 0, totalNz = 0; j < nrow; j++)
227 totalNz = totalNz + nnz[j];
228
229 if (totalNz <= 0) {
230 qWarning("[FiffSparseMatrix::create_sparse_rcs] No nonzero elements specified.");
231 return nullptr;
232 }
233
234 using T = Eigen::Triplet<float>;
235 std::vector<T> triplets;
236 triplets.reserve(totalNz);
237
238 for (j = 0; j < nrow; j++) {
239 for (k = 0; k < nnz[j]; k++) {
240 int col = colindex[j][k];
241 if (col < 0 || col >= ncol) {
242 qWarning("[FiffSparseMatrix::create_sparse_rcs] Column index out of range");
243 return nullptr;
244 }
245 float val = vals ? vals[j][k] : 0.0f;
246 triplets.push_back(T(j, col, val));
247 }
248 }
249
250 Eigen::SparseMatrix<float> eigenMat(nrow, ncol);
251 eigenMat.setFromTriplets(triplets.begin(), triplets.end());
252 eigenMat.makeCompressed();
253
254 return std::make_unique<FiffSparseMatrix>(std::move(eigenMat), FIFFTS_MC_RCS);
255}
256
257//=============================================================================================================
258
260/*
261 * Fill in upper triangle with the lower triangle values
262 */
263{
264 int nRows = rows();
265 int nCols = cols();
266
267 if (nRows != nCols) {
268 qWarning("[FiffSparseMatrix::mne_add_upper_triangle_rcs] input must be square");
269 return nullptr;
270 }
271
272 // Build full (lower + upper) by adding transpose
273 Eigen::SparseMatrix<float> full = m_eigen + Eigen::SparseMatrix<float>(m_eigen.transpose());
274
275 // The diagonal was counted twice — fix by subtracting the diagonal once
276 for (int k = 0; k < full.outerSize(); ++k) {
277 for (Eigen::SparseMatrix<float>::InnerIterator it(full, k); it; ++it) {
278 if (it.row() == it.col()) {
279 // Original diagonal value is in m_eigen; full has 2x, so set back to 1x
280 it.valueRef() = 0.5f * it.value();
281 }
282 }
283 }
284
285 full.makeCompressed();
286 return std::make_unique<FiffSparseMatrix>(std::move(full), FIFFTS_MC_RCS);
287}
288
289//=============================================================================================================
290
291FiffSparseMatrix FiffSparseMatrix::fromEigenSparse(const Eigen::SparseMatrix<double>& mat)
292{
293 FiffSparseMatrix result;
294 if (mat.nonZeros() == 0)
295 return result;
296
297 result.coding = FIFFTS_MC_RCS;
298 result.m_eigen = mat.cast<float>();
299 result.m_eigen.makeCompressed();
300 return result;
301}
302
303//=============================================================================================================
304
305FiffSparseMatrix FiffSparseMatrix::fromEigenSparse(const Eigen::SparseMatrix<float>& mat)
306{
307 FiffSparseMatrix result;
308 if (mat.nonZeros() == 0)
309 return result;
310
311 result.coding = FIFFTS_MC_RCS;
312 result.m_eigen = mat;
313 result.m_eigen.makeCompressed();
314 return result;
315}
316
317//=============================================================================================================
318
320{
321 int nRows = rows();
322 int nCols = cols();
323
324 if (nRows != nCols) {
325 qWarning("[FiffSparseMatrix::pickLowerTriangleRcs] input must be square");
326 return nullptr;
327 }
328
329 using T = Eigen::Triplet<float>;
330 std::vector<T> triplets;
331 triplets.reserve(m_eigen.nonZeros());
332
333 for (int k = 0; k < m_eigen.outerSize(); ++k) {
334 for (Eigen::SparseMatrix<float>::InnerIterator it(m_eigen, k); it; ++it) {
335 if (it.row() >= it.col()) { // lower triangle including diagonal
336 triplets.push_back(T(it.row(), it.col(), it.value()));
337 }
338 }
339 }
340
341 Eigen::SparseMatrix<float> lower(nRows, nCols);
342 lower.setFromTriplets(triplets.begin(), triplets.end());
343 lower.makeCompressed();
344
345 return std::make_unique<FiffSparseMatrix>(std::move(lower), FIFFTS_MC_RCS);
346}
FIFF tag-kind, block-kind and type-code numerical definitions, authoritative for FIFFLIB.
#define FIFFTS_FS_MATRIX
Definition fiff_file.h:259
#define FIFFTS_MC_RCS
Definition fiff_file.h:263
#define FIFFTS_MC_MASK
Definition fiff_file.h:256
#define FIFFT_MATRIX
Definition fiff_file.h:265
#define FIFFC_MATRIX_MAX_DIM
Definition fiff_file.h:252
#define FIFFTS_FS_MASK
Definition fiff_file.h:254
#define FIFFTS_MC_CCS
Definition fiff_file.h:262
#define FIFFT_FLOAT
Definition fiff_file.h:225
#define FIFFTS_MC_DENSE
Definition fiff_file.h:261
#define FIFFTS_BASE_MASK
Definition fiff_file.h:255
fiff_int_t fiff_type_base(fiff_int_t type)
std::vector< int > fiff_get_matrix_dims(const FiffTag::UPtr &tag)
fiff_int_t fiff_type_matrix_coding(fiff_int_t type)
fiff_int_t fiff_type_fundamental(fiff_int_t type)
FIFF sparse matrix: column / row-compressed sparse storage backed by Eigen::SparseMatrix.
Primitive scalar typedefs and forward-compatible aliases backing the FIFF type system.
FIFF file I/O, in-memory data structures and high-level readers/writers.
qint32 fiff_int_t
Definition fiff_types.h:86
float fiff_float_t
Definition fiff_types.h:90
unsigned char fiff_byte_t
Definition fiff_types.h:82
static FiffSparseMatrix fromEigenSparse(const Eigen::SparseMatrix< double > &mat)
static std::vector< int > fiff_get_matrix_sparse_dims(const FIFFLIB::FiffTag::UPtr &tag)
FiffSparseMatrix::UPtr pickLowerTriangleRcs() const
static FiffSparseMatrix::UPtr create_sparse_rcs(int nrow, int ncol, int *nnz, int **colindex, float **vals)
static FiffSparseMatrix::UPtr fiff_get_float_sparse_matrix(const FIFFLIB::FiffTag::UPtr &tag)
std::unique_ptr< FiffSparseMatrix > UPtr
FiffSparseMatrix::UPtr mne_add_upper_triangle_rcs()
std::unique_ptr< FiffTag > UPtr
Definition fiff_tag.h:165