Exemplo n.º 1
0
void save_matrix_market_format_vector(const std::string datafile, const vec & output, bool issparse, std::string comment)
{
  MM_typecode matcode;
  mm_initialize_typecode(&matcode);
  mm_set_matrix(&matcode);
  mm_set_coordinate(&matcode);

  if (issparse)
    mm_set_sparse(&matcode);
  else mm_set_dense(&matcode);

  set_typecode<vec>(matcode);

  FILE * f = fopen(datafile.c_str(),"w");
  if (f == NULL)
    logstream(LOG_FATAL)<<"Failed to open file: " << datafile << " for writing. " << std::endl;

  mm_write_banner(f, matcode);
  if (comment.size() > 0) // add a comment to the matrix market header
    fprintf(f, "%c%s\n", '%', comment.c_str());
  if (issparse)
    mm_write_mtx_crd_size(f, output.size(), 1, output.size());
  else
    mm_write_mtx_array_size(f, output.size(), 1);

  for (int j=0; j<(int)output.size(); j++){
    write_row(j+1, 1, output[j], f, issparse);
    if (!issparse) 
      fprintf(f, "\n");
  }

  fclose(f);
}
Exemplo n.º 2
0
  MMOutputter_mat(std::string fname, uint start, uint end, std::string comment, std::vector<vertex_data> & latent_factors_inmem, int size = 0)  {
    assert(start < end);
    MM_typecode matcode;
    set_matcode(matcode, R_output_format);
    FILE * outf = open_file(fname.c_str(), "w");
    mm_write_banner(outf, matcode);
    if (comment != "")
      fprintf(outf, "%%%s\n", comment.c_str());
    int actual_Size = size > 0 ? size : latent_factors_inmem[start].pvec.size();

    if (R_output_format)
      mm_write_mtx_crd_size(outf, end-start, actual_Size, (end-start)*actual_Size);
    else
      mm_write_mtx_array_size(outf, end-start, actual_Size);

    for (uint i=start; i < end; i++){
      for(int j=0; j < actual_Size; j++) {
        if (R_output_format)
          fprintf(outf, "%d %d %12.8g\n", i-start+input_file_offset, j+input_file_offset, latent_factors_inmem[i].get_val(j));
        else {
          fprintf(outf, "%1.12e ", latent_factors_inmem[i].get_val(j));
          if (j == actual_Size -1)
	    fprintf(outf, "\n");
        }
      }
      }
    fclose(outf);
  }
