int mm_write_mtx_crd(char fname[], int M, int N, int nz, int I[], int J[], double val[], MM_typecode matcode) /******************************************************************************/ /* Purpose: MM_WRITE_MTX_CRD writes an MM coordinate file. Modified: 31 October 2008 */ { FILE *f; int i; if (strcmp(fname, "stdout") == 0) f = stdout; else if ((f = fopen(fname, "w")) == NULL) return MM_COULD_NOT_WRITE_FILE; /* print banner followed by typecode. */ fprintf(f, "%s ", MatrixMarketBanner); fprintf(f, "%s\n", mm_typecode_to_str(matcode)); /* print matrix sizes and nonzeros. */ fprintf(f, "%d %d %d\n", M, N, nz); /* print values. */ if (mm_is_pattern(matcode)) for (i=0; i<nz; i++) fprintf(f, "%d %d\n", I[i], J[i]); else if (mm_is_real(matcode)) for (i=0; i<nz; i++) fprintf(f, "%d %d %20.16g\n", I[i], J[i], val[i]); else if (mm_is_complex(matcode)) for (i=0; i<nz; i++) fprintf(f, "%d %d %20.16g %20.16g\n", I[i], J[i], val[2*i], val[2*i+1]); else { if (f != stdout) fclose(f); return MM_UNSUPPORTED_TYPE; } if ( f !=stdout ) { fclose(f); } return 0; }
void mm_write_banner(FILE *f, MM_typecode matcode) { char *str = mm_typecode_to_str(matcode); fprintf(f, "%s ", MatrixMarketBanner); fprintf(f, "%s\n", str); free(str); }
void convert_2_vec(const char * filename, shotgun_data * prob ) { int ret_code; MM_typecode matcode; FILE *f; int M, N, nz; int i; if ((f = fopen(filename, "r")) == NULL) { printf("Could not file vector input file : %s.\n", filename); exit(1); } if (mm_read_banner(f, &matcode) != 0) { printf("Could not process Matrix Market banner in input file %s.\n", filename); exit(1); } /* This is how one can screen matrix types if their application */ /* only supports a subset of the Matrix Market data types. */ if (mm_is_complex(matcode) && mm_is_matrix(matcode) && mm_is_sparse(matcode) ) { printf("Sorry, this application does not support "); printf("Market Market type: [%s]\n", mm_typecode_to_str(matcode)); exit(1); } /* find out size of sparse matrix .... */ if ((ret_code = mm_read_mtx_crd_size(f, &M, &N, &nz)) !=0){ printf("Could not process Matrix Market size in input file: %s.\n", filename); exit(1); } /* NOTE: when reading in doubles, ANSI C requires the use of the "l" */ /* specifier as in "%lg", "%lf", "%le", otherwise errors will occur */ /* (ANSI C X3.159-1989, Sec. 4.9.6.2, p. 136 lines 13-15) */ prob->y.reserve(nz); int I,J; double val; for (i=0; i<nz; i++) { fscanf(f, "%d %d %lg\n", &I, &J, &val); I--; /* adjust from 1-based to 0-based */ J--; assert(J==0); prob->y.push_back(val); } if (f !=stdin) fclose(f); }
int readSymmMatrix(char* filename, int& n, double*& v) { int m; // try opening the files FILE *fp; if ((fp = fopen(filename, "r")) == NULL) { fprintf(stderr, "Error occurs while reading from file %s.\n", filename); return 1; } // try reading the banner MM_typecode type; if (mm_read_banner(fp, &type) != 0) { fprintf(stderr, "Could not process Matrix Market banner.\n"); return 2; } // check the type if (!mm_is_matrix(type) || !mm_is_array(type) || !mm_is_real(type) || !mm_is_symmetric(type)) { fprintf(stderr, "Sorry, this application does not support Market Market type: [%s]\n", mm_typecode_to_str(type)); return 3; } // read the sizes of the vectors if (mm_read_mtx_array_size(fp, &m, &n)) { fprintf(stderr, "Could not read the size of the matrix.\n"); return 4; } // check if it is a square matrix if (n != m) { fprintf(stderr, "Needs to be square.\n"); return 5; } // allocate the memory printf("reading %s:\n\ta %d x %d matrix...", filename, m, n); v = new double[m * n]; for (int j = 0; j < n; ++j) { for (int i = j; i < m; ++i) { fscanf(fp, "%lf\n", &v[i * n + j]); if (i != j) { v[j * n + i] = v[i * n + j]; } } } printf("done\n"); // close the file fclose(fp); return 0; }
int mm_write_banner(FILE *f, MM_typecode matcode) { char *str = mm_typecode_to_str(matcode); int ret_code; ret_code = fprintf(f, "%s %s\n", MatrixMarketBanner, str); free(str); if (ret_code !=2 ) return MM_COULD_NOT_WRITE_FILE; else return 0; }
int mm_write_banner(FILE *f, MM_typecode matcode) { char buffer[MM_MAX_LINE_LENGTH]; mm_typecode_to_str(matcode, buffer); int ret_code; ret_code = fprintf(f, "%s %s\n", MatrixMarketBanner, buffer); //free(str); //delete [] str; return 0; }
int mm_write_banner(FILE *f, MM_typecode matcode) { char *str = mm_typecode_to_str(matcode); int ret_code; ret_code = fprintf(f, "%s %s\n", MatrixMarketBanner, str); /* free(str); This is a bug from the official distribution - KE fixed */ if (ret_code < 0 ) return MM_COULD_NOT_WRITE_FILE; else return 0; }
/** Reads a matrix market file for a symmetric real valued sparse matrix and returns the matrix in 1-indexed CSR form. */ void read_mm_sym_matrix(FILE* f, MM_typecode mcode, int n, int nnzs, double *values, int* col_ind, int *row_ptr ) { if (!(mm_is_real(mcode) && mm_is_matrix(mcode) && mm_is_sparse(mcode) && mm_is_symmetric(mcode)) ) { printf("First argument must be a symmetric, real-valued, sparse matrix\n"); printf("Market Market type: [%s]\n", mm_typecode_to_str(mcode)); exit(1); } // read Matrix Market matrix in COO format int* I = (int *) malloc(nnzs * sizeof(int)); int *J = (int *) malloc(nnzs * sizeof(int)); double *val = (double *) malloc(nnzs * sizeof(double)); int i; for (i=0; i<nnzs; i++) { fscanf(f, "%d %d %lg\n", &I[i], &J[i], &val[i]); I[i]--; J[i]--; } MKL_INT job[] = { 1, // convert COO to CSR 1, // use 1 based indexing for CSR matrix (required by mkl_dcsrsymv) 0, 0, // Is this used? nnzs, 0 }; MKL_INT info; // convert COO matrix to CSR mkl_dcsrcoo(job, &n, values, col_ind, row_ptr, &nnzs, val, I, J, &info); if (info != 0) { printf("CSR to COO conversion failed: not enough memory!\n"); exit(1); } }
int readBandedMatrix(char* filename, int& n, int& t, int& nz, long long*& AR, long long*& AC, double*& AV) { // try opening the files FILE *fp; if ((fp = fopen(filename, "r")) == NULL) { fprintf(stderr, "Error occurs while reading from file %s.\n", filename); return 1; } // try reading the banner MM_typecode type; if (mm_read_banner(fp, &type)) { fprintf(stderr, "Could not process Matrix Market banner.\n"); return 2; } // check the type if (!mm_is_matrix(type) || !mm_is_coordinate(type) || !mm_is_real(type) || !mm_is_general(type)) { fprintf(stderr, "Sorry, this application does not support Market Market type: [%s]\n", mm_typecode_to_str(type)); return 3; } // read the sizes and nnz of the matrix int m; if (mm_read_mtx_crd_size(fp, &n, &m, &nz)) { fprintf(stderr, "Could not read the size of the matrix.\n"); return 4; } printf("reading %s:\n\ta %d x %d banded matrix ", filename, n, m); // allocate the memory AR = new long long[nz]; AC = new long long[nz]; AV = new double[nz]; t = 0; for (int i = 0; i < nz; ++i) { fscanf(fp, "%d %d %lf\n", AR + i, AC + i, AV + i); --AR[i]; // 0-indexing --AC[i]; // 0-indexing t = std::max(t, (int)(AR[i] - AC[i])); } printf("with bandwidth (2m + 1) = %d...done\n", 2 * t + 1); // close the file fclose(fp); return 0; }
int mm_write_mtx_crd(char fname[], int M, int N, int nz, int I[], int J[], double val[], MM_typecode matcode) { FILE *f; int i; char * tmp; if (strcmp(fname, "stdout") == 0) f = stdout; else if ((f = fopen(fname, "w")) == NULL) return MM_COULD_NOT_WRITE_FILE; /* print banner followed by typecode */ fprintf(f, "%s ", MatrixMarketBanner); tmp = mm_typecode_to_str(matcode); fprintf(f, "%s\n", tmp); if (tmp) { free(tmp); tmp = NULL; } /* print matrix sizes and nonzeros */ fprintf(f, "%d %d %d\n", M, N, nz); /* print values */ if (mm_is_pattern(matcode)) for (i=0; i<nz; i++) fprintf(f, "%d %d\n", I[i], J[i]); else if (mm_is_real(matcode)) for (i=0; i<nz; i++) fprintf(f, "%d %d %20.16g\n", I[i], J[i], val[i]); else if (mm_is_complex(matcode)) for (i=0; i<nz; i++) fprintf(f, "%d %d %20.16g %20.16g\n", I[i], J[i], val[2*i], val[2*i+1]); else { if (f != stdout) fclose(f); return MM_UNSUPPORTED_TYPE; } if (f !=stdout) fclose(f); return 0; }
/*** fread MatrixMarket format file ***/ mm_real * mm_real_fread (FILE *fp) { MM_typecode typecode; mm_real *x; if (mm_read_banner (fp, &typecode) != 0) error_and_exit ("mm_real_fread", "failed to read mm_real.", __FILE__, __LINE__); if (!is_type_supported (typecode)) { char msg[128]; sprintf (msg, "matrix type does not supported :[%s].", mm_typecode_to_str (typecode)); error_and_exit ("mm_real_fread", msg, __FILE__, __LINE__); } x = (mm_is_sparse (typecode)) ? mm_real_fread_sparse (fp, typecode) : mm_real_fread_dense (fp, typecode); if (!x) error_and_exit ("mm_real_fread", "failed to read mm_real.", __FILE__, __LINE__); if (mm_real_is_symmetric (x) && x->m != x->n) error_and_exit ("mm_real_fread", "symmetric matrix must be square.", __FILE__, __LINE__); return x; }
/*** create new mm_real object * MMRealFormat format: MM_REAL_DENSE or MM_REAL_SPARSE * MMRealSymm symm : MM_REAL_GENERAL, MM_REAL_SYMMETRIC_UPPER or MM_REAL_SYMMETRIC_LOWER * int m, n : rows and columns of the matrix * int nnz : number of nonzero elements of the matrix ***/ mm_real * mm_real_new (MMRealFormat format, MMRealSymm symm, const int m, const int n, const int nnz) { mm_real *x; bool symmetric; if (!is_format_valid (format)) error_and_exit ("mm_real_new", "invalid MMRealFormat format.", __FILE__, __LINE__); if (!is_symm_valid (symm)) error_and_exit ("mm_real_new", "invalid MMRealSymm symm.", __FILE__, __LINE__); symmetric = symm & MM_SYMMETRIC; if (symmetric && m != n) error_and_exit ("mm_real_new", "symmetric matrix must be square.", __FILE__, __LINE__); x = mm_real_alloc (); if (x == NULL) error_and_exit ("mm_real_new", "failed to allocate object.", __FILE__, __LINE__); x->m = m; x->n = n; x->nnz = nnz; // typecode[1] = 'C' or 'A' if (format == MM_REAL_SPARSE) { mm_set_coordinate (&x->typecode); x->i = (int *) malloc (x->nnz * sizeof (int)); x->p = (int *) malloc ((x->n + 1) * sizeof (int)); if (x->i == NULL || x->p == NULL) error_and_exit ("mm_real_new", "cannot allocate memory.", __FILE__, __LINE__); // initialize x->p[0] x->p[0] = 0; } else mm_set_array (&x->typecode); x->symm = symm; // typecode[3] = 'G' -> 'S' if (symmetric) mm_set_symmetric (&x->typecode); if (!is_type_supported (x->typecode)) { char msg[128]; sprintf (msg, "matrix type does not supported :[%s].", mm_typecode_to_str (x->typecode)); error_and_exit ("mm_real_new", msg, __FILE__, __LINE__); } // allocate arrays x->data = (double *) malloc (x->nnz * sizeof (double)); if (x->data == NULL) error_and_exit ("mm_real_new", "cannot allocate memory.", __FILE__, __LINE__); return x; }
// Mandatory int mm_write_banner ( FILE *f, MM_typecode matcode ) /******************************************************************************/ /* Purpose: MM_WRITE_BANNER writes the header line of an MM file. Modified: 31 October 2008 Parameters: Input, FILE *F, a pointer to the output file. */ { char *str = mm_typecode_to_str(matcode); int ret_code; ret_code = fprintf(f, "%s %s\n", MatrixMarketBanner, str); free(str); if (ret_code !=2 ) return MM_COULD_NOT_WRITE_FILE; else return 0; }
int get_mm_info(const char *file, int *m, int *n, int *nz) { FILE *fp; MM_typecode matcode; if ((fp = fopen(file, "r")) == NULL) { fprintf(stderr,"ERROR: Could not open file: %s\n",file); exit(1); } if (mm_read_banner(fp, &matcode) != 0) { fprintf(stderr,"ERROR: Could not process Matrix Market banner.\n"); exit(1); } if (!(mm_is_real(matcode) || mm_is_integer(matcode))) { fprintf(stderr,"ERROR: Market Market type: [%s] not supported\n", mm_typecode_to_str(matcode)); exit(1); } if (mm_is_sparse(matcode)) { if (mm_read_mtx_crd_size(fp, m, n, nz) !=0) { /* find out size of sparse matrix */ exit(1); } } else { if (mm_read_mtx_array_size(fp, m, n) !=0) { /* find out size of dense matrix */ exit(1); } *nz = -1; } fclose(fp); return 0; }
//------------------------------------------------------------------------ int test_mm_read(std::string filename) { int ret_code; MM_typecode matcode; FILE *f; int M, N, nz; int i, *I, *J; double *val; int err=0; if ((f = fopen(filename.c_str(), "r")) == NULL) return -1; if (mm_read_banner(f, &matcode) != 0) { printf("Could not process Matrix Market banner.\n"); return -2; } /* This is how one can screen matrix types if their application */ /* only supports a subset of the Matrix Market data types. */ if (mm_is_complex(matcode) && mm_is_matrix(matcode) && mm_is_sparse(matcode) ) { printf("Sorry, this application does not support "); printf("Market Market type: [%s]\n", mm_typecode_to_str(matcode)); return -3; } /* find out size of sparse matrix .... */ if ((ret_code = mm_read_mtx_crd_size(f, &M, &N, &nz)) !=0) return -4; /* reseve memory for matrices */ I = (int *) malloc(nz * sizeof(int)); J = (int *) malloc(nz * sizeof(int)); val = (double *) malloc(nz * sizeof(double)); /* NOTE: when reading in doubles, ANSI C requires the use of the "l" */ /* specifier as in "%lg", "%lf", "%le", otherwise errors will occur */ /* (ANSI C X3.159-1989, Sec. 4.9.6.2, p. 136 lines 13-15) */ for (i=0; i<nz; i++) { fscanf(f, "%d %d %lg\n", &I[i], &J[i], &val[i]); I[i]--; /* adjust from 1-based to 0-based */ J[i]--; } if (f !=stdin) fclose(f); /************************/ /* now write out matrix */ /************************/ fprintf(stdout, "Read full file contents: \n================================\n"); err += mm_write_banner(stdout, matcode); err += mm_write_mtx_crd_size(stdout, M, N, nz); for (i=0; i<nz; i++) { fprintf(stdout, "%d %d %lg\n", I[i]+1, J[i]+1, val[i]); } return err; }
int read_mm_new_matrix_transpose(const char *file, dmatrix **out_mat) { dmatrix *dmat; int i, j, m, n, nz; FILE *fp; MM_typecode matcode; if ((fp = fopen(file, "r")) == NULL) { fprintf(stderr,"ERROR: Could not open file: %s\n",file); exit(1); } if (mm_read_banner(fp, &matcode) != 0) { fprintf(stderr,"ERROR: Could not process Matrix Market banner.\n"); exit(1); } if (!(mm_is_real(matcode) || mm_is_integer(matcode))) { fprintf(stderr,"ERROR: Market Market type: [%s] not supported\n", mm_typecode_to_str(matcode)); exit(1); } if (mm_is_sparse(matcode)) { int cur_i, cur_j; double cur_val; double *val, *vtmp; int *idx, *jdx, *rdx; int *itmp, *jtmp, *tmp; if (mm_read_mtx_crd_size(fp, &n, &m, &nz) !=0) { /* find out size of sparse matrix */ exit(1); } dmat = malloc(sizeof(dmatrix)); itmp = malloc(nz*sizeof(int)); jtmp = malloc(nz*sizeof(int)); vtmp = malloc(nz*sizeof(double)); rdx = malloc((m+1)*sizeof(int)); idx = malloc(nz*sizeof(int)); jdx = malloc(nz*sizeof(int)); val = malloc(nz*sizeof(double)); tmp = malloc(m*sizeof(int)); memset(tmp, 0, sizeof(int)*m); for (i = 0; i < nz; i++) { fscanf(fp, "%d %d %lg\n", &cur_j, &cur_i, &cur_val); itmp[i] = --cur_i; jtmp[i] = --cur_j; vtmp[i] = cur_val; tmp[ itmp[i] ]++ ; } rdx[0] = 0; for (i = 0; i < m ; i++) { rdx[i+1] = rdx[i] + tmp[i]; tmp[i] = rdx[i]; } for (i = 0; i < nz; i++) { int ii; ii = tmp[ itmp[i] ]++; idx[ii] = itmp[i]; jdx[ii] = jtmp[i]; val[ii] = vtmp[i]; } dmat->n = n; dmat->m = m; dmat->nz = nz; dmat->val = val; dmat->idx = idx; dmat->jdx = jdx; dmat->rdx = rdx; free(itmp); free(jtmp); free(vtmp); free(tmp); } else { double *val; if (mm_read_mtx_array_size(fp, &n, &m) !=0) { /* find out size of dense matrix */ exit(1); } dmat = malloc(sizeof(dmatrix)); val = malloc((m*n)*sizeof(double)); for (j = 0; j < n*m; j++) { fscanf(fp, "%lg\n", &val[j]); } dmat->n = n; dmat->m = m; dmat->nz = -1; dmat->val = val; dmat->idx = NULL; dmat->jdx = NULL; dmat->rdx = NULL; } *out_mat = dmat; if (fp !=stdin) fclose(fp); return 0; }
/** \brief Read a vector file. * * Reads a Matrix Market formatted vector from a file. * Returns pointer to dense vector. * * @param file vector file name * @param out_vec vector data * * @return result */ int read_mm_new_vector(const char *file, double **out_vec) { double *val; int i, m, n, nz; FILE *fp; MM_typecode matcode; if ((fp = fopen(file, "r")) == NULL) { fprintf(stderr,"ERROR: Could not open file: %s\n",file); exit(1); } if (mm_read_banner(fp, &matcode) != 0) { fprintf(stderr,"ERROR: Could not process Matrix Market banner.\n"); exit(1); } if (!(mm_is_real(matcode) || mm_is_integer(matcode))) { fprintf(stderr,"ERROR: Market Market type: [%s] not supported\n", mm_typecode_to_str(matcode)); exit(1); } if (mm_is_sparse(matcode)) { if (mm_read_mtx_crd_size(fp, &m, &n, &nz) !=0) { /* find out size of sparse matrix */ exit(1); } if (n != 1) { fprintf(stderr,"ERROR: %s does not contain a column vector\n",file); exit(1); } val = malloc(m*sizeof(double)); memset(val, 0, m*sizeof(double)); for (i = 0; i < nz; i++) { int cur_i, cur_j; double cur_val; fscanf(fp, "%d %d %lg\n", &cur_i, &cur_j, &cur_val); val[cur_i-1] = cur_val; } } else { if (mm_read_mtx_array_size(fp, &m, &n) !=0) { /* find out size of dense matrix */ exit(1); } if (n != 1) { fprintf(stderr,"ERROR: %s does not contain a column vector\n",file); exit(1); } val = malloc(m*sizeof(double)); for (i = 0; i < m; i++) { double cur_val; fscanf(fp, "%lg\n", &cur_val); val[i] = cur_val; } } *out_vec = val; if (fp !=stdin) fclose(fp); return 0; }
int mm_read_unsymmetric_sparse(const char *fname, int *M_, int *N_, int *nz_, double **val_, int **I_, int **J_) { FILE *f; MM_typecode matcode; int M, N, nz; int i; double *val; int *I, *J; if ((f = fopen(fname, "r")) == NULL) return -1; if (mm_read_banner(f, &matcode) != 0) { printf("mm_read_unsymetric: Could not process Matrix Market banner "); printf(" in file [%s]\n", fname); return -1; } if ( !(mm_is_real(matcode) && mm_is_matrix(matcode) && mm_is_sparse(matcode))) { fprintf(stderr, "Sorry, this application does not support "); fprintf(stderr, "Market Market type: [%s]\n", mm_typecode_to_str(matcode)); return -1; } /* find out size of sparse matrix: M, N, nz .... */ if (mm_read_mtx_crd_size(f, &M, &N, &nz) !=0) { fprintf(stderr, "read_unsymmetric_sparse(): could not parse matrix size.\n"); return -1; } *M_ = M; *N_ = N; *nz_ = nz; /* reseve memory for matrices */ I = (int *) malloc(nz * sizeof(int)); J = (int *) malloc(nz * sizeof(int)); val = (double *) malloc(nz * sizeof(double)); *val_ = val; *I_ = I; *J_ = J; /* NOTE: when reading in doubles, ANSI C requires the use of the "l" */ /* specifier as in "%lg", "%lf", "%le", otherwise errors will occur */ /* (ANSI C X3.159-1989, Sec. 4.9.6.2, p. 136 lines 13-15) */ for (i=0; i<nz; i++) { fscanf(f, "%d %d %lg\n", &I[i], &J[i], &val[i]); I[i]--; /* adjust from 1-based to 0-based */ J[i]--; } fclose(f); return 0; }
vec load_matrix_market_vector(const std::string & filename, bool optional_field, bool allow_zeros) { int ret_code; MM_typecode matcode; uint M, N; size_t i,nz; logstream(LOG_INFO) <<"Going to read matrix market vector from input file: " << filename << std::endl; FILE * f = open_file(filename.c_str(), "r", optional_field); //if optional file not found return if (f== NULL && optional_field){ return zeros(1); } if (mm_read_banner(f, &matcode) != 0) logstream(LOG_FATAL) << "Could not process Matrix Market banner." << std::endl; /* This is how one can screen matrix types if their application */ /* only supports a subset of the Matrix Market data types. */ if (mm_is_complex(matcode) && mm_is_matrix(matcode) && mm_is_sparse(matcode) ) logstream(LOG_FATAL) << "sorry, this application does not support " << std::endl << "Market Market type: " << mm_typecode_to_str(matcode) << std::endl; /* find out size of sparse matrix .... */ if (mm_is_sparse(matcode)){ if ((ret_code = mm_read_mtx_crd_size(f, &M, &N, &nz)) !=0) logstream(LOG_FATAL) << "failed to read matrix market cardinality size " << std::endl; } else { if ((ret_code = mm_read_mtx_array_size(f, &M, &N))!= 0) logstream(LOG_FATAL) << "failed to read matrix market vector size " << std::endl; if (N > M){ //if this is a row vector, transpose int tmp = N; N = M; M = tmp; } nz = M*N; } vec ret = zeros(M); uint row,col; double val; for (i=0; i<nz; i++) { if (mm_is_sparse(matcode)){ int rc = fscanf(f, "%u %u %lg\n", &row, &col, &val); if (rc != 3){ logstream(LOG_FATAL) << "Failed reading input file: " << filename << "Problm at data row " << i << " (not including header and comment lines)" << std::endl; } row--; /* adjust from 1-based to 0-based */ col--; } else { int rc = fscanf(f, "%lg\n", &val); if (rc != 1){ logstream(LOG_FATAL) << "Failed reading input file: " << filename << "Problm at data row " << i << " (not including header and comment lines)" << std::endl; } row = i; col = 0; } //some users have gibrish in text file - better check both I and J are >=0 as well assert(row >=0 && row< M); assert(col == 0); if (val == 0 && !allow_zeros) logstream(LOG_FATAL)<<"Zero entries are not allowed in a sparse matrix market vector. Use --zero=true to avoid this error"<<std::endl; //set observation value ret[row] = val; } fclose(f); logstream(LOG_INFO)<<"Succesfully read a vector of size: " << M << " [ " << nz << "]" << std::endl; return ret; }
int main(int argc, char *argv[]) { FILE *input_file, *output_file, *time_file; if (argc < 4) { fprintf(stderr, "Invalid input parameters\n"); fprintf(stderr, "Usage: %s inputfile outputfile timefile \n", argv[0]); exit(1); } else { input_file = fopen(argv[1], "r"); output_file = fopen(argv[2], "w"); time_file = fopen(argv[3], "w"); if (!input_file || !output_file || !time_file) exit(1); } MM_typecode matcode; if (mm_read_banner(input_file, &matcode) != 0) { printf("Could not process Matrix Market banner.\n"); exit(1); } if (!mm_is_matrix(matcode) || !mm_is_real(matcode) || !mm_is_coordinate(matcode)) { printf("Sorry, this application does not support "); printf("Market Market type: [%s]\n", mm_typecode_to_str(matcode)); exit(1); } mtxMatrix inputMatrix, fullMatrix, LMatrix, UMatrix, UMatrixTranspose, MMatrix; ReadMatrix(inputMatrix, input_file); Timer timer; getRowIndex(&inputMatrix, inputMatrix.RowIndex); inputMatrix.RowIndex[inputMatrix.N] = inputMatrix.NZ; int diagNum = 0; for (int i = 0; i < inputMatrix.N; i++) { for (int j = inputMatrix.RowIndex[i]; j < inputMatrix.RowIndex[i + 1]; j++) { if (i == inputMatrix.Col[j]) diagNum++; } } if (mm_is_symmetric(matcode)) { InitializeMatrix(inputMatrix.N, 2 * inputMatrix.NZ - diagNum, fullMatrix); TriangleToFull(&inputMatrix, &fullMatrix); FreeMatrix(inputMatrix); } else { fullMatrix = inputMatrix; } int *diag = new int[fullMatrix.N]; for (int i = 0; i < fullMatrix.N; i++) { for (int j = fullMatrix.RowIndex[i]; j < fullMatrix.RowIndex[i + 1]; j++) { if (i == fullMatrix.Col[j]) diag[i] = j; } } // for (int i = 0; i < fullMatrix.N + 1; i++) { // printf("RowIndex[%i] = %i\n", i, fullMatrix.RowIndex[i]); // } // // // for (int i = 0; i < fullMatrix.N; i++) { // printf("input[%i]= %lf\n", i, fullMatrix.Value[inputMatrix.RowIndex[i]]); // } // // for (int i = 0; i < fullMatrix.N; i++) { // printf("diag[%i]= %d\n", i, diag[i]); // } timer.start(); ilu0(fullMatrix, fullMatrix.Value, diag); LUmatrixSeparation(fullMatrix, diag, LMatrix, UMatrix); Transpose(UMatrix, UMatrixTranspose); Multiplicate(LMatrix, UMatrixTranspose, MMatrix); timer.stop(); std::ofstream timeLog; timeLog.open(argv[3]); timeLog << timer.getElapsed(); WriteFullMatrix(MMatrix, output_file, matcode); FreeMatrix(fullMatrix); return 0; }
int readSparseMatrix(char * filename, PetscInt & n, PetscInt & nz, PetscInt *& nnz, int *& i, int *& j, double *& v) { int in, m, inz; // try opening the files FILE *fp; if ((fp = fopen(filename, "r")) == NULL) { fprintf(stderr, "Error occurs while reading from file %s.\n", filename); return 1; } // try reading the banner MM_typecode type; if (mm_read_banner(fp, &type) != 0) { fprintf(stderr, "Could not process Matrix Market banner.\n"); return 2; } // check the type if (!mm_is_matrix(type) || !mm_is_coordinate(type) || !mm_is_real(type) || !mm_is_symmetric(type)) { fprintf(stderr, "Sorry, this application does not support Market Market type: [%s]\n", mm_typecode_to_str(type)); return 3; } // read the sizes of the vectors if (mm_read_mtx_crd_size(fp, &in, &m, &inz)) { fprintf(stderr, "Could not read the size of the matrix.\n"); return 4; } n = in; nz = inz; // check if it is a square matrix if (in != m) { fprintf(stderr, "Needs to be square.\n"); return 5; } // allocate the memory printf("reading %s:\n\ta %d x %d sparse matrix with %d nonzeros...", filename, m, in, inz); i = new int[nz]; j = new int[nz]; v = new double[nz]; nnz = new PetscInt[n](); for (int k = 0; k < inz; ++k) { fscanf(fp, "%u %u %lf\n", &j[k], &i[k], &v[k]); --i[k]; --j[k]; ++nnz[i[k]]; if (i[k] != j[k]) { ++nnz[j[k]]; } } printf("done\n"); // close the file fclose(fp); return 0; }
static void read_mtx_and_return_csr( int argc, char **argv, int *mm, int *nn, int **ia, int **ja, double **aa) { int ret_code; MM_typecode matcode; FILE *f; int m, n, nz; int i, *I, *J; double *val; if (argc < 2) { fprintf(stderr, "Usage: %s [martix-market-filename]\n", argv[0]); exit(1); } else { printf("\n===================================\n"); printf("mtx file = %s\n", argv[1]); if ((f = fopen(argv[1], "r")) == NULL) { printf("Could not open %s\n", argv[1]); exit(1); } } if (mm_read_banner(f, &matcode) != 0) { printf("Could not process Matrix Market banner.\n"); exit(1); } /* This is how one can screen matrix types if their application */ /* only supports a subset of the Matrix Market data types. */ if ( mm_is_pattern(matcode) || mm_is_dense(matcode) || mm_is_array(matcode) ) { printf("Sorry, this application does not support "); printf("Market Market type: [%s]\n", mm_typecode_to_str(matcode)); exit(1); } if (mm_is_complex(matcode) && mm_is_matrix(matcode) && mm_is_sparse(matcode) ) { printf("Sorry, this application does not support "); printf("Market Market type: [%s]\n", mm_typecode_to_str(matcode)); exit(1); } /* find out size of sparse matrix .... */ if ((ret_code = mm_read_mtx_crd_size(f, &m, &n, &nz)) !=0) exit(1); /* reseve memory for matrices */ I = (int *) malloc(nz * sizeof(int)); J = (int *) malloc(nz * sizeof(int)); val = (double *) malloc(nz * sizeof(double)); /* NOTE: when reading in doubles, ANSI C requires the use of the "l" */ /* specifier as in "%lg", "%lf", "%le", otherwise errors will occur */ /* (ANSI C X3.159-1989, Sec. 4.9.6.2, p. 136 lines 13-15) */ for (i=0; i<nz; i++) { fscanf(f, "%d %d %lg\n", &I[i], &J[i], &val[i]); I[i]--; /* adjust from 1-based to 0-based */ J[i]--; } if (f !=stdin) fclose(f); if (m != n) exit(1); *mm = m; *nn = n; *ia = (int*) malloc (sizeof(int) * (n+1)); *ja = (int*) malloc (sizeof(int) * nz); *aa = (double*) malloc (sizeof(double) * nz); coo2csr(n, nz, val, I, J, *aa, *ja, *ia); free (I); free (J); free (val); }
csr_matrix_t *csr_mm_load(char *filename) { int ret_code; MM_typecode matcode; FILE *f; int entry_count; int i, M, N, nz; matrix_entry_t *entries; matrix_entry_t *entry; int *row_start; int *col_index; double *val; csr_matrix_t *A; if ((f = fopen(filename, "r")) == NULL) exit(1); if (mm_read_banner(f, &matcode) != 0) { printf("Could not process Matrix Market banner.\n"); exit(1); } if (!mm_is_sparse(matcode) || !mm_is_symmetric(matcode) || !mm_is_real(matcode)) { printf("Sorry, this application does not support "); printf("Market Market type: [%s]\n", mm_typecode_to_str(matcode)); exit(1); } /* find out size of sparse matrix .... */ if ((ret_code = mm_read_mtx_crd_size(f, &M, &N, &nz)) != 0) exit(1); /* reserve memory for matrices */ row_start = (int *) malloc((M + 1) * sizeof(int)); col_index = (int *) malloc((2 * nz - M) * sizeof(int)); val = (double *) malloc((2 * nz - M) * sizeof(double)); entries = (matrix_entry_t *) malloc((2 * nz - M) * sizeof(matrix_entry_t)); /* NOTE: when reading in doubles, ANSI C requires the use of the "l" */ /* specifier as in "%lg", "%lf", "%le", otherwise errors will occur */ /* (ANSI C X3.159-1989, Sec. 4.9.6.2, p. 136 lines 13-15) */ entry = entries; entry_count = 0; for (i = 0; i < nz; i++) { int row, col; double val; fscanf(f, "%d %d %lg\n", &row, &col, &val); --row; /* adjust to 0-based */ --col; assert(row >= 0 && col >= 0); assert(entry_count++ < 2 * nz - M); entry->i = row; entry->j = col; entry->val = val; ++entry; if (row != col) { /* Fill out the other half... */ assert(entry_count++ < 2 * nz - M); entry->i = col; entry->j = row; entry->val = val; ++entry; } } if (f != stdin) fclose(f); /**********************************/ /* now make CSR version of matrix */ /**********************************/ nz = 2 * nz - M; qsort(entries, nz, sizeof(matrix_entry_t), entry_comparison); entry = entries; row_start[0] = 0; for (i = 0; i < nz; ++i) { row_start[entry->i + 1] = i + 1; col_index[i] = entry->j; val[i] = entry->val; ++entry; } free(entries); A = (csr_matrix_t *) malloc(sizeof(csr_matrix_t)); A->m = M; A->n = N; A->nz = nz; A->row_start = row_start; A->col_idx = col_index; A->val = val; return A; }
bcsr_t *mm_file_to_bcsr(char *filename, unsigned c, unsigned r) { FILE *f; MM_typecode matcode; int ret_code; int M, N; int nz; int i; unsigned *I, *J; float *val; bcsr_t *bcsr; if ((f = fopen(filename, "r")) == NULL) exit(1); if (mm_read_banner(f, &matcode) != 0) { printf("Could not process Matrix Market banner.\n"); exit(1); } /* This is how one can screen matrix types if their application */ /* only supports a subset of the Matrix Market data types. */ if (mm_is_complex(matcode) && mm_is_matrix(matcode) && mm_is_sparse(matcode) ) { printf("Sorry, this application does not support "); printf("Market Market type: [%s]\n", mm_typecode_to_str(matcode)); exit(1); } /* find out size of sparse matrix .... */ if ((ret_code = mm_read_mtx_crd_size(f, &M, &N, &nz)) !=0) exit(1); /* reseve memory for matrices */ I = malloc(nz * sizeof(unsigned)); J = malloc(nz * sizeof(unsigned)); /* XXX float ! */ val = (float *) malloc(nz * sizeof(float)); for (i=0; i<nz; i++) { fscanf(f, "%d %d %f\n", &I[i], &J[i], &val[i]); I[i]--; /* adjust from 1-based to 0-based */ J[i]--; } if (f !=stdin) fclose(f); bcsr = mm_to_bcsr((unsigned)nz, I, J, val, c, r); free(I); free(J); free(val); return bcsr; }
bool MatrixMarket::read_matrix(const char *file_name) { int ret_code; MM_typecode matcode; FILE *f; int i;//, *I(NULL); //, *J; // double *val; if ((f = fopen(file_name, "r")) == NULL) return false; if (mm_read_banner(f, &matcode) != 0) { printf("Could not process Matrix Market banner.\n"); return false; } /* This is how one can screen matrix types if their application */ /* only supports a subset of the Matrix Market data types. */ if (mm_is_complex(matcode) && mm_is_matrix(matcode) && mm_is_sparse(matcode) ) { printf("Sorry, this application does not support "); printf("Market Market type: [%s]\n", mm_typecode_to_str(matcode)); return false; } /* find out size of sparse matrix .... */ int _num_rows, _num_cols, _num_nnzs; if ((ret_code = mm_read_mtx_crd_size(f, &_num_rows, &_num_cols, &_num_nnzs)) !=0) return false; bool is_vector = (_num_rows == _num_nnzs) && (_num_cols == 1); // convert to 64 bit m_num_rows = _num_rows; m_num_cols = _num_cols; m_num_nnzs = _num_nnzs; /* reseve memory for matrices */ // I = (int *) malloc(nz * sizeof(int)); // J = (int *) malloc(nz * sizeof(int)); // val = (double *) malloc(nz * sizeof(double)); m_rows.resize(m_num_nnzs); m_cols.resize(m_num_nnzs); m_coefs.resize(m_num_nnzs); /* NOTE: when reading in doubles, ANSI C requires the use of the "l" */ /* specifier as in "%lg", "%lf", "%le", otherwise errors will occur */ /* (ANSI C X3.159-1989, Sec. 4.9.6.2, p. 136 lines 13-15) */ if (is_vector) { for (i=0; i<m_num_nnzs; i++) { fscanf(f, "%lg\n", &(m_coefs[i])); m_rows[i] = i; m_cols[i] = 0; } if (f !=stdin) fclose(f); return true; } std::vector<std::map<int32_t,double> > elements; elements.resize(m_num_rows); for (i=0; i<m_num_nnzs; i++) { fscanf(f, "%d %d %lg\n", &(m_rows[i]), &(m_cols[i]), &(m_coefs[i])); m_rows[i]--; /* adjust from 1-based to 0-based */ m_cols[i]--; elements[m_rows[i]][m_cols[i]] += m_coefs[i]; } // now sort by rows std::vector<int> m_rows2; std::vector<int32_t> m_cols2; std::vector<double> m_coefs2; m_rows2.resize(m_num_nnzs); m_cols2.resize(m_num_nnzs); m_coefs2.resize(m_num_nnzs); int index=0; for (int row=0; row<m_num_rows; row++) { assert((int)elements[row].size() > 0); // Make sure diagonal element is first if (elements[row].find(row) != elements[row].end()) { m_cols2[index] = row; m_rows2[index] = row; m_coefs2[index] = elements[row][row]; assert (m_coefs2[index] != 0.0); index++; } else assert(0); for (auto iter = elements[row].begin(); iter != elements[row].end(); iter++) { int col = iter->first; if (col != row) { double C = iter->second; assert(col < m_num_cols); m_rows2[index] = row; m_cols2[index] = col; m_coefs2[index] = C; index++; } } } if (f !=stdin) fclose(f); m_rows.swap(m_rows2); m_cols.swap(m_cols2); m_coefs.swap(m_coefs2); /* convert coo to csr row ptrs */ coo_to_csr_rows(m_rows, m_num_rows, m_row_ptrs); return true; // /************************/ // /* now write out matrix */ // /************************/ // mm_write_banner(stdout, matcode); // mm_write_mtx_crd_size(stdout, m_num_rows, m_num_cols, m_num_nnzs); // for (i=0; i<nz; i++) // fprintf(stdout, "%d %d %20.19g\n", I[i]+1, J[i]+1, val[i]); // free(I); }
void HostMatrixCOO<ValueType>::ReadFileMTX(const std::string filename) { // Follow example_read.c (from Matrix Market web site) int ret_code; MM_typecode matcode; FILE *f; int M, N; int fnz, nnz; // file nnz, real nnz bool sym = false; LOG_INFO("ReadFileMTX: filename="<< filename << "; reading..."); if ((f = fopen(filename.c_str(), "r")) == NULL) { LOG_INFO("ReadFileMTX cannot open file " << filename); FATAL_ERROR(__FILE__, __LINE__); } if (mm_read_banner(f, &matcode) != 0) { LOG_INFO("ReadFileMTX could not process Matrix Market banner."); FATAL_ERROR(__FILE__, __LINE__); } /* This is how one can screen matrix types if their application */ /* only supports a subset of the Matrix Market data types. */ if (mm_is_complex(matcode) && mm_is_matrix(matcode) && mm_is_sparse(matcode) ) { LOG_INFO("ReadFileMTX does not support Market Market type:" << mm_typecode_to_str(matcode)); FATAL_ERROR(__FILE__, __LINE__); } /* find out size of sparse matrix .... */ if ((ret_code = mm_read_mtx_crd_size(f, &M, &N, &fnz)) !=0) { LOG_INFO("ReadFileMTX matrix size error"); FATAL_ERROR(__FILE__, __LINE__); } nnz = fnz ; /* reseve memory for matrices */ if(mm_is_symmetric(matcode)) { if (N != M) { LOG_INFO("ReadFileMTX non-squared symmetric matrices are not supported"); LOG_INFO("What is symmetric and non-squared matrix? e-mail me"); FATAL_ERROR(__FILE__, __LINE__); } nnz = 2*(nnz - N) + N; sym = true ; } this->AllocateCOO(nnz,M,N); int ii=0; int col, row; double val; int ret; for (int i=0; i<fnz; ++i) { ret = fscanf(f, "%d %d %lg\n", &row, &col, &val); if (!ret) FATAL_ERROR(__FILE__, __LINE__); row--; /* adjust from 1-based to 0-based */ col--; assert (ret == 3); // LOG_INFO(row << " " << col << " " << val); this->mat_.row[ii] = row; this->mat_.col[ii] = col; this->mat_.val[ii] = val; if (sym && (row!=col)) { ++ii; this->mat_.row[ii] = col; this->mat_.col[ii] = row; this->mat_.val[ii] = val; } ++ii; } LOG_INFO("ReadFileMTX: filename="<< filename << "; done"); fclose(f); }
static PetscErrorCode loadmtx(const char* filename, Mat *M, PetscBool *pattern) { PetscErrorCode ierr; FILE *f; MM_typecode type; int m,n,nz,i,j,k; PetscInt low,high,lowj,highj,*d_nz,*o_nz; double re,im; PetscScalar s; long pos; PetscFunctionBegin; f = fopen(filename,"r"); if (!f) SETERRQ2(PETSC_COMM_SELF,1,"fopen '%s': %s",filename,strerror(errno)); /* first read to set matrix kind and size */ ierr = mm_read_banner(f,&type);CHKERRQ(ierr); if (!mm_is_valid(type) || !mm_is_sparse(type) || !(mm_is_real(type) || mm_is_complex(type) || mm_is_pattern(type) || mm_is_integer(type))) SETERRQ1(PETSC_COMM_SELF,1,"Matrix format '%s' not supported",mm_typecode_to_str(type)); #if !defined(PETSC_USE_COMPLEX) if (mm_is_complex(type)) SETERRQ(PETSC_COMM_SELF,1,"Complex matrix not supported in real configuration"); #endif if (pattern) *pattern = mm_is_pattern(type) ? PETSC_TRUE : PETSC_FALSE; ierr = mm_read_mtx_crd_size(f,&m,&n,&nz);CHKERRQ(ierr); pos = ftell(f); ierr = MatCreate(PETSC_COMM_WORLD,M);CHKERRQ(ierr); ierr = MatSetSizes(*M,PETSC_DECIDE,PETSC_DECIDE,(PetscInt)m,(PetscInt)n);CHKERRQ(ierr); ierr = MatSetFromOptions(*M);CHKERRQ(ierr); ierr = MatSetUp(*M);CHKERRQ(ierr); ierr = MatGetOwnershipRange(*M,&low,&high);CHKERRQ(ierr); ierr = MatGetOwnershipRangeColumn(*M,&lowj,&highj);CHKERRQ(ierr); ierr = PetscMalloc(sizeof(PetscInt)*(high-low),&d_nz);CHKERRQ(ierr); ierr = PetscMalloc(sizeof(PetscInt)*(high-low),&o_nz);CHKERRQ(ierr); for (i=0; i<high-low;i++) { d_nz[i] = (i+low>=lowj && i+low<highj) ? 1 : 0; o_nz[i] = (i+low>=lowj && i+low<highj) ? 0 : 1; } for (k=0;k<nz;k++) { ierr = mm_read_mtx_crd_entry(f,&i,&j,&re,&im,type);CHKERRQ(ierr); i--; j--; if (i!=j) { if (i>=low && i<high) { if (j>=lowj && j<highj) d_nz[i-low]++; else o_nz[i-low]++; } if (j>=low && j<high && !mm_is_general(type)) { if (i>=low && i<high) d_nz[j-low]++; else o_nz[j-low]++; } } } ierr = preallocation(*M,d_nz,o_nz);CHKERRQ(ierr); ierr = PetscFree(d_nz);CHKERRQ(ierr); ierr = PetscFree(o_nz);CHKERRQ(ierr); /* second read to load the values */ ierr = fseek(f, pos, SEEK_SET); if (ierr) SETERRQ1(PETSC_COMM_SELF,1,"fseek: %s",strerror(errno)); re = 1.0; im = 0.0; /* Set the diagonal to zero */ for (i=low; i<PetscMin(high,n); i++) { ierr = MatSetValue(*M,i,i,0.0,INSERT_VALUES);CHKERRQ(ierr); } for (k=0;k<nz;k++) { ierr = mm_read_mtx_crd_entry(f,&i,&j,&re,&im,type); i--; j--; if (i>=low && i<high) { s = re + IMAGINARY * im; ierr = MatSetValue(*M,i,j,s,INSERT_VALUES);CHKERRQ(ierr); } if (j>=low && j<high && i != j && !mm_is_general(type)) { if (mm_is_symmetric(type)) s = re + IMAGINARY * im; else if (mm_is_hermitian(type)) s = re - IMAGINARY * im; else if (mm_is_skew(type)) s = -re - IMAGINARY * im; else { SETERRQ1(PETSC_COMM_SELF,1,"Matrix format '%s' not supported",mm_typecode_to_str(type)); } ierr = MatSetValue(*M,j,i,s,INSERT_VALUES);CHKERRQ(ierr); } } ierr = MatAssemblyBegin(*M,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr); ierr = MatAssemblyEnd(*M,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr); if (mm_is_symmetric(type)) { ierr = MatSetOption(*M,MAT_SYMMETRIC,PETSC_TRUE);CHKERRQ(ierr); } if ((mm_is_symmetric(type) && mm_is_real(type)) || mm_is_hermitian(type)) { ierr = MatSetOption(*M,MAT_HERMITIAN,PETSC_TRUE);CHKERRQ(ierr); } ierr = fclose(f); if (ierr) SETERRQ1(PETSC_COMM_SELF,1,"fclose: %s",strerror(errno)); PetscFunctionReturn(0); }