Actual source code: pinit.c

petsc-master 2015-04-19
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_HAVE_CUDA)
 10: #include <cublas.h>
 11: #endif

 13: #include <petscthreadcomm.h>

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

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

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

 28: extern FILE *petsc_history;

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

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

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

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

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

 55: PetscInt PetscHotRegionDepth;

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

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

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

 87:    Collective

 89:    Level: advanced

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

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

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

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

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

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

130:    Collective

132:    Level: advanced

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

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

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

152:    Level: beginner

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

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

167:    Level: developer

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

177: extern PetscErrorCode PetscOptionsCheckInitial_Private(void);

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

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

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

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

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

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

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

231: /* ----------------------------------------------------------------------------*/

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

238: PETSC_EXTERN void PetscSum_Local(void *in,void *out,PetscMPIInt *cnt,MPI_Datatype *datatype)
239: {
240:   PetscInt i,count = *cnt;

243:   if (*datatype == MPIU_REAL) {
244:     PetscReal *xin = (PetscReal*)in,*xout = (PetscReal*)out;
245:     for (i=0; i<count; i++) xout[i] += xin[i];
246:   }
247: #if defined(PETSC_HAVE_COMPLEX)
248:   else if (*datatype == MPIU_COMPLEX) {
249:     PetscComplex *xin = (PetscComplex*)in,*xout = (PetscComplex*)out;
250:     for (i=0; i<count; i++) xout[i] += xin[i];
251:   }
252: #endif
253:   else {
254:     (*PetscErrorPrintf)("Can only handle MPIU_REAL or MPIU_COMPLEX data types");
255:     MPI_Abort(MPI_COMM_WORLD,1);
256:   }
257:   PetscFunctionReturnVoid();
258: }
259: #endif

261: #if defined(PETSC_USE_REAL___FLOAT128)
262: MPI_Op MPIU_MAX = 0;
263: MPI_Op MPIU_MIN = 0;

267: PETSC_EXTERN void PetscMax_Local(void *in,void *out,PetscMPIInt *cnt,MPI_Datatype *datatype)
268: {
269:   PetscInt i,count = *cnt;

272:   if (*datatype == MPIU_REAL) {
273:     PetscReal *xin = (PetscReal*)in,*xout = (PetscReal*)out;
274:     for (i=0; i<count; i++) xout[i] = PetscMax(xout[i],xin[i]);
275:   }
276: #if defined(PETSC_HAVE_COMPLEX)
277:   else if (*datatype == MPIU_COMPLEX) {
278:     PetscComplex *xin = (PetscComplex*)in,*xout = (PetscComplex*)out;
279:     for (i=0; i<count; i++) {
280:       xout[i] = PetscRealPartComplex(xout[i])<PetscRealPartComplex(xin[i]) ? xin[i] : xout[i];
281:     }
282:   }
283: #endif
284:   else {
285:     (*PetscErrorPrintf)("Can only handle MPIU_REAL or MPIU_COMPLEX data types");
286:     MPI_Abort(MPI_COMM_WORLD,1);
287:   }
288:   PetscFunctionReturnVoid();
289: }

293: PETSC_EXTERN void PetscMin_Local(void *in,void *out,PetscMPIInt *cnt,MPI_Datatype *datatype)
294: {
295:   PetscInt    i,count = *cnt;

298:   if (*datatype == MPIU_REAL) {
299:     PetscReal *xin = (PetscReal*)in,*xout = (PetscReal*)out;
300:     for (i=0; i<count; i++) xout[i] = PetscMin(xout[i],xin[i]);
301:   }
302: #if defined(PETSC_HAVE_COMPLEX)
303:   else if (*datatype == MPIU_COMPLEX) {
304:     PetscComplex *xin = (PetscComplex*)in,*xout = (PetscComplex*)out;
305:     for (i=0; i<count; i++) {
306:       xout[i] = PetscRealPartComplex(xout[i])>PetscRealPartComplex(xin[i]) ? xin[i] : xout[i];
307:     }
308:   }
309: #endif
310:   else {
311:     (*PetscErrorPrintf)("Can only handle MPIU_REAL or MPIU_SCALAR data (i.e. double or complex) types");
312:     MPI_Abort(MPI_COMM_WORLD,1);
313:   }
314:   PetscFunctionReturnVoid();
315: }
316: #endif

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

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

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

327: */
328: PETSC_EXTERN PetscMPIInt MPIAPI Petsc_DelCounter(MPI_Comm comm,PetscMPIInt keyval,void *count_val,void *extra_state)
329: {

333:   PetscInfo1(0,"Deleting counter data in an MPI_Comm %ld\n",(long)comm);if (ierr) PetscFunctionReturn((PetscMPIInt)ierr);
334:   PetscFree(count_val);if (ierr) PetscFunctionReturn((PetscMPIInt)ierr);
335:   PetscFunctionReturn(MPI_SUCCESS);
336: }

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

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

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

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

350: */
351: PETSC_EXTERN PetscMPIInt MPIAPI Petsc_DelComm_Outer(MPI_Comm comm,PetscMPIInt keyval,void *attr_val,void *extra_state)
352: {
354:   PetscMPIInt    flg;
355:   union {MPI_Comm comm; void *ptr;} icomm,ocomm;

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

361:   MPI_Attr_get(icomm.comm,Petsc_OuterComm_keyval,&ocomm,&flg);
362:   if (!flg) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_CORRUPT,"Inner MPI_Comm does not have expected reference to outer comm");
363:   if (ocomm.comm != comm) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_CORRUPT,"Inner MPI_Comm has reference to non-matching outer comm");
364:   MPI_Attr_delete(icomm.comm,Petsc_OuterComm_keyval); /* Calls Petsc_DelComm_Inner */
365:   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);
366:   PetscFunctionReturn(MPI_SUCCESS);
367: }

