示例#1
0
int main(int argc, char* argv[]){
  static const char *optString = "o:l:f:r:";
  int c;
  char* picture;
  char* output;
  double lambda;
  int factor;

  while((c = getopt(argc, argv, optString)) != -1){
    switch(c){
      case 'l': { lambda  = atof(optarg); break; }
      case 'f': { picture = optarg; break; }
      case 'o': { output = optarg; break; }
      case 'r': { factor = atoi(optarg); break; }
      default:  { printf("Cannot parse.\n"); }
    }
  }

  PGMInfo pgm_info = parse_pgm(picture,factor);
  Matrix matrix = build_matrix(lambda, &pgm_info);
  double results[pgm_info.fHeight * pgm_info.fWidth];

  gauss(matrix, &pgm_info);
  solve_equations(matrix, &pgm_info, results);
  create_new_picture(results, output, &pgm_info);

  free_pixels_memory(&pgm_info);

  return 0;
}
示例#2
0
void Main_win::clear_clicked()
{
  math_->clear();

  remove_matrix();
  build_matrix(mat_dim_);
  reset_display();
}
int main()
{
        int i, j, x, y;
        int n, b; /* n-> number of itens; b-> max weight*/
        int *vs; /* iten values*/ 
        int *ws; /* iten weights*/
        int **ps; /* the picked itens*/
        int **zs; /* the total value in the knapsack*/

        scanf("%d", &n);
        
        vs = (int *) malloc(sizeof(int) * n);
        ws = (int *) malloc(sizeof(int) * n);

        // get iten values
        for (i = 0; i < n; i++)
                scanf("%d", &vs[i]);
        // get iten weights
        for (i = 0; i < n; i++)
                scanf("%d", &ws[i]);

        scanf("%d", &b);

        //allocate matrices
        ps = build_matrix(b + 1, n);
        zs = build_matrix(b + 1, n);

        for (i = 0; i < n; i++)
                zs[0][i] = 0;

        for (i = 1; i <= b; i++)
                for (j = 0; j < n; j++) {
                        x = (j - 1 < 0) ? 0 : zs[i][j-1];
                        y = (i - ws[j] < 0) ? 0 : vs[j] + zs[i - ws[j]][j - 1];
                        zs[i][j] = max(x, y, &ps[i][j]);
                }

        print_matrix(b+1, n, zs);
        puts("");
        print_matrix(b+1, n, ps);
        printf("\nPicked: ");
        print_picked(n, b, ws, zs, ps);
        puts("");

}
示例#4
0
文件: reorder_tnd.c 项目: evatux/kaa
int main(int argc, char **argv)
{
    if (argc < 3) {
        fprintf(stderr, "usage: %s infile outfile {o|m} [res_pic.png] [intermid_pic.png\n");
        return 2;
    }

    int err;
    int is_in_fmc  = (strstr(argv[1], ".mtx") != NULL);
    int is_out_fmc = (strstr(argv[2], ".mtx") != NULL);
    int type = (argv[3][0] == 'o') ? ALG_ORIG : ALG_MULT;

    TMatrix_DCSR _A,  *A  = &_A;
    TMatrix_DCSR _B,  *B  = &_B;
    TWGraph      _gr, *gr = &_gr;
    if (is_in_fmc) err = matrix_load_fmc(A, argv[1]);
    else err = matrix_load(A, argv[1]);
    if (err != ERROR_NO_ERROR)
        PRINT_ERROR_MESSAGE_AND_EXIT(err);

    int size = A->size;
    int *xadj, *adjncy;
    int *perm, *invp;

    if (!perm || !invp)
        PRINT_ERROR_MESSAGE_AND_EXIT(ERROR_MEMORY_ALLOCATION);

    switch (type) {
        case ALG_ORIG: do_orig(A, &xadj, &adjncy); break;
        case ALG_MULT: do_mult(A, &xadj, &adjncy); break;
    }

    TWGraph igr = { NULL, adjncy, xadj, NULL, size, xadj[size] };

    tnd_perm(&igr, &perm, &invp);

    SAFE(build_graph(gr, A));
    SAFE(graph_reorder(gr, perm, invp));
    SAFE(build_matrix(gr, B, 1));

    if (argc > 4) matrix_portrait(B, argv[4], 0, 0, NULL);
    if (is_out_fmc) matrix_save_fmc(B, argv[2]);
    else matrix_save(B, argv[2]);

    free(xadj);
    free(adjncy);
    if (argc > 5) {
        switch (type) {
            case ALG_ORIG: do_orig(B, &xadj, &adjncy); break;
            case ALG_MULT: do_mult(B, &xadj, &adjncy); break;
        }
        igr = (TWGraph){ NULL, adjncy, xadj, NULL, size, 0 };
        graph_portrait(&igr, argv[5]);
    }

    return 0;
}
示例#5
0
void Main_win::load_clicked()
{
  try
  {
    QString q_form = QFileDialog::getOpenFileName(this, tr("Load Matrix"));

    std::ifstream f;
    f.open(q_form.toStdString(), std::ios_base::in);

    if(f.is_open())
    {
      int row = 0;
      int col = 0;
      char c = 0;
      bool flag = true;

      while(f.get(c))
      {
        if(flag && (c == ' '))
          col++;
        if(c == '\n')
        {
          row++;
          flag = false;
        }
      }

      f.clear();
      f.seekg(0, f.beg);

      std::istream_iterator<double> ii{f};
      std::istream_iterator<double> eos{};
      std::vector<double> v{ii, eos};

      f.close();

      remove_matrix();

      build_matrix(row, col);

      mat_dim_.first = row;
      mat_dim_.second = col;

      mat_dim_tmp_.first = row;
      mat_dim_tmp_.second = col;

      display_matrix(row, col, v);
    }
    else throw std::ios_base::failure("cannot open file");
  }
  catch(std::exception& e)
  {
    e.what();
    to_display(e.what());
  }
}
示例#6
0
void Main_win::set_dim_clicked()
{
  Set_dim dialog_set_dim(this, mat_dim_tmp_);
  dialog_set_dim.setModal(true);

  dialog_set_dim.show();
  dialog_set_dim.exec();

  remove_matrix();
  build_matrix(mat_dim_tmp_);
  mat_dim_ = mat_dim_tmp_;
}
示例#7
0
void Main_win::display_result(const Matrix& m)
{
  remove_matrix();
  build_matrix(m.rows(), m.cols());

  mat_dim_.first = m.rows();
  mat_dim_.second = m.cols();

  mat_dim_tmp_.first = m.rows();
  mat_dim_tmp_.second = m.cols();

  display_matrix(m);
}
示例#8
0
文件: tnd.c 项目: evatux/kaa
int tnd(TMatrix_DCSR *matr, real threshold)
{
    TWGraph gr;
    int *perm, *invp;
    int err = 0;

#ifdef _DEBUG_LEVEL_0
printf("[debug(0)]{tnd}: graph_builder\n");
#endif
    err = build_graph(&gr, matr);
    if ( err != ERROR_NO_ERROR ) ERROR_MESSAGE("tnd: graph_builder failed", err);

#ifdef _DEBUG_LEVEL_0
printf("[debug(0)]{tnd}: find_permutation\n");
#endif
    err = find_permutation(&gr,&perm, &invp, threshold);    // !!!REORDERING!!!
    if ( err != ERROR_NO_ERROR ) ERROR_MESSAGE("tnd: find_permutation failed", err);

#ifdef _DEBUG_LEVEL_0
printf("[debug(0)]{tnd}: graph_reoder\n");
#endif
    err = graph_reorder(&gr, perm, invp);
    if ( err != ERROR_NO_ERROR ) ERROR_MESSAGE("tnd: graph_reorder failed", err);

    if (perm) free(perm);
    if (invp) free(invp);

    err = graph_last_stage_reorder(&gr, threshold);
    if ( err != ERROR_NO_ERROR ) ERROR_MESSAGE("tnd: graph_last_stage_reorder failed", err);

#ifdef _DEBUG_LEVEL_0
printf("[debug(0)]{tnd}: matrix_builder\n");
#endif
    err = build_matrix(&gr, matr, 0);
    if ( err != ERROR_NO_ERROR ) ERROR_MESSAGE("tnd: matrix_builder failed", err);

    graph_destroy(&gr);

    return ERROR_NO_ERROR;
}
示例#9
0
void Main_win::init_gui()
{
  ui_->setupUi(this);

  this->setWindowTitle(tr("Matricks"));

  ui_->display->setReadOnly(true);
  ui_->display->setAlignment(Qt::AlignRight);

  ui_->main_layout->setAlignment(Qt::AlignLeft | Qt::AlignTop);

  connect(ui_->action_save, SIGNAL(triggered(bool)), this,
          SLOT(save_clicked()));
  connect(ui_->action_load, SIGNAL(triggered(bool)), this, SLOT(load_clicked()));
  connect(ui_->action_beenden, SIGNAL(triggered(bool)), this, SLOT(close()));

  connect(ui_->pb_set_dim, SIGNAL(clicked(bool)), this, SLOT(set_dim_clicked()));
  connect(ui_->pb_equal, SIGNAL(clicked(bool)), this, SLOT(equal_clicked()));
  connect(ui_->pb_plus, SIGNAL(clicked(bool)), this, SLOT(add_clicked()));
  connect(ui_->pb_sub, SIGNAL(clicked(bool)), this, SLOT(sub_clicked()));
  connect(ui_->pb_mul, SIGNAL(clicked(bool)), this, SLOT(mul_clicked()));
  connect(ui_->pb_div, SIGNAL(clicked(bool)), this, SLOT(div_clicked()));
  connect(ui_->pb_clear, SIGNAL(clicked(bool)), this, SLOT(clear_clicked()));
  connect(ui_->pb_inv, SIGNAL(clicked(bool)), this, SLOT(inv_clicked()));
  connect(ui_->pb_set_A, SIGNAL(clicked(bool)), this, SLOT(set_A_clicked()));
  connect(ui_->pb_set_b, SIGNAL(clicked(bool)), this, SLOT(set_b_clicked()));
  connect(ui_->pb_solve, SIGNAL(clicked(bool)), this, SLOT(solve_clicked()));
  connect(ui_->pb_trans, SIGNAL(clicked(bool)), this, SLOT(trans_clicked()));
  connect(ui_->pb_set_x, SIGNAL(clicked(bool)), this, SLOT(set_x_clicked()));
  connect(ui_->pb_dot, SIGNAL(clicked(bool)), this, SLOT(dot_clicked()));
  connect(ui_->pb_det, SIGNAL(clicked(bool)), this, SLOT(det_clicked()));

  connect(math_.get(), SIGNAL(publish_result(const Matrix&)), this,
          SLOT(display_result(const Matrix&)));

  build_matrix(mat_dim_);
}
示例#10
0
int main(int argc,char **argv)
{
  char stdi=0;
  double *pm;
  long i,j;
  FILE *file;
  double **mat,**inverse,*vec,**coeff,**diff,avpm;
  
  if (scan_help(argc,argv))
    show_options(argv[0]);
  
  scan_options(argc,argv);
#ifndef OMIT_WHAT_I_DO
  if (verbosity&VER_INPUT)
    what_i_do(argv[0],WID_STR);
#endif

  infile=search_datafile(argc,argv,NULL,verbosity);
  if (infile == NULL)
    stdi=1;

  if (outfile == NULL) {
    if (!stdi) {
      check_alloc(outfile=(char*)calloc(strlen(infile)+4,(size_t)1));
      strcpy(outfile,infile);
      strcat(outfile,".ar");
    }
    else {
      check_alloc(outfile=(char*)calloc((size_t)9,(size_t)1));
      strcpy(outfile,"stdin.ar");
    }
  }
  if (!stdo)
    test_outfile(outfile);

  if (column == NULL)
    series=(double**)get_multi_series(infile,&length,exclude,&dim,"",dimset,
				      verbosity);
  else
    series=(double**)get_multi_series(infile,&length,exclude,&dim,column,
				      dimset,verbosity);

  check_alloc(my_average=(double*)malloc(sizeof(double)*dim));
  set_averages_to_zero();

  if (poles >= length) {
    fprintf(stderr,"It makes no sense to have more poles than data! Exiting\n");
    exit(AR_MODEL_TOO_MANY_POLES);
  }
  
  
  check_alloc(vec=(double*)malloc(sizeof(double)*poles*dim));
  check_alloc(mat=(double**)malloc(sizeof(double*)*poles*dim));
  for (i=0;i<poles*dim;i++)
    check_alloc(mat[i]=(double*)malloc(sizeof(double)*poles*dim));

  check_alloc(coeff=(double**)malloc(sizeof(double*)*dim));
  inverse=build_matrix(mat);
  for (i=0;i<dim;i++) {
    build_vector(vec,i);
    coeff[i]=multiply_matrix_vector(inverse,vec);
  }

  check_alloc(diff=(double**)malloc(sizeof(double*)*dim));
  for (i=0;i<dim;i++)
    check_alloc(diff[i]=(double*)malloc(sizeof(double)*length));

  pm=make_residuals(diff,coeff);
  
  if (stdo) {
    avpm=pm[0]*pm[0];
    for (i=1;i<dim;i++)
      avpm += pm[i]*pm[i];
    avpm=sqrt(avpm/dim);
    printf("#average forcast error= %e\n",avpm);
    printf("#individual forecast errors: ");
    for (i=0;i<dim;i++)
      printf("%e ",pm[i]);
    printf("\n");
    for (i=0;i<dim*poles;i++) {
      printf("# ");
      for (j=0;j<dim;j++)
	printf("%e ",coeff[j][i]);
      printf("\n");
    }
    if (!run_model || (verbosity&VER_USR1)) {
      for (i=poles;i<length;i++) {
	if (run_model)
	  printf("#");
	for (j=0;j<dim;j++)
	  if (verbosity&VER_USR2)
	    printf("%e %e ",series[j][i]+my_average[j],diff[j][i]);
	  else
	    printf("%e ",diff[j][i]);
	printf("\n");
      }
    }
    if (run_model && (ilength > 0))
      iterate_model(coeff,pm,NULL);
  }
  else {
    file=fopen(outfile,"w");
    if (verbosity&VER_INPUT)
      fprintf(stderr,"Opened %s for output\n",outfile);
    avpm=pm[0]*pm[0];
    for (i=1;i<dim;i++)
      avpm += pm[i]*pm[i];
    avpm=sqrt(avpm/dim);
    fprintf(file,"#average forcast error= %e\n",avpm);
    fprintf(file,"#individual forecast errors: ");
    for (i=0;i<dim;i++)
      fprintf(file,"%e ",pm[i]);
    fprintf(file,"\n");
    for (i=0;i<dim*poles;i++) {
      fprintf(file,"# ");
      for (j=0;j<dim;j++)
	fprintf(file,"%e ",coeff[j][i]);
      fprintf(file,"\n");
    }
    if (!run_model || (verbosity&VER_USR1)) {
      for (i=poles;i<length;i++) {
	if (run_model)
	  fprintf(file,"#");
	for (j=0;j<dim;j++)
	  if (verbosity&VER_USR2)
	    fprintf(file,"%e %e ",series[j][i]+my_average[j],diff[j][i]);
	  else
	    fprintf(file,"%e ",diff[j][i]);
	fprintf(file,"\n");
      }
    }
    if (run_model && (ilength > 0))
      iterate_model(coeff,pm,file);
    fclose(file);
  }

  if (outfile != NULL)
    free(outfile);
  if (infile != NULL)
    free(infile);
  free(vec);
  for (i=0;i<poles*dim;i++) {
    free(mat[i]);
    free(inverse[i]);
  }
  free(mat);
  free(inverse);
  for (i=0;i<dim;i++) {
    free(coeff[i]);
    free(diff[i]);
  }
  free(coeff);
  free(diff);
  free(pm);

  return 0;
}
示例#11
0
VALUE parse_string(VALUE self, VALUE string) {

  return build_matrix(RSTRING_PTR(string), NUM2INT(rb_str_length(string)));

}
示例#12
0
/*
 * The mex function runs a max-flow min-cut problem.
 */
