Ejemplo n.º 1
0
char  *mm_typecode_to_str(MM_typecode matcode)
{
    char buffer[MM_MAX_LINE_LENGTH];
    char *types[4];
    int error =0;
    int i;

    /* check for MTX type */
    if (mm_is_matrix(matcode))
        types[0] = MM_MTX_STR;
    else
        error=1;

    /* check for CRD or ARR matrix */
    if (mm_is_sparserow(matcode))
        types[1] = MM_SPARSEROW_STR;
    else
    if (mm_is_coordinate(matcode))
        types[1] = MM_COORDINATE_STR;
    else
    if (mm_is_dense(matcode))
        types[1] = MM_DENSE_STR;
    else
        return NULL;

    /* check for element data type */
    if (mm_is_real(matcode))
        types[2] = MM_REAL_STR;
    else
    if (mm_is_complex(matcode))
        types[2] = MM_COMPLEX_STR;
    else
    if (mm_is_pattern(matcode))
        types[2] = MM_PATTERN_STR;
    else
    if (mm_is_integer(matcode))
        types[2] = MM_INT_STR;
    else
        return NULL;


    /* check for symmetry type */
    if (mm_is_general(matcode))
        types[3] = MM_GENERAL_STR;
    else
    if (mm_is_symmetric(matcode))
        types[3] = MM_SYMM_STR;
    else
    if (mm_is_hermitian(matcode))
        types[3] = MM_HERM_STR;
    else
    if (mm_is_skew(matcode))
        types[3] = MM_SKEW_STR;
    else
        return NULL;

    sprintf(buffer,"%s %s %s %s", types[0], types[1], types[2], types[3]);
    return strdup(buffer);

}
Ejemplo n.º 2
0
/* READ_MTX - read symmetric sparse matrix in MatrixMarket format
 */