371: /*
372:  * This is invoked on the inner comm when Petsc_DelComm_Outer calls MPI_Attr_delete.  It should not be reached any other way.
373:  */
374: PETSC_EXTERN PetscMPIInt MPIAPI Petsc_DelComm_Inner(MPI_Comm comm,PetscMPIInt keyval,void *attr_val,void *extra_state)
375: {

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

383: #if defined(PETSC_USE_PETSC_MPI_EXTERNAL32)
384: #if !defined(PETSC_WORDS_BIGENDIAN)
385: PETSC_EXTERN PetscMPIInt PetscDataRep_extent_fn(MPI_Datatype,MPI_Aint*,void*);
386: PETSC_EXTERN PetscMPIInt PetscDataRep_read_conv_fn(void*, MPI_Datatype,PetscMPIInt,void*,MPI_Offset,void*);
387: PETSC_EXTERN PetscMPIInt PetscDataRep_write_conv_fn(void*, MPI_Datatype,PetscMPIInt,void*,MPI_Offset,void*);
388: #endif
389: #endif

391: int  PetscGlobalArgc   = 0;
392: char **PetscGlobalArgs = 0;
393: PetscSegBuffer PetscCitationsList;

397: PetscErrorCode PetscCitationsInitialize()
398: {

402:   PetscSegBufferCreate(1,10000,&PetscCitationsList);
403:   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);
404:   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);
405:   return(0);
406: }

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

414:    Not Collective

416:    Output Parameters:
417: +  argc - count of number of command line arguments
418: -  args - the command line arguments

420:    Level: intermediate

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

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

428:    Concepts: command line arguments

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

432: @*/
433: PetscErrorCode  PetscGetArgs(int *argc,char ***args)
434: {
436:   if (!PetscInitializeCalled && PetscFinalizeCalled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ORDER,"You must call after PetscInitialize() but before PetscFinalize()");
437:   *argc = PetscGlobalArgc;
438:   *args = PetscGlobalArgs;
439:   return(0);
440: }

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

448:    Not Collective

450:    Output Parameters:
451: .  args - the command line arguments

453:    Level: intermediate

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

458:    Concepts: command line arguments

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

462: @*/
463: PetscErrorCode  PetscGetArguments(char ***args)
464: {
465:   PetscInt       i,argc = PetscGlobalArgc;

469:   if (!PetscInitializeCalled && PetscFinalizeCalled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ORDER,"You must call after PetscInitialize() but before PetscFinalize()");
470:   if (!argc) {*args = 0; return(0);}
471:   PetscMalloc1(argc,args);
472:   for (i=0; i<argc-1; i++) {
473:     PetscStrallocpy(PetscGlobalArgs[i+1],&(*args)[i]);
474:   }
475:   (*args)[argc-1] = 0;
476:   return(0);
477: }

481: /*@C
482:    PetscFreeArguments - Frees the memory obtained with PetscGetArguments()

484:    Not Collective

486:    Output Parameters:
487: .  args - the command line arguments

489:    Level: intermediate

491:    Concepts: command line arguments

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

495: @*/
496: PetscErrorCode  PetscFreeArguments(char **args)
497: {
498:   PetscInt       i = 0;

502:   if (!args) return(0);
503:   while (args[i]) {
504:     PetscFree(args[i]);
505:     i++;
506:   }
507:   PetscFree(args);
508:   return(0);
509: }

511: #if defined(PETSC_HAVE_SAWS)
512: #include <petscconfiginfo.h>

516: PetscErrorCode  PetscInitializeSAWs(const char help[])
517: {
518:   if (!PetscGlobalRank) {
519:     char           cert[PETSC_MAX_PATH_LEN],root[PETSC_MAX_PATH_LEN],*intro,programname[64],*appline,*options,version[64];
520:     int            port;
521:     PetscBool      flg,rootlocal = PETSC_FALSE,flg2;
522:     size_t         applinelen,introlen;
524:     /* char           sawsurl[256]; */
525: 
526:     PetscOptionsHasName(NULL,"-saws_log",&flg);
527:     if (flg) {
528:       char  sawslog[PETSC_MAX_PATH_LEN];

530:       PetscOptionsGetString(NULL,"-saws_log",sawslog,PETSC_MAX_PATH_LEN,NULL);
531:       if (sawslog[0]) {
532:         PetscStackCallSAWs(SAWs_Set_Use_Logfile,(sawslog));
533:       } else {
534:         PetscStackCallSAWs(SAWs_Set_Use_Logfile,(NULL));
535:       }
536:     }
537:     PetscOptionsGetString(NULL,"-saws_https",cert,PETSC_MAX_PATH_LEN,&flg);
538:     if (flg) {
539:       PetscStackCallSAWs(SAWs_Set_Use_HTTPS,(cert));
540:     }
541:     PetscOptionsGetInt(NULL,"-saws_port",&port,&flg);
542:     if (flg) {
543:       PetscStackCallSAWs(SAWs_Set_Port,(port));
544:     }
545:     PetscOptionsGetString(NULL,"-saws_root",root,PETSC_MAX_PATH_LEN,&flg);
546:     if (flg) {
547:       PetscStackCallSAWs(SAWs_Set_Document_Root,(root));
548:       PetscStrcmp(root,".",&rootlocal);
549:     } else {
550:       PetscOptionsHasName(NULL,"-saws_options",&flg);
551:       if (flg) {
552:         PetscStrreplace(PETSC_COMM_WORLD,"${PETSC_DIR}/share/petsc/saws",root,PETSC_MAX_PATH_LEN);
553:         PetscStackCallSAWs(SAWs_Set_Document_Root,(root));
554:       }
555:     }
556:     PetscOptionsHasName(NULL,"-saws_local",&flg2);
557:     if (flg2) {
558:       char jsdir[PETSC_MAX_PATH_LEN];
559:       if (!flg) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"-saws_local option requires -saws_root option");
560:       PetscSNPrintf(jsdir,PETSC_MAX_PATH_LEN,"%s/js",root);
561:       PetscTestDirectory(jsdir,'r',&flg);
562:       if (!flg) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_FILE_READ,"-saws_local option requires js directory in root directory");
563:       PetscStackCallSAWs(SAWs_Push_Local_Header,());
564:     }
565:     PetscGetProgramName(programname,64);
566:     PetscStrlen(help,&applinelen);
567:     introlen   = 4096 + applinelen;
568:     applinelen += 1024;
569:     PetscMalloc(applinelen,&appline);
570:     PetscMalloc(introlen,&intro);

