Actual source code: pinit.c

petsc-3.7.7 2017-09-25
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 <petscvalgrind.h>
  7: #include <petscviewer.h>

  9: #if defined(PETSC_USE_LOG)
 10: extern PetscErrorCode PetscLogInitialize(void);
 11: #endif

 13: #if defined(PETSC_SERIALIZE_FUNCTIONS)
 14: PetscFPT PetscFPTData = 0;
 15: #endif

 17: #if defined(PETSC_HAVE_CUDA)
 18: cublasHandle_t cublasv2handle = NULL;
 19: #endif

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

 26: extern FILE *petsc_history;

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

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

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

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

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

 53: PetscInt PetscHotRegionDepth;

 55: #if defined(PETSC_HAVE_THREADSAFETY)
 56: PetscSpinlock PetscViewerASCIISpinLockOpen;
 57: PetscSpinlock PetscViewerASCIISpinLockStdout;
 58: PetscSpinlock PetscViewerASCIISpinLockStderr;
 59: PetscSpinlock PetscCommSpinLock;
 60: #endif

 62: /*
 63:        Checks the options database for initializations related to the
 64:     PETSc components
 65: */
 68: PetscErrorCode  PetscOptionsCheckInitial_Components(void)
 69: {
 70:   PetscBool      flg1;

 74:   PetscOptionsHasName(NULL,NULL,"-help",&flg1);
 75:   if (flg1) {
 76: #if defined(PETSC_USE_LOG)
 77:     MPI_Comm comm = PETSC_COMM_WORLD;
 78:     (*PetscHelpPrintf)(comm,"------Additional PETSc component options--------\n");
 79:     (*PetscHelpPrintf)(comm," -log_exclude: <vec,mat,pc.ksp,snes>\n");
 80:     (*PetscHelpPrintf)(comm," -info_exclude: <null,vec,mat,pc,ksp,snes,ts>\n");
 81:     (*PetscHelpPrintf)(comm,"-----------------------------------------------\n");
 82: #endif
 83:   }
 84:   return(0);
 85: }

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

 92:    Collective

 94:    Level: advanced

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

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

102: .seealso: PetscInitialize(), PetscInitializeFortran(), PetscInitializeNoArguments()
103: */
104: PetscErrorCode  PetscInitializeNoPointers(int argc,char **args,const char *filename,const char *help)
105: {
107:   int            myargc   = argc;
108:   char           **myargs = args;

111:   PetscInitialize(&myargc,&myargs,filename,help);
112:   PetscPopSignalHandler();
113:   PetscBeganMPI = PETSC_FALSE;
114:   PetscFunctionReturn(ierr);
115: }

119: /*
120:       Used by MATLAB and Julia interface to get communicator
121: */
122: PetscErrorCode  PetscGetPETSC_COMM_SELF(MPI_Comm *comm)
123: {
125:   *comm = PETSC_COMM_SELF;
126:   return(0);
127: }

131: /*@C
132:       PetscInitializeNoArguments - Calls PetscInitialize() from C/C++ without
133:         the command line arguments.

135:    Collective

137:    Level: advanced

139: .seealso: PetscInitialize(), PetscInitializeFortran()
140: @*/
141: PetscErrorCode  PetscInitializeNoArguments(void)
142: {
144:   int            argc   = 0;
145:   char           **args = 0;

148:   PetscInitialize(&argc,&args,NULL,NULL);
149:   PetscFunctionReturn(ierr);
150: }

154: /*@
155:       PetscInitialized - Determine whether PETSc is initialized.

157:    Level: beginner

159: .seealso: PetscInitialize(), PetscInitializeNoArguments(), PetscInitializeFortran()
160: @*/
161: PetscErrorCode PetscInitialized(PetscBool  *isInitialized)
162: {
163:   *isInitialized = PetscInitializeCalled;
164:   return 0;
165: }

169: /*@
170:       PetscFinalized - Determine whether PetscFinalize() has been called yet

172:    Level: developer

174: .seealso: PetscInitialize(), PetscInitializeNoArguments(), PetscInitializeFortran()
175: @*/
176: PetscErrorCode  PetscFinalized(PetscBool  *isFinalized)
177: {
178:   *isFinalized = PetscFinalizeCalled;
179:   return 0;
180: }

182: extern PetscErrorCode PetscOptionsCheckInitial_Private(void);

184: /*
185:        This function is the MPI reduction operation used to compute the sum of the
186:    first half of the datatype and the max of the second half.
187: */
188: MPI_Op PetscMaxSum_Op = 0;

