1 2 static char help[] = "Tests binary I/O of vectors and illustrates the use of user-defined event logging.\n\n"; 3 4 #include <petscvec.h> 5 6 /* Note: Most applications would not read and write a vector within 7 the same program. This example is intended only to demonstrate 8 both input and output. */ 9 10 int main(int argc, char **args) { 11 PetscMPIInt rank, size; 12 PetscInt i, m = 10, low, high, ldim, iglobal; 13 PetscScalar v; 14 Vec u; 15 PetscViewer viewer; 16 #if defined(PETSC_USE_LOG) 17 PetscLogEvent VECTOR_GENERATE, VECTOR_READ; 18 #endif 19 20 PetscFunctionBeginUser; 21 PetscCall(PetscInitialize(&argc, &args, (char *)0, help)); 22 PetscCallMPI(MPI_Comm_rank(PETSC_COMM_WORLD, &rank)); 23 PetscCallMPI(MPI_Comm_size(PETSC_COMM_WORLD, &size)); 24 PetscCall(PetscOptionsGetInt(NULL, NULL, "-m", &m, NULL)); 25 26 /* PART 1: Generate vector, then write it in binary format */ 27 28 PetscCall(PetscLogEventRegister("Generate Vector", VEC_CLASSID, &VECTOR_GENERATE)); 29 PetscCall(PetscLogEventBegin(VECTOR_GENERATE, 0, 0, 0, 0)); 30 /* Generate vector */ 31 PetscCall(VecCreate(PETSC_COMM_WORLD, &u)); 32 PetscCall(VecSetSizes(u, PETSC_DECIDE, m)); 33 PetscCall(VecSetFromOptions(u)); 34 PetscCall(VecGetOwnershipRange(u, &low, &high)); 35 PetscCall(VecGetLocalSize(u, &ldim)); 36 for (i = 0; i < ldim; i++) { 37 iglobal = i + low; 38 v = (PetscScalar)(i + 100 * rank); 39 PetscCall(VecSetValues(u, 1, &iglobal, &v, INSERT_VALUES)); 40 } 41 PetscCall(VecAssemblyBegin(u)); 42 PetscCall(VecAssemblyEnd(u)); 43 PetscCall(VecView(u, PETSC_VIEWER_STDOUT_WORLD)); 44 45 PetscCall(PetscPrintf(PETSC_COMM_WORLD, "writing vector in binary to vector.dat ...\n")); 46 PetscCall(PetscViewerBinaryOpen(PETSC_COMM_WORLD, "vector.dat", FILE_MODE_WRITE, &viewer)); 47 PetscCall(VecView(u, viewer)); 48 PetscCall(PetscViewerDestroy(&viewer)); 49 PetscCall(VecDestroy(&u)); 50 PetscCall(PetscOptionsSetValue(NULL, "-viewer_binary_mpiio", "")); 51 52 PetscCall(PetscLogEventEnd(VECTOR_GENERATE, 0, 0, 0, 0)); 53 54 /* PART 2: Read in vector in binary format */ 55 56 /* Read new vector in binary format */ 57 PetscCall(PetscLogEventRegister("Read Vector", VEC_CLASSID, &VECTOR_READ)); 58 PetscCall(PetscLogEventBegin(VECTOR_READ, 0, 0, 0, 0)); 59 PetscCall(PetscPrintf(PETSC_COMM_WORLD, "reading vector in binary from vector.dat ...\n")); 60 PetscCall(PetscViewerBinaryOpen(PETSC_COMM_WORLD, "vector.dat", FILE_MODE_READ, &viewer)); 61 PetscCall(VecCreate(PETSC_COMM_WORLD, &u)); 62 PetscCall(VecLoad(u, viewer)); 63 PetscCall(PetscViewerDestroy(&viewer)); 64 PetscCall(PetscLogEventEnd(VECTOR_READ, 0, 0, 0, 0)); 65 PetscCall(VecView(u, PETSC_VIEWER_STDOUT_WORLD)); 66 67 /* Free data structures */ 68 PetscCall(VecDestroy(&u)); 69 PetscCall(PetscFinalize()); 70 return 0; 71 } 72 73 /*TEST 74 75 test: 76 nsize: 1 77 requires: mpiio 78 79 test: 80 suffix: 2 81 nsize: 2 82 requires: mpiio 83 84 TEST*/ 85