int CreateDenseMatrixGeneral(char *fileName, unsigned long int numRows, unsigned long int numCols, unsigned int seed, double min, double max) {
//Options: numRows numCols fileName seed

	FILE *output;
	//long nz;   
	unsigned long int i, j;
	MM_typecode outputmatcode;
	
	mm_initialize_typecode(&outputmatcode);
	mm_set_matrix(&outputmatcode);
	mm_set_coordinate(&outputmatcode);
	//mm_set_dense(&outputmatcode);
	mm_set_real(&outputmatcode);
	mm_set_general(&outputmatcode);
	
	if(strcmp(fileName,"stdout")==0){
		output = stdout;
	}
	else{
		if ((output = fopen(fileName, "w")) == NULL){
			fprintf(stderr,"[%s] Unable to open file for writing\n",__func__);
			return 0;
		}
	}
			
	
	double value = 0.0;
	
	srand (seed);

	mm_write_banner(output, outputmatcode);
	mm_write_mtx_crd_size(output, numRows, numCols, numRows*numCols);
	//ret_code = fprintf(output,"\%\%MatrixMarket matrix coordinate real symmetric\n");
	
	//unsigned long long int val1 = 0;
	//unsigned long long int val2 = 0;
	

	
	for(i = 0;i < numRows; i++){
	
		for(j = 0; j< numCols; j++){

            value = randfrom(min, max);
			fprintf(output, "%lu %lu %lg\n",i+1,j+1,value);

		}

	}
	

	fclose(output);

	return 1;
}
Exemplo n.º 4
0
void test_predictions3(float (*prediction_func)(const vertex_data & user, const vertex_data & movie, const vertex_data & time, float rating, double & prediction)) {
  int ret_code;
  MM_typecode matcode;
  FILE *f;
  uint Me, Ne;
  size_t nz;   

  if ((f = fopen(test.c_str(), "r")) == NULL) {
    return; //missing validaiton data, nothing to compute
  }
  FILE * fout = fopen((test + ".predict").c_str(),"w");
  if (fout == NULL)
    logstream(LOG_FATAL)<<"Failed to open test prediction file for writing"<<std::endl;

  if (mm_read_banner(f, &matcode) != 0)
    logstream(LOG_FATAL) << "Could not process Matrix Market banner. File: " << test << 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_sparse(matcode))
    logstream(LOG_FATAL) << "Sorry, this application does not support complex values and requires a sparse matrix." << std::endl;

  /* find out size of sparse matrix .... */
  if ((ret_code = mm_read_mtx_crd_size(f, &Me, &Ne, &nz)) !=0) {
    logstream(LOG_FATAL) << "Failed reading matrix size: error=" << ret_code << std::endl;
  }

  if ((M > 0 && N > 0 ) && (Me != M || Ne != N))
    logstream(LOG_FATAL)<<"Input size of test matrix must be identical to training matrix, namely " << M << "x" << N << std::endl;

  mm_write_banner(fout, matcode);
  mm_write_mtx_crd_size(fout ,M,N,nz); 

  for (uint i=0; i<nz; i++)
  {
    int I, J;
    double val;
    int time;
    int rc = fscanf(f, "%d %d %d %lg\n", &I, &J, &time, &val);
    if (rc != 4)
      logstream(LOG_FATAL)<<"Error when reading input file: " << i << std::endl;
    I--;  /* adjust from 1-based to 0-based */
    J--;
    double prediction;
    (*prediction_func)(latent_factors_inmem[I], latent_factors_inmem[J+M], latent_factors_inmem[time+M+N], 1, prediction);
    fprintf(fout, "%d %d %12.8lg\n", I+1, J+1, prediction);
  }
  fclose(f);
  fclose(fout);

  logstream(LOG_INFO)<<"Finished writing " << nz << " predictions to file: " << test << ".predict" << std::endl;
}
int CreateDenseMatrixGeneral(int argc, char *argv[]) {

	FILE *output;
	unsigned long int numRows, numCols, seed, i, j;
	char * outputpath;
	double value;
	MM_typecode outputmatcode;

	int verbose;
	struct st_option options[] = {
		FLAG_BOOL('v', "verbose", "Show more info when executing", &verbose, NULL),
		PARAM_INT("rows", "Number of rows of the matrix", &numRows, NULL),
		PARAM_INT("cols", "Number of columns of the matrix", &numCols, NULL),
		PARAM_STRING("outputfilename", "Filename to write the matrix into", &outputpath, NULL),
		PARAM_INT("seed", "Seed of the random number generator", &seed, "0"),
		OPTIONS_END,
	};

	if (options_parse(options, argc, argv)) {
		options_usage(options, "./MM-Suite CreateDenseMatrixGeneral");
		puts(option_err_msg);
		return 0;
	};

	if ((output = fopen(outputpath, "w")) == NULL){
		return 0;
	}


	mm_initialize_typecode(&outputmatcode);
	mm_set_matrix(&outputmatcode);
	mm_set_coordinate(&outputmatcode);
	mm_set_real(&outputmatcode);
	mm_set_general(&outputmatcode);

	srand(seed);

	mm_write_banner(output, outputmatcode);
	mm_write_mtx_crd_size(output, numRows, numCols, numRows*numCols);
	
	for (i = 0; i < numRows; i++) {
		for (j = 0; j < numCols; j++) {
			value = ((double) rand() / (double) RAND_MAX) / 100;
			fprintf(output, "%lu %lu %lg\n", i + 1, j + 1, value);
		}
	}
	
	fclose(output);

	return 1;
};
Exemplo n.º 6
0
/* fwrite sparse */
static void
mm_real_fwrite_sparse (FILE *stream, const mm_sparse *s, const char *format)
{
	int		j;
	mm_write_banner (stream, s->typecode);
	mm_write_mtx_crd_size (stream, s->m, s->n, s->nnz);
	for (j = 0; j < s->n; j++) {
		int		k = s->p[j];
		int		pend = s->p[j + 1];
		for (; k < pend; k++) {
			fprintf (stream, "%d %d ", s->i[k] + 1, j + 1);	// c -> fortran
			fprintf (stream, format, s->data[k]);
			fprintf (stream, "\n");
		}
	}
	return;
}
Exemplo n.º 7
0
 MMOutputter_vec(std::string fname, uint start, uint end, int index, std::string comment, std::vector<vertex_data> & latent_factors_inmem)  {
   MM_typecode matcode;
   set_matcode(matcode, R_output_format);
   FILE * outf = open_file(fname.c_str(), "w");
   mm_write_banner(outf, matcode);
   if (comment != "")
     fprintf(outf, "%%%s\n", comment.c_str());
   if (R_output_format)
     mm_write_mtx_crd_size(outf, end-start, 1, end-start);
   else
     mm_write_mtx_array_size(outf, end-start, 1);
   for (uint i=start; i< end; i++)
     if (R_output_format)
        fprintf(outf, "%d %d %12.8g\n", i-start+input_file_offset, 1, latent_factors_inmem[i].get_val(index));
     else
        fprintf(outf, "%1.12e\n", latent_factors_inmem[i].get_val(index));
   fclose(outf);
 }