192: PETSC_EXTERN void MPIAPI PetscMaxSum_Local(void *in,void *out,int *cnt,MPI_Datatype *datatype)
193: {
194:   PetscInt *xin = (PetscInt*)in,*xout = (PetscInt*)out,i,count = *cnt;

197:   if (*datatype != MPIU_2INT) {
198:     (*PetscErrorPrintf)("Can only handle MPIU_2INT data types");
199:     MPI_Abort(MPI_COMM_WORLD,1);
200:   }

202:   for (i=0; i<count; i++) {
203:     xout[2*i]    = PetscMax(xout[2*i],xin[2*i]);
204:     xout[2*i+1] += xin[2*i+1];
205:   }
206:   PetscFunctionReturnVoid();
207: }

209: /*
210:     Returns the max of the first entry owned by this processor and the
211: sum of the second entry.

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

224: #if defined(PETSC_HAVE_MPI_REDUCE_SCATTER_BLOCK)
225:   {
226:     struct {PetscInt max,sum;} work;
227:     MPI_Reduce_scatter_block((void*)sizes,&work,1,MPIU_2INT,PetscMaxSum_Op,comm);
228:     *max = work.max;
229:     *sum = work.sum;
230:   }
231: #else
232:   {
233:     PetscMPIInt    size,rank;
234:     struct {PetscInt max,sum;} *work;
235:     MPI_Comm_size(comm,&size);
236:     MPI_Comm_rank(comm,&rank);
237:     PetscMalloc1(size,&work);
238:     MPIU_Allreduce((void*)sizes,work,size,MPIU_2INT,PetscMaxSum_Op,comm);
239:     *max = work[rank].max;
240:     *sum = work[rank].sum;
241:     PetscFree(work);
242:   }
243: #endif
244:   return(0);
245: }

247: /* ----------------------------------------------------------------------------*/

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

254: PETSC_EXTERN void PetscSum_Local(void *in,void *out,PetscMPIInt *cnt,MPI_Datatype *datatype)
255: {
256:   PetscInt i,count = *cnt;

259:   if (*datatype == MPIU_REAL) {
260:     PetscReal *xin = (PetscReal*)in,*xout = (PetscReal*)out;
261:     for (i=0; i<count; i++) xout[i] += xin[i];
262:   }
263: #if defined(PETSC_HAVE_COMPLEX)
264:   else if (*datatype == MPIU_COMPLEX) {
265:     PetscComplex *xin = (PetscComplex*)in,*xout = (PetscComplex*)out;
266:     for (i=0; i<count; i++) xout[i] += xin[i];
267:   }
268: #endif
269:   else {
270:     (*PetscErrorPrintf)("Can only handle MPIU_REAL or MPIU_COMPLEX data types");
271:     MPI_Abort(MPI_COMM_WORLD,1);
272:   }
273:   PetscFunctionReturnVoid();
274: }
275: #endif

277: #if defined(PETSC_USE_REAL___FLOAT128)
278: MPI_Op MPIU_MAX = 0;
279: MPI_Op MPIU_MIN = 0;

283: PETSC_EXTERN void PetscMax_Local(void *in,void *out,PetscMPIInt *cnt,MPI_Datatype *datatype)
284: {
285:   PetscInt i,count = *cnt;

288:   if (*datatype == MPIU_REAL) {
289:     PetscReal *xin = (PetscReal*)in,*xout = (PetscReal*)out;
290:     for (i=0; i<count; i++) xout[i] = PetscMax(xout[i],xin[i]);
291:   }
292: #if defined(PETSC_HAVE_COMPLEX)
293:   else if (*datatype == MPIU_COMPLEX) {
294:     PetscComplex *xin = (PetscComplex*)in,*xout = (PetscComplex*)out;
295:     for (i=0; i<count; i++) {
296:       xout[i] = PetscRealPartComplex(xout[i])<PetscRealPartComplex(xin[i]) ? xin[i] : xout[i];
297:     }
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: }

309: PETSC_EXTERN void PetscMin_Local(void *in,void *out,PetscMPIInt *cnt,MPI_Datatype *datatype)
310: {
311:   PetscInt    i,count = *cnt;

314:   if (*datatype == MPIU_REAL) {
315:     PetscReal *xin = (PetscReal*)in,*xout = (PetscReal*)out;
316:     for (i=0; i<count; i++) xout[i] = PetscMin(xout[i],xin[i]);
317:   }
318: #if defined(PETSC_HAVE_COMPLEX)
319:   else if (*datatype == MPIU_COMPLEX) {
320:     PetscComplex *xin = (PetscComplex*)in,*xout = (PetscComplex*)out;
321:     for (i=0; i<count; i++) {
322:       xout[i] = PetscRealPartComplex(xout[i])>PetscRealPartComplex(xin[i]) ? xin[i] : xout[i];
323:     }
324:   }
325: #endif
326:   else {
327:     (*PetscErrorPrintf)("Can only handle MPIU_REAL or MPIU_SCALAR data (i.e. double or complex) types");
328:     MPI_Abort(MPI_COMM_WORLD,1);
329:   }
330:   PetscFunctionReturnVoid();
331: }
332: #endif

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

339:    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.

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

343: */
344: PETSC_EXTERN PetscMPIInt MPIAPI Petsc_DelCounter(MPI_Comm comm,PetscMPIInt keyval,void *count_val,void *extra_state)
345: {

349:   PetscInfo1(0,"Deleting counter data in an MPI_Comm %ld\n",(long)comm);if (ierr) PetscFunctionReturn((PetscMPIInt)ierr);
350:   PetscFree(count_val);if (ierr) PetscFunctionReturn((PetscMPIInt)ierr);
351:   PetscFunctionReturn(MPI_SUCCESS);
352: }

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

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

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

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

366: */
367: PETSC_EXTERN PetscMPIInt MPIAPI Petsc_DelComm_Outer(MPI_Comm comm,PetscMPIInt keyval,void *attr_val,void *extra_state)
368: {
370:   PetscMPIInt    flg;
371:   union {MPI_Comm comm; void *ptr;} icomm,ocomm;

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

377:   MPI_Attr_get(icomm.comm,Petsc_OuterComm_keyval,&ocomm,&flg);
378:   if (!flg) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_CORRUPT,"Inner MPI_Comm does not have expected reference to outer comm");
379:   if (ocomm.comm != comm) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_CORRUPT,"Inner MPI_Comm has reference to non-matching outer comm");
380:   MPI_Attr_delete(icomm.comm,Petsc_OuterComm_keyval); /* Calls Petsc_DelComm_Inner */
381:   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);
382:   PetscFunctionReturn(MPI_SUCCESS);
383: }

387: /*
388:  * This is invoked on the inner comm when Petsc_DelComm_Outer calls MPI_Attr_delete.  It should not be reached any other way.
389:  */
390: PETSC_EXTERN PetscMPIInt MPIAPI Petsc_DelComm_Inner(MPI_Comm comm,PetscMPIInt keyval,void *attr_val,void *extra_state)
391: {

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

399: #if defined(PETSC_USE_PETSC_MPI_EXTERNAL32)
400: #if !defined(PETSC_WORDS_BIGENDIAN)
401: PETSC_EXTERN PetscMPIInt PetscDataRep_extent_fn(MPI_Datatype,MPI_Aint*,void*);
402: PETSC_EXTERN PetscMPIInt PetscDataRep_read_conv_fn(void*, MPI_Datatype,PetscMPIInt,void*,MPI_Offset,void*);
403: PETSC_EXTERN PetscMPIInt PetscDataRep_write_conv_fn(void*, MPI_Datatype,PetscMPIInt,void*,MPI_Offset,void*);
404: #endif
405: #endif

407: int  PetscGlobalArgc   = 0;
408: char **PetscGlobalArgs = 0;
409: PetscSegBuffer PetscCitationsList;

413: PetscErrorCode PetscCitationsInitialize()
414: {

418:   PetscSegBufferCreate(1,10000,&PetscCitationsList);
419:   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 Lisandro Dalcin 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 Stefano Zampini and Hong Zhang and Hong Zhang},\n  Title = {{PETS}c Users Manual},\n  Number = {ANL-95/11 - Revision 3.7},\n  Institution = {Argonne National Laboratory},\n  Year = {2016}\n}\n",NULL);
420:   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);
421:   return(0);
422: }

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

430:    Not Collective

432:    Output Parameters:
433: +  argc - count of number of command line arguments
434: -  args - the command line arguments

436:    Level: intermediate

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

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

444:    Concepts: command line arguments

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

448: @*/
449: PetscErrorCode  PetscGetArgs(int *argc,char ***args)
450: {
452:   if (!PetscInitializeCalled && PetscFinalizeCalled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ORDER,"You must call after PetscInitialize() but before PetscFinalize()");
453:   *argc = PetscGlobalArgc;
454:   *args = PetscGlobalArgs;
455:   return(0);
456: }

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

464:    Not Collective

466:    Output Parameters:
467: .  args - the command line arguments

469:    Level: intermediate

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

474:    Concepts: command line arguments

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

