Actual source code: pinit.c

petsc-master 2016-05-04
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: /*
 56:        Checks the options database for initializations related to the
 57:     PETSc components
 58: */
 61: PetscErrorCode  PetscOptionsCheckInitial_Components(void)
 62: {
 63:   PetscBool      flg1;

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

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

 86:    Collective

 88:    Level: advanced

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

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

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

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

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

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

129:    Collective

131:    Level: advanced

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

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

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

151:    Level: beginner

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

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

166:    Level: developer

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

176: extern PetscErrorCode PetscOptionsCheckInitial_Private(void);

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

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

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

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

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

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

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

241: /* ----------------------------------------------------------------------------*/

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

248: PETSC_EXTERN void PetscSum_Local(void *in,void *out,PetscMPIInt *cnt,MPI_Datatype *datatype)
249: {
250:   PetscInt i,count = *cnt;

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

271: #if defined(PETSC_USE_REAL___FLOAT128)
272: MPI_Op MPIU_MAX = 0;
273: MPI_Op MPIU_MIN = 0;

277: PETSC_EXTERN void PetscMax_Local(void *in,void *out,PetscMPIInt *cnt,MPI_Datatype *datatype)
278: {
279:   PetscInt i,count = *cnt;

282:   if (*datatype == MPIU_REAL) {
283:     PetscReal *xin = (PetscReal*)in,*xout = (PetscReal*)out;
284:     for (i=0; i<count; i++) xout[i] = PetscMax(xout[i],xin[i]);
285:   }
286: #if defined(PETSC_HAVE_COMPLEX)
287:   else if (*datatype == MPIU_COMPLEX) {
288:     PetscComplex *xin = (PetscComplex*)in,*xout = (PetscComplex*)out;
289:     for (i=0; i<count; i++) {
290:       xout[i] = PetscRealPartComplex(xout[i])<PetscRealPartComplex(xin[i]) ? xin[i] : xout[i];
291:     }
292:   }
293: #endif
294:   else {
295:     (*PetscErrorPrintf)("Can only handle MPIU_REAL or MPIU_COMPLEX data types");
296:     MPI_Abort(MPI_COMM_WORLD,1);
297:   }
298:   PetscFunctionReturnVoid();
299: }

303: PETSC_EXTERN void PetscMin_Local(void *in,void *out,PetscMPIInt *cnt,MPI_Datatype *datatype)
304: {
305:   PetscInt    i,count = *cnt;

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

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

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

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

337: */
338: PETSC_EXTERN PetscMPIInt MPIAPI Petsc_DelCounter(MPI_Comm comm,PetscMPIInt keyval,void *count_val,void *extra_state)
339: {

343:   PetscInfo1(0,"Deleting counter data in an MPI_Comm %ld\n",(long)comm);if (ierr) PetscFunctionReturn((PetscMPIInt)ierr);
344:   PetscFree(count_val);if (ierr) PetscFunctionReturn((PetscMPIInt)ierr);
345:   PetscFunctionReturn(MPI_SUCCESS);
346: }

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

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

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

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

360: */
361: PETSC_EXTERN PetscMPIInt MPIAPI Petsc_DelComm_Outer(MPI_Comm comm,PetscMPIInt keyval,void *attr_val,void *extra_state)
362: {
364:   PetscMPIInt    flg;
365:   union {MPI_Comm comm; void *ptr;} icomm,ocomm;

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

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

381: /*
382:  * This is invoked on the inner comm when Petsc_DelComm_Outer calls MPI_Attr_delete.  It should not be reached any other way.
383:  */
384: PETSC_EXTERN PetscMPIInt MPIAPI Petsc_DelComm_Inner(MPI_Comm comm,PetscMPIInt keyval,void *attr_val,void *extra_state)
385: {

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

393: #if defined(PETSC_USE_PETSC_MPI_EXTERNAL32)
394: #if !defined(PETSC_WORDS_BIGENDIAN)
395: PETSC_EXTERN PetscMPIInt PetscDataRep_extent_fn(MPI_Datatype,MPI_Aint*,void*);
396: PETSC_EXTERN PetscMPIInt PetscDataRep_read_conv_fn(void*, MPI_Datatype,PetscMPIInt,void*,MPI_Offset,void*);
397: PETSC_EXTERN PetscMPIInt PetscDataRep_write_conv_fn(void*, MPI_Datatype,PetscMPIInt,void*,MPI_Offset,void*);
398: #endif
399: #endif

401: int  PetscGlobalArgc   = 0;
402: char **PetscGlobalArgs = 0;
403: PetscSegBuffer PetscCitationsList;

407: PetscErrorCode PetscCitationsInitialize()
408: {

412:   PetscSegBufferCreate(1,10000,&PetscCitationsList);
413:   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);
414:   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);
415:   return(0);
416: }

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

424:    Not Collective

426:    Output Parameters:
427: +  argc - count of number of command line arguments
428: -  args - the command line arguments

430:    Level: intermediate

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

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

438:    Concepts: command line arguments

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

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

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

458:    Not Collective

460:    Output Parameters:
461: .  args - the command line arguments

463:    Level: intermediate

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

468:    Concepts: command line arguments

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

472: @*/
473: PetscErrorCode  PetscGetArguments(char ***args)
474: {
475:   PetscInt       i,argc = PetscGlobalArgc;

479:   if (!PetscInitializeCalled && PetscFinalizeCalled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ORDER,"You must call after PetscInitialize() but before PetscFinalize()");
480:   if (!argc) {*args = 0; return(0);}
481:   PetscMalloc1(argc,args);
482:   for (i=0; i<argc-1; i++) {
483:     PetscStrallocpy(PetscGlobalArgs[i+1],&(*args)[i]);
484:   }
485:   (*args)[argc-1] = 0;
486:   return(0);
487: }

491: /*@C
492:    PetscFreeArguments - Frees the memory obtained with PetscGetArguments()

494:    Not Collective

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

499:    Level: intermediate

501:    Concepts: command line arguments

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

505: @*/
506: PetscErrorCode  PetscFreeArguments(char **args)
507: {
508:   PetscInt       i = 0;

512:   if (!args) return(0);
513:   while (args[i]) {
514:     PetscFree(args[i]);
515:     i++;
516:   }
517:   PetscFree(args);
518:   return(0);
519: }

521: #if defined(PETSC_HAVE_SAWS)
522: #include <petscconfiginfo.h>

526: PetscErrorCode  PetscInitializeSAWs(const char help[])
527: {
528:   if (!PetscGlobalRank) {
529:     char           cert[PETSC_MAX_PATH_LEN],root[PETSC_MAX_PATH_LEN],*intro,programname[64],*appline,*options,version[64];
530:     int            port;
531:     PetscBool      flg,rootlocal = PETSC_FALSE,flg2,selectport = PETSC_FALSE;
532:     size_t         applinelen,introlen;
534:     char           sawsurl[256];

536:     PetscOptionsHasName(NULL,NULL,"-saws_log",&flg);
537:     if (flg) {
538:       char  sawslog[PETSC_MAX_PATH_LEN];

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

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

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

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

634:    Input Parameters:
635: +  argc - count of number of command line arguments
636: .  args - the command line arguments
637: .  file - [optional] PETSc database file, also checks ~username/.petscrc and .petscrc use NULL to not check for
638:           code specific file. Use -skip_petscrc in the code specific file to skip the .petscrc files
639: -  help - [optional] Help message to print, use NULL for no message

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

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

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

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

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

698:    Environmental Variables:
699: +   PETSC_TMP - alternative tmp directory
700: .   PETSC_SHARED_TMP - tmp is shared by all processes
701: .   PETSC_NOT_SHARED_TMP - each process has its own private tmp
702: .   PETSC_VIEWER_SOCKET_PORT - socket number to use for socket viewer
703: -   PETSC_VIEWER_SOCKET_MACHINE - machine to use for socket viewer to connect to


706:    Level: beginner

708:    Notes:
709:    If for some reason you must call MPI_Init() separately, call
710:    it before PetscInitialize().

712:    Fortran Version:
713:    In Fortran this routine has the format
714: $       call PetscInitialize(file,ierr)

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

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

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

728:    Concepts: initializing PETSc

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

732: @*/
733: PetscErrorCode  PetscInitialize(int *argc,char ***args,const char file[],const char help[])
734: {
736:   PetscMPIInt    flag, size;
737:   PetscBool      flg;
738:   char           hostname[256];
739: #if defined(PETSC_HAVE_CUDA)
740:   cublasStatus_t cberr;
741: #endif

744:   if (PetscInitializeCalled) return(0);

746:   /* these must be initialized in a routine, not as a constant declaration*/
747:   PETSC_STDOUT = stdout;
748:   PETSC_STDERR = stderr;

750:   /* on Windows - set printf to default to printing 2 digit exponents */
751: #if defined(PETSC_HAVE__SET_OUTPUT_FORMAT)
752:   _set_output_format(_TWO_DIGIT_EXPONENT);
753: #endif

755:   PetscOptionsCreateDefault();

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

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

790:   if (PETSC_COMM_WORLD == MPI_COMM_NULL) PETSC_COMM_WORLD = MPI_COMM_WORLD;
791:   MPI_Comm_set_errhandler(PETSC_COMM_WORLD,MPI_ERRORS_RETURN);

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

796:   MPI_Comm_rank(MPI_COMM_WORLD,&PetscGlobalRank);
797:   MPI_Comm_size(MPI_COMM_WORLD,&PetscGlobalSize);

799:   MPIU_BOOL = MPI_INT;
800:   MPIU_ENUM = MPI_INT;

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

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

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

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

842: #if (defined(PETSC_HAVE_COMPLEX) && !defined(PETSC_HAVE_MPI_C_DOUBLE_COMPLEX)) || defined(PETSC_USE_REAL___FLOAT128)
843:   MPI_Op_create(PetscSum_Local,1,&MPIU_SUM);
844: #endif

846:   MPI_Type_contiguous(2,MPIU_SCALAR,&MPIU_2SCALAR);
847:   MPI_Type_commit(&MPIU_2SCALAR);

849: #if defined(PETSC_USE_64BIT_INDICES) || !defined(MPI_2INT)
850:   MPI_Type_contiguous(2,MPIU_INT,&MPIU_2INT);
851:   MPI_Type_commit(&MPIU_2INT);
852: #endif


855:   /*
856:      Attributes to be set on PETSc communicators
857:   */
858:   MPI_Keyval_create(MPI_NULL_COPY_FN,Petsc_DelCounter,&Petsc_Counter_keyval,(void*)0);
859:   MPI_Keyval_create(MPI_NULL_COPY_FN,Petsc_DelComm_Outer,&Petsc_InnerComm_keyval,(void*)0);
860:   MPI_Keyval_create(MPI_NULL_COPY_FN,Petsc_DelComm_Inner,&Petsc_OuterComm_keyval,(void*)0);

862:   /*
863:      Build the options database
864:   */
865:   PetscOptionsInsert(NULL,argc,args,file);


868:   /*
869:      Print main application help message
870:   */
871:   PetscOptionsHasName(NULL,NULL,"-help",&flg);
872:   if (help && flg) {
873:     PetscPrintf(PETSC_COMM_WORLD,help);
874:   }
875:   PetscOptionsCheckInitial_Private();

877:   PetscCitationsInitialize();

879: #if defined(PETSC_HAVE_SAWS)
880:   PetscInitializeSAWs(help);
881: #endif

883:   /* Creates the logging data structures; this is enabled even if logging is not turned on */
884: #if defined(PETSC_USE_LOG)
885:   PetscLogInitialize();
886: #endif

888:   /*
889:      Load the dynamic libraries (on machines that support them), this registers all
890:      the solvers etc. (On non-dynamic machines this initializes the PetscDraw and PetscViewer classes)
891:   */
892:   PetscInitialize_DynamicLibraries();

894:   MPI_Comm_size(PETSC_COMM_WORLD,&size);
895:   PetscInfo1(0,"PETSc successfully started: number of processors = %d\n",size);
896:   PetscGetHostName(hostname,256);
897:   PetscInfo1(0,"Running on machine: %s\n",hostname);

899:   PetscOptionsCheckInitial_Components();
900:   /* Check the options database for options related to the options database itself */
901:   PetscOptionsSetFromOptions(NULL);

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

907:       Currently not used because it is not supported by MPICH.
908:   */
909: #if !defined(PETSC_WORDS_BIGENDIAN)
910:   MPI_Register_datarep((char*)"petsc",PetscDataRep_read_conv_fn,PetscDataRep_write_conv_fn,PetscDataRep_extent_fn,NULL);
911: #endif
912: #endif

914: #if defined(PETSC_HAVE_CUDA)
915:   flg  = PETSC_TRUE;
916:   PetscOptionsGetBool(NULL,NULL,"-cublas",&flg,NULL);
917:   if (flg) {
918:     PetscMPIInt p;
919:     for (p = 0; p < PetscGlobalSize; ++p) {
920:       if (p == PetscGlobalRank) {
921:         cberr = cublasCreate(&cublasv2handle);CHKERRCUBLAS(cberr);
922:       }
923:       MPI_Barrier(PETSC_COMM_WORLD);
924:     }
925:   }
926: #endif

928:   PetscOptionsHasName(NULL,NULL,"-python",&flg);
929:   if (flg) {
930:     PetscInitializeCalled = PETSC_TRUE;
931:     PetscPythonInitialize(NULL,NULL);
932:   }

934:   /*
935:       Setup building of stack frames for all function calls
936:   */
937: #if defined(PETSC_USE_DEBUG) && !defined(PETSC_HAVE_THREADSAFETY)
938:   PetscStackCreate();
939: #endif

941: #if defined(PETSC_SERIALIZE_FUNCTIONS)
942:   PetscFPTCreate(10000);
943: #endif


946:   /*
947:       Once we are completedly initialized then we can set this variables
948:   */
949:   PetscInitializeCalled = PETSC_TRUE;
950:   return(0);
951: }

953: #if defined(PETSC_USE_LOG)
954: extern PetscObject *PetscObjects;
955: extern PetscInt    PetscObjectsCounts, PetscObjectsMaxCounts;
956: extern PetscBool   PetscObjectsLog;
957: #endif

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

966:    Collective on PETSC_COMM_WORLD

968:    Options Database Keys:
969: +  -options_table - Calls PetscOptionsView()
970: .  -options_left - Prints unused options that remain in the database
971: .  -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
972: .  -mpidump - Calls PetscMPIDump()
973: .  -malloc_dump - Calls PetscMallocDump()
974: .  -malloc_info - Prints total memory usage
975: -  -malloc_log - Prints summary of memory usage

977:    Level: beginner

979:    Note:
980:    See PetscInitialize() for more general runtime options.

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

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

1005:   MPI_Comm_rank(PETSC_COMM_WORLD,&rank);

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

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

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

1056: #if defined(PETSC_SERIALIZE_FUNCTIONS)
1057:   PetscFPTDestroy();
1058: #endif


1061: #if defined(PETSC_HAVE_SAWS)
1062:   flg = PETSC_FALSE;
1063:   PetscOptionsGetBool(NULL,NULL,"-saw_options",&flg,NULL);
1064:   if (flg) {
1065:     PetscOptionsSAWsDestroy();
1066:   }
1067: #endif

1069: #if defined(PETSC_HAVE_X)
1070:   flg1 = PETSC_FALSE;
1071:   PetscOptionsGetBool(NULL,NULL,"-x_virtual",&flg1,NULL);
1072:   if (flg1) {
1073:     /*  this is a crude hack, but better than nothing */
1074:     PetscPOpen(PETSC_COMM_WORLD,NULL,"pkill -9 Xvfb","r",NULL);
1075:   }
1076: #endif

1078: #if !defined(PETSC_HAVE_THREADSAFETY)
1079:   PetscOptionsGetBool(NULL,NULL,"-malloc_info",&flg2,NULL);
1080:   if (!flg2) {
1081:     flg2 = PETSC_FALSE;
1082:     PetscOptionsGetBool(NULL,NULL,"-memory_view",&flg2,NULL);
1083:   }
1084:   if (flg2) {
1085:     PetscMemoryView(PETSC_VIEWER_STDOUT_WORLD,"Summary of Memory Usage in PETSc\n");
1086:   }
1087: #endif

1089: #if defined(PETSC_USE_LOG)
1090:   flg1 = PETSC_FALSE;
1091:   PetscOptionsGetBool(NULL,NULL,"-get_total_flops",&flg1,NULL);
1092:   if (flg1) {
1093:     PetscLogDouble flops = 0;
1094:     MPI_Reduce(&petsc_TotalFlops,&flops,1,MPI_DOUBLE,MPI_SUM,0,PETSC_COMM_WORLD);
1095:     PetscPrintf(PETSC_COMM_WORLD,"Total flops over all processors %g\n",flops);
1096:   }
1097: #endif


1100: #if defined(PETSC_USE_LOG)
1101: #if defined(PETSC_HAVE_MPE)
1102:   mname[0] = 0;

1104:   PetscOptionsGetString(NULL,NULL,"-log_mpe",mname,PETSC_MAX_PATH_LEN,&flg1);
1105:   if (flg1) {
1106:     if (mname[0]) {PetscLogMPEDump(mname);}
1107:     else          {PetscLogMPEDump(0);}
1108:   }
1109: #endif
1110:   mname[0] = 0;

1112:   PetscLogViewFromOptions();
1113:   PetscOptionsGetString(NULL,NULL,"-log_summary",mname,PETSC_MAX_PATH_LEN,&flg1);
1114:   if (flg1) {
1115:     PetscViewer viewer;
1116:     (*PetscHelpPrintf)(PETSC_COMM_WORLD,"\n\n WARNING:   -log_summary is being deprecated; switch to -log_view\n\n\n");
1117:     if (mname[0]) {
1118:       PetscViewerASCIIOpen(PETSC_COMM_WORLD,mname,&viewer);
1119:       PetscLogView(viewer);
1120:       PetscViewerDestroy(&viewer);
1121:     } else {
1122:       viewer = PETSC_VIEWER_STDOUT_WORLD;
1123:       PetscViewerPushFormat(viewer,PETSC_VIEWER_DEFAULT);
1124:       PetscLogView(viewer);
1125:       PetscViewerPopFormat(viewer);
1126:     }
1127:   }
1128:   mname[0] = 0;

1130:   PetscOptionsGetString(NULL,NULL,"-log_all",mname,PETSC_MAX_PATH_LEN,&flg1);
1131:   PetscOptionsGetString(NULL,NULL,"-log",mname,PETSC_MAX_PATH_LEN,&flg2);
1132:   if (flg1 || flg2) {
1133:     if (mname[0]) PetscLogDump(mname);
1134:     else          PetscLogDump(0);
1135:   }
1136: #endif

1138:   /*
1139:      Free all objects registered with PetscObjectRegisterDestroy() such as PETSC_VIEWER_XXX_().
1140:   */
1141:   PetscObjectRegisterDestroyAll();

1143:   PetscStackDestroy();

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

1160:   if (flg2) {
1161:     PetscViewer viewer;
1162:     PetscViewerCreate(PETSC_COMM_WORLD,&viewer);
1163:     PetscViewerSetType(viewer,PETSCVIEWERASCII);
1164:     PetscOptionsView(NULL,viewer);
1165:     PetscViewerDestroy(&viewer);
1166:   }

1168:   /* to prevent PETSc -options_left from warning */
1169:   PetscOptionsHasName(NULL,NULL,"-nox",&flg1);
1170:   PetscOptionsHasName(NULL,NULL,"-nox_warning",&flg1);

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

1203: #if defined(PETSC_HAVE_SAWS)
1204:   if (!PetscGlobalRank) {
1205:     PetscStackSAWsViewOff();
1206:     PetscStackCallSAWs(SAWs_Finalize,());
1207:   }
1208: #endif

1210: #if defined(PETSC_USE_LOG)
1211:   /*
1212:        List all objects the user may have forgot to free
1213:   */
1214:   if (PetscObjectsLog) {
1215:     PetscOptionsHasName(NULL,NULL,"-objects_dump",&flg1);
1216:     if (flg1) {
1217:       MPI_Comm local_comm;
1218:       char     string[64];

1220:       PetscOptionsGetString(NULL,NULL,"-objects_dump",string,64,NULL);
1221:       MPI_Comm_dup(MPI_COMM_WORLD,&local_comm);
1222:       PetscSequentialPhaseBegin_Private(local_comm,1);
1223:       PetscObjectsDump(stdout,(string[0] == 'a') ? PETSC_TRUE : PETSC_FALSE);
1224:       PetscSequentialPhaseEnd_Private(local_comm,1);
1225:       MPI_Comm_free(&local_comm);
1226:     }
1227:   }
1228: #endif

1230: #if defined(PETSC_USE_LOG)
1231:   PetscObjectsCounts    = 0;
1232:   PetscObjectsMaxCounts = 0;
1233:   PetscFree(PetscObjects);
1234: #endif

1236:   /*
1237:      Destroy any packages that registered a finalize
1238:   */
1239:   PetscRegisterFinalizeAll();

1241: #if defined(PETSC_USE_LOG)
1242:   PetscLogDestroy();
1243: #endif

1245:   /*
1246:      Print PetscFunctionLists that have not been properly freed

1248:   PetscFunctionListPrintAll();
1249:   */

1251:   if (petsc_history) {
1252:     PetscCloseHistoryFile(&petsc_history);
1253:     petsc_history = 0;
1254:   }

1256:   PetscInfoAllow(PETSC_FALSE,NULL);

1258: #if !defined(PETSC_HAVE_THREADSAFETY)
1259:   {
1260:     char fname[PETSC_MAX_PATH_LEN];
1261:     FILE *fd;
1262:     int  err;

1264:     fname[0] = 0;

1266:     PetscOptionsGetString(NULL,NULL,"-malloc_dump",fname,250,&flg1);
1267:     flg2 = PETSC_FALSE;
1268:     PetscOptionsGetBool(NULL,NULL,"-malloc_test",&flg2,NULL);
1269: #if defined(PETSC_USE_DEBUG)
1270:     if (PETSC_RUNNING_ON_VALGRIND) flg2 = PETSC_FALSE;
1271: #else
1272:     flg2 = PETSC_FALSE;         /* Skip reporting for optimized builds regardless of -malloc_test */
1273: #endif
1274:     if (flg1 && fname[0]) {
1275:       char sname[PETSC_MAX_PATH_LEN];

1277:       sprintf(sname,"%s_%d",fname,rank);
1278:       fd   = fopen(sname,"w"); if (!fd) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_FILE_OPEN,"Cannot open log file: %s",sname);
1279:       PetscMallocDump(fd);
1280:       err  = fclose(fd);
1281:       if (err) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SYS,"fclose() failed on file");
1282:     } else if (flg1 || flg2) {
1283:       MPI_Comm local_comm;

1285:       MPI_Comm_dup(MPI_COMM_WORLD,&local_comm);
1286:       PetscSequentialPhaseBegin_Private(local_comm,1);
1287:       PetscMallocDump(stdout);
1288:       PetscSequentialPhaseEnd_Private(local_comm,1);
1289:       MPI_Comm_free(&local_comm);
1290:     }
1291:   }

1293:   {
1294:     char fname[PETSC_MAX_PATH_LEN];
1295:     FILE *fd = NULL;

1297:     fname[0] = 0;

1299:     PetscOptionsGetString(NULL,NULL,"-malloc_log",fname,250,&flg1);
1300:     PetscOptionsHasName(NULL,NULL,"-malloc_log_threshold",&flg2);
1301:     if (flg1 && fname[0]) {
1302:       int err;

1304:       if (!rank) {
1305:         fd = fopen(fname,"w");
1306:         if (!fd) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_FILE_OPEN,"Cannot open log file: %s",fname);
1307:       }
1308:       PetscMallocDumpLog(fd);
1309:       if (fd) {
1310:         err = fclose(fd);
1311:         if (err) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SYS,"fclose() failed on file");
1312:       }
1313:     } else if (flg1 || flg2) {
1314:       PetscMallocDumpLog(stdout);
1315:     }
1316:   }
1317: #endif

1319:   /*
1320:      Close any open dynamic libraries
1321:   */
1322:   PetscFinalize_DynamicLibraries();

1324: #if defined(PETSC_HAVE_CUDA)
1325:   flg  = PETSC_TRUE;
1326:   PetscOptionsGetBool(NULL,NULL,"-cublas",&flg,NULL);
1327:   if (flg) {
1328:     PetscInt p;
1329:     for (p = 0; p < PetscGlobalSize; ++p) {
1330:       if (p == PetscGlobalRank) {
1331:         if (cublasv2handle) {
1332:           cberr = cublasDestroy(cublasv2handle);CHKERRCUBLAS(cberr);
1333:         }
1334:       }
1335:       MPI_Barrier(PETSC_COMM_WORLD);
1336:     }
1337:   }
1338: #endif

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

1343:   PetscGlobalArgc = 0;
1344:   PetscGlobalArgs = 0;

1346: #if defined(PETSC_USE_REAL___FLOAT128)
1347:   MPI_Type_free(&MPIU___FLOAT128);
1348: #if defined(PETSC_HAVE_COMPLEX)
1349:   MPI_Type_free(&MPIU___COMPLEX128);
1350: #endif
1351:   MPI_Op_free(&MPIU_MAX);
1352:   MPI_Op_free(&MPIU_MIN);
1353: #endif

1355: #if defined(PETSC_HAVE_COMPLEX)
1356: #if !defined(PETSC_HAVE_MPI_C_DOUBLE_COMPLEX)
1357:   MPI_Type_free(&MPIU_C_DOUBLE_COMPLEX);
1358:   MPI_Type_free(&MPIU_C_COMPLEX);
1359: #endif
1360: #endif

1362: #if (defined(PETSC_HAVE_COMPLEX) && !defined(PETSC_HAVE_MPI_C_DOUBLE_COMPLEX)) || defined(PETSC_USE_REAL___FLOAT128)
1363:   MPI_Op_free(&MPIU_SUM);
1364: #endif

1366:   MPI_Type_free(&MPIU_2SCALAR);
1367: #if defined(PETSC_USE_64BIT_INDICES) || !defined(MPI_2INT)
1368:   MPI_Type_free(&MPIU_2INT);
1369: #endif
1370:   MPI_Op_free(&PetscMaxSum_Op);

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

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

1390:       MPI_Attr_delete(PETSC_COMM_SELF,Petsc_InnerComm_keyval);
1391:       MPI_Attr_delete(icomm,Petsc_Counter_keyval);
1392:       MPI_Comm_free(&icomm);
1393:     }
1394:     MPI_Attr_get(PETSC_COMM_WORLD,Petsc_InnerComm_keyval,&ucomm,&flg);
1395:     if (flg) {
1396:       icomm = ucomm.comm;
1397:       MPI_Attr_get(icomm,Petsc_Counter_keyval,&counter,&flg);
1398:       if (!flg) SETERRQ(PETSC_COMM_WORLD,PETSC_ERR_ARG_CORRUPT,"Inner MPI_Comm does not have expected tag/name counter, problem with corrupted memory");

1400:       MPI_Attr_delete(PETSC_COMM_WORLD,Petsc_InnerComm_keyval);
1401:       MPI_Attr_delete(icomm,Petsc_Counter_keyval);
1402:       MPI_Comm_free(&icomm);
1403:     }
1404:   }

1406:   MPI_Keyval_free(&Petsc_Counter_keyval);
1407:   MPI_Keyval_free(&Petsc_InnerComm_keyval);
1408:   MPI_Keyval_free(&Petsc_OuterComm_keyval);

1410:   PetscSpinlockDestroy(&PetscViewerASCIISpinLockOpen);
1411:   PetscSpinlockDestroy(&PetscViewerASCIISpinLockStdout);
1412:   PetscSpinlockDestroy(&PetscViewerASCIISpinLockStderr);
1413:   PetscSpinlockDestroy(&PetscCommSpinLock);

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

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

1433: */
1434:   PetscMallocClear();

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

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

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