572:     if (rootlocal) {
573:       PetscSNPrintf(appline,applinelen,"%s.c.html",programname);
574:       PetscTestFile(appline,'r',&rootlocal);
575:     }
576:     PetscOptionsGetAll(&options);
577:     if (rootlocal && help) {
578:       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);
579:     } else if (help) {
580:       PetscSNPrintf(appline,applinelen,"<center>Running %s %s</center><br><center><pre>%s</pre></center><br>",programname,options,help);
581:     } else {
582:       PetscSNPrintf(appline,applinelen,"<center> Running %s %s</center><br>\n",programname,options);
583:     }
584:     PetscFree(options);
585:     PetscGetVersion(version,sizeof(version));
586:     PetscSNPrintf(intro,introlen,"<body>\n"
587:                                     "<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"
588:                                     "<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"
589:                                     "%s",version,petscconfigureoptions,appline);
590:     PetscStackCallSAWs(SAWs_Push_Body,("index.html",0,intro));
591:     PetscFree(intro);
592:     PetscFree(appline);
593:     PetscStackCallSAWs(SAWs_Initialize,());
594:     /* PetscStackCallSAWs(SAWs_Get_FullURL,(sizeof(sawsurl),sawsurl));
595:      PetscPrintf(PETSC_COMM_WORLD,"Point your browser to %s for SAWs\n",sawsurl); */
596:     PetscCitationsRegister("@TechReport{ saws,\n"
597:                                   "  Author = {Matt Otten and Jed Brown and Barry Smith},\n"
598:                                   "  Title  = {Scientific Application Web Server (SAWs) Users Manual},\n"
599:                                   "  Institution = {Argonne National Laboratory},\n"
600:                                   "  Year   = 2013\n}\n",NULL);
601:   }
602:   return(0);
603: }
604: #endif

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

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

616:    Input Parameters:
617: +  argc - count of number of command line arguments
618: .  args - the command line arguments
619: .  file - [optional] PETSc database file, also checks ~username/.petscrc and .petscrc use NULL to not check for
620:           code specific file. Use -skip_petscrc in the code specific file to skip the .petscrc files
621: -  help - [optional] Help message to print, use NULL for no message

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

629:    Options Database Keys:
630: +  -start_in_debugger [noxterm,dbx,xdb,gdb,...] - Starts program in debugger
631: .  -on_error_attach_debugger [noxterm,dbx,xdb,gdb,...] - Starts debugger when error detected
632: .  -on_error_emacs <machinename> causes emacsclient to jump to error file
633: .  -on_error_abort calls abort() when error detected (no traceback)
634: .  -on_error_mpiabort calls MPI_abort() when error detected
635: .  -error_output_stderr prints error messages to stderr instead of the default stdout
636: .  -error_output_none does not print the error messages (but handles errors in the same way as if this was not called)
637: .  -debugger_nodes [node1,node2,...] - Indicates nodes to start in debugger
638: .  -debugger_pause [sleeptime] (in seconds) - Pauses debugger
639: .  -stop_for_debugger - Print message on how to attach debugger manually to
640:                         process and wait (-debugger_pause) seconds for attachment
641: .  -malloc - Indicates use of PETSc error-checking malloc (on by default for debug version of libraries)
642: .  -malloc no - Indicates not to use error-checking malloc
643: .  -malloc_debug - check for memory corruption at EVERY malloc or free
644: .  -malloc_dump - prints a list of all unfreed memory at the end of the run
645: .  -malloc_test - like -malloc_dump -malloc_debug, but only active for debugging builds
646: .  -fp_trap - Stops on floating point exceptions (Note that on the
647:               IBM RS6000 this slows code by at least a factor of 10.)
648: .  -no_signal_handler - Indicates not to trap error signals
649: .  -shared_tmp - indicates /tmp directory is shared by all processors
650: .  -not_shared_tmp - each processor has own /tmp
651: .  -tmp - alternative name of /tmp directory
652: .  -get_total_flops - returns total flops done by all processors
653: -  -memory_info - Print memory usage at end of run

655:    Options Database Keys for Profiling:
656:    See Users-Manual: Chapter 13 Profiling for details.
657: +  -info <optional filename> - Prints verbose information to the screen
658: .  -info_exclude <null,vec,mat,pc,ksp,snes,ts> - Excludes some of the verbose messages
659: .  -log_sync - Log the synchronization in scatters, inner products and norms
660: .  -log_trace [filename] - Print traces of all PETSc calls to the screen (useful to determine where a program
661:         hangs without running in the debugger).  See PetscLogTraceBegin().
662: .  -log_summary [filename] - Prints summary of flop and timing information to screen. If the filename is specified the
663:         summary is written to the file.  See PetscLogView().
664: .  -log_all [filename] - Logs extensive profiling information  See PetscLogDump().
665: .  -log [filename] - Logs basic profiline information  See PetscLogDump().
666: -  -log_mpe [filename] - Creates a logfile viewable by the utility Jumpshot (in MPICH distribution)

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

670:    Environmental Variables:
671: +   PETSC_TMP - alternative tmp directory
672: .   PETSC_SHARED_TMP - tmp is shared by all processes
673: .   PETSC_NOT_SHARED_TMP - each process has its own private tmp
674: .   PETSC_VIEWER_SOCKET_PORT - socket number to use for socket viewer
675: -   PETSC_VIEWER_SOCKET_MACHINE - machine to use for socket viewer to connect to


678:    Level: beginner

680:    Notes:
681:    If for some reason you must call MPI_Init() separately, call
682:    it before PetscInitialize().

684:    Fortran Version:
685:    In Fortran this routine has the format
686: $       call PetscInitialize(file,ierr)

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

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

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

700:    Concepts: initializing PETSc

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

704: @*/
705: PetscErrorCode  PetscInitialize(int *argc,char ***args,const char file[],const char help[])
706: {
708:   PetscMPIInt    flag, size;
709:   PetscBool      flg;
710:   char           hostname[256];

713:   if (PetscInitializeCalled) return(0);

715:   /* these must be initialized in a routine, not as a constant declaration*/
716:   PETSC_STDOUT = stdout;
717:   PETSC_STDERR = stderr;

719:   /* on Windows - set printf to default to printing 2 digit exponents */
720: #if defined(PETSC_HAVE__SET_OUTPUT_FORMAT)
721:   _set_output_format(_TWO_DIGIT_EXPONENT);
722: #endif

724:   PetscOptionsCreate();

726:   /*
727:      We initialize the program name here (before MPI_Init()) because MPICH has a bug in
728:      it that it sets args[0] on all processors to be args[0] on the first processor.
729:   */
730:   if (argc && *argc) {
731:     PetscSetProgramName(**args);
732:   } else {
733:     PetscSetProgramName("Unknown Name");
734:   }

736:   MPI_Initialized(&flag);
737:   if (!flag) {
738:     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");
739: #if defined(PETSC_HAVE_MPI_INIT_THREAD)
740:     {
741:       PetscMPIInt provided;
742:       MPI_Init_thread(argc,args,MPI_THREAD_FUNNELED,&provided);
743:     }
744: #else
745:     MPI_Init(argc,args);
746: #endif
747:     PetscBeganMPI = PETSC_TRUE;
748:   }
749:   if (argc && args) {
750:     PetscGlobalArgc = *argc;
751:     PetscGlobalArgs = *args;
752:   }
753:   PetscFinalizeCalled = PETSC_FALSE;

755:   if (PETSC_COMM_WORLD == MPI_COMM_NULL) PETSC_COMM_WORLD = MPI_COMM_WORLD;
756:   MPI_Comm_set_errhandler(PETSC_COMM_WORLD,MPI_ERRORS_RETURN);

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

761:   MPI_Comm_rank(MPI_COMM_WORLD,&PetscGlobalRank);
762:   MPI_Comm_size(MPI_COMM_WORLD,&PetscGlobalSize);

764:   MPIU_BOOL = MPI_INT;
765:   MPIU_ENUM = MPI_INT;

767:   /*
768:      Initialized the global complex variable; this is because with
769:      shared libraries the constructors for global variables
770:      are not called; at least on IRIX.
771:   */
772: #if defined(PETSC_HAVE_COMPLEX)
773:   {
774: #if defined(PETSC_CLANGUAGE_CXX)
775:     PetscComplex ic(0.0,1.0);
776:     PETSC_i = ic;
777: #elif defined(PETSC_CLANGUAGE_C)
778:     PETSC_i = _Complex_I;
779: #endif
780:   }

782: #if !defined(PETSC_HAVE_MPI_C_DOUBLE_COMPLEX)
783:   MPI_Type_contiguous(2,MPI_DOUBLE,&MPIU_C_DOUBLE_COMPLEX);
784:   MPI_Type_commit(&MPIU_C_DOUBLE_COMPLEX);
785:   MPI_Type_contiguous(2,MPI_FLOAT,&MPIU_C_COMPLEX);
786:   MPI_Type_commit(&MPIU_C_COMPLEX);
787: #endif
788: #endif /* PETSC_HAVE_COMPLEX */

790:   /*
791:      Create the PETSc MPI reduction operator that sums of the first
792:      half of the entries and maxes the second half.
793:   */
794:   MPI_Op_create(PetscMaxSum_Local,1,&PetscMaxSum_Op);

796: #if defined(PETSC_USE_REAL___FLOAT128)
797:   MPI_Type_contiguous(2,MPI_DOUBLE,&MPIU___FLOAT128);
798:   MPI_Type_commit(&MPIU___FLOAT128);
799: #if defined(PETSC_HAVE_COMPLEX)
800:   MPI_Type_contiguous(4,MPI_DOUBLE,&MPIU___COMPLEX128);
801:   MPI_Type_commit(&MPIU___COMPLEX128);
802: #endif
803:   MPI_Op_create(PetscMax_Local,1,&MPIU_MAX);
804:   MPI_Op_create(PetscMin_Local,1,&MPIU_MIN);
805: #endif

807: #if (defined(PETSC_HAVE_COMPLEX) && !defined(PETSC_HAVE_MPI_C_DOUBLE_COMPLEX)) || defined(PETSC_USE_REAL___FLOAT128)
808:   MPI_Op_create(PetscSum_Local,1,&MPIU_SUM);
809: #endif

811:   MPI_Type_contiguous(2,MPIU_SCALAR,&MPIU_2SCALAR);
812:   MPI_Type_commit(&MPIU_2SCALAR);

814: #if defined(PETSC_USE_64BIT_INDICES) || !defined(MPI_2INT)
815:   MPI_Type_contiguous(2,MPIU_INT,&MPIU_2INT);
816:   MPI_Type_commit(&MPIU_2INT);
817: #endif


820:   /*
821:      Attributes to be set on PETSc communicators
822:   */
823:   MPI_Keyval_create(MPI_NULL_COPY_FN,Petsc_DelCounter,&Petsc_Counter_keyval,(void*)0);
824:   MPI_Keyval_create(MPI_NULL_COPY_FN,Petsc_DelComm_Outer,&Petsc_InnerComm_keyval,(void*)0);
825:   MPI_Keyval_create(MPI_NULL_COPY_FN,Petsc_DelComm_Inner,&Petsc_OuterComm_keyval,(void*)0);

827:   /*
828:      Build the options database
829:   */
830:   PetscOptionsInsert(argc,args,file);


833:   /*
834:      Print main application help message
835:   */
836:   PetscOptionsHasName(NULL,"-help",&flg);
837:   if (help && flg) {
838:     PetscPrintf(PETSC_COMM_WORLD,help);
839:   }
840:   PetscOptionsCheckInitial_Private();

842:   PetscCitationsInitialize();

844: #if defined(PETSC_HAVE_SAWS)
845:   PetscInitializeSAWs(help);
846: #endif

848:   /* SHOULD PUT IN GUARDS: Make sure logging is initialized, even if we do not print it out */
849: #if defined(PETSC_USE_LOG)
850:   PetscLogBegin_Private();
851: #endif

853:   /*
854:      Load the dynamic libraries (on machines that support them), this registers all
855:      the solvers etc. (On non-dynamic machines this initializes the PetscDraw and PetscViewer classes)
856:   */
857:   PetscInitialize_DynamicLibraries();

859:   MPI_Comm_size(PETSC_COMM_WORLD,&size);
860:   PetscInfo1(0,"PETSc successfully started: number of processors = %d\n",size);
861:   PetscGetHostName(hostname,256);
862:   PetscInfo1(0,"Running on machine: %s\n",hostname);

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

867:   PetscOptionsCheckInitial_Components();
868:   /* Check the options database for options related to the options database itself */
869:   PetscOptionsSetFromOptions();

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

875:       Currently not used because it is not supported by MPICH.
876:   */
877: #if !defined(PETSC_WORDS_BIGENDIAN)
878:   MPI_Register_datarep((char*)"petsc",PetscDataRep_read_conv_fn,PetscDataRep_write_conv_fn,PetscDataRep_extent_fn,NULL);
879: #endif
880: #endif

882: #if defined(PETSC_HAVE_CUDA)
883:   flg  = PETSC_TRUE;
884:   PetscOptionsGetBool(NULL,"-cublas",&flg,NULL);
885:   if (flg) {
886:     PetscMPIInt p;
887:     for (p = 0; p < PetscGlobalSize; ++p) {
888:       if (p == PetscGlobalRank) cublasInit();
889:       MPI_Barrier(PETSC_COMM_WORLD);
890:     }
891:   }
892: #endif

894:   PetscOptionsHasName(NULL,"-python",&flg);
895:   if (flg) {
896:     PetscInitializeCalled = PETSC_TRUE;
897:     PetscPythonInitialize(NULL,NULL);
898:   }

900:   /*
901:       Setup building of stack frames for all function calls
902:   */
903:   PetscThreadLocalRegister((PetscThreadKey*)&petscstack); /* Creates pthread_key */
904: #if defined(PETSC_USE_DEBUG)
905:   PetscStackCreate();
906: #endif

908: #if defined(PETSC_SERIALIZE_FUNCTIONS)
909:   PetscFPTCreate(10000);
910: #endif


913:   /*
914:       Once we are completedly initialized then we can set this variables
915:   */
916:   PetscInitializeCalled = PETSC_TRUE;
917:   return(0);
918: }