478: @*/
479: PetscErrorCode  PetscGetArguments(char ***args)
480: {
481:   PetscInt       i,argc = PetscGlobalArgc;

485:   if (!PetscInitializeCalled && PetscFinalizeCalled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ORDER,"You must call after PetscInitialize() but before PetscFinalize()");
486:   if (!argc) {*args = 0; return(0);}
487:   PetscMalloc1(argc,args);
488:   for (i=0; i<argc-1; i++) {
489:     PetscStrallocpy(PetscGlobalArgs[i+1],&(*args)[i]);
490:   }
491:   (*args)[argc-1] = 0;
492:   return(0);
493: }

497: /*@C
498:    PetscFreeArguments - Frees the memory obtained with PetscGetArguments()

500:    Not Collective

502:    Output Parameters:
503: .  args - the command line arguments

505:    Level: intermediate

507:    Concepts: command line arguments

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

511: @*/
512: PetscErrorCode  PetscFreeArguments(char **args)
513: {
514:   PetscInt       i = 0;

518:   if (!args) return(0);
519:   while (args[i]) {
520:     PetscFree(args[i]);
521:     i++;
522:   }
523:   PetscFree(args);
524:   return(0);
525: }

527: #if defined(PETSC_HAVE_SAWS)
528: #include <petscconfiginfo.h>

532: PetscErrorCode  PetscInitializeSAWs(const char help[])
533: {
534:   if (!PetscGlobalRank) {
535:     char           cert[PETSC_MAX_PATH_LEN],root[PETSC_MAX_PATH_LEN],*intro,programname[64],*appline,*options,version[64];
536:     int            port;
537:     PetscBool      flg,rootlocal = PETSC_FALSE,flg2,selectport = PETSC_FALSE;
538:     size_t         applinelen,introlen;
540:     char           sawsurl[256];

542:     PetscOptionsHasName(NULL,NULL,"-saws_log",&flg);
543:     if (flg) {
544:       char  sawslog[PETSC_MAX_PATH_LEN];

546:       PetscOptionsGetString(NULL,NULL,"-saws_log",sawslog,PETSC_MAX_PATH_LEN,NULL);
547:       if (sawslog[0]) {
548:         PetscStackCallSAWs(SAWs_Set_Use_Logfile,(sawslog));
549:       } else {
550:         PetscStackCallSAWs(SAWs_Set_Use_Logfile,(NULL));
551:       }
552:     }
553:     PetscOptionsGetString(NULL,NULL,"-saws_https",cert,PETSC_MAX_PATH_LEN,&flg);
554:     if (flg) {
555:       PetscStackCallSAWs(SAWs_Set_Use_HTTPS,(cert));
556:     }
557:     PetscOptionsGetBool(NULL,NULL,"-saws_port_auto_select",&selectport,NULL);
558:     if (selectport) {
559:         PetscStackCallSAWs(SAWs_Get_Available_Port,(&port));
560:         PetscStackCallSAWs(SAWs_Set_Port,(port));
561:     } else {
562:       PetscOptionsGetInt(NULL,NULL,"-saws_port",&port,&flg);
563:       if (flg) {
564:         PetscStackCallSAWs(SAWs_Set_Port,(port));
565:       }
566:     }
567:     PetscOptionsGetString(NULL,NULL,"-saws_root",root,PETSC_MAX_PATH_LEN,&flg);
568:     if (flg) {
569:       PetscStackCallSAWs(SAWs_Set_Document_Root,(root));
570:       PetscStrcmp(root,".",&rootlocal);
571:     } else {
572:       PetscOptionsHasName(NULL,NULL,"-saws_options",&flg);
573:       if (flg) {
574:         PetscStrreplace(PETSC_COMM_WORLD,"${PETSC_DIR}/share/petsc/saws",root,PETSC_MAX_PATH_LEN);
575:         PetscStackCallSAWs(SAWs_Set_Document_Root,(root));
576:       }
577:     }
578:     PetscOptionsHasName(NULL,NULL,"-saws_local",&flg2);
579:     if (flg2) {
580:       char jsdir[PETSC_MAX_PATH_LEN];
581:       if (!flg) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"-saws_local option requires -saws_root option");
582:       PetscSNPrintf(jsdir,PETSC_MAX_PATH_LEN,"%s/js",root);
583:       PetscTestDirectory(jsdir,'r',&flg);
584:       if (!flg) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_FILE_READ,"-saws_local option requires js directory in root directory");
585:       PetscStackCallSAWs(SAWs_Push_Local_Header,());
586:     }
587:     PetscGetProgramName(programname,64);
588:     PetscStrlen(help,&applinelen);
589:     introlen   = 4096 + applinelen;
590:     applinelen += 1024;
591:     PetscMalloc(applinelen,&appline);
592:     PetscMalloc(introlen,&intro);