Exemplo n.º 8
0
  MMOutputter_scalar(std::string fname, std::string comment, double val)  {
    MM_typecode matcode;
    set_matcode(matcode, R_output_format);
    FILE * outf = open_file(fname.c_str(), "w");
    mm_write_banner(outf, matcode);
    if (comment != "")
      fprintf(outf, "%%%s\n", comment.c_str());

    if (R_output_format)
      mm_write_mtx_crd_size(outf, 1, 1, 1);
    else 
      mm_write_mtx_array_size(outf, 1, 1);

    if (R_output_format)
      fprintf(outf, "%d %d %12.8g\n", 1, 1, val);
    else
      fprintf(outf, "%1.12e\n", val);
    fclose(outf);
  }
Exemplo n.º 9
0
int write_mm_matrix_crd_header(FILE *fp, const int m, const int n,
                               const int nnz, const char *comments)
{
    MM_typecode matcode;

    mm_initialize_typecode(&matcode);
    mm_set_matrix(&matcode);
    mm_set_coordinate(&matcode);
    mm_set_real(&matcode);

    /* banner */
    mm_write_banner(fp, matcode); 
    /* comments */
    fprintf(fp, "%s", comments);
    /* size */
    mm_write_mtx_crd_size(fp, m, n, nnz);
    /* contents */

    return 0;
}
Exemplo n.º 10
0
int RowMatrixToMatrixMarketFile( const char *filename, const Epetra_RowMatrix & A, 
				 const char * matrixName,
				 const char *matrixDescription, 
				 bool writeHeader) {
  long long M = A.NumGlobalRows64();
  long long N = A.NumGlobalCols64();
  long long nz = A.NumGlobalNonzeros64();

  FILE * handle = 0;

  if (A.RowMatrixRowMap().Comm().MyPID()==0) { // Only PE 0 does this section

    handle = fopen(filename,"w");
    if (!handle) {EPETRA_CHK_ERR(-1);}
    MM_typecode matcode;
    mm_initialize_typecode(&matcode);
    mm_set_matrix(&matcode);
    mm_set_coordinate(&matcode);
    mm_set_real(&matcode);

    if (writeHeader==true) { // Only write header if requested (true by default)
    
      if (mm_write_banner(handle, matcode)!=0) {EPETRA_CHK_ERR(-1);}
      
      if (matrixName!=0) fprintf(handle, "%% \n%% %s\n", matrixName);
      if (matrixDescription!=0) fprintf(handle, "%% %s\n%% \n", matrixDescription);
      
      if (mm_write_mtx_crd_size(handle, M, N, nz)!=0) {EPETRA_CHK_ERR(-1);}
    }
  }
    
  if (RowMatrixToHandle(handle, A)!=0) {EPETRA_CHK_ERR(-1);}// Everybody calls this routine

  if (A.RowMatrixRowMap().Comm().MyPID()==0) // Only PE 0 opened a file
    if (fclose(handle)!=0) {EPETRA_CHK_ERR(-1);}
  return(0);
}
Exemplo n.º 11
0
//------------------------------------------------------------------------
int test_mm_write(std::string filename)
{
    const int nz = 4;
    const int M = 10;
    const int N= 10;

    MM_typecode matcode;                        
    int I[nz] = { 0, 4, 2, 8 };
    int J[nz] = { 3, 8, 7, 5 };
    double val[nz] = {1.1, 2.2, 3.2, 4.4};
    int i;

    int err = 0; 
    FILE *f; 
    f = fopen(filename.c_str(), "w"); 
    err += mm_initialize_typecode(&matcode);
    err += mm_set_matrix(&matcode);
    err += mm_set_coordinate(&matcode);
    err += mm_set_real(&matcode);

    err += mm_write_banner(f, matcode); 
    err += mm_write_mtx_crd_size(f, M, N, nz);

    /* NOTE: matrix market files use 1-based indices, i.e. first element
       of a vector has index 1, not 0.  */
    fprintf(stdout, "Writing file contents: \n"); 
    for (i=0; i<nz; i++)
    {
        fprintf(f, "%d %d %lg\n", I[i]+1, J[i]+1, val[i]);
        fprintf(stdout, "%d %d %lg\n", I[i]+1, J[i]+1, val[i]);
    }

    fclose(f);

    return err;
}
Exemplo n.º 12
0
int main()
{
    MM_typecode matcode;                        
    int I[nz] = { 0, 4, 2, 8 };
    int J[nz] = { 3, 8, 7, 5 };
    double val[nz] = {1.1, 2.2, 3.2, 4.4};
    int i;

    mm_initialize_typecode(&matcode);
    mm_set_matrix(&matcode);
    mm_set_coordinate(&matcode);
    mm_set_real(&matcode);

    mm_write_banner(stdout, matcode); 
    mm_write_mtx_crd_size(stdout, M, N, nz);

    /* NOTE: matrix market files use 1-based indices, i.e. first element
      of a vector has index 1, not 0.  */

    for (i=0; i<nz; i++)
        fprintf(stdout, "%d %d %10.3g\n", I[i]+1, J[i]+1, val[i]);

	return 0;
}
Exemplo n.º 13
0
void HostMatrixCOO<ValueType>::WriteFileMTX(const std::string filename) const {

  MM_typecode matcode; 
  FILE *f;

  LOG_INFO("WriteFileMTX: filename="<< filename << "; writing...");

  if ((f = fopen(filename.c_str(), "w")) == NULL) {
    LOG_INFO("WriteFileMTX cannot open file " << filename);
    FATAL_ERROR(__FILE__, __LINE__);
  }

  mm_initialize_typecode(&matcode);
  mm_set_matrix(&matcode);
  mm_set_coordinate(&matcode);
  mm_set_real(&matcode);
  
  mm_write_banner(f, matcode); 

  //  mm_write_mtx_crd_size(f, this->get_ncol(), this->get_nrow(), this->get_nnz());
  mm_write_mtx_crd_size(f, this->get_nrow(), this->get_ncol(), this->get_nnz());

  /* NOTE: matrix market files use 1-based indices, i.e. first element
     of a vector has index 1, not 0.  */

  for (int i=0; i<this->nnz_; i++)
    fprintf(f, "%d %d %2.14e\n",
            this->mat_.row[i]+1, 
            this->mat_.col[i]+1, 
            this->mat_.val[i]);
  
  LOG_INFO("WriteFileMTX: filename="<< filename << "; done");

  fclose(f);

}
Exemplo n.º 14
0
int write_mm_matrix(const char *file, dmatrix *mat,
                    const char *comments, const int type)
{
    int i, j, m, n;
    FILE *fp;
    m = mat->m;
    n = mat->n;
    
    MM_typecode matcode;

    mm_initialize_typecode(&matcode);
    mm_set_matrix(&matcode);

    if (mat->nz < 0)
        mm_set_array(&matcode);
    else
        mm_set_coordinate(&matcode);

    mm_set_real(&matcode);

    if ((fp = fopen(file, "w")) == NULL)
    {
        fprintf(stderr,"ERROR: Could not open file: %s\n",file);
        exit(1);
    }
    /* banner */
    mm_write_banner(fp, matcode); 
    /* comments */
    fprintf(fp, "%s", comments);
    /* size */
    if (mat->nz < 0)
        mm_write_mtx_array_size(fp, m, n);
    else
        mm_write_mtx_crd_size(fp, m, n, mat->nz);

    /* contents */

    if (mat->nz < 0)
    {
        double *val;
        val = mat->val;

        if (type == TYPE_G)
        {
            for (j = 0; j < n; j++)
                for (i = 0; i < m; i++)
                    fprintf(fp, "%10g\n", val[i*n+j]);
        }
        else
        {
            for (j = 0; j < n; j++)
                for (i = 0; i < m; i++)
                    fprintf(fp, "%22.15e\n", val[i*n+j]);
        }
    }
    else
    {
        int *idx;
        int *jdx;
        double *val;
        idx = mat->idx;
        jdx = mat->jdx;
        val = mat->val;
        if (type == TYPE_G)
        {
            for (i = 0; i < mat->nz; i++)
            {
                fprintf(fp, "%d %d %15g\n", idx[i]+1, jdx[i]+1, val[i]);
            }
        }
        else
        {
            for (i = 0; i < mat->nz; i++)
            {
                fprintf(fp, "%d %d %22.15e\n", idx[i]+1, jdx[i]+1, val[i]);
            }
        }
    }
    fclose(fp);

    return 0;
}
Exemplo n.º 15
0
/* Save a matrix column subset to a MatrixMarket formatted file,
   say to export the basis matrix for further numerical analysis.
   If colndx is NULL, then the full constraint matrix is assumed. */