920: #if defined(PETSC_USE_LOG)
921: extern PetscObject *PetscObjects;
922: extern PetscInt    PetscObjectsCounts, PetscObjectsMaxCounts;
923: extern PetscBool   PetscObjectsLog;
924: #endif

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

933:    Collective on PETSC_COMM_WORLD

935:    Options Database Keys:
936: +  -options_table - Calls PetscOptionsView()
937: .  -options_left - Prints unused options that remain in the database
938: .  -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
939: .  -mpidump - Calls PetscMPIDump()
940: .  -malloc_dump - Calls PetscMallocDump()
941: .  -malloc_info - Prints total memory usage
942: -  -malloc_log - Prints summary of memory usage

944:    Level: beginner

946:    Note:
947:    See PetscInitialize() for more general runtime options.

949: .seealso: PetscInitialize(), PetscOptionsView(), PetscMallocDump(), PetscMPIDump(), PetscEnd()
950: @*/
951: PetscErrorCode  PetscFinalize(void)
952: {
954:   PetscMPIInt    rank;
955:   PetscInt       nopt;
956:   PetscBool      flg1 = PETSC_FALSE,flg2 = PETSC_FALSE,flg3 = PETSC_FALSE;
957:   PetscBool      flg;
958: #if defined(PETSC_USE_LOG)
959:   char           mname[PETSC_MAX_PATH_LEN];
960: #endif

963:   if (!PetscInitializeCalled) {
964:     printf("PetscInitialize() must be called before PetscFinalize()\n");
965:     PetscFunctionReturn(PETSC_ERR_ARG_WRONGSTATE);
966:   }
967:   PetscInfo(NULL,"PetscFinalize() called\n");

969:   MPI_Comm_rank(PETSC_COMM_WORLD,&rank);

971:   PetscOptionsHasName(NULL,"-citations",&flg);
972:   if (flg) {
973:     char  *cits, filename[PETSC_MAX_PATH_LEN];
974:     FILE  *fd = PETSC_STDOUT;

976:     PetscOptionsGetString(NULL,"-citations",filename,PETSC_MAX_PATH_LEN,NULL);
977:     if (filename[0]) {
978:       PetscFOpen(PETSC_COMM_WORLD,filename,"w",&fd);
979:     }
980:     PetscSegBufferGet(PetscCitationsList,1,&cits);
981:     cits[0] = 0;
982:     PetscSegBufferExtractAlloc(PetscCitationsList,&cits);
983:     PetscFPrintf(PETSC_COMM_WORLD,fd,"If you publish results based on this computation please cite the following:\n");
984:     PetscFPrintf(PETSC_COMM_WORLD,fd,"===========================================================================\n");
985:     PetscFPrintf(PETSC_COMM_WORLD,fd,"%s",cits);
986:     PetscFPrintf(PETSC_COMM_WORLD,fd,"===========================================================================\n");
987:     PetscFClose(PETSC_COMM_WORLD,fd);
988:     PetscFree(cits);
989:   }
990:   PetscSegBufferDestroy(&PetscCitationsList);

992: #if defined(PETSC_HAVE_SSL) && defined(PETSC_USE_SOCKET_VIEWER)
993:   /* TextBelt is run for testing purposes only, please do not use this feature often */
994:   {
995:     PetscInt nmax = 2;
996:     char     **buffs;
997:     PetscMalloc1(2,&buffs);
998:     PetscOptionsGetStringArray(NULL,"-textbelt",buffs,&nmax,&flg1);
999:     if (flg1) {
1000:       if (!nmax) SETERRQ(PETSC_COMM_WORLD,PETSC_ERR_USER,"-textbelt requires either the phone number or number,\"message\"");
1001:       if (nmax == 1) {
1002:         PetscMalloc1(128,&buffs[1]);
1003:         PetscGetProgramName(buffs[1],32);
1004:         PetscStrcat(buffs[1]," has completed");
1005:       }
1006:       PetscTextBelt(PETSC_COMM_WORLD,buffs[0],buffs[1],NULL);
1007:       PetscFree(buffs[0]);
1008:       PetscFree(buffs[1]);
1009:     }
1010:     PetscFree(buffs);
1011:   }
1012: #endif
1013:   /*
1014:     It should be safe to cancel the options monitors, since we don't expect to be setting options
1015:     here (at least that are worth monitoring).  Monitors ought to be released so that they release
1016:     whatever memory was allocated there before -malloc_dump reports unfreed memory.
1017:   */
1018:   PetscOptionsMonitorCancel();

1020: #if defined(PETSC_SERIALIZE_FUNCTIONS)
1021:   PetscFPTDestroy();
1022: #endif


1025: #if defined(PETSC_HAVE_SAWS)
1026:   flg = PETSC_FALSE;
1027:   PetscOptionsGetBool(NULL,"-saw_options",&flg,NULL);
1028:   if (flg) {
1029:     PetscOptionsSAWsDestroy();
1030:   }
1031: #endif

1033: #if defined(PETSC_HAVE_X)
1034:   flg1 = PETSC_FALSE;
1035:   PetscOptionsGetBool(NULL,"-x_virtual",&flg1,NULL);
1036:   if (flg1) {
1037:     /*  this is a crude hack, but better than nothing */
1038:     PetscPOpen(PETSC_COMM_WORLD,NULL,"pkill -9 Xvfb","r",NULL);
1039:   }
1040: #endif

1042: #if !defined(PETSC_HAVE_THREADSAFETY)
1043:   PetscOptionsGetBool(NULL,"-malloc_info",&flg2,NULL);
1044:   if (!flg2) {
1045:     flg2 = PETSC_FALSE;
1046:     PetscOptionsGetBool(NULL,"-memory_info",&flg2,NULL);
1047:   }
1048:   if (flg2) {
1049:     PetscMemoryShowUsage(PETSC_VIEWER_STDOUT_WORLD,"Summary of Memory Usage in PETSc\n");
1050:   }
1051: #endif

1053: #if defined(PETSC_USE_LOG)
1054:   flg1 = PETSC_FALSE;
1055:   PetscOptionsGetBool(NULL,"-get_total_flops",&flg1,NULL);
1056:   if (flg1) {
1057:     PetscLogDouble flops = 0;
1058:     MPI_Reduce(&petsc_TotalFlops,&flops,1,MPI_DOUBLE,MPI_SUM,0,PETSC_COMM_WORLD);
1059:     PetscPrintf(PETSC_COMM_WORLD,"Total flops over all processors %g\n",flops);
1060:   }
1061: #endif


1064: #if defined(PETSC_USE_LOG)
1065: #if defined(PETSC_HAVE_MPE)
1066:   mname[0] = 0;

1068:   PetscOptionsGetString(NULL,"-log_mpe",mname,PETSC_MAX_PATH_LEN,&flg1);
1069:   if (flg1) {
1070:     if (mname[0]) {PetscLogMPEDump(mname);}
1071:     else          {PetscLogMPEDump(0);}
1072:   }
1073: #endif
1074:   mname[0] = 0;

1076:   PetscLogViewFromOptions();
1077:   PetscOptionsGetString(NULL,"-log_summary",mname,PETSC_MAX_PATH_LEN,&flg1);
1078:   if (flg1) {
1079:     PetscViewer viewer;
1080:     if (mname[0]) {
1081:       PetscViewerASCIIOpen(PETSC_COMM_WORLD,mname,&viewer);
1082:       PetscLogView(viewer);
1083:       PetscViewerDestroy(&viewer);
1084:     } else {
1085:       viewer = PETSC_VIEWER_STDOUT_WORLD;
1086:       PetscLogView(viewer);
1087:     }
1088:   }
1089:   mname[0] = 0;

1091:   PetscOptionsGetString(NULL,"-log_all",mname,PETSC_MAX_PATH_LEN,&flg1);
1092:   PetscOptionsGetString(NULL,"-log",mname,PETSC_MAX_PATH_LEN,&flg2);
1093:   if (flg1 || flg2) {
1094:     if (mname[0]) PetscLogDump(mname);
1095:     else          PetscLogDump(0);
1096:   }
1097: #endif

1099:   /*
1100:      Free all objects registered with PetscObjectRegisterDestroy() such as PETSC_VIEWER_XXX_().
1101:   */
1102:   PetscObjectRegisterDestroyAll();

1104:   PetscStackDestroy();
1105:   PetscThreadLocalDestroy((PetscThreadKey)petscstack); /* Deletes pthread_key */

1107:   flg1 = PETSC_FALSE;
1108:   PetscOptionsGetBool(NULL,"-no_signal_handler",&flg1,NULL);
1109:   if (!flg1) { PetscPopSignalHandler();}
1110:   flg1 = PETSC_FALSE;
1111:   PetscOptionsGetBool(NULL,"-mpidump",&flg1,NULL);
1112:   if (flg1) {
1113:     PetscMPIDump(stdout);
1114:   }
1115:   flg1 = PETSC_FALSE;
1116:   flg2 = PETSC_FALSE;
1117:   /* preemptive call to avoid listing this option in options table as unused */
1118:   PetscOptionsHasName(NULL,"-malloc_dump",&flg1);
1119:   PetscOptionsHasName(NULL,"-objects_dump",&flg1);
1120:   PetscOptionsGetBool(NULL,"-options_view",&flg2,NULL);

1122:   if (flg2) {
1123:     PetscViewer viewer;
1124:     PetscViewerCreate(PETSC_COMM_WORLD,&viewer);
1125:     PetscViewerSetType(viewer,PETSCVIEWERASCII);
1126:     PetscOptionsView(viewer);
1127:     PetscViewerDestroy(&viewer);
1128:   }

1130:   /* to prevent PETSc -options_left from warning */
1131:   PetscOptionsHasName(NULL,"-nox",&flg1);
1132:   PetscOptionsHasName(NULL,"-nox_warning",&flg1);

1134:   flg3 = PETSC_FALSE; /* default value is required */
1135:   PetscOptionsGetBool(NULL,"-options_left",&flg3,&flg1);
1136:   PetscOptionsAllUsed(&nopt);
1137:   if (flg3) {
1138:     if (!flg2) { /* have not yet printed the options */
1139:       PetscViewer viewer;
1140:       PetscViewerCreate(PETSC_COMM_WORLD,&viewer);
1141:       PetscViewerSetType(viewer,PETSCVIEWERASCII);
1142:       PetscOptionsView(viewer);
1143:       PetscViewerDestroy(&viewer);
1144:     }
1145:     if (!nopt) {
1146:       PetscPrintf(PETSC_COMM_WORLD,"There are no unused options.\n");
1147:     } else if (nopt == 1) {
1148:       PetscPrintf(PETSC_COMM_WORLD,"There is one unused database option. It is:\n");
1149:     } else {
1150:       PetscPrintf(PETSC_COMM_WORLD,"There are %D unused database options. They are:\n",nopt);
1151:     }
1152:   }
1153: #if defined(PETSC_USE_DEBUG)
1154:   if (nopt && !flg3 && !flg1) {
1155:     PetscPrintf(PETSC_COMM_WORLD,"WARNING! There are options you set that were not used!\n");
1156:     PetscPrintf(PETSC_COMM_WORLD,"WARNING! could be spelling mistake, etc!\n");
1157:     PetscOptionsLeft();
1158:   } else if (nopt && flg3) {
1159: #else
1160:   if (nopt && flg3) {
1161: #endif
1162:     PetscOptionsLeft();
1163:   }

1165: #if defined(PETSC_HAVE_SAWS)
1166:   if (!PetscGlobalRank) {
1167:     PetscStackSAWsViewOff();
1168:     PetscStackCallSAWs(SAWs_Finalize,());
1169:   }
1170: #endif

1172:   {
1173:     PetscThreadComm tcomm_world;
1174:     PetscGetThreadCommWorld(&tcomm_world);
1175:     /* Free global thread communicator */
1176:     PetscThreadCommDestroy(&tcomm_world);
1177:   }

1179: #if defined(PETSC_USE_LOG)
1180:   /*
1181:        List all objects the user may have forgot to free
1182:   */
1183:   if (PetscObjectsLog) {
1184:     PetscOptionsHasName(NULL,"-objects_dump",&flg1);
1185:     if (flg1) {
1186:       MPI_Comm local_comm;
1187:       char     string[64];

1189:       PetscOptionsGetString(NULL,"-objects_dump",string,64,NULL);
1190:       MPI_Comm_dup(MPI_COMM_WORLD,&local_comm);
1191:       PetscSequentialPhaseBegin_Private(local_comm,1);
1192:       PetscObjectsDump(stdout,(string[0] == 'a') ? PETSC_TRUE : PETSC_FALSE);
1193:       PetscSequentialPhaseEnd_Private(local_comm,1);
1194:       MPI_Comm_free(&local_comm);
1195:     }
1196:   }
1197: #endif

1199: #if defined(PETSC_USE_LOG)
1200:   PetscObjectsCounts    = 0;
1201:   PetscObjectsMaxCounts = 0;
1202:   PetscFree(PetscObjects);
1203: #endif

1205: #if defined(PETSC_USE_LOG)
1206:   PetscLogDestroy();
1207: #endif

1209:   /*
1210:      Close any open dynamic libraries
1211:   */
1212:   PetscFinalize_DynamicLibraries();

1214:   /*
1215:      Destroy any packages that registered a finalize
1216:   */
1217:   PetscRegisterFinalizeAll();

1219:   /*
1220:      Print PetscFunctionLists that have not been properly freed

1222:   PetscFunctionListPrintAll();
1223:   */

1225:   if (petsc_history) {
1226:     PetscCloseHistoryFile(&petsc_history);
1227:     petsc_history = 0;
1228:   }

1230:   PetscInfoAllow(PETSC_FALSE,NULL);

1232: #if !defined(PETSC_HAVE_THREADSAFETY)
1233:   {
1234:     char fname[PETSC_MAX_PATH_LEN];
1235:     FILE *fd;
1236:     int  err;

1238:     fname[0] = 0;

1240:     PetscOptionsGetString(NULL,"-malloc_dump",fname,250,&flg1);
1241:     flg2 = PETSC_FALSE;
1242:     PetscOptionsGetBool(NULL,"-malloc_test",&flg2,NULL);
1243: #if defined(PETSC_USE_DEBUG)
1244:     if (PETSC_RUNNING_ON_VALGRIND) flg2 = PETSC_FALSE;
1245: #else
1246:     flg2 = PETSC_FALSE;         /* Skip reporting for optimized builds regardless of -malloc_test */
1247: #endif
1248:     if (flg1 && fname[0]) {
1249:       char sname[PETSC_MAX_PATH_LEN];

1251:       sprintf(sname,"%s_%d",fname,rank);
1252:       fd   = fopen(sname,"w"); if (!fd) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_FILE_OPEN,"Cannot open log file: %s",sname);
1253:       PetscMallocDump(fd);
1254:       err  = fclose(fd);
1255:       if (err) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SYS,"fclose() failed on file");
1256:     } else if (flg1 || flg2) {
1257:       MPI_Comm local_comm;

1259:       MPI_Comm_dup(MPI_COMM_WORLD,&local_comm);
1260:       PetscSequentialPhaseBegin_Private(local_comm,1);
1261:       PetscMallocDump(stdout);
1262:       PetscSequentialPhaseEnd_Private(local_comm,1);
1263:       MPI_Comm_free(&local_comm);
1264:     }
1265:   }