594:     if (rootlocal) {
595:       PetscSNPrintf(appline,applinelen,"%s.c.html",programname);
596:       PetscTestFile(appline,'r',&rootlocal);
597:     }
598:     PetscOptionsGetAll(NULL,&options);
599:     if (rootlocal && help) {
600:       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);
601:     } else if (help) {
602:       PetscSNPrintf(appline,applinelen,"<center>Running %s %s</center><br><center><pre>%s</pre></center><br>",programname,options,help);
603:     } else {
604:       PetscSNPrintf(appline,applinelen,"<center> Running %s %s</center><br>\n",programname,options);
605:     }
606:     PetscFree(options);
607:     PetscGetVersion(version,sizeof(version));
608:     PetscSNPrintf(intro,introlen,"<body>\n"
609:                                     "<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"
610:                                     "<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"
611:                                     "%s",version,petscconfigureoptions,appline);
612:     PetscStackCallSAWs(SAWs_Push_Body,("index.html",0,intro));
613:     PetscFree(intro);
614:     PetscFree(appline);
615:     PetscStackCallSAWs(SAWs_Initialize,());
616:     if (selectport) {
617:       PetscStackCallSAWs(SAWs_Get_FullURL,(sizeof(sawsurl),sawsurl));
618:       PetscPrintf(PETSC_COMM_WORLD,"Point your browser to %s for SAWs\n",sawsurl);
619:     }
620:     PetscCitationsRegister("@TechReport{ saws,\n"
621:                                   "  Author = {Matt Otten and Jed Brown and Barry Smith},\n"
622:                                   "  Title  = {Scientific Application Web Server (SAWs) Users Manual},\n"
623:                                   "  Institution = {Argonne National Laboratory},\n"
624:                                   "  Year   = 2013\n}\n",NULL);
625:   }
626:   return(0);
627: }
628: #endif

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

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

640:    Input Parameters:
641: +  argc - count of number of command line arguments
642: .  args - the command line arguments
643: .  file - [optional] PETSc database file, also checks ~username/.petscrc and .petscrc use NULL to not check for
644:           code specific file. Use -skip_petscrc in the code specific file to skip the .petscrc files
645: -  help - [optional] Help message to print, use NULL for no message

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

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

679:    Options Database Keys for Profiling:
680:    See Users-Manual: Chapter 13 Profiling for details.
681: +  -info <optional filename> - Prints verbose information to the screen
682: .  -info_exclude <null,vec,mat,pc,ksp,snes,ts> - Excludes some of the verbose messages
683: .  -log_sync - Log the synchronization in scatters, inner products and norms
684: .  -log_trace [filename] - Print traces of all PETSc calls to the screen (useful to determine where a program
685:         hangs without running in the debugger).  See PetscLogTraceBegin().
686: .  -log_view [:filename:format] - Prints summary of flop and timing information to screen or file, see PetscLogView().
687: .  -log_summary [filename] - (Deprecated, use -log_view) Prints summary of flop and timing information to screen. If the filename is specified the
688:         summary is written to the file.  See PetscLogView().
689: .  -log_exclude: <vec,mat,pc.ksp,snes> - excludes subset of object classes from logging
690: .  -log_all [filename] - Logs extensive profiling information  See PetscLogDump().
691: .  -log [filename] - Logs basic profiline information  See PetscLogDump().
692: -  -log_mpe [filename] - Creates a logfile viewable by the utility Jumpshot (in MPICH distribution)

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

696:    Options Database Keys for SAWs:
697: +  -saws_port <portnumber> - port number to publish SAWs data, default is 8080
698: .  -saws_port_auto_select - have SAWs select a new unique port number where it publishes the data, the URL is printed to the screen
699:                             this is useful when you are running many jobs that utilize SAWs at the same time
700: .  -saws_log <filename> - save a log of all SAWs communication
701: .  -saws_https <certificate file> - have SAWs use HTTPS instead of HTTP
702: -  -saws_root <directory> - allow SAWs to have access to the given directory to search for requested resources and files

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


712:    Level: beginner

714:    Notes:
715:    If for some reason you must call MPI_Init() separately, call
716:    it before PetscInitialize().

718:    Fortran Version:
719:    In Fortran this routine has the format
720: $       call PetscInitialize(file,ierr)

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

726:    Important Fortran Note:
727:    In Fortran, you MUST use PETSC_NULL_CHARACTER to indicate a
728:    null character string; you CANNOT just use NULL as
729:    in the C version. See Users-Manual: Chapter 12 PETSc for Fortran Users for details.

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

734:    Concepts: initializing PETSc

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

738: @*/
739: PetscErrorCode  PetscInitialize(int *argc,char ***args,const char file[],const char help[])
740: {
742:   PetscMPIInt    flag, size;
743:   PetscBool      flg;
744:   char           hostname[256];
745: #if defined(PETSC_HAVE_CUDA)
746:   cublasStatus_t cberr;
747: #endif

750:   if (PetscInitializeCalled) return(0);

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

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

761:   PetscOptionsCreateDefault();

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

773:   MPI_Initialized(&flag);
774:   if (!flag) {
775:     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");
776: #if defined(PETSC_HAVE_MPI_INIT_THREAD)
777:     {
778:       PetscMPIInt provided;
779:       MPI_Init_thread(argc,args,MPI_THREAD_FUNNELED,&provided);
780:     }
781: #else
782:     MPI_Init(argc,args);
783: #endif
784:     PetscBeganMPI = PETSC_TRUE;
785:   }
786:   if (argc && args) {
787:     PetscGlobalArgc = *argc;
788:     PetscGlobalArgs = *args;
789:   }
790:   PetscFinalizeCalled = PETSC_FALSE;
791:   PetscSpinlockCreate(&PetscViewerASCIISpinLockOpen);
792:   PetscSpinlockCreate(&PetscViewerASCIISpinLockStdout);
793:   PetscSpinlockCreate(&PetscViewerASCIISpinLockStderr);
794:   PetscSpinlockCreate(&PetscCommSpinLock);

796:   if (PETSC_COMM_WORLD == MPI_COMM_NULL) PETSC_COMM_WORLD = MPI_COMM_WORLD;
797:   MPI_Comm_set_errhandler(PETSC_COMM_WORLD,MPI_ERRORS_RETURN);

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

802:   MPI_Comm_rank(MPI_COMM_WORLD,&PetscGlobalRank);
803:   MPI_Comm_size(MPI_COMM_WORLD,&PetscGlobalSize);

805:   MPIU_BOOL = MPI_INT;
806:   MPIU_ENUM = MPI_INT;

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

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

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

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

848: #if (defined(PETSC_HAVE_COMPLEX) && !defined(PETSC_HAVE_MPI_C_DOUBLE_COMPLEX)) || defined(PETSC_USE_REAL___FLOAT128)
849:   MPI_Op_create(PetscSum_Local,1,&MPIU_SUM);
850: #endif

852:   MPI_Type_contiguous(2,MPIU_SCALAR,&MPIU_2SCALAR);
853:   MPI_Type_commit(&MPIU_2SCALAR);

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


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

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


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

883:   PetscCitationsInitialize();

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

889:   /* Creates the logging data structures; this is enabled even if logging is not turned on */
890: #if defined(PETSC_USE_LOG)
891:   PetscLogInitialize();
892: #endif

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

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

905:   PetscOptionsCheckInitial_Components();
906:   /* Check the options database for options related to the options database itself */
907:   PetscOptionsSetFromOptions(NULL);

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

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

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

934:   PetscOptionsHasName(NULL,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: #if defined(PETSC_USE_DEBUG) && !defined(PETSC_HAVE_THREADSAFETY)
944:   PetscStackCreate();
945: #endif

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


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

959: #if defined(PETSC_USE_LOG)
960: extern PetscObject *PetscObjects;
961: extern PetscInt    PetscObjectsCounts, PetscObjectsMaxCounts;
962: extern PetscBool   PetscObjectsLog;
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
1000: #if defined(PETSC_HAVE_CUDA)
1001:   cublasStatus_t cberr;
1002: #endif

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

1011:   MPI_Comm_rank(PETSC_COMM_WORLD,&rank);

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

1018:     PetscOptionsGetString(NULL,NULL,"-citations",filename,PETSC_MAX_PATH_LEN,NULL);
1019:     if (filename[0]) {
1020:       PetscFOpen(PETSC_COMM_WORLD,filename,"w",&fd);
1021:     }
1022:     PetscSegBufferGet(PetscCitationsList,1,&cits);
1023:     cits[0] = 0;
1024:     PetscSegBufferExtractAlloc(PetscCitationsList,&cits);
1025:     PetscFPrintf(PETSC_COMM_WORLD,fd,"If you publish results based on this computation please cite the following:\n");
1026:     PetscFPrintf(PETSC_COMM_WORLD,fd,"===========================================================================\n");
1027:     PetscFPrintf(PETSC_COMM_WORLD,fd,"%s",cits);
1028:     PetscFPrintf(PETSC_COMM_WORLD,fd,"===========================================================================\n");
1029:     PetscFClose(PETSC_COMM_WORLD,fd);
1030:     PetscFree(cits);
1031:   }
1032:   PetscSegBufferDestroy(&PetscCitationsList);

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

1062: #if defined(PETSC_SERIALIZE_FUNCTIONS)
1063:   PetscFPTDestroy();
1064: #endif


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

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

1084: #if !defined(PETSC_HAVE_THREADSAFETY)
1085:   PetscOptionsGetBool(NULL,NULL,"-malloc_info",&flg2,NULL);
1086:   if (!flg2) {
1087:     flg2 = PETSC_FALSE;
1088:     PetscOptionsGetBool(NULL,NULL,"-memory_view",&flg2,NULL);
1089:   }
1090:   if (flg2) {
1091:     PetscMemoryView(PETSC_VIEWER_STDOUT_WORLD,"Summary of Memory Usage in PETSc\n");
1092:   }
1093: #endif

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


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

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

1118:   PetscLogViewFromOptions();
1119:   PetscOptionsGetString(NULL,NULL,"-log_summary",mname,PETSC_MAX_PATH_LEN,&flg1);
1120:   if (flg1) {
1121:     PetscViewer viewer;
1122:     (*PetscHelpPrintf)(PETSC_COMM_WORLD,"\n\n WARNING:   -log_summary is being deprecated; switch to -log_view\n\n\n");
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:       PetscViewerPushFormat(viewer,PETSC_VIEWER_DEFAULT);
1130:       PetscLogView(viewer);
1131:       PetscViewerPopFormat(viewer);
1132:     }
1133:   }
1134:   mname[0] = 0;

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

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

