Skip to content

Instantly share code, notes, and snippets.

@totegamma
Created February 9, 2020 09:32
Show Gist options
  • Save totegamma/d678d806925d66d11f9f409c15b4e72b to your computer and use it in GitHub Desktop.
Save totegamma/d678d806925d66d11f9f409c15b4e72b to your computer and use it in GitHub Desktop.
mat_coo_t* create_coo_from_mmfile(const char* filename) {
MTR_BEGIN_FUNC();
const int BufferSize = 1024;
FILE* fp = fopen(filename, "r");
char line[BufferSize];
int state = 0; //0: size, else: content
mat_coo_t* coo;
int itr = 0;
enum {
GENERAL,
SYMMETRIC,
SKEW,
HERMITIAN
} attr;
if (fgets(line, BufferSize, fp) != NULL) {
char object[16];
char format[16];
char field[16];
char attribute[16];
sscanf(line, "%%%%MatrixMarket %15s %15s %15s %15s", object, format, field, attribute);
if (strcmp(object, "matrix") != 0) {
printf("mmfile: not a matrix file(%s)\n", object);
assert(false);
}
if (strcmp(format, "coordinate") != 0) {
printf("mmfile: unsupported format(%s)\n", format);
assert(false);
}
if (strcmp(field, "real") != 0) {
printf("mmfile: unsupported field(%s)\n", field);
assert(false);
}
if (strcmp(attribute, "general") == 0) {
attr = GENERAL;
} else if(strcmp(attribute, "symmetric") == 0) {
attr = SYMMETRIC;
} else {
printf("mmfile: unsupported attribute (%s)\n", attribute);
assert(false);
}
} else {
printf("empty file\n");
assert(false);
}
while (fgets(line, BufferSize, fp) != NULL) {
if (line[0] == '%') continue;
if (state == 0) {
int cols;
int rows;
int nnz;
sscanf(line, "%d %d %d", &cols, &rows, &nnz);
if (attr == SYMMETRIC) {
nnz -= cols;
nnz *= 2;
nnz += cols;
}
coo = new_mat_coo(cols, rows, nnz);
state = 1;
} else {
int col;
int row;
double val;
sscanf(line, "%d %d %lf", &col, &row, &val);
coo->colind[itr] = col-1;
coo->rowind[itr] = row-1;
coo->data[itr] = val;
itr++;
if (attr == SYMMETRIC) {
if (col != row) {
coo->colind[itr] = row-1;
coo->rowind[itr] = col-1;
coo->data[itr] = val;
itr++;
}
}
}
}
fclose(fp);
MTR_END_FUNC();
return coo;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment