Actual source code: pinit.c

petsc-dev 2014-08-28
Report Typos and Errors
  2: /*
  3:    This file defines the initialization of PETSc, including PetscInitialize()
  4: */
  5: #include <petsc-private/petscimpl.h>        /*I  "petscsys.h"   I*/
  6: #include <petscviewer.h>

  8: #if defined(PETSC_HAVE_CUDA)
  9: #include <cublas.h>
 10: #endif

 12: #include <petscthreadcomm.h>

 14: #if defined(PETSC_USE_LOG)
 15: extern PetscErrorCode PetscLogBegin_Private(void);
 16: #endif

 18: #if defined(PETSC_SERIALIZE_FUNCTIONS)
 19: PetscFPT PetscFPTData = 0;
 20: #endif

 22: #if defined(PETSC_HAVE_SAWS)
 23: #include <petscviewersaws.h>
 24: #endif
 25: /* -----------------------------------------------------------------------------------------*/

 27: extern FILE *petsc_history;

 29: extern PetscErrorCode PetscInitialize_DynamicLibraries(void);
 30: extern PetscErrorCode PetscFinalize_DynamicLibraries(void);
 31: extern PetscErrorCode PetscFunctionListPrintAll(void);
 32: extern PetscErrorCode PetscSequentialPhaseBegin_Private(MPI_Comm,int);
 33: extern PetscErrorCode PetscSequentialPhaseEnd_Private(MPI_Comm,int);
 34: extern PetscErrorCode PetscCloseHistoryFile(FILE**);

 36: /* user may set this BEFORE calling PetscInitialize() */
 37: MPI_Comm PETSC_COMM_WORLD = MPI_COMM_NULL;

 39: PetscMPIInt Petsc_Counter_keyval   = MPI_KEYVAL_INVALID;
 40: PetscMPIInt Petsc_InnerComm_keyval = MPI_KEYVAL_INVALID;
 41: PetscMPIInt Petsc_OuterComm_keyval = MPI_KEYVAL_INVALID;

 43: /*
 44:      Declare and set all the string names of the PETSc enums
 45: */
 46: const char *const PetscBools[]     = {"FALSE","TRUE","PetscBool","PETSC_",0};
 47: const char *const PetscCopyModes[] = {"COPY_VALUES","OWN_POINTER","USE_POINTER","PetscCopyMode","PETSC_",0};
 48: const char *const PetscDataTypes[] = {"INT","DOUBLE","COMPLEX","LONG","SHORT","FLOAT",
 49:                                       "CHAR","LOGICAL","ENUM","BOOL","LONGDOUBLE","OBJECT","FUNCTION","PetscDataType","PETSC_",0};

 51: PetscBool PetscPreLoadingUsed = PETSC_FALSE;
 52: PetscBool PetscPreLoadingOn   = PETSC_FALSE;

 54: PetscInt PetscHotRegionDepth;

 56: /*
 57:        Checks the options database for initializations related to the
 58:     PETSc components
 59: */
 62: PetscErrorCode  PetscOptionsCheckInitial_Components(void)
 63: {
 64:   PetscBool      flg1;

 68:   PetscOptionsHasName(NULL,"-help",&flg1);
 69:   if (flg1) {
 70: #if defined(PETSC_USE_LOG)
 71:     MPI_Comm comm = PETSC_COMM_WORLD;
 72:     (*PetscHelpPrintf)(comm,"------Additional PETSc component options--------\n");
 73:     (*PetscHelpPrintf)(comm," -log_summary_exclude: <vec,mat,pc.ksp,snes>\n");
 74:     (*PetscHelpPrintf)(comm," -info_exclude: <null,vec,mat,pc,ksp,snes,ts>\n");
 75:     (*PetscHelpPrintf)(comm,"-----------------------------------------------\n");
 76: #endif
 77:   }
 78:   return(0);
 79: }

 83: /*
 84:       PetscInitializeNoPointers - Calls PetscInitialize() from C/C++ without the pointers to argc and args

 86:    Collective

 88:    Level: advanced

 90:     Notes: this is called only by the PETSc MATLAB and Julia interface. Even though it might start MPI it sets the flag to
 91:      indicate that it did NOT start MPI so that the PetscFinalize() does not end MPI, thus allowing PetscInitialize() to
 92:      be called multiple times from MATLAB and Julia without the problem of trying to initialize MPI more than once.

 94:      Turns off PETSc signal handling because that can interact with MATLAB's signal handling causing random crashes.

 96: .seealso: PetscInitialize(), PetscInitializeFortran(), PetscInitializeNoArguments()
 97: */
 98: PetscErrorCode  PetscInitializeNoPointers(int argc,char **args,const char *filename,const char *help)
 99: {
101:   int            myargc   = argc;
102:   char           **myargs = args;

105:   PetscInitialize(&myargc,&myargs,filename,help);
106:   PetscPopSignalHandler();
107:   PetscBeganMPI = PETSC_FALSE;
108:   PetscFunctionReturn(ierr);
109: }

113: /*
114:       Used by MATLAB and Julia interface to get communicator
115: */
116: PetscErrorCode  PetscGetPETSC_COMM_SELF(MPI_Comm *comm)
117: {
119:   *comm = PETSC_COMM_SELF;
120:   return(0);
121: }

125: /*@C
126:       PetscInitializeNoArguments - Calls PetscInitialize() from C/C++ without
127:         the command line arguments.

129:    Collective

131:    Level: advanced

133: .seealso: PetscInitialize(), PetscInitializeFortran()
134: @*/
135: PetscErrorCode  PetscInitializeNoArguments(void)
136: {
138:   int            argc   = 0;
139:   char           **args = 0;

142:   PetscInitialize(&argc,&args,NULL,NULL);
143:   PetscFunctionReturn(ierr);
144: }

148: /*@
149:       PetscInitialized - Determine whether PETSc is initialized.

151:    Level: beginner

153: .seealso: PetscInitialize(), PetscInitializeNoArguments(), PetscInitializeFortran()
154: @*/
155: PetscErrorCode PetscInitialized(PetscBool  *isInitialized)
156: {
157:   *isInitialized = PetscInitializeCalled;
158:   return 0;
159: }

163: /*@
164:       PetscFinalized - Determine whether PetscFinalize() has been called yet

166:    Level: developer

168: .seealso: PetscInitialize(), PetscInitializeNoArguments(), PetscInitializeFortran()
169: @*/
170: PetscErrorCode  PetscFinalized(PetscBool  *isFinalized)
171: {
172:   *isFinalized = PetscFinalizeCalled;
173:   return 0;
174: }

176: extern PetscErrorCode PetscOptionsCheckInitial_Private(void);

178: /*
179:        This function is the MPI reduction operation used to compute the sum of the
180:    first half of the datatype and the max of the second half.
181: */
182: MPI_Op PetscMaxSum_Op = 0;

186: PETSC_EXTERN void MPIAPI PetscMaxSum_Local(void *in,void *out,int *cnt,MPI_Datatype *datatype)
187: {
188:   PetscInt *xin = (PetscInt*)in,*xout = (PetscInt*)out,i,count = *cnt;

191:   if (*datatype != MPIU_2INT) {
192:     (*PetscErrorPrintf)("Can only handle MPIU_2INT data types");
193:     MPI_Abort(MPI_COMM_WORLD,1);
194:   }

196:   for (i=0; i<count; i++) {
197:     xout[2*i]    = PetscMax(xout[2*i],xin[2*i]);
198:     xout[2*i+1] += xin[2*i+1];
199:   }
200:   PetscFunctionReturnVoid();
201: }

203: /*
204:     Returns the max of the first entry owned by this processor and the
205: sum of the second entry.

207:     The reason nprocs[2*i] contains lengths nprocs[2*i+1] contains flag of 1 if length is nonzero
208: is so that the PetscMaxSum_Op() can set TWO values, if we passed in only nprocs[i] with lengths
209: there would be no place to store the both needed results.
210: */
213: PetscErrorCode  PetscMaxSum(MPI_Comm comm,const PetscInt sizes[],PetscInt *max,PetscInt *sum)
214: {
215:   PetscMPIInt    size,rank;
216:   struct {PetscInt max,sum;} *work;

220:   MPI_Comm_size(comm,&size);
221:   MPI_Comm_rank(comm,&rank);
222:   PetscMalloc1(size,&work);
223:   MPI_Allreduce((void*)sizes,work,size,MPIU_2INT,PetscMaxSum_Op,comm);
224:   *max = work[rank].max;
225:   *sum = work[rank].sum;
226:   PetscFree(work);
227:   return(0);
228: }

230: /* ----------------------------------------------------------------------------*/
231: MPI_Op  PetscADMax_Op = 0;

235: PETSC_EXTERN void MPIAPI PetscADMax_Local(void *in,void *out,PetscMPIInt *cnt,MPI_Datatype *datatype)
236: {
237:   PetscScalar *xin = (PetscScalar*)in,*xout = (PetscScalar*)out;
238:   PetscInt    i,count = *cnt;

241:   if (*datatype != MPIU_2SCALAR) {
242:     (*PetscErrorPrintf)("Can only handle MPIU_2SCALAR data (i.e. double or complex) types");
243:     MPI_Abort(MPI_COMM_WORLD,1);
244:   }

246:   for (i=0; i<count; i++) {
247:     if (PetscRealPart(xout[2*i]) < PetscRealPart(xin[2*i])) {
248:       xout[2*i]   = xin[2*i];
249:       xout[2*i+1] = xin[2*i+1];
250:     }
251:   }
252:   PetscFunctionReturnVoid();
253: }

255: MPI_Op PetscADMin_Op = 0;

259: PETSC_EXTERN void MPIAPI PetscADMin_Local(void *in,void *out,PetscMPIInt *cnt,MPI_Datatype *datatype)
260: {
261:   PetscScalar *xin = (PetscScalar*)in,*xout = (PetscScalar*)out;
262:   PetscInt    i,count = *cnt;

265:   if (*datatype != MPIU_2SCALAR) {
266:     (*PetscErrorPrintf)("Can only handle MPIU_2SCALAR data (i.e. double or complex) types");
267:     MPI_Abort(MPI_COMM_WORLD,1);
268:   }

270:   for (i=0; i<count; i++) {
271:     if (PetscRealPart(xout[2*i]) > PetscRealPart(xin[2*i])) {
272:       xout[2*i]   = xin[2*i];
273:       xout[2*i+1] = xin[2*i+1];
274:     }
275:   }
276:   PetscFunctionReturnVoid();
277: }
278: /* ---------------------------------------------------------------------------------------*/

280: #if (defined(PETSC_HAVE_COMPLEX) && !defined(PETSC_HAVE_MPI_C_DOUBLE_COMPLEX)) || defined(PETSC_USE_REAL___FLOAT128)
281: MPI_Op MPIU_SUM = 0;

285: PETSC_EXTERN void PetscSum_Local(void *in,void *out,PetscMPIInt *cnt,MPI_Datatype *datatype)
286: {
287:   PetscInt i,count = *cnt;

290:   if (*datatype == MPIU_REAL) {
291:     PetscReal *xin = (PetscReal*)in,*xout = (PetscReal*)out;
292:     for (i=0; i<count; i++) xout[i] += xin[i];
293:   }
294: #if defined(PETSC_HAVE_COMPLEX)
295:   else if (*datatype == MPIU_COMPLEX) {
296:     PetscComplex *xin = (PetscComplex*)in,*xout = (PetscComplex*)out;
297:     for (i=0; i<count; i++) xout[i] += xin[i];
298:   }
299: #endif
300:   else {
301:     (*PetscErrorPrintf)("Can only handle MPIU_REAL or MPIU_COMPLEX data types");
302:     MPI_Abort(MPI_COMM_WORLD,1);
303:   }
304:   PetscFunctionReturnVoid();
305: }
306: #endif

308: #if defined(PETSC_USE_REAL___FLOAT128)
309: MPI_Op MPIU_MAX = 0;
310: MPI_Op MPIU_MIN = 0;

314: PETSC_EXTERN void PetscMax_Local(void *in,void *out,PetscMPIInt *cnt,MPI_Datatype *datatype)
315: {
316:   PetscInt i,count = *cnt;

319:   if (*datatype == MPIU_REAL) {
320:     PetscReal *xin = (PetscReal*)in,*xout = (PetscReal*)out;
321:     for (i=0; i<count; i++) xout[i] = PetscMax(xout[i],xin[i]);
322:   }
323: #if defined(PETSC_HAVE_COMPLEX)
324:   else if (*datatype == MPIU_COMPLEX) {
325:     PetscComplex *xin = (PetscComplex*)in,*xout = (PetscComplex*)out;
326:     for (i=0; i<count; i++) {
327:       xout[i] = PetscRealPartComplex(xout[i])<PetscRealPartComplex(xin[i]) ? xin[i] : xout[i];
328:     }
329:   }
330: #endif
331:   else {
332:     (*PetscErrorPrintf)("Can only handle MPIU_REAL or MPIU_COMPLEX data types");
333:     MPI_Abort(MPI_COMM_WORLD,1);
334:   }
335:   PetscFunctionReturnVoid();
336: }

340: PETSC_EXTERN void PetscMin_Local(void *in,void *out,PetscMPIInt *cnt,MPI_Datatype *datatype)
341: {
342:   PetscInt    i,count = *cnt;

345:   if (*datatype == MPIU_REAL) {
346:     PetscReal *xin = (PetscReal*)in,*xout = (PetscReal*)out;
347:     for (i=0; i<count; i++) xout[i] = PetscMin(xout[i],xin[i]);
348:   }
349: #if defined(PETSC_HAVE_COMPLEX)
350:   else if (*datatype == MPIU_COMPLEX) {
351:     PetscComplex *xin = (PetscComplex*)in,*xout = (PetscComplex*)out;
352:     for (i=0; i<count; i++) {
353:       xout[i] = PetscRealPartComplex(xout[i])>PetscRealPartComplex(xin[i]) ? xin[i] : xout[i];
354:     }
355:   }
356: #endif
357:   else {
358:     (*PetscErrorPrintf)("Can only handle MPIU_REAL or MPIU_SCALAR data (i.e. double or complex) types");
359:     MPI_Abort(MPI_COMM_WORLD,1);
360:   }
361:   PetscFunctionReturnVoid();
362: }
363: #endif

367: /*
368:    Private routine to delete internal tag/name counter storage when a communicator is freed.

370:    This is called by MPI, not by users. This is called by MPI_Comm_free() when the communicator that has this  data as an attribute is freed.

372:    Note: this is declared extern "C" because it is passed to MPI_Keyval_create()

374: */
375: PETSC_EXTERN PetscMPIInt MPIAPI Petsc_DelCounter(MPI_Comm comm,PetscMPIInt keyval,void *count_val,void *extra_state)
376: {

380:   PetscInfo1(0,"Deleting counter data in an MPI_Comm %ld\n",(long)comm);if (ierr) PetscFunctionReturn((PetscMPIInt)ierr);
381:   PetscFree(count_val);if (ierr) PetscFunctionReturn((PetscMPIInt)ierr);
382:   PetscFunctionReturn(MPI_SUCCESS);
383: }

387: /*
388:   This is invoked on the outer comm as a result of either PetscCommDestroy() (via MPI_Attr_delete) or when the user
389:   calls MPI_Comm_free().

391:   This is the only entry point for breaking the links between inner and outer comms.

393:   This is called by MPI, not by users. This is called when MPI_Comm_free() is called on the communicator.

395:   Note: this is declared extern "C" because it is passed to MPI_Keyval_create()

397: */
398: PETSC_EXTERN PetscMPIInt MPIAPI Petsc_DelComm_Outer(MPI_Comm comm,PetscMPIInt keyval,void *attr_val,void *extra_state)
399: {
401:   PetscMPIInt    flg;
402:   union {MPI_Comm comm; void *ptr;} icomm,ocomm;

405:   if (keyval != Petsc_InnerComm_keyval) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_CORRUPT,"Unexpected keyval");
406:   icomm.ptr = attr_val;

408:   MPI_Attr_get(icomm.comm,Petsc_OuterComm_keyval,&ocomm,&flg);
409:   if (!flg) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_CORRUPT,"Inner MPI_Comm does not have expected reference to outer comm");
410:   if (ocomm.comm != comm) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_CORRUPT,"Inner MPI_Comm has reference to non-matching outer comm");
411:   MPI_Attr_delete(icomm.comm,Petsc_OuterComm_keyval); /* Calls Petsc_DelComm_Inner */
412:   PetscInfo1(0,"User MPI_Comm %ld is being freed after removing reference from inner PETSc comm to this outer comm\n",(long)comm);if (ierr) PetscFunctionReturn((PetscMPIInt)ierr);
413:   PetscFunctionReturn(MPI_SUCCESS);
414: }

418: /*
419:  * This is invoked on the inner comm when Petsc_DelComm_Outer calls MPI_Attr_delete.  It should not be reached any other way.
420:  */
421: PETSC_EXTERN PetscMPIInt MPIAPI Petsc_DelComm_Inner(MPI_Comm comm,PetscMPIInt keyval,void *attr_val,void *extra_state)
422: {

426:   PetscInfo1(0,"Removing reference to PETSc communicator embedded in a user MPI_Comm %ld\n",(long)comm);if (ierr) PetscFunctionReturn((PetscMPIInt)ierr);
427:   PetscFunctionReturn(MPI_SUCCESS);
428: }

430: #if defined(PETSC_USE_PETSC_MPI_EXTERNAL32)
431: #if !defined(PETSC_WORDS_BIGENDIAN)
432: PETSC_EXTERN PetscMPIInt PetscDataRep_extent_fn(MPI_Datatype,MPI_Aint*,void*);
433: PETSC_EXTERN PetscMPIInt PetscDataRep_read_conv_fn(void*, MPI_Datatype,PetscMPIInt,void*,MPI_Offset,void*);
434: PETSC_EXTERN PetscMPIInt PetscDataRep_write_conv_fn(void*, MPI_Datatype,PetscMPIInt,void*,MPI_Offset,void*);
435: #endif
436: #endif

438: int  PetscGlobalArgc   = 0;
439: char **PetscGlobalArgs = 0;
440: PetscSegBuffer PetscCitationsList;

444: PetscErrorCode PetscCitationsInitialize()
445: {

449:   PetscSegBufferCreate(1,10000,&PetscCitationsList);
450:   PetscCitationsRegister("@TechReport{petsc-user-ref,\n  Author = {Satish Balay and Shrirang Abhyankar and Mark F. Adams and Jed Brown and Peter Brune\n            and Kris Buschelman and Victor Eijkhout and William D. Gropp\n            and Dinesh Kaushik and Matthew G. Knepley\n            and Lois Curfman McInnes and Karl Rupp and Barry F. Smith\n            and Hong Zhang},\n  Title = {{PETS}c Users Manual},\n  Number = {ANL-95/11 - Revision 3.5},\n  Institution = {Argonne National Laboratory},\n  Year = {2014}\n}\n",NULL);
451:   PetscCitationsRegister("@InProceedings{petsc-efficient,\n  Author = {Satish Balay and William D. Gropp and Lois Curfman McInnes and Barry F. Smith},\n  Title = {Efficient Management of Parallelism in Object Oriented Numerical Software Libraries},\n  Booktitle = {Modern Software Tools in Scientific Computing},\n  Editor = {E. Arge and A. M. Bruaset and H. P. Langtangen},\n  Pages = {163--202},\n  Publisher = {Birkh{\\\"{a}}user Press},\n  Year = {1997}\n}\n",NULL);
452:   return(0);
453: }

457: /*@C
458:    PetscGetArgs - Allows you to access the raw command line arguments anywhere
459:      after PetscInitialize() is called but before PetscFinalize().

461:    Not Collective

463:    Output Parameters:
464: +  argc - count of number of command line arguments
465: -  args - the command line arguments

467:    Level: intermediate

469:    Notes:
470:       This is usually used to pass the command line arguments into other libraries
471:    that are called internally deep in PETSc or the application.

473:       The first argument contains the program name as is normal for C arguments.

475:    Concepts: command line arguments

477: .seealso: PetscFinalize(), PetscInitializeFortran(), PetscGetArguments()

479: @*/
480: PetscErrorCode  PetscGetArgs(int *argc,char ***args)
481: {
483:   if (!PetscInitializeCalled && PetscFinalizeCalled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ORDER,"You must call after PetscInitialize() but before PetscFinalize()");
484:   *argc = PetscGlobalArgc;
485:   *args = PetscGlobalArgs;
486:   return(0);
487: }

491: /*@C
492:    PetscGetArguments - Allows you to access the  command line arguments anywhere
493:      after PetscInitialize() is called but before PetscFinalize().

495:    Not Collective

497:    Output Parameters:
498: .  args - the command line arguments

500:    Level: intermediate

502:    Notes:
503:       This does NOT start with the program name and IS null terminated (final arg is void)

505:    Concepts: command line arguments

507: .seealso: PetscFinalize(), PetscInitializeFortran(), PetscGetArgs(), PetscFreeArguments()

509: @*/
510: PetscErrorCode  PetscGetArguments(char ***args)
511: {
512:   PetscInt       i,argc = PetscGlobalArgc;

516:   if (!PetscInitializeCalled && PetscFinalizeCalled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ORDER,"You must call after PetscInitialize() but before PetscFinalize()");
517:   if (!argc) {*args = 0; return(0);}
518:   PetscMalloc1(argc,args);
519:   for (i=0; i<argc-1; i++) {
520:     PetscStrallocpy(PetscGlobalArgs[i+1],&(*args)[i]);
521:   }
522:   (*args)[argc-1] = 0;
523:   return(0);
524: }

528: /*@C
529:    PetscFreeArguments - Frees the memory obtained with PetscGetArguments()

531:    Not Collective

533:    Output Parameters:
534: .  args - the command line arguments

536:    Level: intermediate

538:    Concepts: command line arguments

540: .seealso: PetscFinalize(), PetscInitializeFortran(), PetscGetArgs(), PetscGetArguments()

542: @*/
543: PetscErrorCode  PetscFreeArguments(char **args)
544: {
545:   PetscInt       i = 0;

549:   if (!args) return(0);
550:   while (args[i]) {
551:     PetscFree(args[i]);
552:     i++;
553:   }
554:   PetscFree(args);
555:   return(0);
556: }

558: #if defined(PETSC_HAVE_SAWS)
559: #include <petscconfiginfo.h>

563: PetscErrorCode  PetscInitializeSAWs(const char help[])
564: {
565:   if (!PetscGlobalRank) {
566:     char           cert[PETSC_MAX_PATH_LEN],root[PETSC_MAX_PATH_LEN],*intro,programname[64],*appline,*options,version[64];
567:     int            port;
568:     PetscBool      flg,rootlocal = PETSC_FALSE,flg2;
569:     size_t         applinelen,introlen;

572:     PetscOptionsHasName(NULL,"-saws_log",&flg);
573:     if (flg) {
574:       char  sawslog[PETSC_MAX_PATH_LEN];

576:       PetscOptionsGetString(NULL,"-saws_log",sawslog,PETSC_MAX_PATH_LEN,NULL);
577:       if (sawslog[0]) {
578:         PetscStackCallSAWs(SAWs_Set_Use_Logfile,(sawslog));
579:       } else {
580:         PetscStackCallSAWs(SAWs_Set_Use_Logfile,(NULL));
581:       }
582:     }
583:     PetscOptionsGetString(NULL,"-saws_https",cert,PETSC_MAX_PATH_LEN,&flg);
584:     if (flg) {
585:       PetscStackCallSAWs(SAWs_Set_Use_HTTPS,(cert));
586:     }
587:     PetscOptionsGetInt(NULL,"-saws_port",&port,&flg);
588:     if (flg) {
589:       PetscStackCallSAWs(SAWs_Set_Port,(port));
590:     }
591:     PetscOptionsGetString(NULL,"-saws_root",root,PETSC_MAX_PATH_LEN,&flg);
592:     if (flg) {
593:       PetscStackCallSAWs(SAWs_Set_Document_Root,(root));
594:       PetscStrcmp(root,".",&rootlocal);
595:     }
596:     PetscOptionsHasName(NULL,"-saws_local",&flg2);
597:     if (flg2) {
598:       char jsdir[PETSC_MAX_PATH_LEN];
599:       if (!flg) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"-saws_local option requires -saws_root option");
600:       PetscSNPrintf(jsdir,PETSC_MAX_PATH_LEN,"%s/js",root);
601:       PetscTestDirectory(jsdir,'r',&flg);
602:       if (!flg) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_FILE_READ,"-saws_local option requires js directory in root directory");
603:       PetscStackCallSAWs(SAWs_Push_Local_Header,());
604:     }
605:     PetscGetProgramName(programname,64);
606:     PetscStrlen(help,&applinelen);
607:     introlen   = 4096 + applinelen;
608:     applinelen += 256;
609:     PetscMalloc(applinelen,&appline);
610:     PetscMalloc(introlen,&intro);

612:     if (rootlocal) {
613:       PetscSNPrintf(appline,applinelen,"%s.c.html",programname);
614:       PetscTestFile(appline,'r',&rootlocal);
615:     }
616:     PetscOptionsGetAll(&options);
617:     if (rootlocal && help) {
618:       PetscSNPrintf(appline,applinelen,"<center> Running <a href=\"%s.c.html\">%s</a> %s</center><br><center><pre>%s</pre></center><br>\n",programname,programname,options,help);
619:     } else if (help) {
620:       PetscSNPrintf(appline,applinelen,"<center>Running %s %s</center><br><center><pre>%s</pre></center><br>\n",programname,options,help);
621:     } else {
622:       PetscSNPrintf(appline,applinelen,"<center> Running %s %s</center><br>\n",programname,options);
623:     }
624:     PetscFree(options);
625:     PetscGetVersion(version,sizeof(version));
626:     PetscSNPrintf(intro,introlen,"<body>\n"
627:                                     "<center><h2> <a href=\"http://www.mcs.anl.gov/petsc\">PETSc</a> Application Web server powered by <a href=\"https://bitbucket.org/saws/saws\">SAWs</a> </h2></center>\n"
628:                                     "<center>This is the default PETSc application dashboard, from it you can access any published PETSc objects or logging data</center><br><center>%s configured with %s</center><br>\n"
629:                                     "%s",version,petscconfigureoptions,appline);
630:     PetscStackCallSAWs(SAWs_Push_Body,("index.html",0,intro));
631:     PetscFree(intro);
632:     PetscFree(appline);
633:     PetscStackCallSAWs(SAWs_Initialize,());
634:     PetscCitationsRegister("@TechReport{ saws,\n"
635:                                   "  Author = {Matt Otten and Jed Brown and Barry Smith},\n"
636:                                   "  Title  = {Scientific Application Web Server (SAWs) Users Manual},\n"
637:                                   "  Institution = {Argonne National Laboratory},\n"
638:                                   "  Year   = 2013\n}\n",NULL);
639:   }
640:   return(0);
641: }
642: #endif

646: /*@C
647:    PetscInitialize - Initializes the PETSc database and MPI.
648:    PetscInitialize() calls MPI_Init() if that has yet to be called,
649:    so this routine should always be called near the beginning of
650:    your program -- usually the very first line!

652:    Collective on MPI_COMM_WORLD or PETSC_COMM_WORLD if it has been set

654:    Input Parameters:
655: +  argc - count of number of command line arguments
656: .  args - the command line arguments
657: .  file - [optional] PETSc database file, also checks ~username/.petscrc and .petscrc use NULL to not check for
658:           code specific file. Use -skip_petscrc in the code specific file to skip the .petscrc files
659: -  help - [optional] Help message to print, use NULL for no message

661:    If you wish PETSc code to run ONLY on a subcommunicator of MPI_COMM_WORLD, create that
662:    communicator first and assign it to PETSC_COMM_WORLD BEFORE calling PetscInitialize(). Thus if you are running a
663:    four process job and two processes will run PETSc and have PetscInitialize() and PetscFinalize() and two process will not,
664:    then do this. If ALL processes in the job are using PetscInitialize() and PetscFinalize() then you don't need to do this, even
665:    if different subcommunicators of the job are doing different things with PETSc.

667:    Options Database Keys:
668: +  -start_in_debugger [noxterm,dbx,xdb,gdb,...] - Starts program in debugger
669: .  -on_error_attach_debugger [noxterm,dbx,xdb,gdb,...] - Starts debugger when error detected
670: .  -on_error_emacs <machinename> causes emacsclient to jump to error file
671: .  -on_error_abort calls abort() when error detected (no traceback)
672: .  -on_error_mpiabort calls MPI_abort() when error detected
673: .  -error_output_stderr prints error messages to stderr instead of the default stdout
674: .  -error_output_none does not print the error messages (but handles errors in the same way as if this was not called)
675: .  -debugger_nodes [node1,node2,...] - Indicates nodes to start in debugger
676: .  -debugger_pause [sleeptime] (in seconds) - Pauses debugger
677: .  -stop_for_debugger - Print message on how to attach debugger manually to
678:                         process and wait (-debugger_pause) seconds for attachment
679: .  -malloc - Indicates use of PETSc error-checking malloc (on by default for debug version of libraries)
680: .  -malloc no - Indicates not to use error-checking malloc
681: .  -malloc_debug - check for memory corruption at EVERY malloc or free
682: .  -malloc_dump - prints a list of all unfreed memory at the end of the run
683: .  -malloc_test - like -malloc_dump -malloc_debug, but only active for debugging builds
684: .  -fp_trap - Stops on floating point exceptions (Note that on the
685:               IBM RS6000 this slows code by at least a factor of 10.)
686: .  -no_signal_handler - Indicates not to trap error signals
687: .  -shared_tmp - indicates /tmp directory is shared by all processors
688: .  -not_shared_tmp - each processor has own /tmp
689: .  -tmp - alternative name of /tmp directory
690: .  -get_total_flops - returns total flops done by all processors
691: -  -memory_info - Print memory usage at end of run

693:    Options Database Keys for Profiling:
694:    See Users-Manual: Chapter 12 Profiling for details.
695: +  -info <optional filename> - Prints verbose information to the screen
696: .  -info_exclude <null,vec,mat,pc,ksp,snes,ts> - Excludes some of the verbose messages
697: .  -log_sync - Log the synchronization in scatters, inner products and norms
698: .  -log_trace [filename] - Print traces of all PETSc calls to the screen (useful to determine where a program
699:         hangs without running in the debugger).  See PetscLogTraceBegin().
700: .  -log_summary [filename] - Prints summary of flop and timing information to screen. If the filename is specified the
701:         summary is written to the file.  See PetscLogView().
702: .  -log_all [filename] - Logs extensive profiling information  See PetscLogDump().
703: .  -log [filename] - Logs basic profiline information  See PetscLogDump().
704: -  -log_mpe [filename] - Creates a logfile viewable by the utility Jumpshot (in MPICH distribution)

706:     Only one of -log_trace, -log_summary, -log_all, -log, or -log_mpe may be used at a time

708:    Environmental Variables:
709: +   PETSC_TMP - alternative tmp directory
710: .   PETSC_SHARED_TMP - tmp is shared by all processes
711: .   PETSC_NOT_SHARED_TMP - each process has its own private tmp
712: .   PETSC_VIEWER_SOCKET_PORT - socket number to use for socket viewer
713: -   PETSC_VIEWER_SOCKET_MACHINE - machine to use for socket viewer to connect to


716:    Level: beginner

718:    Notes:
719:    If for some reason you must call MPI_Init() separately, call
720:    it before PetscInitialize().

722:    Fortran Version:
723:    In Fortran this routine has the format
724: $       call PetscInitialize(file,ierr)

726: +   ierr - error return code
727: -  file - [optional] PETSc database file, also checks ~username/.petscrc and .petscrc use NULL_CHARACTER to not check for
728:           code specific file. Use -skip_petscrc in the code specific file to skip the .petscrc files

730:    Important Fortran Note:
731:    In Fortran, you MUST use NULL_CHARACTER to indicate a
732:    null character string; you CANNOT just use NULL as
733:    in the C version. See Users-Manual: Chapter 11 PETSc for Fortran Users for details.

735:    If your main program is C but you call Fortran code that also uses PETSc you need to call PetscInitializeFortran() soon after
736:    calling PetscInitialize().

738:    Concepts: initializing PETSc

740: .seealso: PetscFinalize(), PetscInitializeFortran(), PetscGetArgs(), PetscInitializeNoArguments()

742: @*/
743: PetscErrorCode  PetscInitialize(int *argc,char ***args,const char file[],const char help[])
744: {
746:   PetscMPIInt    flag, size;
747:   PetscBool      flg;
748:   char           hostname[256];

751:   if (PetscInitializeCalled) return(0);

753:   /* these must be initialized in a routine, not as a constant declaration*/
754:   PETSC_STDOUT = stdout;
755:   PETSC_STDERR = stderr;

757:   /* on Windows - set printf to default to printing 2 digit exponents */
758: #if defined(PETSC_HAVE__SET_OUTPUT_FORMAT)
759:   _set_output_format(_TWO_DIGIT_EXPONENT);
760: #endif

762:   PetscOptionsCreate();

764:   /*
765:      We initialize the program name here (before MPI_Init()) because MPICH has a bug in
766:      it that it sets args[0] on all processors to be args[0] on the first processor.
767:   */
768:   if (argc && *argc) {
769:     PetscSetProgramName(**args);
770:   } else {
771:     PetscSetProgramName("Unknown Name");
772:   }

774:   MPI_Initialized(&flag);
775:   if (!flag) {
776:     if (PETSC_COMM_WORLD != MPI_COMM_NULL) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"You cannot set PETSC_COMM_WORLD if you have not initialized MPI first");
777: #if defined(PETSC_HAVE_MPI_INIT_THREAD)
778:     {
779:       PetscMPIInt provided;
780:       MPI_Init_thread(argc,args,MPI_THREAD_FUNNELED,&provided);
781:     }
782: #else
783:     MPI_Init(argc,args);
784: #endif
785:     PetscBeganMPI = PETSC_TRUE;
786:   }
787:   if (argc && args) {
788:     PetscGlobalArgc = *argc;
789:     PetscGlobalArgs = *args;
790:   }
791:   PetscFinalizeCalled = PETSC_FALSE;

793:   if (PETSC_COMM_WORLD == MPI_COMM_NULL) PETSC_COMM_WORLD = MPI_COMM_WORLD;
794:   MPI_Comm_set_errhandler(PETSC_COMM_WORLD,MPI_ERRORS_RETURN);

796:   /* Done after init due to a bug in MPICH-GM? */
797:   PetscErrorPrintfInitialize();

799:   MPI_Comm_rank(MPI_COMM_WORLD,&PetscGlobalRank);
800:   MPI_Comm_size(MPI_COMM_WORLD,&PetscGlobalSize);

802:   MPIU_BOOL = MPI_INT;
803:   MPIU_ENUM = MPI_INT;

805:   /*
806:      Initialized the global complex variable; this is because with
807:      shared libraries the constructors for global variables
808:      are not called; at least on IRIX.
809:   */
810: #if defined(PETSC_HAVE_COMPLEX)
811:   {
812: #if defined(PETSC_CLANGUAGE_CXX)
813:     PetscComplex ic(0.0,1.0);
814:     PETSC_i = ic;
815: #elif defined(PETSC_CLANGUAGE_C)
816:     PETSC_i = _Complex_I;
817: #endif
818:   }

820: #if !defined(PETSC_HAVE_MPI_C_DOUBLE_COMPLEX)
821:   MPI_Type_contiguous(2,MPI_DOUBLE,&MPIU_C_DOUBLE_COMPLEX);
822:   MPI_Type_commit(&MPIU_C_DOUBLE_COMPLEX);
823:   MPI_Type_contiguous(2,MPI_FLOAT,&MPIU_C_COMPLEX);
824:   MPI_Type_commit(&MPIU_C_COMPLEX);
825: #endif
826: #endif /* PETSC_HAVE_COMPLEX */

828:   /*
829:      Create the PETSc MPI reduction operator that sums of the first
830:      half of the entries and maxes the second half.
831:   */
832:   MPI_Op_create(PetscMaxSum_Local,1,&PetscMaxSum_Op);

834: #if defined(PETSC_USE_REAL___FLOAT128)
835:   MPI_Type_contiguous(2,MPI_DOUBLE,&MPIU___FLOAT128);
836:   MPI_Type_commit(&MPIU___FLOAT128);
837: #if defined(PETSC_HAVE_COMPLEX)
838:   MPI_Type_contiguous(4,MPI_DOUBLE,&MPIU___COMPLEX128);
839:   MPI_Type_commit(&MPIU___COMPLEX128);
840: #endif
841:   MPI_Op_create(PetscMax_Local,1,&MPIU_MAX);
842:   MPI_Op_create(PetscMin_Local,1,&MPIU_MIN);
843: #endif

845: #if (defined(PETSC_HAVE_COMPLEX) && !defined(PETSC_HAVE_MPI_C_DOUBLE_COMPLEX)) || defined(PETSC_USE_REAL___FLOAT128)
846:   MPI_Op_create(PetscSum_Local,1,&MPIU_SUM);
847: #endif

849:   MPI_Type_contiguous(2,MPIU_SCALAR,&MPIU_2SCALAR);
850:   MPI_Type_commit(&MPIU_2SCALAR);
851:   MPI_Op_create(PetscADMax_Local,1,&PetscADMax_Op);
852:   MPI_Op_create(PetscADMin_Local,1,&PetscADMin_Op);

854: #if defined(PETSC_USE_64BIT_INDICES) || !defined(MPI_2INT)
855:   MPI_Type_contiguous(2,MPIU_INT,&MPIU_2INT);
856:   MPI_Type_commit(&MPIU_2INT);
857: #endif


860:   /*
861:      Attributes to be set on PETSc communicators
862:   */
863:   MPI_Keyval_create(MPI_NULL_COPY_FN,Petsc_DelCounter,&Petsc_Counter_keyval,(void*)0);
864:   MPI_Keyval_create(MPI_NULL_COPY_FN,Petsc_DelComm_Outer,&Petsc_InnerComm_keyval,(void*)0);
865:   MPI_Keyval_create(MPI_NULL_COPY_FN,Petsc_DelComm_Inner,&Petsc_OuterComm_keyval,(void*)0);

867:   /*
868:      Build the options database
869:   */
870:   PetscOptionsInsert(argc,args,file);


873:   /*
874:      Print main application help message
875:   */
876:   PetscOptionsHasName(NULL,"-help",&flg);
877:   if (help && flg) {
878:     PetscPrintf(PETSC_COMM_WORLD,help);
879:   }
880:   PetscOptionsCheckInitial_Private();

882:   PetscCitationsInitialize();

884: #if defined(PETSC_HAVE_SAWS)
885:   PetscInitializeSAWs(help);
886: #endif

888:   /* SHOULD PUT IN GUARDS: Make sure logging is initialized, even if we do not print it out */
889: #if defined(PETSC_USE_LOG)
890:   PetscLogBegin_Private();
891: #endif

893:   /*
894:      Load the dynamic libraries (on machines that support them), this registers all
895:      the solvers etc. (On non-dynamic machines this initializes the PetscDraw and PetscViewer classes)
896:   */
897:   PetscInitialize_DynamicLibraries();

899:   MPI_Comm_size(PETSC_COMM_WORLD,&size);
900:   PetscInfo1(0,"PETSc successfully started: number of processors = %d\n",size);
901:   PetscGetHostName(hostname,256);
902:   PetscInfo1(0,"Running on machine: %s\n",hostname);

904:   /* Ensure that threadcomm-related keyval exists, so that PetscOptionsSetFromOptions can use PetscCommDuplicate. */
905:   PetscThreadCommInitializePackage();

907:   PetscOptionsCheckInitial_Components();
908:   /* Check the options database for options related to the options database itself */
909:   PetscOptionsSetFromOptions();

911: #if defined(PETSC_USE_PETSC_MPI_EXTERNAL32)
912:   /*
913:       Tell MPI about our own data representation converter, this would/should be used if extern32 is not supported by the MPI

915:       Currently not used because it is not supported by MPICH.
916:   */
917: #if !defined(PETSC_WORDS_BIGENDIAN)
918:   MPI_Register_datarep((char*)"petsc",PetscDataRep_read_conv_fn,PetscDataRep_write_conv_fn,PetscDataRep_extent_fn,NULL);
919: #endif
920: #endif

922: #if defined(PETSC_HAVE_CUDA)
923:   flg  = PETSC_TRUE;
924:   PetscOptionsGetBool(NULL,"-cublas",&flg,NULL);
925:   if (flg) {
926:     PetscMPIInt p;
927:     for (p = 0; p < PetscGlobalSize; ++p) {
928:       if (p == PetscGlobalRank) cublasInit();
929:       MPI_Barrier(PETSC_COMM_WORLD);
930:     }
931:   }
932: #endif

934:   PetscOptionsHasName(NULL,"-python",&flg);
935:   if (flg) {
936:     PetscInitializeCalled = PETSC_TRUE;
937:     PetscPythonInitialize(NULL,NULL);
938:   }

940:   /*
941:       Setup building of stack frames for all function calls
942:   */
943:   PetscThreadLocalRegister((PetscThreadKey*)&petscstack); /* Creates pthread_key */
944: #if defined(PETSC_USE_DEBUG)
945:   PetscStackCreate();
946: #endif

948: #if defined(PETSC_SERIALIZE_FUNCTIONS)
949:   PetscFPTCreate(10000);
950: #endif


953:   /*
954:       Once we are completedly initialized then we can set this variables
955:   */
956:   PetscInitializeCalled = PETSC_TRUE;
957:   return(0);
958: }

960: #if defined(PETSC_USE_LOG)
961: extern PetscObject *PetscObjects;
962: extern PetscInt    PetscObjectsCounts, PetscObjectsMaxCounts;
963: #endif