1267:   {
1268:     char fname[PETSC_MAX_PATH_LEN];
1269:     FILE *fd = NULL;

1271:     fname[0] = 0;

1273:     PetscOptionsGetString(NULL,"-malloc_log",fname,250,&flg1);
1274:     PetscOptionsHasName(NULL,"-malloc_log_threshold",&flg2);
1275:     if (flg1 && fname[0]) {
1276:       int err;

1278:       if (!rank) {
1279:         fd = fopen(fname,"w");
1280:         if (!fd) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_FILE_OPEN,"Cannot open log file: %s",fname);
1281:       }
1282:       PetscMallocDumpLog(fd);
1283:       if (fd) {
1284:         err = fclose(fd);
1285:         if (err) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SYS,"fclose() failed on file");
1286:       }
1287:     } else if (flg1 || flg2) {
1288:       PetscMallocDumpLog(stdout);
1289:     }
1290:   }
1291: #endif

1293: #if defined(PETSC_HAVE_CUDA)
1294:   flg  = PETSC_TRUE;
1295:   PetscOptionsGetBool(NULL,"-cublas",&flg,NULL);
1296:   if (flg) {
1297:     PetscInt p;
1298:     for (p = 0; p < PetscGlobalSize; ++p) {
1299:       if (p == PetscGlobalRank) cublasShutdown();
1300:       MPI_Barrier(PETSC_COMM_WORLD);
1301:     }
1302:   }
1303: #endif

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

