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 { 12 PetscMPIInt rank, size; 13 PetscInt i, m = 10, low, high, ldim, iglobal; 14 PetscScalar v; 15 Vec u; 16 PetscViewer viewer; 17 #if defined(PETSC_USE_LOG) 18 PetscLogEvent VECTOR_GENERATE, VECTOR_READ; 19 #endif 20 21 PetscFunctionBeginUser; 22 PetscCall(PetscInitialize(&argc, &args, (char *)0, help)); 23 PetscCallMPI(MPI_Comm_rank(PETSC_COMM_WORLD, &rank)); 24 PetscCallMPI(MPI_Comm_size(PETSC_COMM_WORLD, &size)); 25 PetscCall(PetscOptionsGetInt(NULL, NULL, "-m", &m, NULL)); 26 27 /* PART 1: Generate vector, then write it in binary format */ 28 29 PetscCall(PetscLogEventRegister("Generate Vector", VEC_CLASSID, &VECTOR_GENERATE)); 30 PetscCall(PetscLogEventBegin(VECTOR_GENERATE, 0, 0, 0, 0)); 31 /* Generate vector */ 32 PetscCall(VecCreate(PETSC_COMM_WORLD, &u)); 33 PetscCall(VecSetSizes(u, PETSC_DECIDE, m)); 34 PetscCall(VecSetFromOptions(u)); 35 PetscCall(VecGetOwnershipRange(u, &low, &high)); 36 PetscCall(VecGetLocalSize(u, &ldim)); 37 for (i = 0; i < ldim; i++) { 38 iglobal = i + low; 39 v = (PetscScalar)(i + 100 * rank); 40 PetscCall(VecSetValues(u, 1, &iglobal, &v, INSERT_VALUES)); 41 } 42 PetscCall(VecAssemblyBegin(u)); 43 PetscCall(VecAssemblyEnd(u)); 44 PetscCall(VecView(u, PETSC_VIEWER_STDOUT_WORLD)); 45 46 PetscCall(PetscPrintf(PETSC_COMM_WORLD, "writing vector in binary to vector.dat ...\n")); 47 PetscCall(PetscViewerBinaryOpen(PETSC_COMM_WORLD, "vector.dat", FILE_MODE_WRITE, &viewer)); 48 PetscCall(VecView(u, viewer)); 49 PetscCall(PetscViewerDestroy(&viewer)); 50 PetscCall(VecDestroy(&u)); 51 PetscCall(PetscOptionsSetValue(NULL, "-viewer_binary_mpiio", "")); 52 53 PetscCall(PetscLogEventEnd(VECTOR_GENERATE, 0, 0, 0, 0)); 54 55 /* PART 2: Read in vector in binary format */ 56 57 /* Read new vector in binary format */ 58 PetscCall(PetscLogEventRegister("Read Vector", VEC_CLASSID, &VECTOR_READ)); 59 PetscCall(PetscLogEventBegin(VECTOR_READ, 0, 0, 0, 0)); 60 PetscCall(PetscPrintf(PETSC_COMM_WORLD, "reading vector in binary from vector.dat ...\n")); 61 PetscCall(PetscViewerBinaryOpen(PETSC_COMM_WORLD, "vector.dat", FILE_MODE_READ, &viewer)); 62 PetscCall(VecCreate(PETSC_COMM_WORLD, &u)); 63 PetscCall(VecLoad(u, viewer)); 64 PetscCall(PetscViewerDestroy(&viewer)); 65 PetscCall(PetscLogEventEnd(VECTOR_READ, 0, 0, 0, 0)); 66 PetscCall(VecView(u, PETSC_VIEWER_STDOUT_WORLD)); 67 68 /* Free data structures */ 69 PetscCall(VecDestroy(&u)); 70 PetscCall(PetscFinalize()); 71 return 0; 72 } 73 74 /*TEST 75 76 test: 77 nsize: 1 78 requires: mpiio 79 80 test: 81 suffix: 2 82 nsize: 2 83 requires: mpiio 84 85 TEST*/ 86