1149:   PetscStackDestroy();

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

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

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

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

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

1216: #if defined(PETSC_USE_LOG)
1217:   /*
1218:        List all objects the user may have forgot to free
1219:   */
1220:   if (PetscObjectsLog) {
1221:     PetscOptionsHasName(NULL,NULL,"-objects_dump",&flg1);
1222:     if (flg1) {
1223:       MPI_Comm local_comm;
1224:       char     string[64];

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

1236: #if defined(PETSC_USE_LOG)
1237:   PetscObjectsCounts    = 0;
1238:   PetscObjectsMaxCounts = 0;
1239:   PetscFree(PetscObjects);
1240: #endif

1242:   /*
1243:      Destroy any packages that registered a finalize
1244:   */
1245:   PetscRegisterFinalizeAll();

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

1251:   /*
1252:      Print PetscFunctionLists that have not been properly freed

1254:   PetscFunctionListPrintAll();
1255:   */

1257:   if (petsc_history) {
1258:     PetscCloseHistoryFile(&petsc_history);
1259:     petsc_history = 0;
1260:   }
1261:   PetscOptionsHelpPrintedDestroy(&PetscOptionsHelpPrintedSingleton);

1263:   PetscInfoAllow(PETSC_FALSE,NULL);

1265: #if !defined(PETSC_HAVE_THREADSAFETY)
1266:   {
1267:     char fname[PETSC_MAX_PATH_LEN];
1268:     FILE *fd;
1269:     int  err;

1271:     fname[0] = 0;

1273:     PetscOptionsGetString(NULL,NULL,"-malloc_dump",fname,250,&flg1);
1274:     flg2 = PETSC_FALSE;
1275:     PetscOptionsGetBool(NULL,NULL,"-malloc_test",&flg2,NULL);
1276: #if defined(PETSC_USE_DEBUG)
1277:     if (PETSC_RUNNING_ON_VALGRIND) flg2 = PETSC_FALSE;
1278: #else
1279:     flg2 = PETSC_FALSE;         /* Skip reporting for optimized builds regardless of -malloc_test */
1280: #endif
1281:     if (flg1 && fname[0]) {
1282:       char sname[PETSC_MAX_PATH_LEN];

1284:       sprintf(sname,"%s_%d",fname,rank);
1285:       fd   = fopen(sname,"w"); if (!fd) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_FILE_OPEN,"Cannot open log file: %s",sname);
1286:       PetscMallocDump(fd);
1287:       err  = fclose(fd);
1288:       if (err) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SYS,"fclose() failed on file");
1289:     } else if (flg1 || flg2) {
1290:       MPI_Comm local_comm;

1292:       MPI_Comm_dup(MPI_COMM_WORLD,&local_comm);
1293:       PetscSequentialPhaseBegin_Private(local_comm,1);
1294:       PetscMallocDump(stdout);
1295:       PetscSequentialPhaseEnd_Private(local_comm,1);
1296:       MPI_Comm_free(&local_comm);
1297:     }
1298:   }