1308:   PetscGlobalArgc = 0;
1309:   PetscGlobalArgs = 0;

1311: #if defined(PETSC_USE_REAL___FLOAT128)
1312:   MPI_Type_free(&MPIU___FLOAT128);
1313: #if defined(PETSC_HAVE_COMPLEX)
1314:   MPI_Type_free(&MPIU___COMPLEX128);
1315: #endif
1316:   MPI_Op_free(&MPIU_MAX);
1317:   MPI_Op_free(&MPIU_MIN);
1318: #endif

1320: #if defined(PETSC_HAVE_COMPLEX)
1321: #if !defined(PETSC_HAVE_MPI_C_DOUBLE_COMPLEX)
1322:   MPI_Type_free(&MPIU_C_DOUBLE_COMPLEX);
1323:   MPI_Type_free(&MPIU_C_COMPLEX);
1324: #endif
1325: #endif

1327: #if (defined(PETSC_HAVE_COMPLEX) && !defined(PETSC_HAVE_MPI_C_DOUBLE_COMPLEX)) || defined(PETSC_USE_REAL___FLOAT128)
1328:   MPI_Op_free(&MPIU_SUM);
1329: #endif

1331:   MPI_Type_free(&MPIU_2SCALAR);
1332: #if defined(PETSC_USE_64BIT_INDICES) || !defined(MPI_2INT)
1333:   MPI_Type_free(&MPIU_2INT);
1334: #endif
1335:   MPI_Op_free(&PetscMaxSum_Op);

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