void read_MTX_SSS(char *fname, int *n,
                  double **va, double **da, int **ja, int **ia) {
  int m, nz, ret_code, i;
  double *v_coo;
  int *i_coo, *j_coo;
  MM_typecode matcode;
  FILE *f;

  f = fopen(fname, "r");
  assert(f != NULL);
  ret_code = mm_read_banner(f, &matcode);
  assert(ret_code == 0);
  assert(mm_is_real(matcode) && mm_is_matrix(matcode) &&
         mm_is_sparse(matcode) && mm_is_symmetric(matcode));
  ret_code = mm_read_mtx_crd_size(f, &m, n, &nz);
  assert(ret_code == 0);
  assert(m == *n);
  /* read COO format */
  i_coo = (int *)malloc(nz * sizeof(int));
  j_coo = (int *)malloc(nz * sizeof(int));
  v_coo = (double *)malloc(nz * sizeof(double));
  assert(i_coo && j_coo && v_coo);
  for (i = 0; i < nz; i ++) {
    fscanf(f, "%d %d %lg\n", &i_coo[i], &j_coo[i], &v_coo[i]);
    i_coo[i]--;  /* adjust from 1-based to 0-based */
    j_coo[i]--;
  }
  fclose(f);
  /* convert to SSS format */
  convert_COO_SSS(*n, nz, i_coo, j_coo, v_coo, ia, ja, va, da);
  free(i_coo); free(j_coo); free(v_coo);
}
Ejemplo n.º 3
0
int mm_is_valid ( MM_typecode matcode )
/******************************************************************************/
/*
  Purpose:
    MM_IS_VALID checks whether the MM header information is valid.
  Modified:
    31 October 2008
  Parameters:
    Input, MM_typecode MATCODE, the header information.
    Output, int MM_IS_VALID, is TRUE if the matrix code is valid.
*/
{
  if ( !mm_is_matrix ( matcode ) ) 
  {
    return 0;
  }
  if ( mm_is_dense ( matcode ) && mm_is_pattern ( matcode ) ) 
  {
    return 0;
  }
  if ( mm_is_real ( matcode ) && mm_is_hermitian ( matcode ) ) 
  {
    return 0;
  }
  if ( mm_is_pattern ( matcode ) && 
      ( mm_is_hermitian ( matcode ) || mm_is_skew ( matcode ) ) ) 
  {
    return 0;
  }
  return 1;
}
Ejemplo n.º 4
0
int mm_read_mtx_crd(char *fname, int *M, int *N, int *nz, int **I, int **J,
        double **val, MM_typecode *matcode)
{
    int ret_code;
    FILE *f;

    if (strcmp(fname, "stdin") == 0) f=stdin;
    else
    if ((f = fopen(fname, "r")) == NULL)
        return MM_COULD_NOT_READ_FILE;


    if ((ret_code = mm_read_banner(f, matcode)) != 0)
        return ret_code;

    if (!(mm_is_valid(*matcode) && mm_is_sparse(*matcode) &&
            mm_is_matrix(*matcode)))
        return MM_UNSUPPORTED_TYPE;

    if ((ret_code = mm_read_mtx_crd_size(f, M, N, nz)) != 0)
        return ret_code;


    //*I = (int *)  malloc(*nz * sizeof(int));
    //*J = (int *)  malloc(*nz * sizeof(int));
    //*val = NULL;

    *I = new int[*nz];
    *J = new int[*nz];
    *val = 0;

    if (mm_is_complex(*matcode))
    {
        //*val = (double *) malloc(*nz * 2 * sizeof(double));
        *val = new double[2*(*nz)];
        ret_code = mm_read_mtx_crd_data(f, *M, *N, *nz, *I, *J, *val,
                *matcode);
        if (ret_code != 0) return ret_code;
    }
    else if (mm_is_real(*matcode))
    {
        //*val = (double *) malloc(*nz * sizeof(double));
        *val = new double[*nz];
        ret_code = mm_read_mtx_crd_data(f, *M, *N, *nz, *I, *J, *val,
                *matcode);
        if (ret_code != 0) return ret_code;
    }

    else if (mm_is_pattern(*matcode))
    {
        ret_code = mm_read_mtx_crd_data(f, *M, *N, *nz, *I, *J, *val,
                *matcode);
        if (ret_code != 0) return ret_code;
    }

    if (f != stdin) fclose(f);
    return 0;
}
Ejemplo n.º 5
0
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);

}
Ejemplo n.º 6
0
int mm_is_valid(MM_typecode matcode)
{
    if (!mm_is_matrix(matcode)) return 0;
    if (mm_is_dense(matcode) && mm_is_pattern(matcode)) return 0;
    if (mm_is_real(matcode) && mm_is_hermitian(matcode)) return 0;
    if (mm_is_pattern(matcode) && (mm_is_hermitian(matcode) || 
                mm_is_skew(matcode))) return 0;
    return 1;
}
Ejemplo n.º 7
0
 void mm_typecode_to_str(MM_typecode matcode, char * buffer)
{
    char type0[20];
    char type1[20];
    char type2[20];
    char type3[20];
    int error =0;

    /* check for MTX type */
    if (mm_is_matrix(matcode))
        strcpy(type0, MM_MTX_STR);
    else
        error=1;

    /* check for CRD or ARR matrix */
    if (mm_is_sparse(matcode))
        strcpy(type1, MM_SPARSE_STR);
    else
    if (mm_is_dense(matcode))
        strcpy(type1, MM_DENSE_STR);
    else
        return;

    /* check for element data type */
    if (mm_is_real(matcode))
        strcpy(type2, MM_REAL_STR);
    else
    if (mm_is_complex(matcode))
        strcpy(type2, MM_COMPLEX_STR);
    else
    if (mm_is_pattern(matcode))
        strcpy(type2, MM_PATTERN_STR);
    else
    if (mm_is_integer(matcode))
        strcpy(type2, MM_INT_STR);
    else
        return;

    /* check for symmetry type */
    if (mm_is_general(matcode))
        strcpy(type3, MM_GENERAL_STR);
    else
    if (mm_is_symmetric(matcode))
        strcpy(type3, MM_SYMM_STR);
    else
    if (mm_is_hermitian(matcode))
        strcpy(type3, MM_HERM_STR);
    else
    if (mm_is_skew(matcode))
        strcpy(type3, MM_SKEW_STR);
    else
        return;

    sprintf(buffer,"%s %s %s %s", type0, type1, type2, type3);
    return;
}
Ejemplo n.º 8
0
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;
}
Ejemplo n.º 9
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);
  }
}
Ejemplo n.º 10
0
int mm_read_mtx_crd(char *fname, int *M, int *N, int *nz, int **I, int **J,
	double **val, MM_typecode *matcode)
{
    int ret_code;
    ZOLTAN_FILE* f;

    if ((f = ZOLTAN_FILE_open(fname, "r", STANDARD)) == NULL)
      return MM_COULD_NOT_READ_FILE;


    if ((ret_code = mm_read_banner(f, matcode)) != 0)
	return ret_code;

    if (!(mm_is_valid(*matcode) && mm_is_sparse(*matcode) &&
	    mm_is_matrix(*matcode)))
	return MM_UNSUPPORTED_TYPE;

    if ((ret_code = mm_read_mtx_crd_size(f, M, N, nz)) != 0)
	return ret_code;


    *I = (int *)  malloc(*nz * sizeof(int));
    *J = (int *)  malloc(*nz * sizeof(int));
    *val = NULL;

    if (mm_is_complex(*matcode))
    {
	*val = (double *) malloc(*nz * 2 * sizeof(double));
	ret_code = mm_read_mtx_crd_data(f, *M, *N, *nz, *I, *J, *val,
		*matcode);
	if (ret_code != 0) return ret_code;
    }
    else if (mm_is_real(*matcode))
    {
	*val = (double *) malloc(*nz * sizeof(double));
	ret_code = mm_read_mtx_crd_data(f, *M, *N, *nz, *I, *J, *val,
		*matcode);
	if (ret_code != 0) return ret_code;
    }

    else if (mm_is_pattern(*matcode))
    {
	ret_code = mm_read_mtx_crd_data(f, *M, *N, *nz, *I, *J, *val,
		*matcode);
	if (ret_code != 0) return ret_code;
    }

    ZOLTAN_FILE_close(f);
    return 0;
}
Ejemplo n.º 11
0
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;
}
Ejemplo n.º 12
0
bool loadMmProperties(int *rowsCount,
	int *columnsCount,
	int *nonZerosCount,
	bool *isStoredSparse,
	int* matrixStorage,
	int* matrixType,
	FILE *file)
{
	MM_typecode matcode;

	// supports only valid matrices
	if ((mm_read_banner(file, &matcode) != 0) 
		|| (!mm_is_matrix(matcode))
		|| (!mm_is_valid(matcode))) 
		return false;

	if ( mm_read_mtx_crd_size(file, rowsCount, columnsCount, nonZerosCount) != 0 ) 
		return false;

	// is it stored sparse?
	if (mm_is_sparse(matcode))
		*isStoredSparse = true;
	else
		*isStoredSparse = false;

	if (mm_is_integer(matcode))
		*matrixStorage = MATRIX_STORAGE_INTEGER;
	else if (mm_is_real(matcode))
		*matrixStorage = MATRIX_STORAGE_REAL;
	else if (mm_is_complex(matcode))
		*matrixStorage = MATRIX_STORAGE_COMPLEX;
	else if (mm_is_pattern(matcode))
		*matrixStorage = MATRIX_STORAGE_PATTERN;
	
	if (mm_is_general(matcode))
		*matrixType = MATRIX_TYPE_GENERAL;
	else if (mm_is_symmetric(matcode))
		*matrixType = MATRIX_TYPE_SYMMETRIC;
	else if (mm_is_skew(matcode))
		*matrixType = MATRIX_TYPE_SKEW;
	else if (mm_is_hermitian(matcode))
		*matrixType = MATRIX_TYPE_HERMITIAN;

	return true;
}
Ejemplo n.º 13
0
int DenseMatrix_mm_read_strassen(DenseMatrix *m, char *file_name, int *nr_rows, int *nr_cols) {
	int res;
	MM_typecode matcode;
	FILE *file;

	file = fopen(file_name, "r");
	CHECK_NULL_RETURN(file);

	res = mm_read_banner(file, &matcode);
	CHECK_ZERO_ERROR_RETURN(res, "Failed to read matrix code");

	CHECK_ERROR_RETURN(!mm_is_matrix(matcode), "File is not a matrix", 1);

	if (mm_is_sparse(matcode)) {
		int nr_sparse_elements;

		res = mm_read_mtx_crd_size(file, nr_rows, nr_cols, &nr_sparse_elements);
		CHECK_ZERO_ERROR_RETURN(res, "Failed to read sparse mm dimensions");

		int dim = pow2dim(*nr_rows, *nr_cols);

		// Initialzie matrix to zero to fill in with sparse elements
		res = DenseMatrix_init_zero(m, dim, dim);
		CHECK_ZERO_ERROR_RETURN(res, "Failed to allocate memory for mm matrix");

		res = DenseMatrix_parse_mm_sparse(m, file, nr_sparse_elements);
	} else if (mm_is_dense(matcode)) {
		res = mm_read_mtx_array_size(file, nr_rows, nr_cols);
		CHECK_ZERO_ERROR_RETURN(res, "Failed to read dense mm dimensions");

		int dim = pow2dim(*nr_rows, *nr_cols);

		res = DenseMatrix_init_zero(m, dim, dim);
		CHECK_ZERO_ERROR_RETURN(res, "Failed to allocate memory for mm matrix");

		res = DenseMatrix_parse_mm_dense(m, file);
	} else {
		ERROR("mm matrix code is not supported. Only supports dense and sparse matrices");
	}
	CHECK_ZERO_ERROR_RETURN(res, "Failed to parse mm file");

	return 0;
}
int MatrixMarketFileToRowMap(const char* filename,
                             const Epetra_Comm& comm,
                             Epetra_BlockMap*& rowmap)
{
  FILE* infile = fopen(filename, "r");
  MM_typecode matcode;

  int err = mm_read_banner(infile, &matcode);
  if (err != 0) return(err);

  if (!mm_is_matrix(matcode) || !mm_is_coordinate(matcode) ||
      !mm_is_real(matcode)   || !mm_is_general(matcode)) {
    return(-1);
  }

  int numrows, numcols;
  err = mm_read_mtx_array_size(infile, &numrows, &numcols);
  if (err != 0) return(err);

  fclose(infile);

  rowmap = new Epetra_BlockMap(numrows, 1, 0, comm);
  return(0);
}
Ejemplo n.º 15
0
  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);
  }
