Actual source code: ex57.c


  2: static char help[] = "Reads in a binary file, extracts a submatrix from it, and writes to another binary file.\n\
  3: Options:\n\
  4:   -fin  <mat>  : input matrix file\n\
  5:   -fout <mat>  : output marrix file\n\
  6:   -start <row> : the row from where the submat should be extracted\n\
  7:   -m  <sx>  : the size of the submatrix\n";

  9: #include <petscmat.h>
 10: #include <petscvec.h>

 12: int main(int argc, char **args)
 13: {
 14:   char        fin[PETSC_MAX_PATH_LEN], fout[PETSC_MAX_PATH_LEN] = "default.mat";
 15:   PetscViewer fdin, fdout;
 16:   Vec         b;
 17:   MatType     mtype = MATSEQBAIJ;
 18:   Mat         A, *B;
 19:   PetscInt    start = 0;
 20:   PetscInt    m;
 21:   IS          isrow, iscol;
 22:   PetscBool   flg;

 24:   PetscFunctionBeginUser;
 25:   PetscCall(PetscInitialize(&argc, &args, (char *)0, help));
 26:   PetscCall(PetscOptionsGetString(NULL, NULL, "-fin", fin, sizeof(fin), &flg));
 27:   PetscCheck(flg, PETSC_COMM_WORLD, PETSC_ERR_USER, "Must indicate binary file with the -fin option");
 28:   PetscCall(PetscViewerBinaryOpen(PETSC_COMM_SELF, fin, FILE_MODE_READ, &fdin));

 30:   PetscCall(PetscOptionsGetString(NULL, NULL, "-fout", fout, sizeof(fout), &flg));
 31:   if (!flg) PetscCall(PetscPrintf(PETSC_COMM_WORLD, "Writing submatrix to file : %s\n", fout));
 32:   PetscCall(PetscViewerBinaryOpen(PETSC_COMM_SELF, fout, FILE_MODE_WRITE, &fdout));

 34:   PetscCall(MatCreate(PETSC_COMM_SELF, &A));
 35:   PetscCall(MatSetType(A, mtype));
 36:   PetscCall(MatLoad(A, fdin));
 37:   PetscCall(PetscViewerDestroy(&fdin));

 39:   PetscCall(MatGetSize(A, &m, &m));
 40:   m /= 2;
 41:   PetscCall(PetscOptionsGetInt(NULL, NULL, "-start", &start, NULL));
 42:   PetscCall(PetscOptionsGetInt(NULL, NULL, "-m", &m, NULL));

 44:   PetscCall(ISCreateStride(PETSC_COMM_SELF, m, start, 1, &isrow));
 45:   PetscCall(ISCreateStride(PETSC_COMM_SELF, m, start, 1, &iscol));
 46:   PetscCall(MatCreateSubMatrices(A, 1, &isrow, &iscol, MAT_INITIAL_MATRIX, &B));
 47:   PetscCall(MatView(B[0], fdout));

 49:   PetscCall(VecCreate(PETSC_COMM_SELF, &b));
 50:   PetscCall(VecSetSizes(b, PETSC_DECIDE, m));
 51:   PetscCall(VecSetFromOptions(b));
 52:   PetscCall(MatView(B[0], fdout));
 53:   PetscCall(PetscViewerDestroy(&fdout));

 55:   PetscCall(MatDestroy(&A));
 56:   PetscCall(MatDestroy(&B[0]));
 57:   PetscCall(VecDestroy(&b));
 58:   PetscCall(PetscFree(B));
 59:   PetscCall(ISDestroy(&iscol));
 60:   PetscCall(ISDestroy(&isrow));
 61:   PetscCall(PetscFinalize());
 62:   return 0;
 63: }

 65: /*TEST

 67:     test:
 68:       args: -fin ${DATAFILESPATH}/matrices/small -fout joe -start 2 -m 4
 69:       requires: datafilespath double !complex !defined(PETSC_USE_64BIT_INDICES)

 71: TEST*/