967: /*@C
968:    PetscFinalize - Checks for options to be called at the conclusion
969:    of the program. MPI_Finalize() is called only if the user had not
970:    called MPI_Init() before calling PetscInitialize().

972:    Collective on PETSC_COMM_WORLD

974:    Options Database Keys:
975: +  -options_table - Calls PetscOptionsView()
976: .  -options_left - Prints unused options that remain in the database
977: .  -objects_dump [all] - Prints list of objects allocated by the user that have not been freed, the option all cause all outstanding objects to be listed
978: .  -mpidump - Calls PetscMPIDump()
979: .  -malloc_dump - Calls PetscMallocDump()
980: .  -malloc_info - Prints total memory usage
981: -  -malloc_log - Prints summary of memory usage

983:    Level: beginner

985:    Note:
986:    See PetscInitialize() for more general runtime options.

988: .seealso: PetscInitialize(), PetscOptionsView(), PetscMallocDump(), PetscMPIDump(), PetscEnd()
989: @*/
990: PetscErrorCode  PetscFinalize(void)
991: {
993:   PetscMPIInt    rank;
994:   PetscInt       nopt;
995:   PetscBool      flg1 = PETSC_FALSE,flg2 = PETSC_FALSE,flg3 = PETSC_FALSE;
996:   PetscBool      flg;
997: #if defined(PETSC_USE_LOG)
998:   char           mname[PETSC_MAX_PATH_LEN];
999: #endif

1002:   if (!PetscInitializeCalled) {
1003:     printf("PetscInitialize() must be called before PetscFinalize()\n");
1004:     PetscFunctionReturn(PETSC_ERR_ARG_WRONGSTATE);
1005:   }
1006:   PetscInfo(NULL,"PetscFinalize() called\n");

1008:   MPI_Comm_rank(PETSC_COMM_WORLD,&rank);

1010:   PetscOptionsHasName(NULL,"-citations",&flg);
1011:   if (flg) {
1012:     char  *cits, filename[PETSC_MAX_PATH_LEN];
1013:     FILE  *fd = PETSC_STDOUT;

1015:     PetscOptionsGetString(NULL,"-citations",filename,PETSC_MAX_PATH_LEN,NULL);
1016:     if (filename[0]) {
1017:       PetscFOpen(PETSC_COMM_WORLD,filename,"w",&fd);
1018:     }
1019:     PetscSegBufferGet(PetscCitationsList,1,&cits);
1020:     cits[0] = 0;
1021:     PetscSegBufferExtractAlloc(PetscCitationsList,&cits);
1022:     PetscFPrintf(PETSC_COMM_WORLD,fd,"If you publish results based on this computation please cite the following:\n");
1023:     PetscFPrintf(PETSC_COMM_WORLD,fd,"===========================================================================\n");
1024:     PetscFPrintf(PETSC_COMM_WORLD,fd,"%s",cits);
1025:     PetscFPrintf(PETSC_COMM_WORLD,fd,"===========================================================================\n");
1026:     PetscFClose(PETSC_COMM_WORLD,fd);
1027:     PetscFree(cits);
1028:   }
1029:   PetscSegBufferDestroy(&PetscCitationsList);
1030:   /*
1031:     It should be safe to cancel the options monitors, since we don't expect to be setting options
1032:     here (at least that are worth monitoring).  Monitors ought to be released so that they release
1033:     whatever memory was allocated there before -malloc_dump reports unfreed memory.
1034:   */
1035:   PetscOptionsMonitorCancel();

1037: #if defined(PETSC_HAVE_SSL) && defined(PETSC_USE_SOCKET_VIEWER)
1038:   /* TextBelt is run for testing purposes only, please do not use this feature often */
1039:   {
1040:     PetscInt nmax = 2;
1041:     char     **buffs;
1042:     PetscMalloc1(2,&buffs);
1043:     PetscOptionsGetStringArray(NULL,"-textbelt",buffs,&nmax,&flg1);
1044:     if (flg1) {
1045:       if (!nmax) SETERRQ(PETSC_COMM_WORLD,PETSC_ERR_USER,"-textbelt requires either the phone number or number,\"message\"");
1046:       if (nmax == 1) {
1047:         PetscMalloc1(128,&buffs[1]);
1048:         PetscGetProgramName(buffs[1],32);
1049:         PetscStrcat(buffs[1]," has completed");
1050:       }
1051:       PetscTextBelt(PETSC_COMM_WORLD,buffs[0],buffs[1],NULL);
1052:       PetscFree(buffs[0]);
1053:       PetscFree(buffs[1]);
1054:     }
1055:     PetscFree(buffs);
1056:   }
1057: #endif
1058:   /*
1059:     It should be safe to cancel the options monitors, since we don't expect to be setting options
1060:     here (at least that are worth monitoring).  Monitors ought to be released so that they release
1061:     whatever memory was allocated there before -malloc_dump reports unfreed memory.
1062:   */
1063:   PetscOptionsMonitorCancel();

1065: #if defined(PETSC_SERIALIZE_FUNCTIONS)
1066:   PetscFPTDestroy();
1067: #endif


1070: #if defined(PETSC_HAVE_SAWS)
1071:   flg = PETSC_FALSE;
1072:   PetscOptionsGetBool(NULL,"-saw_options",&flg,NULL);
1073:   if (flg) {
1074:     PetscOptionsSAWsDestroy();
1075:   }
1076: #endif

1078: #if defined(PETSC_HAVE_X)
1079:   flg1 = PETSC_FALSE;
1080:   PetscOptionsGetBool(NULL,"-x_virtual",&flg1,NULL);
1081:   if (flg1) {
1082:     /*  this is a crude hack, but better than nothing */
1083:     PetscPOpen(PETSC_COMM_WORLD,NULL,"pkill -9 Xvfb","r",NULL);
1084:   }
1085: #endif

1087:   PetscOptionsGetBool(NULL,"-malloc_info",&flg2,NULL);
1088:   if (!flg2) {
1089:     flg2 = PETSC_FALSE;
1090:     PetscOptionsGetBool(NULL,"-memory_info",&flg2,NULL);
1091:   }
1092:   if (flg2) {
1093:     PetscMemoryShowUsage(PETSC_VIEWER_STDOUT_WORLD,"Summary of Memory Usage in PETSc\n");
1094:   }

1096: #if defined(PETSC_USE_LOG)
1097:   flg1 = PETSC_FALSE;
1098:   PetscOptionsGetBool(NULL,"-get_total_flops",&flg1,NULL);
1099:   if (flg1) {
1100:     PetscLogDouble flops = 0;
1101:     MPI_Reduce(&petsc_TotalFlops,&flops,1,MPI_DOUBLE,MPI_SUM,0,PETSC_COMM_WORLD);
1102:     PetscPrintf(PETSC_COMM_WORLD,"Total flops over all processors %g\n",flops);
1103:   }
1104: #endif


1107: #if defined(PETSC_USE_LOG)
1108: #if defined(PETSC_HAVE_MPE)
1109:   mname[0] = 0;

1111:   PetscOptionsGetString(NULL,"-log_mpe",mname,PETSC_MAX_PATH_LEN,&flg1);
1112:   if (flg1) {
1113:     if (mname[0]) {PetscLogMPEDump(mname);}
1114:     else          {PetscLogMPEDump(0);}
1115:   }
1116: #endif
1117:   mname[0] = 0;

1119:   PetscLogViewFromOptions();
1120:   PetscOptionsGetString(NULL,"-log_summary",mname,PETSC_MAX_PATH_LEN,&flg1);
1121:   if (flg1) {
1122:     PetscViewer viewer;
1123:     if (mname[0]) {
1124:       PetscViewerASCIIOpen(PETSC_COMM_WORLD,mname,&viewer);
1125:       PetscLogView(viewer);
1126:       PetscViewerDestroy(&viewer);
1127:     } else {
1128:       viewer = PETSC_VIEWER_STDOUT_WORLD;
1129:       PetscLogView(viewer);
1130:     }
1131:   }
1132:   mname[0] = 0;

1134:   PetscOptionsGetString(NULL,"-log_all",mname,PETSC_MAX_PATH_LEN,&flg1);
1135:   PetscOptionsGetString(NULL,"-log",mname,PETSC_MAX_PATH_LEN,&flg2);
1136:   if (flg1 || flg2) {
1137:     if (mname[0]) PetscLogDump(mname);
1138:     else          PetscLogDump(0);
1139:   }
1140: #endif

1142:   /*
1143:      Free all objects registered with PetscObjectRegisterDestroy() such as PETSC_VIEWER_XXX_().
1144:   */
1145:   PetscObjectRegisterDestroyAll();

1147:   PetscStackDestroy();
1148:   PetscThreadLocalDestroy((PetscThreadKey)petscstack); /* Deletes pthread_key */

1150:   flg1 = PETSC_FALSE;
1151:   PetscOptionsGetBool(NULL,"-no_signal_handler",&flg1,NULL);
1152:   if (!flg1) { PetscPopSignalHandler();}
1153:   flg1 = PETSC_FALSE;
1154:   PetscOptionsGetBool(NULL,"-mpidump",&flg1,NULL);
1155:   if (flg1) {
1156:     PetscMPIDump(stdout);
1157:   }
1158:   flg1 = PETSC_FALSE;
1159:   flg2 = PETSC_FALSE;
1160:   /* preemptive call to avoid listing this option in options table as unused */
1161:   PetscOptionsHasName(NULL,"-malloc_dump",&flg1);
1162:   PetscOptionsHasName(NULL,"-objects_dump",&flg1);
1163:   PetscOptionsGetBool(NULL,"-options_view",&flg2,NULL);

1165:   if (flg2) {
1166:     PetscViewer viewer;
1167:     PetscViewerCreate(PETSC_COMM_WORLD,&viewer);
1168:     PetscViewerSetType(viewer,PETSCVIEWERASCII);
1169:     PetscOptionsView(viewer);
1170:     PetscViewerDestroy(&viewer);
1171:   }

1173:   /* to prevent PETSc -options_left from warning */
1174:   PetscOptionsHasName(NULL,"-nox",&flg1);
1175:   PetscOptionsHasName(NULL,"-nox_warning",&flg1);

1177:   flg3 = PETSC_FALSE; /* default value is required */
1178:   PetscOptionsGetBool(NULL,"-options_left",&flg3,&flg1);
1179:   PetscOptionsAllUsed(&nopt);
1180:   if (flg3) {
1181:     if (!flg2) { /* have not yet printed the options */
1182:       PetscViewer viewer;
1183:       PetscViewerCreate(PETSC_COMM_WORLD,&viewer);
1184:       PetscViewerSetType(viewer,PETSCVIEWERASCII);
1185:       PetscOptionsView(viewer);
1186:       PetscViewerDestroy(&viewer);
1187:     }
1188:     if (!nopt) {
1189:       PetscPrintf(PETSC_COMM_WORLD,"There are no unused options.\n");
1190:     } else if (nopt == 1) {
1191:       PetscPrintf(PETSC_COMM_WORLD,"There is one unused database option. It is:\n");
1192:     } else {
1193:       PetscPrintf(PETSC_COMM_WORLD,"There are %D unused database options. They are:\n",nopt);
1194:     }
1195:   }
1196: #if defined(PETSC_USE_DEBUG)
1197:   if (nopt && !flg3 && !flg1) {
1198:     PetscPrintf(PETSC_COMM_WORLD,"WARNING! There are options you set that were not used!\n");
1199:     PetscPrintf(PETSC_COMM_WORLD,"WARNING! could be spelling mistake, etc!\n");
1200:     PetscOptionsLeft();
1201:   } else if (nopt && flg3) {
1202: #else
1203:   if (nopt && flg3) {
1204: #endif
1205:     PetscOptionsLeft();
1206:   }

1208: #if defined(PETSC_HAVE_SAWS)
1209:   if (!PetscGlobalRank) {
1210:     PetscStackSAWsViewOff();
1211:     PetscStackCallSAWs(SAWs_Finalize,());
1212:   }
1213: #endif

1215:   {
1216:     PetscThreadComm tcomm_world;
1217:     PetscGetThreadCommWorld(&tcomm_world);
1218:     /* Free global thread communicator */
1219:     PetscThreadCommDestroy(&tcomm_world);
1220:   }

1222: #if defined(PETSC_USE_LOG)
1223:   /*
1224:        List all objects the user may have forgot to free
1225:   */
1226:   PetscOptionsHasName(NULL,"-objects_dump",&flg1);
1227:   if (flg1) {
1228:     MPI_Comm local_comm;
1229:     char     string[64];

1231:     PetscOptionsGetString(NULL,"-objects_dump",string,64,NULL);
1232:     MPI_Comm_dup(MPI_COMM_WORLD,&local_comm);
1233:     PetscSequentialPhaseBegin_Private(local_comm,1);
1234:     PetscObjectsDump(stdout,(string[0] == 'a') ? PETSC_TRUE : PETSC_FALSE);
1235:     PetscSequentialPhaseEnd_Private(local_comm,1);
1236:     MPI_Comm_free(&local_comm);
1237:   }
1238: #endif

1240: #if defined(PETSC_USE_LOG)
1241:   PetscObjectsCounts    = 0;
1242:   PetscObjectsMaxCounts = 0;
1243:   PetscFree(PetscObjects);
1244: #endif

1246: #if defined(PETSC_USE_LOG)
1247:   PetscLogDestroy();
1248: #endif

1250:   /*
1251:      Destroy any packages that registered a finalize
1252:   */
1253:   PetscRegisterFinalizeAll();

1255:   /*
1256:      Destroy all the function registration lists created
1257:   */
1258:   PetscFinalize_DynamicLibraries();

1260:   /*
1261:      Print PetscFunctionLists that have not been properly freed

1263:   PetscFunctionListPrintAll();
1264:   */

1266:   if (petsc_history) {
1267:     PetscCloseHistoryFile(&petsc_history);
1268:     petsc_history = 0;
1269:   }

1271:   PetscInfoAllow(PETSC_FALSE,NULL);

1273:   {
1274:     char fname[PETSC_MAX_PATH_LEN];
1275:     FILE *fd;
1276:     int  err;

1278:     fname[0] = 0;

1280:     PetscOptionsGetString(NULL,"-malloc_dump",fname,250,&flg1);
1281:     flg2 = PETSC_FALSE;
1282:     PetscOptionsGetBool(NULL,"-malloc_test",&flg2,NULL);
1283: #if defined(PETSC_USE_DEBUG)
1284:     if (PETSC_RUNNING_ON_VALGRIND) flg2 = PETSC_FALSE;
1285: #else
1286:     flg2 = PETSC_FALSE;         /* Skip reporting for optimized builds regardless of -malloc_test */
1287: #endif
1288:     if (flg1 && fname[0]) {
1289:       char sname[PETSC_MAX_PATH_LEN];

1291:       sprintf(sname,"%s_%d",fname,rank);
1292:       fd   = fopen(sname,"w"); if (!fd) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_FILE_OPEN,"Cannot open log file: %s",sname);
1293:       PetscMallocDump(fd);
1294:       err  = fclose(fd);
1295:       if (err) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SYS,"fclose() failed on file");
1296:     } else if (flg1 || flg2) {
1297:       MPI_Comm local_comm;

1299:       MPI_Comm_dup(MPI_COMM_WORLD,&local_comm);
1300:       PetscSequentialPhaseBegin_Private(local_comm,1);
1301:       PetscMallocDump(stdout);
1302:       PetscSequentialPhaseEnd_Private(local_comm,1);
1303:       MPI_Comm_free(&local_comm);
1304:     }
1305:   }