1341:      If all PETSc objects were not destroyed those left over objects will have hanging references to
1342:      the MPI_Comms that were freed; but that is ok because those PETSc objects will never be used again
1343:  */
1344:   {
1345:     PetscCommCounter *counter;
1346:     PetscMPIInt      flg;
1347:     MPI_Comm         icomm;
1348:     union {MPI_Comm comm; void *ptr;} ucomm;
1349:     MPI_Attr_get(PETSC_COMM_SELF,Petsc_InnerComm_keyval,&ucomm,&flg);
1350:     if (flg) {
1351:       icomm = ucomm.comm;
1352:       MPI_Attr_get(icomm,Petsc_Counter_keyval,&counter,&flg);
1353:       if (!flg) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_CORRUPT,"Inner MPI_Comm does not have expected tag/name counter, problem with corrupted memory");

1355:       MPI_Attr_delete(PETSC_COMM_SELF,Petsc_InnerComm_keyval);
1356:       MPI_Attr_delete(icomm,Petsc_Counter_keyval);
1357:       MPI_Comm_free(&icomm);
1358:     }
1359:     MPI_Attr_get(PETSC_COMM_WORLD,Petsc_InnerComm_keyval,&ucomm,&flg);
1360:     if (flg) {
1361:       icomm = ucomm.comm;
1362:       MPI_Attr_get(icomm,Petsc_Counter_keyval,&counter,&flg);
1363:       if (!flg) SETERRQ(PETSC_COMM_WORLD,PETSC_ERR_ARG_CORRUPT,"Inner MPI_Comm does not have expected tag/name counter, problem with corrupted memory");

1365:       MPI_Attr_delete(PETSC_COMM_WORLD,Petsc_InnerComm_keyval);
1366:       MPI_Attr_delete(icomm,Petsc_Counter_keyval);
1367:       MPI_Comm_free(&icomm);
1368:     }
1369:   }

1371:   MPI_Keyval_free(&Petsc_Counter_keyval);
1372:   MPI_Keyval_free(&Petsc_InnerComm_keyval);
1373:   MPI_Keyval_free(&Petsc_OuterComm_keyval);

1375:   if (PetscBeganMPI) {
1376: #if defined(PETSC_HAVE_MPI_FINALIZED)
1377:     PetscMPIInt flag;
1378:     MPI_Finalized(&flag);
1379:     if (flag) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_LIB,"MPI_Finalize() has already been called, even though MPI_Init() was called by PetscInitialize()");
1380: #endif
1381:     MPI_Finalize();
1382:   }
1383: /*

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

1393: */
1394:   PetscMallocClear();

1396:   PetscInitializeCalled = PETSC_FALSE;
1397:   PetscFinalizeCalled   = PETSC_TRUE;
1398:   PetscFunctionReturn(ierr);
1399: }

1401: #if defined(PETSC_MISSING_LAPACK_lsame_)
1402: PETSC_EXTERN int lsame_(char *a,char *b)
1403: {
1404:   if (*a == *b) return 1;
1405:   if (*a + 32 == *b) return 1;
1406:   if (*a - 32 == *b) return 1;
1407:   return 0;
1408: }
1409: #endif

1411: #if defined(PETSC_MISSING_LAPACK_lsame)
1412: PETSC_EXTERN int lsame(char *a,char *b)
1413: {
1414:   if (*a == *b) return 1;
1415:   if (*a + 32 == *b) return 1;
1416:   if (*a - 32 == *b) return 1;
1417:   return 0;
1418: }
1419: #endif