void mexFunction(int nlhs, mxArray *plhs[],
                 int nrhs, const mxArray *prhs[])
{
    mbglIndex i,j,k;
    
    mbglIndex mrows, ncols;
    
    mbglIndex n,nz;
    
    /* sparse matrix */
    mwIndex *A_row, *A_col;
    double *A_val;
    
    /* source/sink */
    mbglIndex u, v;
    
    /* algorithm name */
    char *algname;
    
    /* flow matrix connectivity */
    mbglIndex *pi_flow, *j_flow;
    
    /* capacity and residual structures */
    int *cap, *res;
    
    /* reverse edge map */
    mbglIndex *rev_edge_map;
    
    /* result */
    int flow;
    
    /* output */
    double *pflowval;
    double *pmincut;
    
    double *pri;
    double *prj;
    double *prv;
    
    /* 
     * The current calling pattern is
     * matching_mex(A,verify,initial_match_name,augmenting_path_name)
     */
    
    const mxArray* arg_matrix;
    const mxArray* arg_source;
    const mxArray* arg_sink;
    const mxArray* arg_algname;    
    int required_arguments = 4;
    
    if (nrhs != required_arguments) {
        mexErrMsgIdAndTxt("matlab_bgl:invalidMexArgument",
            "the function requires %i arguments, not %i\n", 
            required_arguments, nrhs);
    }
    
    arg_matrix = prhs[0];
    arg_source = prhs[1];
    arg_sink = prhs[2];
    arg_algname = prhs[3];
    
    u = (mbglIndex)load_scalar_arg(arg_source,1);
    v = (mbglIndex)load_scalar_arg(arg_sink,2);
    algname = load_string_arg(arg_algname,3);
    
    /* The first input must be a sparse matrix. */
    mrows = mxGetM(prhs[0]);
    ncols = mxGetN(prhs[0]);
    if (mrows != ncols ||
        !mxIsSparse(prhs[0]) ||
        !mxIsDouble(prhs[0]) || 
        mxIsComplex(prhs[0])) 
    {
        mexErrMsgIdAndTxt("matlab_bgl:invalidMexArgument",
            "the matrix must be sparse, square, and double valued");
    }
    
    n = mrows;
    
    /* Get the sparse matrix */
    A_val = mxGetPr(prhs[0]);
    A_row = mxGetIr(prhs[0]);
    A_col = mxGetJc(prhs[0]);
    
    nz = A_col[n];
    
    /* Quick input check */
    if (u > n || u < 1) {
        mexErrMsgIdAndTxt("matlab_bgl:invalidMexArgument",
            "invalid source vertex: %i\n", u);
    } 
    
    if (v > n || v < 1) {
        mexErrMsgIdAndTxt("matlab_bgl:invalidMexArgument",
            "invalid sink vertex: %i\n", v);
    }
    
    u = u-1;
    v = v-1;
    
    /* build flow connectivity structure */
    build_matrix(n,A_row,A_col,A_val, 
        &pi_flow, &j_flow, &cap, &rev_edge_map);
    
    /* allocate the residual map */
    res = mxCalloc(sizeof(int),pi_flow[n]);
    
    /*i = 0;
    for (k=0; k < pi_flow[n]; k++)
    {
        // get the correct row
        while (k >= pi_flow[i+1]) { ++i; }
        mexPrintf("(%i,%i) (%i,%i)\n", i,j_flow[k],cap[k],res[k]);
    }*/
    
    /* mexPrintf("Calling flow (%i,%i)...\n", u, v); */
    #ifdef _DEBUG
    mexPrintf("max_flow(%s)...", algname);
    #endif 
    if (strcmp(algname,"push_relabel") == 0) {
        push_relabel_max_flow(n,j_flow,pi_flow,
            u,v,cap,res,rev_edge_map,&flow);
    } else if (strcmp(algname, "edmunds_karp") == 0) {
        edmonds_karp_max_flow(n,j_flow,pi_flow,
            u,v,cap,res,rev_edge_map,&flow);
    } else if (strcmp(algname, "kolmogorov") == 0) {
        boykov_kolmogorov_max_flow(n,j_flow,pi_flow,
            u,v,cap,res,rev_edge_map,&flow);
    } else {
        mexErrMsgIdAndTxt("matlab_bgl:invalidMexArgument",
            "algname option %s is invalid\n", 
            algname);
    }
    
    #ifdef _DEBUG
    mexPrintf("done!\n");
    #endif 
    
    /*i = 0;
    for (k=0; k < pi_flow[n]; k++)
    {
        // get the correct row
        while (k >= pi_flow[i+1]) { ++i; }
        mexPrintf("(%i,%i) (%i,%i)\n", i,j_flow[k],cap[k],res[k]);
    }*/
    
    if (nlhs >= 1)
    {
        plhs[0] = mxCreateDoubleMatrix(1,1, mxREAL);
        pflowval = mxGetPr(plhs[0]);
        pflowval[0] = (double)flow;
    }
    
    if (nlhs >= 2)
    {
        int *pimincut;
        
        plhs[1] = mxCreateDoubleMatrix(n,1,mxREAL);
        pmincut = mxGetPr(plhs[1]);
        
        pimincut = (int*)pmincut;
        
        build_cut(u, n, pi_flow, j_flow, cap, res, pimincut);
        
        test_cut(flow,pimincut,n,A_row,A_col,A_val);
        
        /* now expand mincut to the full dataset, we need to
         * do this operation backwards because pimincut has integer
         * entries specified and we are expanding them to double.
         */
        expand_int_to_double(pimincut,pmincut,n,0.0);
    }
    
    if (nlhs >= 3)
    {
        plhs[2] = mxCreateDoubleMatrix(nz,1,mxREAL);
        plhs[3] = mxCreateDoubleMatrix(nz,1,mxREAL);
        plhs[4] = mxCreateDoubleMatrix(nz,1,mxREAL);
        
        pri = mxGetPr(plhs[2]);
        prj = mxGetPr(plhs[3]);
        prv = mxGetPr(plhs[4]);
        
        /* j will be our index into the new matrix. */
        j = 0;
        
        for (i=0;i<n;i++)
        {
            for (k=pi_flow[i];k<pi_flow[i+1];k++)
            {
                if (cap[k] != 0)
                {
                    /* since cap[k] != 0, this is a real edge */
                    pri[j] = i+1;
                    prj[j] = j_flow[k]+1;
                    prv[j] = res[k];
                    j++;
                }
            }
        }
        
        if (j != nz)
        {
            mexPrintf("error... j != nz...\n");
        }
    }
    
    #ifdef _DEBUG
    mexPrintf("return\n");
    #endif 
}
示例#13
0
int main(int argc, char *argv[]) {
  int ret = ERR_SUCCESS;

#ifndef H3D_COMPLEX
  if (argc < 3) error("Not enough parameters.");
#else
  if (argc < 2) error("Not enough parameters.");
#endif

  int n;
  std::map<unsigned int, MatrixEntry> ar_mat;
  std::map<unsigned int, scalar> ar_rhs;

  if (read_matrix_and_rhs(argv[2], n, ar_mat, ar_rhs) != ERR_SUCCESS)
    error("Failed to read the matrix and rhs.");

  if (strcasecmp(argv[1], "petsc") == 0) {
#ifdef WITH_PETSC
    PetscMatrix mat;
    PetscVector rhs;
    build_matrix(n, ar_mat, ar_rhs, &mat, &rhs);

    PetscLinearSolver solver(&mat, &rhs);
    solve(solver, n);
#endif
  }
  else if (strcasecmp(argv[1], "petsc-block") == 0) {
#ifdef WITH_PETSC
    PetscMatrix mat;
    PetscVector rhs;
    build_matrix_block(n, ar_mat, ar_rhs, &mat, &rhs);

    PetscLinearSolver solver(&mat, &rhs);
    solve(solver, n);
#endif
  }
  else if (strcasecmp(argv[1], "umfpack") == 0) {
#ifdef WITH_UMFPACK
    UMFPackMatrix mat;
    UMFPackVector rhs;
    build_matrix(n, ar_mat, ar_rhs, &mat, &rhs);

    UMFPackLinearSolver solver(&mat, &rhs);
    solve(solver, n);
#endif
  }
  else if (strcasecmp(argv[1], "umfpack-block") == 0) {
#ifdef WITH_UMFPACK
    UMFPackMatrix mat;
    UMFPackVector rhs;
    build_matrix_block(n, ar_mat, ar_rhs, &mat, &rhs);

    UMFPackLinearSolver solver(&mat, &rhs);
    solve(solver, n);
#endif
  }
  else if (strcasecmp(argv[1], "aztecoo") == 0) {
#ifdef WITH_TRILINOS
    EpetraMatrix mat;
    EpetraVector rhs;
    build_matrix(n, ar_mat, ar_rhs, &mat, &rhs);

    AztecOOSolver solver(&mat, &rhs);
    solve(solver, n);
#endif
  }
  else if (strcasecmp(argv[1], "aztecoo-block") == 0) {
#ifdef WITH_TRILINOS
    EpetraMatrix mat;
    EpetraVector rhs;
    build_matrix_block(n, ar_mat, ar_rhs, &mat, &rhs);

    AztecOOSolver solver(&mat, &rhs);
    solve(solver, n);
#endif
  }
  else if (strcasecmp(argv[1], "amesos") == 0) {
#ifdef WITH_TRILINOS
    EpetraMatrix mat;
    EpetraVector rhs;
    build_matrix(n, ar_mat, ar_rhs, &mat, &rhs);

    if (AmesosSolver::is_available("Klu")) {
      AmesosSolver solver("Klu", &mat, &rhs);
      solve(solver, n);
    }
#endif
  }
  else if (strcasecmp(argv[1], "amesos-block") == 0) {
#ifdef WITH_TRILINOS
    EpetraMatrix mat;
    EpetraVector rhs;
    build_matrix_block(n, ar_mat, ar_rhs, &mat, &rhs);

    if (AmesosSolver::is_available("Klu")) {
      AmesosSolver solver("Klu", &mat, &rhs);
      solve(solver, n);
    } 
#endif
  }
  else if (strcasecmp(argv[1], "mumps") == 0) {
#ifdef WITH_MUMPS
    MumpsMatrix mat;
    MumpsVector rhs;
    build_matrix(n, ar_mat, ar_rhs, &mat, &rhs);

    MumpsSolver solver(&mat, &rhs);
    solve(solver, n);
#endif
  }
  else if (strcasecmp(argv[1], "mumps-block") == 0) {
#ifdef WITH_MUMPS
    MumpsMatrix mat;
    MumpsVector rhs;
    build_matrix_block(n, ar_mat, ar_rhs, &mat, &rhs);

    MumpsSolver solver(&mat, &rhs);
    solve(solver, n);
#endif
  }  
  else
    ret = ERR_FAILURE;

  return ret;
}
示例#14
0
/* Funzione poco chiara che gestisce il posizionamento delle navi sullo schermo */
int posiziona_navi() {
    int nave=0;
    int ch;
    int x=0,y=0,v=1;
    wprintw(score, "POSIZIONAMENTO NAVI\n"
            "Comandi: frecce: muovi nave\n"
            "         n: nave successiva\n"
            "         r: ruota nave\n"
            "         c: conferma disposizione\n");
    wrefresh(score);
    wclear(msg);
    wprintw(msg, "Posizionamento nave %d/%d\nNave di tipo %s", nave, numero_navi, navi[nave].name);
    wrefresh(msg);
    build_matrix(0);
    updateA();
    while ((ch=getch())) {
        switch(ch) {
        case KEY_LEFT:
            if (x>0) x--;
            break;
        case KEY_RIGHT:
            x++;
            if (!posiziona_nave(nave, y, x, v)) {
                x--;
            }
            break;
        case KEY_UP:
            if (y>0) y--;
            break;
        case KEY_DOWN:
            y++;
            if (!posiziona_nave(nave, y, x, v)) {
                y--;
            }
            break;
        case 'r':
            v = v ? 0 : 1;
            if (!posiziona_nave(nave, y, x, v)) {
                v = v ? 0 : 1;
            }
            break;
        case 'n':
            nave++;
            if (nave >= numero_navi) nave=0;
            x=navi[nave].x;
            y=navi[nave].y;
            v=navi[nave].orientamento;
            break;
        case 'c':
            if (build_matrix(0)>0) {
                wclear(msg);
                wprintw(msg, "Sono preseti delle collisioni: risolvere prima di confermare!\n");
                wrefresh(msg);
            } else {
                if (conferma("Confermare disposizione corrente ? \nNB: una volta confermata non sarà possibile\n effettuare ulteriori modifiche")) {
                    build_matrix(1);
                    return 1;
                }
            }
        }
        mvwprintw(msg, 0, 0, "Posizionamento nave %d/%d\nNave di tipo %s, rotazione %d", nave, numero_navi, navi[nave].name, v);
        wrefresh(msg);
        posiziona_nave(nave, y, x, v);
        build_matrix(0);
        updateA();
    }
    return 0;
}
示例#15
0
int
main(int argc, char *argv[])
{
    GRID *g;
    DOF *u_h;
    MAT *A, *A0, *B;
    MAP *map;
    INT i;
    size_t nnz, mem, mem_peak;
    VEC *x, *y0, *y1, *y2;
    double t0, t1, dnz, dnz1, mflops, mop;
    char *fn = "../test/cube.dat";
    FLOAT mem_max = 300;
    INT refine = 0;

    phgOptionsRegisterFilename("-mesh_file", "Mesh file", (char **)&fn);
    phgOptionsRegisterInt("-loop_count", "Loop count", &loop_count);
    phgOptionsRegisterInt("-refine", "Refinement level", &refine);
    phgOptionsRegisterFloat("-mem_max", "Maximum memory", &mem_max);

    phgInit(&argc, &argv);
    g = phgNewGrid(-1);
    if (!phgImport(g, fn, FALSE))
	phgError(1, "can't read file \"%s\".\n", fn);
    phgRefineAllElements(g, refine);
    u_h = phgDofNew(g, DOF_DEFAULT, 1, "u_h", DofNoAction);

    while (TRUE) {
	phgPrintf("\n");
	if (phgBalanceGrid(g, 1.2, 1, NULL, 0.))
	    phgPrintf("Repartition mesh, %d submeshes, load imbalance: %lg\n",
			g->nprocs, (double)g->lif);
	map = phgMapCreate(u_h, NULL);
	A = phgMapCreateMat(map, map);
	A->handle_bdry_eqns = TRUE;
	build_matrix(A, u_h);
	phgMatAssemble(A);

	/* Note: A is unsymmetric (A' != A) if boundary entries not removed */
	phgMatRemoveBoundaryEntries(A);

#if 0
	/* test block matrix operation */
	A0 = phgMatCreateBlockMatrix(g->comm, 1, 1, &A, NULL);
#else
	A0 = A;
#endif

	phgPrintf("%d DOF, %d elems, %d submeshes, matrix size: %d, LIF: %lg\n",
			DofGetDataCountGlobal(u_h), g->nleaf_global,
			g->nprocs, A->rmap->nglobal, (double)g->lif);

	/* test PHG mat-vec multiply */
	x = phgMapCreateVec(A->cmap, 1);
	y1 = phgMapCreateVec(A->rmap, 1);
	phgVecRandomize(x, 123);
	phgMatVec(MAT_OP_N, 1.0, A0, x, 0.0, &y1);

	phgPerfGetMflops(g, NULL, NULL);	/* reset flops counter */
	t0 = phgGetTime(NULL);
	for (i = 0; i < loop_count; i++) {
	    phgMatVec(MAT_OP_N, 1.0, A0, x, 0.0, &y1);
	}
	t1 = phgGetTime(NULL);
	mflops = phgPerfGetMflops(g, NULL, NULL);
	y0 = phgVecCopy(y1, NULL);
	nnz = A->nnz_d + A->nnz_o;
#if USE_MPI
	dnz1 = nnz;
	MPI_Reduce(&dnz1, &dnz, 1, MPI_DOUBLE, MPI_SUM, 0, g->comm);
#else
	dnz = nnz;
#endif
	mop = loop_count * (dnz + dnz - A->rmap->nlocal) * 1e-6;

	phgPrintf("\n");
	t1 -= t0;
	phgPrintf("   PHG:  time %0.4lf, nnz %0.16lg, %0.2lfMF (%0.2lfMF)\n",
			t1, dnz, mop / (t1 == 0 ? 1. : t1), mflops);

	/* test trans(A)*x */
	phgPerfGetMflops(g, NULL, NULL);	/* reset flops counter */
	t0 = phgGetTime(NULL);
	for (i = 0; i < loop_count; i++) {
	    phgMatVec(MAT_OP_T, 1.0, A0, x, 0.0, &y1);
	}
	t1 = phgGetTime(NULL);
	mflops = phgPerfGetMflops(g, NULL, NULL);
	t1 -= t0;
	phgPrintf("  A'*x:  time %0.4lf, nnz %0.16lg, %0.2lfMF (%0.2lfMF), "
		  "err: %le\n", t1, dnz, mop / (t1 == 0 ? 1. : t1), mflops,
		 (double)phgVecNorm2(phgVecAXPBY(-1.0, y0, 1.0, &y1), 0, NULL));

	/* time A * trans(A) */
	phgPerfGetMflops(g, NULL, NULL);	/* reset flops counter */
	t0 = phgGetTime(NULL);
	B = phgMatMat(MAT_OP_N, MAT_OP_N, 1.0, A, A, 0.0, NULL);
	t1 = phgGetTime(NULL);
	mflops = phgPerfGetMflops(g, NULL, NULL);
	nnz = B->nnz_d + B->nnz_o;
#if USE_MPI
	dnz1 = nnz;
	MPI_Reduce(&dnz1, &dnz, 1, MPI_DOUBLE, MPI_SUM, 0, g->comm);
#else
	dnz = nnz;
#endif
	/* compare B*x <--> A*A*x */
	y2 = phgMatVec(MAT_OP_N, 1.0, B, x, 0.0, NULL);
	phgMatVec(MAT_OP_N, 1.0, A0, y0, 0.0, &y1);
	phgMatDestroy(&B);
	t1 -= t0;
	phgPrintf("   A*A:  time %0.4lf, nnz %0.16lg, %0.2lfMF, err: %le\n",
		  t1, dnz, mflops,
		 (double)phgVecNorm2(phgVecAXPBY(-1.0, y1, 1.0, &y2), 0, NULL));

#if USE_PETSC
	{
	    Mat ma, mb;
	    MatInfo info;
	    Vec va, vb, vc;
	    PetscScalar *vec;

	    ma = phgPetscCreateMatAIJ(A);
	    MatGetVecs(ma, PETSC_NULL, &va);
	    VecDuplicate(va, &vb);
	    VecGetArray(va, &vec);
	    memcpy(vec, x->data, x->map->nlocal * sizeof(*vec));
	    VecRestoreArray(va, &vec);
	    MatMult(ma, va, vb);
	    phgPerfGetMflops(g, NULL, NULL);	/* reset flops counter */
	    t0 = phgGetTime(NULL);
	    for (i = 0; i < loop_count; i++) {
		MatMult(ma, va, vb);
	    }
	    t1 = phgGetTime(NULL);
	    mflops = phgPerfGetMflops(g, NULL, NULL);
	    VecGetArray(vb, &vec);
	    memcpy(y1->data, vec, x->map->nlocal * sizeof(*vec));
	    VecRestoreArray(vb, &vec);

	    MatGetInfo(ma, MAT_GLOBAL_SUM, &info);
	    /*phgPrintf("    --------------------------------------------"
		      "-------------------------\n");*/
	    phgPrintf("\n");
	    t1 -= t0;
	    dnz = info.nz_used;
	    phgPrintf(" PETSc:  time %0.4lf, nnz %0.16lg, %0.2lfMF (%0.2lfMF), "
		      "err: %le\n", t1, dnz, mop / (t1==0 ? 1.:t1), mflops,
		 (double)phgVecNorm2(phgVecAXPBY(-1.0, y0, 1.0, &y1), 0, NULL));

	    phgPerfGetMflops(g, NULL, NULL);	/* reset flops counter */
	    t0 = phgGetTime(NULL);
	    for (i = 0; i < loop_count; i++) {
		MatMultTranspose(ma, va, vb);
	    }
	    t1 = phgGetTime(NULL);
	    mflops = phgPerfGetMflops(g, NULL, NULL);
	    VecGetArray(vb, &vec);
	    memcpy(y1->data, vec, x->map->nlocal * sizeof(*vec));
	    VecRestoreArray(vb, &vec);
	    t1 -= t0;
	    phgPrintf("  A'*x:  time %0.4lf, nnz %0.16lg, %0.2lfMF (%0.2lfMF), "
		      "err: %le\n", t1, dnz, mop / (t1==0 ? 1.:t1), mflops,
		(double)phgVecNorm2(phgVecAXPBY(-1.0, y0, 1.0, &y1), 0, NULL));

	    phgPerfGetMflops(g, NULL, NULL);	/* reset flops counter */
	    t0 = phgGetTime(NULL);
	    MatMatMult(ma, ma, MAT_INITIAL_MATRIX, PETSC_DEFAULT, &mb);
	    t1 = phgGetTime(NULL);
	    mflops = phgPerfGetMflops(g, NULL, NULL);
	    t1 -= t0;
	    MatGetInfo(mb, MAT_GLOBAL_SUM, &info);
	    dnz = info.nz_used;
	    VecDuplicate(va, &vc);
	    /* compare B*x <--> A*A*x */
	    MatMult(ma, vb, vc);
	    MatMult(mb, va, vb);
	    VecGetArray(vb, &vec);
	    memcpy(y1->data, vec, x->map->nlocal * sizeof(*vec));
	    VecRestoreArray(vb, &vec);
	    VecGetArray(vc, &vec);
	    memcpy(y2->data, vec, x->map->nlocal * sizeof(*vec));
	    VecRestoreArray(vc, &vec);
	    phgPrintf("   A*A:  time %0.4lf, nnz %0.16lg, %0.2lfMF, err: %le\n",
		  t1, dnz, mflops,
		 (double)phgVecNorm2(phgVecAXPBY(-1.0, y1, 1.0, &y2), 0, NULL));

	    phgPetscMatDestroy(&mb);
	    phgPetscMatDestroy(&ma);
	    phgPetscVecDestroy(&va);
	    phgPetscVecDestroy(&vb);
	    phgPetscVecDestroy(&vc);
	}
#endif	/* USE_PETSC */

#if USE_HYPRE
	{
	    HYPRE_IJMatrix ma;
	    HYPRE_IJVector va, vb, vc;
	    HYPRE_ParCSRMatrix  par_ma;
	    hypre_ParCSRMatrix  *par_mb;
	    HYPRE_ParVector	par_va, par_vb, par_vc;
	    HYPRE_Int offset, *ni, start, end;
	    assert(sizeof(INT)==sizeof(int) && sizeof(FLOAT)==sizeof(double));
	    setup_hypre_mat(A, &ma);
	    ni = phgAlloc(2 * A->rmap->nlocal * sizeof(*ni));
	    offset = A->cmap->partition[A->cmap->rank];
	    for (i = 0; i < A->rmap->nlocal; i++)
		ni[i] = i + offset;
	    HYPRE_IJVectorCreate(g->comm, offset, offset + A->rmap->nlocal - 1,
				 &va);
	    HYPRE_IJVectorCreate(g->comm, offset, offset + A->rmap->nlocal - 1,
				 &vb);
	    HYPRE_IJVectorCreate(g->comm, offset, offset + A->rmap->nlocal - 1,
				 &vc);
	    HYPRE_IJVectorSetObjectType(va, HYPRE_PARCSR);
	    HYPRE_IJVectorSetObjectType(vb, HYPRE_PARCSR);
	    HYPRE_IJVectorSetObjectType(vc, HYPRE_PARCSR);
	    HYPRE_IJVectorSetMaxOffProcElmts(va, 0);
	    HYPRE_IJVectorSetMaxOffProcElmts(vb, 0);
	    HYPRE_IJVectorSetMaxOffProcElmts(vc, 0);
	    HYPRE_IJVectorInitialize(va);
	    HYPRE_IJVectorInitialize(vb);
	    HYPRE_IJVectorInitialize(vc);
	    HYPRE_IJMatrixGetObject(ma, (void **)(void *)&par_ma);
	    HYPRE_IJVectorGetObject(va, (void **)(void *)&par_va);
	    HYPRE_IJVectorGetObject(vb, (void **)(void *)&par_vb);
	    HYPRE_IJVectorGetObject(vc, (void **)(void *)&par_vc);
	    HYPRE_IJVectorSetValues(va, A->cmap->nlocal, ni, (double *)x->data);
	    HYPRE_IJVectorAssemble(va);
	    HYPRE_IJVectorAssemble(vb);
	    HYPRE_IJVectorAssemble(vc);

	    HYPRE_IJMatrixGetRowCounts(ma, A->cmap->nlocal,
					ni, ni + A->rmap->nlocal);
	    for (i = 0, nnz = 0; i < A->rmap->nlocal; i++)
		nnz += ni[A->rmap->nlocal + i];
#if USE_MPI
	    dnz1 = nnz;
	    MPI_Reduce(&dnz1, &dnz, 1, MPI_DOUBLE, MPI_SUM, 0, g->comm);
#else
	    dnz = nnz;
#endif

	    HYPRE_ParCSRMatrixMatvec(1.0, par_ma, par_va, 0.0, par_vb);
	    phgPerfGetMflops(g, NULL, NULL);	/* reset flops counter */
	    t0 = phgGetTime(NULL);
	    for (i = 0; i < loop_count; i++) {
		HYPRE_ParCSRMatrixMatvec(1.0, par_ma, par_va, 0.0, par_vb);
	    }
	    t1 = phgGetTime(NULL);
	    mflops = phgPerfGetMflops(g, NULL, NULL);
	    HYPRE_IJVectorGetValues(vb, A->rmap->nlocal, ni, (double*)y1->data);
	    /*phgPrintf("    --------------------------------------------"
		      "-------------------------\n");*/
	    phgPrintf("\n");
	    t1 -= t0;
	    phgPrintf(" HYPRE:  time %0.4lf, nnz %0.16lg, %0.2lfMF (%0.2lfMF), "
		      "err: %le\n", t1, dnz, mop / (t1==0 ? 1.:t1), mflops,
		(double)phgVecNorm2(phgVecAXPBY(-1.0, y0, 1.0, &y1), 0, NULL));

	    phgPerfGetMflops(g, NULL, NULL);	/* reset flops counter */
	    t0 = phgGetTime(NULL);
	    for (i = 0; i < loop_count; i++) {
		HYPRE_ParCSRMatrixMatvecT(1.0, par_ma, par_va, 0.0, par_vb);
	    }
	    t1 = phgGetTime(NULL);
	    mflops = phgPerfGetMflops(g, NULL, NULL);
	    HYPRE_IJVectorGetValues(vb, A->rmap->nlocal, ni, (double*)y1->data);
	    t1 -= t0;
	    phgPrintf("  A'*x:  time %0.4lf, nnz %0.16lg, %0.2lfMF (%0.2lfMF), "
		      "err: %le\n", t1, dnz, mop / (t1==0 ? 1.:t1), mflops,
		(double)phgVecNorm2(phgVecAXPBY(-1.0, y0, 1.0, &y1), 0, NULL));

	    phgPerfGetMflops(g, NULL, NULL);	/* reset flops counter */
	    t0 = phgGetTime(NULL);
	    /* Note: 'HYPRE_ParCSRMatrix' is currently typedef'ed to
	     *	     'hypre_ParCSRMatrix *' */
	    par_mb = hypre_ParMatmul((hypre_ParCSRMatrix *)par_ma,
					(hypre_ParCSRMatrix *)par_ma);
	    t1 = phgGetTime(NULL);
	    mflops = phgPerfGetMflops(g, NULL, NULL);
	    start = hypre_ParCSRMatrixFirstRowIndex(par_mb);
	    end = hypre_ParCSRMatrixLastRowIndex(par_mb) + 1;
	    for (i = start, nnz = 0; i < end; i++) {
		HYPRE_Int ncols;
		hypre_ParCSRMatrixGetRow(par_mb, i, &ncols, NULL, NULL);
		hypre_ParCSRMatrixRestoreRow(par_mb, i, &ncols, NULL, NULL);
		nnz += ncols;
	    }
#if USE_MPI
	    dnz1 = nnz;
	    MPI_Reduce(&dnz1, &dnz, 1, MPI_DOUBLE, MPI_SUM, 0, g->comm);
#else
	    dnz = nnz;
#endif
	    /* compare B*x <--> A*A*x */
	    HYPRE_ParCSRMatrixMatvec(1.0, par_ma, par_vb, 0.0, par_vc);
	    HYPRE_ParCSRMatrixMatvec(1.0, (void *)par_mb, par_va, 0.0, par_vb);
	    HYPRE_IJVectorGetValues(vb, A->rmap->nlocal, ni, (double*)y1->data);
	    HYPRE_IJVectorGetValues(vc, A->rmap->nlocal, ni, (double*)y2->data);
	    hypre_ParCSRMatrixDestroy((par_mb));
	    t1 -= t0;
	    phgPrintf("   A*A:  time %0.4lf, nnz %0.16lg, %0.2lfMF, err: %le\n",
		  t1, dnz, mflops,
		 (double)phgVecNorm2(phgVecAXPBY(-1.0, y1, 1.0, &y2), 0, NULL));

	    phgFree(ni);
	    HYPRE_IJMatrixDestroy(ma);
	    HYPRE_IJVectorDestroy(va);
	    HYPRE_IJVectorDestroy(vb);
	    HYPRE_IJVectorDestroy(vc);
	}
#endif	/* USE_HYPRE */

	if (A0 != A)
	    phgMatDestroy(&A0);
#if 0
if (A->rmap->nglobal > 1000) {
    VEC *v = phgMapCreateVec(A->rmap, 3);
    for (i = 0; i < v->map->nlocal; i++) {
	v->data[i + 0 * v->map->nlocal] = 1 * (i + v->map->partition[g->rank]);
	v->data[i + 1 * v->map->nlocal] = 2 * (i + v->map->partition[g->rank]);
	v->data[i + 2 * v->map->nlocal] = 3 * (i + v->map->partition[g->rank]);
    }
    phgMatDumpMATLAB(A, "A", "A.m");
    phgVecDumpMATLAB(v, "v", "v.m");
    phgFinalize();
    exit(0);
}
#endif
	phgMatDestroy(&A);
	phgVecDestroy(&x);
	phgVecDestroy(&y0);
	phgVecDestroy(&y1);
	phgVecDestroy(&y2);
	phgMapDestroy(&map);
	mem = phgMemoryUsage(g, &mem_peak);
	dnz = mem / (1024.0 * 1024.0);
	dnz1 = mem_peak / (1024.0 * 1024.0);
	/*phgPrintf("    --------------------------------------------"
		  "-------------------------\n");*/
	phgPrintf("\n");
	phgPrintf("  Memory: current %0.4lgMB, peak %0.4lgMB\n", dnz, dnz1);
#if 0
{
    static int loop_count = 0;
    if (++loop_count == 4)
	break;
}
#endif
	if (mem_peak > 1024 * (size_t)1024 * mem_max)
	    break;
	phgRefineAllElements(g, 1);
    }
    phgDofFree(&u_h);
    phgFreeGrid(&g);
    phgFinalize();

    return 0;
}