1307:   {
1308:     char fname[PETSC_MAX_PATH_LEN];
1309:     FILE *fd = NULL;

1311:     fname[0] = 0;

1313:     PetscOptionsGetString(NULL,"-malloc_log",fname,250,&flg1);
1314:     PetscOptionsHasName(NULL,"-malloc_log_threshold",&flg2);
1315:     if (flg1 && fname[0]) {
1316:       int err;

1318:       if (!rank) {
1319:         fd = fopen(fname,"w");
1320:         if (!fd) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_FILE_OPEN,"Cannot open log file: %s",fname);
1321:       }
1322:       PetscMallocDumpLog(fd);
1323:       if (fd) {
1324:         err = fclose(fd);
1325:         if (err) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SYS,"fclose() failed on file");
1326:       }
1327:     } else if (flg1 || flg2) {
1328:       PetscMallocDumpLog(stdout);
1329:     }
1330:   }

1332: #if defined(PETSC_HAVE_CUDA)
1333:   flg  = PETSC_TRUE;
1334:   PetscOptionsGetBool(NULL,"-cublas",&flg,NULL);
1335:   if (flg) {
1336:     PetscInt p;
1337:     for (p = 0; p < PetscGlobalSize; ++p) {
1338:       if (p == PetscGlobalRank) cublasShutdown();
1339:       MPI_Barrier(PETSC_COMM_WORLD);
1340:     }
1341:   }
1342: #endif

1344:   /* Can be destroyed only after all the options are used */
1345:   PetscOptionsDestroy();

1347:   PetscGlobalArgc = 0;
1348:   PetscGlobalArgs = 0;

1350: #if defined(PETSC_USE_REAL___FLOAT128)
1351:   MPI_Type_free(&MPIU___FLOAT128);
1352: #if defined(PETSC_HAVE_COMPLEX)
1353:   MPI_Type_free(&MPIU___COMPLEX128);
1354: #endif
1355:   MPI_Op_free(&MPIU_MAX);
1356:   MPI_Op_free(&MPIU_MIN);
1357: #endif

1359: #if defined(PETSC_HAVE_COMPLEX)
1360: #if !defined(PETSC_HAVE_MPI_C_DOUBLE_COMPLEX)
1361:   MPI_Type_free(&MPIU_C_DOUBLE_COMPLEX);
1362:   MPI_Type_free(&MPIU_C_COMPLEX);
1363: #endif
1364: #endif

1366: #if (defined(PETSC_HAVE_COMPLEX) && !defined(PETSC_HAVE_MPI_C_DOUBLE_COMPLEX)) || defined(PETSC_USE_REAL___FLOAT128)
1367:   MPI_Op_free(&MPIU_SUM);
1368: #endif

1370:   MPI_Type_free(&MPIU_2SCALAR);
1371: #if defined(PETSC_USE_64BIT_INDICES) || !defined(MPI_2INT)
1372:   MPI_Type_free(&MPIU_2INT);
1373: #endif
1374:   MPI_Op_free(&PetscMaxSum_Op);
1375:   MPI_Op_free(&PetscADMax_Op);
1376:   MPI_Op_free(&PetscADMin_Op);

1378:   /*
1379:      Destroy any known inner MPI_Comm's and attributes pointing to them
1380:      Note this will not destroy any new communicators the user has created.

1382:      If all PETSc objects were not destroyed those left over objects will have hanging references to
1383:      the MPI_Comms that were freed; but that is ok because those PETSc objects will never be used again
1384:  */
1385:   {
1386:     PetscCommCounter *counter;
1387:     PetscMPIInt      flg;
1388:     MPI_Comm         icomm;
1389:     union {MPI_Comm comm; void *ptr;} ucomm;
1390:     MPI_Attr_get(PETSC_COMM_SELF,Petsc_InnerComm_keyval,&ucomm,&flg);
1391:     if (flg) {
1392:       icomm = ucomm.comm;
1393:       MPI_Attr_get(icomm,Petsc_Counter_keyval,&counter,&flg);
1394:       if (!flg) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_CORRUPT,"Inner MPI_Comm does not have expected tag/name counter, problem with corrupted memory");

1396:       MPI_Attr_delete(PETSC_COMM_SELF,Petsc_InnerComm_keyval);
1397:       MPI_Attr_delete(icomm,Petsc_Counter_keyval);
1398:       MPI_Comm_free(&icomm);
1399:     }
1400:     MPI_Attr_get(PETSC_COMM_WORLD,Petsc_InnerComm_keyval,&ucomm,&flg);
1401:     if (flg) {
1402:       icomm = ucomm.comm;
1403:       MPI_Attr_get(icomm,Petsc_Counter_keyval,&counter,&flg);
1404:       if (!flg) SETERRQ(PETSC_COMM_WORLD,PETSC_ERR_ARG_CORRUPT,"Inner MPI_Comm does not have expected tag/name counter, problem with corrupted memory");

1406:       MPI_Attr_delete(PETSC_COMM_WORLD,Petsc_InnerComm_keyval);
1407:       MPI_Attr_delete(icomm,Petsc_Counter_keyval);
1408:       MPI_Comm_free(&icomm);
1409:     }
1410:   }

1412:   MPI_Keyval_free(&Petsc_Counter_keyval);
1413:   MPI_Keyval_free(&Petsc_InnerComm_keyval);
1414:   MPI_Keyval_free(&Petsc_OuterComm_keyval);

1416:   if (PetscBeganMPI) {
1417: #if defined(PETSC_HAVE_MPI_FINALIZED)
1418:     PetscMPIInt flag;
1419:     MPI_Finalized(&flag);
1420:     if (flag) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_LIB,"MPI_Finalize() has already been called, even though MPI_Init() was called by PetscInitialize()");
1421: #endif
1422:     MPI_Finalize();
1423:   }
1424: /*

1426:      Note: In certain cases PETSC_COMM_WORLD is never MPI_Comm_free()ed because
1427:    the communicator has some outstanding requests on it. Specifically if the
1428:    flag PETSC_HAVE_BROKEN_REQUEST_FREE is set (for IBM MPI implementation). See
1429:    src/vec/utils/vpscat.c. Due to this the memory allocated in PetscCommDuplicate()
1430:    is never freed as it should be. Thus one may obtain messages of the form
1431:    [ 1] 8 bytes PetscCommDuplicate() line 645 in src/sys/mpiu.c indicating the
1432:    memory was not freed.

1434: */
1435:   PetscMallocClear();

1437:   PetscInitializeCalled = PETSC_FALSE;
1438:   PetscFinalizeCalled   = PETSC_TRUE;
1439:   PetscFunctionReturn(ierr);
1440: }

1442: #if defined(PETSC_MISSING_LAPACK_lsame_)
1443: PETSC_EXTERN int lsame_(char *a,char *b)
1444: {
1445:   if (*a == *b) return 1;
1446:   if (*a + 32 == *b) return 1;
1447:   if (*a - 32 == *b) return 1;
1448:   return 0;
1449: }
1450: #endif

1452: #if defined(PETSC_MISSING_LAPACK_lsame)
1453: PETSC_EXTERN int lsame(char *a,char *b)
1454: {
1455:   if (*a == *b) return 1;
1456:   if (*a + 32 == *b) return 1;
1457:   if (*a - 32 == *b) return 1;
1458:   return 0;
1459: }
1460: #endif