MYBOOL REPORT_mat_mmsave(lprec *lp, char *filename, int *colndx, MYBOOL includeOF, char *infotext)
{
  int         n, m, nz, i, j, k, kk;
  MATrec      *mat = lp->matA;
  MM_typecode matcode;
  FILE        *output = stdout;
  MYBOOL      ok;
  LPSREAL        *acol = NULL;
  int         *nzlist = NULL;

  /* Open file */
  ok = (MYBOOL) ((filename == NULL) || ((output = fopen(filename,"w")) != NULL));
  if(!ok)
    return(ok);
  if((filename == NULL) && (lp->outstream != NULL))
    output = lp->outstream;

  /* Compute column and non-zero counts */
  if(colndx == lp->var_basic) {
    if(!lp->basis_valid)
      return( FALSE );
    m = lp->rows;
  }
  else if(colndx != NULL)
    m = colndx[0];
  else
    m = lp->columns;
  n = lp->rows;
  nz = 0;

  for(j = 1; j <= m; j++) {
    k = (colndx == NULL ? n + j : colndx[j]);
    if(k > n) {
      k -= lp->rows;
      nz += mat_collength(mat, k);
      if(includeOF && is_OF_nz(lp, k))
        nz++;
    }
    else
      nz++;
  }
  kk = 0;
  if(includeOF) {
    n++;   /* Row count */
    kk++;  /* Row index offset */
  }

  /* Initialize */
  mm_initialize_typecode(&matcode);
  mm_set_matrix(&matcode);
  mm_set_coordinate(&matcode);
  mm_set_real(&matcode);

  mm_write_banner(output, matcode);
  mm_write_mtx_crd_size(output, n+kk, m, nz+(colndx == lp->var_basic ? 1 : 0));

  /* Allocate working arrays for sparse column storage */
  allocREAL(lp, &acol, n+2, FALSE);
  allocINT(lp, &nzlist, n+2, FALSE);

  /* Write the matrix non-zero values column-by-column.
     NOTE: matrixMarket files use 1-based indeces,
     i.e. first row of a vector has index 1, not 0. */
  if(infotext != NULL) {
    fprintf(output, "%%\n");
    fprintf(output, "%% %s\n", infotext);
    fprintf(output, "%%\n");
  }
  if(includeOF && (colndx == lp->var_basic))
    fprintf(output, "%d %d %g\n", 1, 1, 1.0);
  for(j = 1; j <= m; j++) {
    k = (colndx == NULL ? lp->rows + j : colndx[j]);
    if(k == 0)
      continue;
    nz = obtain_column(lp, k, acol, nzlist, NULL);
    for(i = 1; i <= nz; i++) {
      if(!includeOF && (nzlist[i] == 0))
        continue;
      fprintf(output, "%d %d %g\n", nzlist[i]+kk, j+kk, acol[i]);
    }
  }
  fprintf(output, "%% End of MatrixMarket file\n");

  /* Finish */
  FREE(acol);
  FREE(nzlist);
  fclose(output);

  return(ok);
}
Exemplo n.º 16
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;
}
Exemplo n.º 17
0
int main(int argc, char *argv[])
{
  FILE *in_file;
  char Title[73], Key[9], Rhstype[4];
  char Type[4];
  char Ptrfmt[17], Indfmt[17], Valfmt[21], Rhsfmt[21];
  int Ptrcrd, Indcrd, Valcrd;
  int Rhscrd = 0;
  int Indperline, Indwidth;
  int Valperline, Valwidth, Valprec;
  int Valflag;           /* Indicates 'E','D', or 'F' float format */
  int Nrow, Ncol, Nnzero;
  int Nrhs;
  char *valc = NULL;
  char *Valfmtc;
  char *tmp1;
  char *tmp2;
  char format[30];
  char rformat[30];
  char cformat[30];
  int *colptr, *rowind;
  int i,j, indxval, rowp1, colp1;
  MM_typecode matcode;

  if (argc != 2) {
    printf("Usage: %s HBfile \n", argv[0]);
    exit(-1);
  }

  in_file = fopen( argv[1], "r");
  if (in_file == NULL)
  {
    fprintf(stderr,"Error: Cannot open file: %s\n",argv[1]);
    exit(1);
  }

  readHB_header(in_file, Title, Key, Type, &Nrow, &Ncol, &Nnzero, &Nrhs,
      Ptrfmt, Indfmt, Valfmt, Rhsfmt,
      &Ptrcrd, &Indcrd, &Valcrd, &Rhscrd, Rhstype);
  fclose(in_file);

  readHB_newmat_char(argv[1], &Nrow, &Ncol, &Nnzero, &colptr, &rowind, &valc,
      &Valfmtc);
  ParseIfmt(Indfmt,&Indperline,&Indwidth);
  ParseRfmt(Valfmt,&Valperline,&Valwidth,&Valprec,&Valflag);
  sprintf(format,"%%%dd %%%dd \n",Indwidth,Indwidth);
  sprintf(rformat,"%%%dd %%%dd %%%ds\n",Indwidth,Indwidth,Valwidth);
  sprintf(cformat,"%%%dd %%%dd %%%ds %%%ds\n",Indwidth,Indwidth,Valwidth,Valwidth);


  mm_set_matrix(&matcode);
  mm_set_coordinate(&matcode);
  if ( Type[0] == 'R' )
    mm_set_real(&matcode);
  else if ( Type[0] == 'C' )
    mm_set_complex(&matcode);
  else if ( Type[0] == 'P' )
    mm_set_pattern(&matcode);
  else {
    fprintf(stderr,"Unrecognized field in HB Type: %1s",Type);
    exit(1);
  }
  if ( Type[1] == 'U' || Type[1] == 'R' )
    mm_set_general(&matcode);
  else if ( Type[1] == 'S' )
    mm_set_symmetric(&matcode);
  else if ( Type[1] == 'Z' )
    mm_set_skew(&matcode);
  else if ( Type[1] == 'H' )
    mm_set_hermitian(&matcode);
  else {
    fprintf(stderr,"Unrecognized field in HB Type: %1s",&Type[1]);
    exit(1);
  }
  if ( Type[2] != 'A' ){
    fprintf(stderr,"Unrecognized format in HB Type: %1s",&Type[2]);
    exit(1);
  }
  mm_write_banner(stdout, matcode);
  fprintf(stdout,"%% RBTitle: %s\n",Title);
  fprintf(stdout,"%% RBKey:   %s\n",Key);
  mm_write_mtx_crd_size(stdout, Nrow, Ncol, Nnzero);

  if ( Type[0] == 'C' ) {
    /*  Loop through columns */
    for (j = 0; j < Ncol ; j++)
      for (i=colptr[j];i<colptr[j+1];i++)
      {
        indxval = 2*(i-1);
        rowp1 = rowind[i-1]+1-1;
        colp1 = j + 1;
        tmp1 = substr(valc,indxval*Valwidth,Valwidth);
        tmp2 = substr(valc,(indxval+1)*Valwidth,Valwidth);
        fprintf(stdout,cformat,rowp1,colp1,tmp1,tmp2);
      }
  } else if ( Type[0] == 'R' ) {
    /*  Loop through columns */
    for (j = 0; j < Ncol ; j++)
      for (i=colptr[j];i<colptr[j+1];i++)
      {
        rowp1 = rowind[i-1];
        colp1 = j + 1;
        tmp1 = substr(valc,(i-1)*Valwidth,Valwidth);
        fprintf(stdout,rformat,rowp1,colp1,tmp1);
      }
  } else {
    /*  Loop through columns */
    for (j = 0; j < Ncol ; j++)
      for (i=colptr[j];i<colptr[j+1];i++)
      {
        rowp1 = rowind[i-1];
        colp1 = j + 1;
        fprintf(stdout,format,rowp1,colp1);
      }
  }
  return 0;
}
Exemplo n.º 18
0
void main(int argc, char *argv[])
{
    FILE *in_file;
    char Title[73], Key[9], Rhstype[4];
    char Type[4];
    char Ptrfmt[17], Indfmt[17], Valfmt[21], Rhsfmt[21];
    int Ptrcrd, Indcrd, Valcrd, Rhscrd;
    int Indperline, Indwidth;
    int Valperline, Valwidth, Valprec;
    int Valflag;           /* Indicates 'E','D', or 'F' float format */
    int Nrow, Ncol, Nnzero;
    int Nrhs;
    char* ThisElement;
    char format[30];
    char rformat[30];
    int *colptr, *rowind;
    int *colcount;
    int i,j, repeat, count, col, ind, items, last;
    char line[BUFSIZ];
    MM_typecode matcode;

    if (argc != 2) {
      printf("Usage: %s HBfile\n\n", argv[0]);
      printf("   Sends Matrix Market formatted output to stdout\n");
      exit(-1);
    } 

    in_file = fopen( argv[1], "r");
    if (in_file == NULL)
    {
       fprintf(stderr,"Error: Cannot open file: %s\n",argv[1]);
       exit(1);
    }

    readHB_header(in_file, Title, Key, Type, &Nrow, &Ncol, &Nnzero, &Nrhs,
                  Ptrfmt, Indfmt, Valfmt, Rhsfmt,
                  &Ptrcrd, &Indcrd, &Valcrd, &Rhscrd, Rhstype);
    fclose(in_file);

    if (Type[0] == 'P' ) {
      fprintf(stderr,"This is a streaming translator for LARGE files with ");
      fprintf(stderr,"REAL or COMPLEX data.  Use 'hbmat2mtx' for PATTERN matrices.\n");
      exit(1);
    }
    in_file = readHB_newind(argv[1], &Nrow, &Ncol, &Nnzero, &colptr, &rowind);
    ParseIfmt(Indfmt,&Indperline,&Indwidth);
    sprintf(format,"%%%dd %%%dd ",Indwidth,Indwidth);
    ParseRfmt(Valfmt,&Valperline,&Valwidth,&Valprec,&Valflag);
    sprintf(rformat,"%%%ds ",Valwidth);
    ThisElement = (char *) malloc(Valwidth+1);


/*  Skip to values in hb file: */

   mm_set_matrix(&matcode);
   mm_set_coordinate(&matcode);
   if ( Type[0] == 'R' )
    mm_set_real(&matcode);
   else if ( Type[0] == 'C' )
    mm_set_complex(&matcode);
   else if ( Type[0] == 'P' )
    mm_set_pattern(&matcode);
   else {
    fprintf(stderr,"Unrecognized field in HB Type: %1s",Type);
    exit(1);
   }
   if ( Type[1] == 'U' || Type[1] == 'R' )
    mm_set_general(&matcode);
   else if ( Type[1] == 'S' )
    mm_set_symmetric(&matcode);
   else if ( Type[1] == 'Z' )
    mm_set_skew(&matcode);
   else if ( Type[1] == 'H' )
    mm_set_hermitian(&matcode);
   else {
    fprintf(stderr,"Unrecognized field in HB Type: %1s",&Type[1]);
    exit(1);
   }
   if ( Type[2] != 'A' ){
    fprintf(stderr,"Unrecognized format in HB Type: %1s",&Type[2]);
    exit(1);
   }
    mm_write_banner(stdout, matcode);
    fprintf(stdout,"%% RBTitle: %s\n",Title);
    fprintf(stdout,"%% RBKey:   %s\n",Key);
    mm_write_mtx_crd_size(stdout, Nrow, Ncol, Nnzero);

    if ( ThisElement == NULL ) IOHBTerminate("Insufficient memory for ThisElement.\nhb2mtxstrm.c: Line 117 approx.");
    repeat=0;
    if ( Type[0] == 'C') repeat=1;
    count = 0;
    colcount = &colptr[1];
    items = 0; 
    for (i=0;i<Valcrd;i++)
    {
       fgets(line, BUFSIZ, in_file);
       if ( sscanf(line,"%*s") < 0 ) {
         fprintf(stderr,"iohb.c: Null (or blank) line in value data region of HB file.\n");
         exit(1);
       }
       if (Valflag == 'D') {
          while( strchr(line,'D') ) *strchr(line,'D') = 'E';
       }
       col =  0;
       for (ind = 0;ind<Valperline;ind++)
       {
          if (count == Nnzero) break;
          if (count == *colcount-1) colcount++;
          strncpy(ThisElement,line+col,Valwidth);
          *(ThisElement+Valwidth) = (char) NULL;
          if ( Valflag != 'F' && strchr(ThisElement,'E') == NULL ) {
             /* insert a char prefix for exp */
             last = strlen(ThisElement);
             for (j=last+1;j>=0;j--) {
                ThisElement[j] = ThisElement[j-1];
                if ( ThisElement[j] == '+' || ThisElement[j] == '-' ) {
                   ThisElement[j-1] = Valflag;
                   break;
                }
             }
          }
         items++;
         if (items==1) fprintf(stdout,format,rowind[count],colcount-colptr);
         if (items > repeat) { 
            fprintf(stdout,rformat,ThisElement);
            fprintf(stdout,"\n");
            count++; 
            items=0;
         } else {
            fprintf(stdout,rformat,ThisElement);
         }
         col += Valwidth;
       }
    }
       
}