Ejemplo n.º 16
0
int mm_read_mtx_crd(char *fname, int *M, int *N, int *nz, int **I, int **J, 
        double **val, MM_typecode *matcode)

/******************************************************************************/
/*
  Purpose:

    MM_READ_MTX_CRD reads the values in an MM coordinate file.

  Discussion:

    This function allocates the storage for the arrays.

  Modified:

    31 October 2008

  Parameters:

*/
/*
    mm_read_mtx_crd()  fills M, N, nz, array of values, and return
                        type code, e.g. 'MCRS'

                        if matrix is complex, values[] is of size 2*nz,
                            (nz pairs of real/imaginary values)
*/
{
    int ret_code;
    FILE *f;

    if (strcmp(fname, "stdin") == 0) f=stdin;
    else
    if ((f = fopen(fname, "r")) == NULL)
        return MM_COULD_NOT_READ_FILE;


    if ((ret_code = mm_read_banner(f, matcode)) != 0)
        return ret_code;

    if (!(mm_is_valid(*matcode) && mm_is_sparse(*matcode) && 
            mm_is_matrix(*matcode)))
        return MM_UNSUPPORTED_TYPE;

    if ((ret_code = mm_read_mtx_crd_size(f, M, N, nz)) != 0)
        return ret_code;


    *I = (int *)  malloc(*nz * sizeof(int));
    *J = (int *)  malloc(*nz * sizeof(int));
    *val = NULL;

    if (mm_is_complex(*matcode))
    {
        *val = (double *) malloc(*nz * 2 * sizeof(double));
        ret_code = mm_read_mtx_crd_data(f, *M, *N, *nz, *I, *J, *val, 
                *matcode);
        if (ret_code != 0) return ret_code;
    }
    else if (mm_is_real(*matcode))
    {
        *val = (double *) malloc(*nz * sizeof(double));
        ret_code = mm_read_mtx_crd_data(f, *M, *N, *nz, *I, *J, *val, 
                *matcode);
        if (ret_code != 0) return ret_code;
    }

    else if (mm_is_pattern(*matcode))
    {
        ret_code = mm_read_mtx_crd_data(f, *M, *N, *nz, *I, *J, *val, 
                *matcode);
        if (ret_code != 0) return ret_code;
    }

    if (f != stdin) fclose(f);
    return 0;
}
Ejemplo n.º 17
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;
}
Ejemplo n.º 18
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;
}
Ejemplo n.º 19
0
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;
}
Ejemplo n.º 20
0
cs *read_matrix(const char *filename, MM_typecode &matcode)
{
    LogInfo("Reading Matrix from " << std::string(filename) << "\n");
    FILE *file = fopen(filename, "r");
    if (!file)
    {
        LogError("Error: Cannot read file " << std::string(filename) << "\n");
        return NULL;
    }

    LogInfo("Reading Matrix Market banner...");
    if (mm_read_banner(file, &matcode) != 0)
    {
        LogError("Error: Could not process Matrix Market banner\n");
        fclose(file);
        return NULL;
    }
    if (!mm_is_matrix(matcode) || !mm_is_sparse(matcode)
        || mm_is_complex(matcode))
    {
        LogError(
            "Error: Unsupported matrix format - Must be real and sparse\n");
        fclose(file);
        return NULL;
    }

    Int M, N, nz;
    if ((mm_read_mtx_crd_size(file, &M, &N, &nz)) != 0)
    {
        LogError("Error: Could not parse matrix dimension and size.\n");
        fclose(file);
        return NULL;
    }
    if (M != N)
    {
        LogError("Error: Matrix must be square.\n");
        fclose(file);
        return NULL;
    }

    LogInfo("Reading matrix data...\n");
    Int *I = (Int *)SuiteSparse_malloc(static_cast<size_t>(nz), sizeof(Int));
    Int *J = (Int *)SuiteSparse_malloc(static_cast<size_t>(nz), sizeof(Int));
    double *val
        = (double *)SuiteSparse_malloc(static_cast<size_t>(nz), sizeof(double));

    if (!I || !J || !val)
    {
        LogError("Error: Ran out of memory in Mongoose::read_matrix\n");
        SuiteSparse_free(I);
        SuiteSparse_free(J);
        SuiteSparse_free(val);
        fclose(file);
        return NULL;
    }

    mm_read_mtx_crd_data(file, M, N, nz, I, J, val, matcode);
    fclose(file); // Close the file

    for (Int k = 0; k < nz; k++)
    {
        --I[k];
        --J[k];
        if (mm_is_pattern(matcode))
            val[k] = 1;
    }

    cs *A = (cs *)SuiteSparse_malloc(1, sizeof(cs));
    if (!A)
    {
        LogError("Error: Ran out of memory in Mongoose::read_matrix\n");
        SuiteSparse_free(I);
        SuiteSparse_free(J);
        SuiteSparse_free(val);
        return NULL;
    }

    A->nzmax = nz;
    A->m     = M;
    A->n     = N;
    A->p     = J;
    A->i     = I;
    A->x     = val;
    A->nz    = nz;

    LogInfo("Compressing matrix from triplet to CSC format...\n");
    cs *compressed_A = cs_compress(A);
    cs_spfree(A);
    if (!compressed_A)
    {
        LogError("Error: Ran out of memory in Mongoose::read_matrix\n");
        return NULL;
    }

    return compressed_A;
}
Ejemplo n.º 21
0
char  *mm_typecode_to_str(MM_typecode matcode)
{
    char buffer[MM_MAX_LINE_LENGTH];
    const char *types[4];
	char *mm_strdup(const char *);
    int error =0;

    /* check for MTX type */
    if (mm_is_matrix(matcode)) 
        types[0] = MM_MTX_STR;
    else {
        types[0] = NULL;
        error=1;
    }

    /* check for CRD or ARR matrix */
    if (mm_is_sparse(matcode))
        types[1] = MM_SPARSE_STR;
    else
    if (mm_is_dense(matcode))
        types[1] = MM_DENSE_STR;
    else
        return NULL;

    /* check for element data type */
    if (mm_is_real(matcode))
        types[2] = MM_REAL_STR;
    else
    if (mm_is_complex(matcode))
        types[2] = MM_COMPLEX_STR;
    else
    if (mm_is_pattern(matcode))
        types[2] = MM_PATTERN_STR;
    else
    if (mm_is_integer(matcode))
        types[2] = MM_INT_STR;
    else
        return NULL;


    /* check for symmetry type */
    if (mm_is_general(matcode))
        types[3] = MM_GENERAL_STR;
    else
    if (mm_is_symmetric(matcode))
        types[3] = MM_SYMM_STR;
    else 
    if (mm_is_hermitian(matcode))
        types[3] = MM_HERM_STR;
    else 
    if (mm_is_skew(matcode))
        types[3] = MM_SKEW_STR;
    else
        return NULL;

    if( error == 1 )
        sprintf(buffer,"Object to write is not a matrix; this is unsupported by the current mmio code.");
    else
        sprintf(buffer,"%s %s %s %s", types[0], types[1], types[2], types[3]);
    return mm_strdup(buffer);

}
int MatrixMarketFileToBlockMaps(const char* filename,
                                const Epetra_Comm& comm,
                                Epetra_BlockMap*& rowmap,
                                Epetra_BlockMap*& colmap,
                                Epetra_BlockMap*& rangemap,
                                Epetra_BlockMap*& domainmap)
{
  FILE* infile = fopen(filename, "r");
  if (infile == NULL) {
    return(-1);
  }

  MM_typecode matcode;

  int err = mm_read_banner(infile, &matcode);
  if (err != 0) return(err);

  if (!mm_is_matrix(matcode) || !mm_is_coordinate(matcode) ||
      !mm_is_real(matcode)   || !mm_is_general(matcode)) {
    return(-1);
  }

  int numrows, numcols, nnz;
  err = mm_read_mtx_crd_size(infile, &numrows, &numcols, &nnz);
  if (err != 0) return(err);

  //for this case, we'll assume that the row-map is the same as
  //the range-map.
  //create row-map and range-map with linear distributions.

  rowmap = new Epetra_BlockMap(numrows, 1, 0, comm);
  rangemap = new Epetra_BlockMap(numrows, 1, 0, comm);

  int I, J;
  double val, imag;

  int num_map_cols = 0, insertPoint, foundOffset;
  int allocLen = numcols;
  int* map_cols = new int[allocLen];

  //read through all matrix data and construct a list of the column-
  //indices that occur in rows that are local to this processor.
 
  for(int i=0; i<nnz; ++i) {
    err = mm_read_mtx_crd_entry(infile, &I, &J, &val,
                                &imag, matcode);

    if (err == 0) {
      --I;
      --J;
      if (rowmap->MyGID(I)) {
        foundOffset = Epetra_Util_binary_search(J, map_cols, num_map_cols,
                                                insertPoint);
        if (foundOffset < 0) {
          Epetra_Util_insert(J, insertPoint, map_cols,
                             num_map_cols, allocLen);
        }
      }
    } 
  }

  //create colmap with the list of columns associated with rows that are
  //local to this processor.
  colmap = new Epetra_Map(-1, num_map_cols, map_cols, 0, comm);

  //create domainmap which has a linear distribution
  domainmap = new Epetra_BlockMap(numcols, 1, 0, comm);

  delete [] map_cols;

  return(0);
}
Ejemplo n.º 23
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;
}
Ejemplo n.º 24
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;
}
Ejemplo n.º 25
0
char *mm_typecode_to_str ( MM_typecode matcode )
/******************************************************************************/
/*
  Purpose:
    MM_TYPECODE_TO_STR converts the internal typecode to an MM header string.
  Modified:
    31 October 2008
*/
{
    char buffer[MM_MAX_LINE_LENGTH];
    char *types[4];
	char *mm_strdup(const char *);
	//int error =0;
/* 
  check for MTX type 
*/
    if (mm_is_matrix(matcode)) 
      types[0] = MM_MTX_STR;
    //    else
    //    error=1;
/* 
  check for CRD or ARR matrix 
*/
    if (mm_is_sparse(matcode))
        types[1] = MM_SPARSE_STR;
    else
    if (mm_is_dense(matcode))
        types[1] = MM_DENSE_STR;
    else
        return NULL;
/* 
  check for element data type 
*/
    if (mm_is_real(matcode))
        types[2] = MM_REAL_STR;
    else
    if (mm_is_complex(matcode))
        types[2] = MM_COMPLEX_STR;
    else
    if (mm_is_pattern(matcode))
        types[2] = MM_PATTERN_STR;
    else
    if (mm_is_integer(matcode))
        types[2] = MM_INT_STR;
    else
        return NULL;
/* 
  check for symmetry type 
*/
    if (mm_is_general(matcode))
        types[3] = MM_GENERAL_STR;
    else
    if (mm_is_symmetric(matcode))
        types[3] = MM_SYMM_STR;
    else 
    if (mm_is_hermitian(matcode))
        types[3] = MM_HERM_STR;
    else 
    if (mm_is_skew(matcode))
        types[3] = MM_SKEW_STR;
    else
        return NULL;
    sprintf(buffer,"%s %s %s %s", types[0], types[1], types[2], types[3]);
    return mm_strdup(buffer);
}
Ejemplo n.º 26
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);
}  
Ejemplo n.º 27
0
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);

}
Ejemplo n.º 28
0
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;
}