1300:   {
1301:     char fname[PETSC_MAX_PATH_LEN];
1302:     FILE *fd = NULL;

1304:     fname[0] = 0;

1306:     PetscOptionsGetString(NULL,NULL,"-malloc_log",fname,250,&flg1);
1307:     PetscOptionsHasName(NULL,NULL,"-malloc_log_threshold",&flg2);
1308:     if (flg1 && fname[0]) {
1309:       int err;

1311:       if (!rank) {
1312:         fd = fopen(fname,"w");
1313:         if (!fd) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_FILE_OPEN,"Cannot open log file: %s",fname);
1314:       }
1315:       PetscMallocDumpLog(fd);
1316:       if (fd) {
1317:         err = fclose(fd);
1318:         if (err) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SYS,"fclose() failed on file");
1319:       }
1320:     } else if (flg1 || flg2) {
1321:       PetscMallocDumpLog(stdout);
1322:     }
1323:   }
1324: #endif

1326:   /*
1327:      Close any open dynamic libraries
1328:   */
1329:   PetscFinalize_DynamicLibraries();

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

1347:   /* Can be destroyed only after all the options are used */
1348:   PetscOptionsDestroyDefault();

1350:   PetscGlobalArgc = 0;
1351:   PetscGlobalArgs = 0;

1353: #if defined(PETSC_USE_REAL___FLOAT128)
1354:   MPI_Type_free(&MPIU___FLOAT128);
1355: #if defined(PETSC_HAVE_COMPLEX)
1356:   MPI_Type_free(&MPIU___COMPLEX128);
1357: #endif
1358:   MPI_Op_free(&MPIU_MAX);
1359:   MPI_Op_free(&MPIU_MIN);
1360: #endif

1362: #if defined(PETSC_HAVE_COMPLEX)
1363: #if !defined(PETSC_HAVE_MPI_C_DOUBLE_COMPLEX)
1364:   MPI_Type_free(&MPIU_C_DOUBLE_COMPLEX);
1365:   MPI_Type_free(&MPIU_C_COMPLEX);
1366: #endif
1367: #endif

1369: #if (defined(PETSC_HAVE_COMPLEX) && !defined(PETSC_HAVE_MPI_C_DOUBLE_COMPLEX)) || defined(PETSC_USE_REAL___FLOAT128)
1370:   MPI_Op_free(&MPIU_SUM);
1371: #endif

1373:   MPI_Type_free(&MPIU_2SCALAR);
1374: #if defined(PETSC_USE_64BIT_INDICES) || !defined(MPI_2INT)
1375:   MPI_Type_free(&MPIU_2INT);
1376: #endif
1377:   MPI_Op_free(&PetscMaxSum_Op);

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

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

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

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

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

1417:   PetscSpinlockDestroy(&PetscViewerASCIISpinLockOpen);
1418:   PetscSpinlockDestroy(&PetscViewerASCIISpinLockStdout);
1419:   PetscSpinlockDestroy(&PetscViewerASCIISpinLockStderr);
1420:   PetscSpinlockDestroy(&PetscCommSpinLock);

1422:   if (PetscBeganMPI) {
1423: #if defined(PETSC_HAVE_MPI_FINALIZED)
1424:     PetscMPIInt flag;
1425:     MPI_Finalized(&flag);
1426:     if (flag) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_LIB,"MPI_Finalize() has already been called, even though MPI_Init() was called by PetscInitialize()");
1427: #endif
1428:     MPI_Finalize();
1429:   }
1430: /*

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

1440: */
1441:   PetscMallocClear();

1443:   PetscInitializeCalled = PETSC_FALSE;
1444:   PetscFinalizeCalled   = PETSC_TRUE;
1445:   PetscFunctionReturn(ierr);
1446: }

1448: #if defined(PETSC_MISSING_LAPACK_lsame_)
1449: PETSC_EXTERN int lsame_(char *a,char *b)
1450: {
1451:   if (*a == *b) return 1;
1452:   if (*a + 32 == *b) return 1;
1453:   if (*a - 32 == *b) return 1;
1454:   return 0;
1455: }
1456: #endif

1458: #if defined(PETSC_MISSING_LAPACK_lsame)
1459: PETSC_EXTERN int lsame(char *a,char *b)
1460: {
1461:   if (*a == *b) return 1;
1462:   if (*a + 32 == *b) return 1;
1463:   if (*a - 32 == *b) return 1;
1464:   return 0;
1465: }
1466: #endif