Actual source code: pinit.c

petsc-3.9.4 2018-09-11
Report Typos and Errors

  2: /*
  3:    This file defines the initialization of PETSc, including PetscInitialize()
  4: */
  5:  #include <petsc/private/petscimpl.h>
  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_SAWS)
 18:  #include <petscviewersaws.h>
 19: #endif
 20: /* -----------------------------------------------------------------------------------------*/

 22: extern FILE *petsc_history;

 24: extern PetscErrorCode PetscInitialize_DynamicLibraries(void);
 25: extern PetscErrorCode PetscFinalize_DynamicLibraries(void);
 26: extern PetscErrorCode PetscFunctionListPrintAll(void);
 27: extern PetscErrorCode PetscSequentialPhaseBegin_Private(MPI_Comm,int);
 28: extern PetscErrorCode PetscSequentialPhaseEnd_Private(MPI_Comm,int);
 29: extern PetscErrorCode PetscCloseHistoryFile(FILE**);

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

 34: PetscMPIInt Petsc_Counter_keyval   = MPI_KEYVAL_INVALID;
 35: PetscMPIInt Petsc_InnerComm_keyval = MPI_KEYVAL_INVALID;
 36: PetscMPIInt Petsc_OuterComm_keyval = MPI_KEYVAL_INVALID;
 37: PetscMPIInt Petsc_Shared_keyval    = MPI_KEYVAL_INVALID;

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

 47: PetscBool PetscPreLoadingUsed = PETSC_FALSE;
 48: PetscBool PetscPreLoadingOn   = PETSC_FALSE;

 50: PetscInt PetscHotRegionDepth;

 52: #if defined(PETSC_HAVE_THREADSAFETY)
 53: PetscSpinlock PetscViewerASCIISpinLockOpen;
 54: PetscSpinlock PetscViewerASCIISpinLockStdout;
 55: PetscSpinlock PetscViewerASCIISpinLockStderr;
 56: PetscSpinlock PetscCommSpinLock;
 57: #endif

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

 69:   PetscOptionsHasName(NULL,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_exclude: <vec,mat,pc,ksp,snes,tao,ts>\n");
 75:     (*PetscHelpPrintf)(comm," -info_exclude: <null,vec,mat,pc,ksp,snes,tao,ts>\n");
 76:     (*PetscHelpPrintf)(comm,"-----------------------------------------------\n");
 77: #endif
 78:   }
 79:   return(0);
 80: }

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

 85:    Collective

 87:    Level: advanced

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

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

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

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

110: /*
111:       Used by MATLAB and Julia interface to get communicator
112: */
113: PetscErrorCode  PetscGetPETSC_COMM_SELF(MPI_Comm *comm)
114: {
116:   *comm = PETSC_COMM_SELF;
117:   return(0);
118: }

120: /*@C
121:       PetscInitializeNoArguments - Calls PetscInitialize() from C/C++ without
122:         the command line arguments.

124:    Collective

126:    Level: advanced

128: .seealso: PetscInitialize(), PetscInitializeFortran()
129: @*/
130: PetscErrorCode  PetscInitializeNoArguments(void)
131: {
133:   int            argc   = 0;
134:   char           **args = 0;

137:   PetscInitialize(&argc,&args,NULL,NULL);
138:   PetscFunctionReturn(ierr);
139: }

141: /*@
142:       PetscInitialized - Determine whether PETSc is initialized.

144:    Level: beginner

146: .seealso: PetscInitialize(), PetscInitializeNoArguments(), PetscInitializeFortran()
147: @*/
148: PetscErrorCode PetscInitialized(PetscBool  *isInitialized)
149: {
150:   *isInitialized = PetscInitializeCalled;
151:   return 0;
152: }

154: /*@
155:       PetscFinalized - Determine whether PetscFinalize() has been called yet

157:    Level: developer

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

167: extern PetscErrorCode PetscOptionsCheckInitial_Private(void);

169: /*
170:        This function is the MPI reduction operation used to compute the sum of the
171:    first half of the datatype and the max of the second half.
172: */
173: MPI_Op MPIU_MAXSUM_OP = 0;

175: PETSC_INTERN void MPIAPI MPIU_MaxSum_Local(void *in,void *out,int *cnt,MPI_Datatype *datatype)
176: {
177:   PetscInt *xin = (PetscInt*)in,*xout = (PetscInt*)out,i,count = *cnt;

180:   if (*datatype != MPIU_2INT) {
181:     (*PetscErrorPrintf)("Can only handle MPIU_2INT data types");
182:     MPI_Abort(MPI_COMM_WORLD,1);
183:   }

185:   for (i=0; i<count; i++) {
186:     xout[2*i]    = PetscMax(xout[2*i],xin[2*i]);
187:     xout[2*i+1] += xin[2*i+1];
188:   }
189:   PetscFunctionReturnVoid();
190: }

192: /*
193:     Returns the max of the first entry owned by this processor and the
194: sum of the second entry.

196:     The reason sizes[2*i] contains lengths sizes[2*i+1] contains flag of 1 if length is nonzero
197: is so that the MPIU_MAXSUM_OP() can set TWO values, if we passed in only sizes[i] with lengths
198: there would be no place to store the both needed results.
199: */
200: PetscErrorCode  PetscMaxSum(MPI_Comm comm,const PetscInt sizes[],PetscInt *max,PetscInt *sum)
201: {

205: #if defined(PETSC_HAVE_MPI_REDUCE_SCATTER_BLOCK)
206:   {
207:     struct {PetscInt max,sum;} work;
208:     MPI_Reduce_scatter_block((void*)sizes,&work,1,MPIU_2INT,MPIU_MAXSUM_OP,comm);
209:     *max = work.max;
210:     *sum = work.sum;
211:   }
212: #else
213:   {
214:     PetscMPIInt    size,rank;
215:     struct {PetscInt max,sum;} *work;
216:     MPI_Comm_size(comm,&size);
217:     MPI_Comm_rank(comm,&rank);
218:     PetscMalloc1(size,&work);
219:     MPIU_Allreduce((void*)sizes,work,size,MPIU_2INT,MPIU_MAXSUM_OP,comm);
220:     *max = work[rank].max;
221:     *sum = work[rank].sum;
222:     PetscFree(work);
223:   }
224: #endif
225:   return(0);
226: }

228: /* ----------------------------------------------------------------------------*/

230: #if (defined(PETSC_HAVE_COMPLEX) && !defined(PETSC_HAVE_MPI_C_DOUBLE_COMPLEX)) || defined(PETSC_USE_REAL___FLOAT128) || defined(PETSC_USE_REAL___FP16)
231: MPI_Op MPIU_SUM = 0;

233: PETSC_EXTERN void PetscSum_Local(void *in,void *out,PetscMPIInt *cnt,MPI_Datatype *datatype)
234: {
235:   PetscInt i,count = *cnt;

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

256: #if defined(PETSC_USE_REAL___FLOAT128) || defined(PETSC_USE_REAL___FP16)
257: MPI_Op MPIU_MAX = 0;
258: MPI_Op MPIU_MIN = 0;

260: PETSC_EXTERN void PetscMax_Local(void *in,void *out,PetscMPIInt *cnt,MPI_Datatype *datatype)
261: {
262:   PetscInt i,count = *cnt;

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

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

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

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

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

314:    Note: this is declared extern "C" because it is passed to MPI_Comm_create_keyval()

316: */
317: PETSC_EXTERN PetscMPIInt MPIAPI Petsc_DelCounter(MPI_Comm comm,PetscMPIInt keyval,void *count_val,void *extra_state)
318: {

322:   PetscInfo1(0,"Deleting counter data in an MPI_Comm %ld\n",(long)comm);CHKERRMPI(ierr);
323:   PetscFree(count_val);CHKERRMPI(ierr);
324:   PetscFunctionReturn(MPI_SUCCESS);
325: }

327: /*
328:   This is invoked on the outer comm as a result of either PetscCommDestroy() (via MPI_Comm_delete_attr) or when the user
329:   calls MPI_Comm_free().

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

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

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

337: */
338: PETSC_EXTERN PetscMPIInt MPIAPI Petsc_DelComm_Outer(MPI_Comm comm,PetscMPIInt keyval,void *attr_val,void *extra_state)
339: {
340:   PetscErrorCode                    ierr;
341:   PetscMPIInt                       flg;
342:   union {MPI_Comm comm; void *ptr;} icomm,ocomm;

345:   if (keyval != Petsc_InnerComm_keyval) SETERRMPI(PETSC_COMM_SELF,PETSC_ERR_ARG_CORRUPT,"Unexpected keyval");
346:   icomm.ptr = attr_val;

348:   MPI_Comm_get_attr(icomm.comm,Petsc_OuterComm_keyval,&ocomm,&flg);CHKERRMPI(ierr);
349:   if (!flg) SETERRMPI(PETSC_COMM_SELF,PETSC_ERR_ARG_CORRUPT,"Inner MPI_Comm does not have expected reference to outer comm");
350:   if (ocomm.comm != comm) SETERRMPI(PETSC_COMM_SELF,PETSC_ERR_ARG_CORRUPT,"Inner MPI_Comm has reference to non-matching outer comm");
351:   MPI_Comm_delete_attr(icomm.comm,Petsc_OuterComm_keyval);CHKERRMPI(ierr);
352:   PetscInfo1(0,"User MPI_Comm %ld is being freed after removing reference from inner PETSc comm to this outer comm\n",(long)comm);CHKERRMPI(ierr);
353:   PetscFunctionReturn(MPI_SUCCESS);
354: }

356: /*
357:  * This is invoked on the inner comm when Petsc_DelComm_Outer calls MPI_Comm_delete_attr.  It should not be reached any other way.
358:  */
359: PETSC_EXTERN PetscMPIInt MPIAPI Petsc_DelComm_Inner(MPI_Comm comm,PetscMPIInt keyval,void *attr_val,void *extra_state)
360: {

364:   PetscInfo1(0,"Removing reference to PETSc communicator embedded in a user MPI_Comm %ld\n",(long)comm);CHKERRMPI(ierr);
365:   PetscFunctionReturn(MPI_SUCCESS);
366: }

368: PETSC_EXTERN PetscMPIInt MPIAPI Petsc_DelShared(MPI_Comm,PetscMPIInt,void *,void *);

370: #if defined(PETSC_USE_PETSC_MPI_EXTERNAL32)
371: #if !defined(PETSC_WORDS_BIGENDIAN)
372: PETSC_EXTERN PetscMPIInt PetscDataRep_extent_fn(MPI_Datatype,MPI_Aint*,void*);
373: PETSC_EXTERN PetscMPIInt PetscDataRep_read_conv_fn(void*, MPI_Datatype,PetscMPIInt,void*,MPI_Offset,void*);
374: PETSC_EXTERN PetscMPIInt PetscDataRep_write_conv_fn(void*, MPI_Datatype,PetscMPIInt,void*,MPI_Offset,void*);
375: #endif
376: #endif

378: PetscMPIInt PETSC_MPI_ERROR_CLASS,PETSC_MPI_ERROR_CODE;

380: int  PetscGlobalArgc   = 0;
381: char **PetscGlobalArgs = 0;
382: PetscSegBuffer PetscCitationsList;

384: PetscErrorCode PetscCitationsInitialize(void)
385: {

389:   PetscSegBufferCreate(1,10000,&PetscCitationsList);
390:   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 and Dave A. May and Lois Curfman McInnes\n            and Richard Tran Mills and Todd Munson and Karl Rupp and Patrick Sanan\n            and Barry F. Smith and Stefano Zampini and Hong Zhang and Hong Zhang},\n  Title = {{PETS}c Users Manual},\n  Number = {ANL-95/11 - Revision 3.9},\n  Institution = {Argonne National Laboratory},\n  Year = {2018}\n}\n",NULL);
391:   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);
392:   return(0);
393: }

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

399:    Not Collective

401:    Output Parameters:
402: +  argc - count of number of command line arguments
403: -  args - the command line arguments

405:    Level: intermediate

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

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

413:    Concepts: command line arguments

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

417: @*/
418: PetscErrorCode  PetscGetArgs(int *argc,char ***args)
419: {
421:   if (!PetscInitializeCalled && PetscFinalizeCalled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ORDER,"You must call after PetscInitialize() but before PetscFinalize()");
422:   *argc = PetscGlobalArgc;
423:   *args = PetscGlobalArgs;
424:   return(0);
425: }

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

431:    Not Collective

433:    Output Parameters:
434: .  args - the command line arguments

436:    Level: intermediate

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

441:    Concepts: command line arguments

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

445: @*/
446: PetscErrorCode  PetscGetArguments(char ***args)
447: {
448:   PetscInt       i,argc = PetscGlobalArgc;

452:   if (!PetscInitializeCalled && PetscFinalizeCalled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ORDER,"You must call after PetscInitialize() but before PetscFinalize()");
453:   if (!argc) {*args = 0; return(0);}
454:   PetscMalloc1(argc,args);
455:   for (i=0; i<argc-1; i++) {
456:     PetscStrallocpy(PetscGlobalArgs[i+1],&(*args)[i]);
457:   }
458:   (*args)[argc-1] = 0;
459:   return(0);
460: }

462: /*@C
463:    PetscFreeArguments - Frees the memory obtained with PetscGetArguments()

465:    Not Collective

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

470:    Level: intermediate

472:    Concepts: command line arguments

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

476: @*/
477: PetscErrorCode  PetscFreeArguments(char **args)
478: {
479:   PetscInt       i = 0;

483:   if (!args) return(0);
484:   while (args[i]) {
485:     PetscFree(args[i]);
486:     i++;
487:   }
488:   PetscFree(args);
489:   return(0);
490: }

492: #if defined(PETSC_HAVE_SAWS)
493: #include <petscconfiginfo.h>

495: PetscErrorCode  PetscInitializeSAWs(const char help[])
496: {
497:   if (!PetscGlobalRank) {
498:     char           cert[PETSC_MAX_PATH_LEN],root[PETSC_MAX_PATH_LEN],*intro,programname[64],*appline,*options,version[64];
499:     int            port;
500:     PetscBool      flg,rootlocal = PETSC_FALSE,flg2,selectport = PETSC_FALSE;
501:     size_t         applinelen,introlen;
503:     char           sawsurl[256];

505:     PetscOptionsHasName(NULL,NULL,"-saws_log",&flg);
506:     if (flg) {
507:       char  sawslog[PETSC_MAX_PATH_LEN];

509:       PetscOptionsGetString(NULL,NULL,"-saws_log",sawslog,PETSC_MAX_PATH_LEN,NULL);
510:       if (sawslog[0]) {
511:         PetscStackCallSAWs(SAWs_Set_Use_Logfile,(sawslog));
512:       } else {
513:         PetscStackCallSAWs(SAWs_Set_Use_Logfile,(NULL));
514:       }
515:     }
516:     PetscOptionsGetString(NULL,NULL,"-saws_https",cert,PETSC_MAX_PATH_LEN,&flg);
517:     if (flg) {
518:       PetscStackCallSAWs(SAWs_Set_Use_HTTPS,(cert));
519:     }
520:     PetscOptionsGetBool(NULL,NULL,"-saws_port_auto_select",&selectport,NULL);
521:     if (selectport) {
522:         PetscStackCallSAWs(SAWs_Get_Available_Port,(&port));
523:         PetscStackCallSAWs(SAWs_Set_Port,(port));
524:     } else {
525:       PetscOptionsGetInt(NULL,NULL,"-saws_port",&port,&flg);
526:       if (flg) {
527:         PetscStackCallSAWs(SAWs_Set_Port,(port));
528:       }
529:     }
530:     PetscOptionsGetString(NULL,NULL,"-saws_root",root,PETSC_MAX_PATH_LEN,&flg);
531:     if (flg) {
532:       PetscStackCallSAWs(SAWs_Set_Document_Root,(root));
533:       PetscStrcmp(root,".",&rootlocal);
534:     } else {
535:       PetscOptionsHasName(NULL,NULL,"-saws_options",&flg);
536:       if (flg) {
537:         PetscStrreplace(PETSC_COMM_WORLD,"${PETSC_DIR}/share/petsc/saws",root,PETSC_MAX_PATH_LEN);
538:         PetscStackCallSAWs(SAWs_Set_Document_Root,(root));
539:       }
540:     }
541:     PetscOptionsHasName(NULL,NULL,"-saws_local",&flg2);
542:     if (flg2) {
543:       char jsdir[PETSC_MAX_PATH_LEN];
544:       if (!flg) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"-saws_local option requires -saws_root option");
545:       PetscSNPrintf(jsdir,PETSC_MAX_PATH_LEN,"%s/js",root);
546:       PetscTestDirectory(jsdir,'r',&flg);
547:       if (!flg) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_FILE_READ,"-saws_local option requires js directory in root directory");
548:       PetscStackCallSAWs(SAWs_Push_Local_Header,());
549:     }
550:     PetscGetProgramName(programname,64);
551:     PetscStrlen(help,&applinelen);
552:     introlen   = 4096 + applinelen;
553:     applinelen += 1024;
554:     PetscMalloc(applinelen,&appline);
555:     PetscMalloc(introlen,&intro);

557:     if (rootlocal) {
558:       PetscSNPrintf(appline,applinelen,"%s.c.html",programname);
559:       PetscTestFile(appline,'r',&rootlocal);
560:     }
561:     PetscOptionsGetAll(NULL,&options);
562:     if (rootlocal && help) {
563:       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);
564:     } else if (help) {
565:       PetscSNPrintf(appline,applinelen,"<center>Running %s %s</center><br><center><pre>%s</pre></center><br>",programname,options,help);
566:     } else {
567:       PetscSNPrintf(appline,applinelen,"<center> Running %s %s</center><br>\n",programname,options);
568:     }
569:     PetscFree(options);
570:     PetscGetVersion(version,sizeof(version));
571:     PetscSNPrintf(intro,introlen,"<body>\n"
572:                                     "<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"
573:                                     "<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"
574:                                     "%s",version,petscconfigureoptions,appline);
575:     PetscStackCallSAWs(SAWs_Push_Body,("index.html",0,intro));
576:     PetscFree(intro);
577:     PetscFree(appline);
578:     if (selectport) {
579:       PetscBool silent;

581:       SAWs_Initialize();
582:       /* another process may have grabbed the port so keep trying */
583:       while (ierr) {
584:         PetscStackCallSAWs(SAWs_Get_Available_Port,(&port));
585:         PetscStackCallSAWs(SAWs_Set_Port,(port));
586:         SAWs_Initialize();
587:       }

589:       PetscOptionsGetBool(NULL,NULL,"-saws_port_auto_select_silent",&silent,NULL);
590:       if (!silent) {
591:         PetscStackCallSAWs(SAWs_Get_FullURL,(sizeof(sawsurl),sawsurl));
592:         PetscPrintf(PETSC_COMM_WORLD,"Point your browser to %s for SAWs\n",sawsurl);
593:       }
594:     } else {
595:       PetscStackCallSAWs(SAWs_Initialize,());
596:     }
597:     PetscCitationsRegister("@TechReport{ saws,\n"
598:                                   "  Author = {Matt Otten and Jed Brown and Barry Smith},\n"
599:                                   "  Title  = {Scientific Application Web Server (SAWs) Users Manual},\n"
600:                                   "  Institution = {Argonne National Laboratory},\n"
601:                                   "  Year   = 2013\n}\n",NULL);
602:   }
603:   return(0);
604: }
605: #endif

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

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

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

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

628:    Options Database Keys:
629: +  -help [intro] - prints help method for each option; if intro is given the program stops after printing the introductory help message
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_view - 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_view [:filename:format] - Prints summary of flop and timing information to screen or file, see PetscLogView().
663: .  -log_summary [filename] - (Deprecated, use -log_view) Prints summary of flop and timing information to screen. If the filename is specified the
664:         summary is written to the file.  See PetscLogView().
665: .  -log_exclude: <vec,mat,pc.ksp,snes> - excludes subset of object classes from logging
666: .  -log_all [filename] - Logs extensive profiling information  See PetscLogDump().
667: .  -log [filename] - Logs basic profiline information  See PetscLogDump().
668: .  -log_mpe [filename] - Creates a logfile viewable by the utility Jumpshot (in MPICH distribution)
669: -  -check_pointer_intensity 0,1,2 - if pointers are checked for validity (debug version only), using 0 will result in faster code

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

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

681:    Environmental Variables:
682: +   PETSC_TMP - alternative tmp directory
683: .   PETSC_SHARED_TMP - tmp is shared by all processes
684: .   PETSC_NOT_SHARED_TMP - each process has its own private tmp
685: .   PETSC_VIEWER_SOCKET_PORT - socket number to use for socket viewer
686: -   PETSC_VIEWER_SOCKET_MACHINE - machine to use for socket viewer to connect to


689:    Level: beginner

691:    Notes:
692:    If for some reason you must call MPI_Init() separately, call
693:    it before PetscInitialize().

695:    Fortran Version:
696:    In Fortran this routine has the format
697: $       call PetscInitialize(file,ierr)

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

703:    Important Fortran Note:
704:    In Fortran, you MUST use PETSC_NULL_CHARACTER to indicate a
705:    null character string; you CANNOT just use NULL as
706:    in the C version. See Users-Manual: Chapter 11 PETSc for Fortran Users for details.

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

711:    Concepts: initializing PETSc

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

715: @*/
716: PetscErrorCode  PetscInitialize(int *argc,char ***args,const char file[],const char help[])
717: {
719:   PetscMPIInt    flag, size;
720:   PetscBool      flg = PETSC_TRUE;
721:   char           hostname[256];
722: #if defined(PETSC_HAVE_HWLOC)
723:   PetscViewer    viewer;
724: #endif

727:   if (PetscInitializeCalled) return(0);
728:   /*
729:       The checking over compatible runtime libraries is complicated by the MPI ABI initiative
730:       https://wiki.mpich.org/mpich/index.php/ABI_Compatibility_Initiative which started with
731:         MPICH v3.1 (Released Feburary 2014)
732:         IBM MPI v2.1 (December 2014)
733:         Intel� MPI Library v5.0 (2014)
734:         Cray MPT v7.0.0 (June 2014)
735:       As of July 31, 2017 the ABI number still appears to be 12, that is all of the versions
736:       listed above and since that time are compatible.

738:       Unfortunately the MPI ABI initiative has not defined a way to determine the ABI number
739:       at compile time or runtime. Thus we will need to systematically track the allowed versions
740:       and how they are represented in the mpi.h and MPI_Get_library_version() output in order
741:       to perform the checking.

743:       Currently we only check for pre MPI ABI versions (and packages that do not follow the MPI ABI).

745:       Questions:

747:         Should the checks for ABI incompatibility be only on the major version number below?
748:         Presumably the output to stderr will be removed before a release.
749:   */

751: #if defined(PETSC_HAVE_MPI_GET_LIBRARY_VERSION)
752:   {
753:     char        mpilibraryversion[MPI_MAX_LIBRARY_VERSION_STRING];
754:     PetscMPIInt mpilibraryversionlength;
755:     MPI_Get_library_version(mpilibraryversion,&mpilibraryversionlength);if (ierr) return ierr;
756:     /* check for MPICH versions before MPI ABI initiative */
757: #if defined(MPICH_VERSION)
758: #if MPICH_NUMVERSION < 30100000
759:     {
760:       char *ver,*lf;
761:       flg = PETSC_FALSE;
762:       PetscStrstr(mpilibraryversion,"MPICH Version:",&ver);if (ierr) return ierr;
763:       if (ver) {
764:         PetscStrchr(ver,'\n',&lf);if (ierr) return ierr;
765:         if (lf) {
766:           *lf = 0;
767:           PetscStrendswith(ver,MPICH_VERSION,&flg);if (ierr) return ierr;
768:         }
769:       }
770:       if (!flg) {
771:         fprintf(stderr,"PETSc Error --- MPICH library version \n%s does not match what PETSc was compiled with %s, aborting\n",mpilibraryversion,MPICH_VERSION);
772:         return PETSC_ERR_MPI_LIB_INCOMP;
773:       }
774:     }
775: #endif
776:     /* check for OpenMPI version, it is not part of the MPI ABI initiative (is it part of another initiative that needs to be handled?) */
777: #elif defined(OMPI_MAJOR_VERSION)
778:     {
779:       char *ver,bs[32],*bsf;
780:       flg = PETSC_FALSE;
781:       PetscStrstr(mpilibraryversion,"Open MPI",&ver);if (ierr) return ierr;
782:       if (ver) {
783:         PetscSNPrintf(bs,32,"v%d.%d",OMPI_MAJOR_VERSION,OMPI_MINOR_VERSION);
784:         PetscStrstr(ver,bs,&bsf);if (ierr) return ierr;
785:         if (bsf) flg = PETSC_TRUE;
786:       }
787:       if (!flg) {
788:         fprintf(stderr,"PETSc Error --- Open MPI library version \n%s does not match what PETSc was compiled with %d.%d, aborting\n",mpilibraryversion,OMPI_MAJOR_VERSION,OMPI_MINOR_VERSION);
789:         return PETSC_ERR_MPI_LIB_INCOMP;
790:       }
791:     }
792: #endif
793:   }
794: #endif


797:   /* these must be initialized in a routine, not as a constant declaration*/
798:   PETSC_STDOUT = stdout;
799:   PETSC_STDERR = stderr;

801:   /* on Windows - set printf to default to printing 2 digit exponents */
802: #if defined(PETSC_HAVE__SET_OUTPUT_FORMAT)
803:   _set_output_format(_TWO_DIGIT_EXPONENT);
804: #endif

806:   PetscOptionsCreateDefault();

808:   /*
809:      We initialize the program name here (before MPI_Init()) because MPICH has a bug in
810:      it that it sets args[0] on all processors to be args[0] on the first processor.
811:   */
812:   if (argc && *argc) {
813:     PetscSetProgramName(**args);
814:   } else {
815:     PetscSetProgramName("Unknown Name");
816:   }

818:   MPI_Initialized(&flag);
819:   if (!flag) {
820:     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");
821: #if defined(PETSC_HAVE_MPI_INIT_THREAD)
822:     {
823:       PetscMPIInt provided;
824:       MPI_Init_thread(argc,args,MPI_THREAD_FUNNELED,&provided);
825:     }
826: #else
827:     MPI_Init(argc,args);
828: #endif
829:     PetscBeganMPI = PETSC_TRUE;
830:   }
831:   if (argc && args) {
832:     PetscGlobalArgc = *argc;
833:     PetscGlobalArgs = *args;
834:   }
835:   PetscFinalizeCalled = PETSC_FALSE;
836:   PetscSpinlockCreate(&PetscViewerASCIISpinLockOpen);
837:   PetscSpinlockCreate(&PetscViewerASCIISpinLockStdout);
838:   PetscSpinlockCreate(&PetscViewerASCIISpinLockStderr);
839:   PetscSpinlockCreate(&PetscCommSpinLock);

841:   if (PETSC_COMM_WORLD == MPI_COMM_NULL) PETSC_COMM_WORLD = MPI_COMM_WORLD;
842:   MPI_Comm_set_errhandler(PETSC_COMM_WORLD,MPI_ERRORS_RETURN);

844:   MPI_Add_error_class(&PETSC_MPI_ERROR_CLASS);
845:   MPI_Add_error_code(PETSC_MPI_ERROR_CLASS,&PETSC_MPI_ERROR_CODE);

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

850:   MPI_Comm_rank(MPI_COMM_WORLD,&PetscGlobalRank);
851:   MPI_Comm_size(MPI_COMM_WORLD,&PetscGlobalSize);

853:   MPIU_BOOL = MPI_INT;
854:   MPIU_ENUM = MPI_INT;

856:   /*
857:      Initialized the global complex variable; this is because with
858:      shared libraries the constructors for global variables
859:      are not called; at least on IRIX.
860:   */
861: #if defined(PETSC_HAVE_COMPLEX)
862:   {
863: #if defined(PETSC_CLANGUAGE_CXX) && !defined(PETSC_USE_REAL___FLOAT128)
864:     PetscComplex ic(0.0,1.0);
865:     PETSC_i = ic;
866: #else
867:     PETSC_i = _Complex_I;
868: #endif
869:   }

871: #if !defined(PETSC_HAVE_MPI_C_DOUBLE_COMPLEX)
872:   MPI_Type_contiguous(2,MPI_DOUBLE,&MPIU_C_DOUBLE_COMPLEX);
873:   MPI_Type_commit(&MPIU_C_DOUBLE_COMPLEX);
874:   MPI_Type_contiguous(2,MPI_FLOAT,&MPIU_C_COMPLEX);
875:   MPI_Type_commit(&MPIU_C_COMPLEX);
876: #endif
877: #endif /* PETSC_HAVE_COMPLEX */

879:   /*
880:      Create the PETSc MPI reduction operator that sums of the first
881:      half of the entries and maxes the second half.
882:   */
883:   MPI_Op_create(MPIU_MaxSum_Local,1,&MPIU_MAXSUM_OP);

885: #if defined(PETSC_USE_REAL___FLOAT128)
886:   MPI_Type_contiguous(2,MPI_DOUBLE,&MPIU___FLOAT128);
887:   MPI_Type_commit(&MPIU___FLOAT128);
888: #if defined(PETSC_HAVE_COMPLEX)
889:   MPI_Type_contiguous(4,MPI_DOUBLE,&MPIU___COMPLEX128);
890:   MPI_Type_commit(&MPIU___COMPLEX128);
891: #endif
892:   MPI_Op_create(PetscMax_Local,1,&MPIU_MAX);
893:   MPI_Op_create(PetscMin_Local,1,&MPIU_MIN);
894: #elif defined(PETSC_USE_REAL___FP16)
895:   MPI_Type_contiguous(2,MPI_CHAR,&MPIU___FP16);
896:   MPI_Type_commit(&MPIU___FP16);
897:   MPI_Op_create(PetscMax_Local,1,&MPIU_MAX);
898:   MPI_Op_create(PetscMin_Local,1,&MPIU_MIN);
899: #endif

901: #if (defined(PETSC_HAVE_COMPLEX) && !defined(PETSC_HAVE_MPI_C_DOUBLE_COMPLEX)) || defined(PETSC_USE_REAL___FLOAT128) || defined(PETSC_USE_REAL___FP16)
902:   MPI_Op_create(PetscSum_Local,1,&MPIU_SUM);
903: #endif

905:   MPI_Type_contiguous(2,MPIU_SCALAR,&MPIU_2SCALAR);
906:   MPI_Type_commit(&MPIU_2SCALAR);

908: #if defined(PETSC_USE_64BIT_INDICES) || !defined(MPI_2INT)
909:   MPI_Type_contiguous(2,MPIU_INT,&MPIU_2INT);
910:   MPI_Type_commit(&MPIU_2INT);
911: #endif


914:   /*
915:      Attributes to be set on PETSc communicators
916:   */
917:   MPI_Comm_create_keyval(MPI_COMM_NULL_COPY_FN,Petsc_DelCounter,&Petsc_Counter_keyval,(void*)0);
918:   MPI_Comm_create_keyval(MPI_COMM_NULL_COPY_FN,Petsc_DelComm_Outer,&Petsc_InnerComm_keyval,(void*)0);
919:   MPI_Comm_create_keyval(MPI_COMM_NULL_COPY_FN,Petsc_DelComm_Inner,&Petsc_OuterComm_keyval,(void*)0);
920:   MPI_Comm_create_keyval(MPI_COMM_NULL_COPY_FN,Petsc_DelShared,&Petsc_Shared_keyval,(void*)0);

922:   /*
923:      Build the options database
924:   */
925:   PetscOptionsInsert(NULL,argc,args,file);

927:   /* call a second time so it can look in the options database */
928:   PetscErrorPrintfInitialize();

930:   /*
931:      Print main application help message
932:   */
933:   PetscOptionsHasName(NULL,NULL,"-help",&flg);
934:   if (help && flg) {
935:     PetscPrintf(PETSC_COMM_WORLD,help);
936:   }
937:   PetscOptionsCheckInitial_Private();

939:   PetscCitationsInitialize();

941: #if defined(PETSC_HAVE_SAWS)
942:   PetscInitializeSAWs(help);
943: #endif

945:   /* Creates the logging data structures; this is enabled even if logging is not turned on */
946: #if defined(PETSC_USE_LOG)
947:   PetscLogInitialize();
948: #endif

950:   /*
951:      Load the dynamic libraries (on machines that support them), this registers all
952:      the solvers etc. (On non-dynamic machines this initializes the PetscDraw and PetscViewer classes)
953:   */
954:   PetscInitialize_DynamicLibraries();

956:   MPI_Comm_size(PETSC_COMM_WORLD,&size);
957:   PetscInfo1(0,"PETSc successfully started: number of processors = %d\n",size);
958:   PetscGetHostName(hostname,256);
959:   PetscInfo1(0,"Running on machine: %s\n",hostname);

961:   PetscOptionsCheckInitial_Components();
962:   /* Check the options database for options related to the options database itself */
963:   PetscOptionsSetFromOptions(NULL);

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

969:       Currently not used because it is not supported by MPICH.
970:   */
971: #if !defined(PETSC_WORDS_BIGENDIAN)
972:   MPI_Register_datarep((char*)"petsc",PetscDataRep_read_conv_fn,PetscDataRep_write_conv_fn,PetscDataRep_extent_fn,NULL);
973: #endif
974: #endif

976:   PetscOptionsHasName(NULL,NULL,"-python",&flg);
977:   if (flg) {
978:     PetscInitializeCalled = PETSC_TRUE;
979:     PetscPythonInitialize(NULL,NULL);
980:   }

982:   /*
983:       Setup building of stack frames for all function calls
984:   */
985: #if defined(PETSC_USE_DEBUG) && !defined(PETSC_HAVE_THREADSAFETY)
986:   PetscStackCreate();
987: #endif

989: #if defined(PETSC_SERIALIZE_FUNCTIONS)
990:   PetscFPTCreate(10000);
991: #endif

993: #if defined(PETSC_HAVE_HWLOC)
994:   PetscOptionsGetViewer(PETSC_COMM_WORLD,NULL,"-process_view",&viewer,NULL,&flg);
995:   if (flg) {
996:     PetscProcessPlacementView(viewer);
997:   }
998: #endif

1000:   /*
1001:       Once we are completedly initialized then we can set this variables
1002:   */
1003:   PetscInitializeCalled = PETSC_TRUE;
1004:   return(0);
1005: }

1007: #if defined(PETSC_USE_LOG)
1008: extern PetscObject *PetscObjects;
1009: extern PetscInt    PetscObjectsCounts, PetscObjectsMaxCounts;
1010: extern PetscBool   PetscObjectsLog;
1011: #endif

1013: /*
1014:     Frees all the MPI types and operations that PETSc may have created
1015: */
1016: PetscErrorCode  PetscFreeMPIResources(void)
1017: {

1021: #if defined(PETSC_USE_REAL___FLOAT128)
1022:   MPI_Type_free(&MPIU___FLOAT128);
1023: #if defined(PETSC_HAVE_COMPLEX)
1024:   MPI_Type_free(&MPIU___COMPLEX128);
1025: #endif
1026:   MPI_Op_free(&MPIU_MAX);
1027:   MPI_Op_free(&MPIU_MIN);
1028: #elif defined(PETSC_USE_REAL___FP16)
1029:   MPI_Type_free(&MPIU___FP16);
1030:   MPI_Op_free(&MPIU_MAX);
1031:   MPI_Op_free(&MPIU_MIN);
1032: #endif

1034: #if defined(PETSC_HAVE_COMPLEX)
1035: #if !defined(PETSC_HAVE_MPI_C_DOUBLE_COMPLEX)
1036:   MPI_Type_free(&MPIU_C_DOUBLE_COMPLEX);
1037:   MPI_Type_free(&MPIU_C_COMPLEX);
1038: #endif
1039: #endif

1041: #if (defined(PETSC_HAVE_COMPLEX) && !defined(PETSC_HAVE_MPI_C_DOUBLE_COMPLEX)) || defined(PETSC_USE_REAL___FLOAT128) || defined(PETSC_USE_REAL___FP16)
1042:   MPI_Op_free(&MPIU_SUM);
1043: #endif

1045:   MPI_Type_free(&MPIU_2SCALAR);
1046: #if defined(PETSC_USE_64BIT_INDICES) || !defined(MPI_2INT)
1047:   MPI_Type_free(&MPIU_2INT);
1048: #endif
1049:   MPI_Op_free(&MPIU_MAXSUM_OP);
1050:   return(0);
1051: }

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

1058:    Collective on PETSC_COMM_WORLD

1060:    Options Database Keys:
1061: +  -options_view - Calls PetscOptionsView()
1062: .  -options_left - Prints unused options that remain in the database
1063: .  -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
1064: .  -mpidump - Calls PetscMPIDump()
1065: .  -malloc_dump - Calls PetscMallocDump()
1066: .  -malloc_info - Prints total memory usage
1067: -  -malloc_log - Prints summary of memory usage

1069:    Level: beginner

1071:    Note:
1072:    See PetscInitialize() for more general runtime options.

1074: .seealso: PetscInitialize(), PetscOptionsView(), PetscMallocDump(), PetscMPIDump(), PetscEnd()
1075: @*/
1076: PetscErrorCode  PetscFinalize(void)
1077: {
1079:   PetscMPIInt    rank;
1080:   PetscInt       nopt;
1081:   PetscBool      flg1 = PETSC_FALSE,flg2 = PETSC_FALSE,flg3 = PETSC_FALSE;
1082:   PetscBool      flg;
1083: #if defined(PETSC_USE_LOG)
1084:   char           mname[PETSC_MAX_PATH_LEN];
1085: #endif

1087:   if (!PetscInitializeCalled) {
1088:     printf("PetscInitialize() must be called before PetscFinalize()\n");
1089:     return(PETSC_ERR_ARG_WRONGSTATE);
1090:   }
1092:   PetscInfo(NULL,"PetscFinalize() called\n");

1094:   MPI_Comm_rank(PETSC_COMM_WORLD,&rank);

1096:   PetscOptionsHasName(NULL,NULL,"-citations",&flg);
1097:   if (flg) {
1098:     char  *cits, filename[PETSC_MAX_PATH_LEN];
1099:     FILE  *fd = PETSC_STDOUT;

1101:     PetscOptionsGetString(NULL,NULL,"-citations",filename,PETSC_MAX_PATH_LEN,NULL);
1102:     if (filename[0]) {
1103:       PetscFOpen(PETSC_COMM_WORLD,filename,"w",&fd);
1104:     }
1105:     PetscSegBufferGet(PetscCitationsList,1,&cits);
1106:     cits[0] = 0;
1107:     PetscSegBufferExtractAlloc(PetscCitationsList,&cits);
1108:     PetscFPrintf(PETSC_COMM_WORLD,fd,"If you publish results based on this computation please cite the following:\n");
1109:     PetscFPrintf(PETSC_COMM_WORLD,fd,"===========================================================================\n");
1110:     PetscFPrintf(PETSC_COMM_WORLD,fd,"%s",cits);
1111:     PetscFPrintf(PETSC_COMM_WORLD,fd,"===========================================================================\n");
1112:     PetscFClose(PETSC_COMM_WORLD,fd);
1113:     PetscFree(cits);
1114:   }
1115:   PetscSegBufferDestroy(&PetscCitationsList);

1117: #if defined(PETSC_HAVE_SSL) && defined(PETSC_USE_SOCKET_VIEWER)
1118:   /* TextBelt is run for testing purposes only, please do not use this feature often */
1119:   {
1120:     PetscInt nmax = 2;
1121:     char     **buffs;
1122:     PetscMalloc1(2,&buffs);
1123:     PetscOptionsGetStringArray(NULL,NULL,"-textbelt",buffs,&nmax,&flg1);
1124:     if (flg1) {
1125:       if (!nmax) SETERRQ(PETSC_COMM_WORLD,PETSC_ERR_USER,"-textbelt requires either the phone number or number,\"message\"");
1126:       if (nmax == 1) {
1127:         PetscMalloc1(128,&buffs[1]);
1128:         PetscGetProgramName(buffs[1],32);
1129:         PetscStrcat(buffs[1]," has completed");
1130:       }
1131:       PetscTextBelt(PETSC_COMM_WORLD,buffs[0],buffs[1],NULL);
1132:       PetscFree(buffs[0]);
1133:       PetscFree(buffs[1]);
1134:     }
1135:     PetscFree(buffs);
1136:   }
1137:   {
1138:     PetscInt nmax = 2;
1139:     char     **buffs;
1140:     PetscMalloc1(2,&buffs);
1141:     PetscOptionsGetStringArray(NULL,NULL,"-tellmycell",buffs,&nmax,&flg1);
1142:     if (flg1) {
1143:       if (!nmax) SETERRQ(PETSC_COMM_WORLD,PETSC_ERR_USER,"-tellmycell requires either the phone number or number,\"message\"");
1144:       if (nmax == 1) {
1145:         PetscMalloc1(128,&buffs[1]);
1146:         PetscGetProgramName(buffs[1],32);
1147:         PetscStrcat(buffs[1]," has completed");
1148:       }
1149:       PetscTellMyCell(PETSC_COMM_WORLD,buffs[0],buffs[1],NULL);
1150:       PetscFree(buffs[0]);
1151:       PetscFree(buffs[1]);
1152:     }
1153:     PetscFree(buffs);
1154:   }
1155: #endif
1156:   /*
1157:     It should be safe to cancel the options monitors, since we don't expect to be setting options
1158:     here (at least that are worth monitoring).  Monitors ought to be released so that they release
1159:     whatever memory was allocated there before -malloc_dump reports unfreed memory.
1160:   */
1161:   PetscOptionsMonitorCancel();

1163: #if defined(PETSC_SERIALIZE_FUNCTIONS)
1164:   PetscFPTDestroy();
1165: #endif


1168: #if defined(PETSC_HAVE_SAWS)
1169:   flg = PETSC_FALSE;
1170:   PetscOptionsGetBool(NULL,NULL,"-saw_options",&flg,NULL);
1171:   if (flg) {
1172:     PetscOptionsSAWsDestroy();
1173:   }
1174: #endif

1176: #if defined(PETSC_HAVE_X)
1177:   flg1 = PETSC_FALSE;
1178:   PetscOptionsGetBool(NULL,NULL,"-x_virtual",&flg1,NULL);
1179:   if (flg1) {
1180:     /*  this is a crude hack, but better than nothing */
1181:     PetscPOpen(PETSC_COMM_WORLD,NULL,"pkill -9 Xvfb","r",NULL);
1182:   }
1183: #endif

1185: #if !defined(PETSC_HAVE_THREADSAFETY)
1186:   PetscOptionsGetBool(NULL,NULL,"-malloc_info",&flg2,NULL);
1187:   if (!flg2) {
1188:     flg2 = PETSC_FALSE;
1189:     PetscOptionsGetBool(NULL,NULL,"-memory_view",&flg2,NULL);
1190:   }
1191:   if (flg2) {
1192:     PetscMemoryView(PETSC_VIEWER_STDOUT_WORLD,"Summary of Memory Usage in PETSc\n");
1193:   }
1194: #endif

1196: #if defined(PETSC_USE_LOG)
1197:   flg1 = PETSC_FALSE;
1198:   PetscOptionsGetBool(NULL,NULL,"-get_total_flops",&flg1,NULL);
1199:   if (flg1) {
1200:     PetscLogDouble flops = 0;
1201:     MPI_Reduce(&petsc_TotalFlops,&flops,1,MPI_DOUBLE,MPI_SUM,0,PETSC_COMM_WORLD);
1202:     PetscPrintf(PETSC_COMM_WORLD,"Total flops over all processors %g\n",flops);
1203:   }
1204: #endif


1207: #if defined(PETSC_USE_LOG)
1208: #if defined(PETSC_HAVE_MPE)
1209:   mname[0] = 0;
1210:   PetscOptionsGetString(NULL,NULL,"-log_mpe",mname,PETSC_MAX_PATH_LEN,&flg1);
1211:   if (flg1) {
1212:     if (mname[0]) {PetscLogMPEDump(mname);}
1213:     else          {PetscLogMPEDump(0);}
1214:   }
1215: #endif
1216: #endif

1218:   /*
1219:      Free all objects registered with PetscObjectRegisterDestroy() such as PETSC_VIEWER_XXX_().
1220:   */
1221:   PetscObjectRegisterDestroyAll();

1223: #if defined(PETSC_USE_LOG)
1224:   PetscLogViewFromOptions();
1225:   mname[0] = 0;
1226:   PetscOptionsGetString(NULL,NULL,"-log_summary",mname,PETSC_MAX_PATH_LEN,&flg1);
1227:   if (flg1) {
1228:     PetscViewer viewer;
1229:     (*PetscHelpPrintf)(PETSC_COMM_WORLD,"\n\n WARNING:   -log_summary is being deprecated; switch to -log_view\n\n\n");
1230:     if (mname[0]) {
1231:       PetscViewerASCIIOpen(PETSC_COMM_WORLD,mname,&viewer);
1232:       PetscLogView(viewer);
1233:       PetscViewerDestroy(&viewer);
1234:     } else {
1235:       viewer = PETSC_VIEWER_STDOUT_WORLD;
1236:       PetscViewerPushFormat(viewer,PETSC_VIEWER_DEFAULT);
1237:       PetscLogView(viewer);
1238:       PetscViewerPopFormat(viewer);
1239:     }
1240:   }

1242:   /*
1243:      Free any objects created by the last block of code.
1244:   */
1245:   PetscObjectRegisterDestroyAll();

1247:   mname[0] = 0;
1248:   PetscOptionsGetString(NULL,NULL,"-log_all",mname,PETSC_MAX_PATH_LEN,&flg1);
1249:   PetscOptionsGetString(NULL,NULL,"-log",mname,PETSC_MAX_PATH_LEN,&flg2);
1250:   if (flg1 || flg2) {
1251:     if (mname[0]) PetscLogDump(mname);
1252:     else          PetscLogDump(0);
1253:   }
1254: #endif

1256:   PetscStackDestroy();

1258:   flg1 = PETSC_FALSE;
1259:   PetscOptionsGetBool(NULL,NULL,"-no_signal_handler",&flg1,NULL);
1260:   if (!flg1) { PetscPopSignalHandler();}
1261:   flg1 = PETSC_FALSE;
1262:   PetscOptionsGetBool(NULL,NULL,"-mpidump",&flg1,NULL);
1263:   if (flg1) {
1264:     PetscMPIDump(stdout);
1265:   }
1266:   flg1 = PETSC_FALSE;
1267:   flg2 = PETSC_FALSE;
1268:   /* preemptive call to avoid listing this option in options table as unused */
1269:   PetscOptionsHasName(NULL,NULL,"-malloc_dump",&flg1);
1270:   PetscOptionsHasName(NULL,NULL,"-objects_dump",&flg1);
1271:   PetscOptionsGetBool(NULL,NULL,"-options_view",&flg2,NULL);

1273:   if (flg2) {
1274:     PetscViewer viewer;
1275:     PetscViewerCreate(PETSC_COMM_WORLD,&viewer);
1276:     PetscViewerSetType(viewer,PETSCVIEWERASCII);
1277:     PetscOptionsView(NULL,viewer);
1278:     PetscViewerDestroy(&viewer);
1279:   }

1281:   /* to prevent PETSc -options_left from warning */
1282:   PetscOptionsHasName(NULL,NULL,"-nox",&flg1);
1283:   PetscOptionsHasName(NULL,NULL,"-nox_warning",&flg1);

1285:   flg3 = PETSC_FALSE; /* default value is required */
1286:   PetscOptionsGetBool(NULL,NULL,"-options_left",&flg3,&flg1);
1287:   PetscOptionsAllUsed(NULL,&nopt);
1288:   if (flg3) {
1289:     if (!flg2) { /* have not yet printed the options */
1290:       PetscViewer viewer;
1291:       PetscViewerCreate(PETSC_COMM_WORLD,&viewer);
1292:       PetscViewerSetType(viewer,PETSCVIEWERASCII);
1293:       PetscOptionsView(NULL,viewer);
1294:       PetscViewerDestroy(&viewer);
1295:     }
1296:     if (!nopt) {
1297:       PetscPrintf(PETSC_COMM_WORLD,"There are no unused options.\n");
1298:     } else if (nopt == 1) {
1299:       PetscPrintf(PETSC_COMM_WORLD,"There is one unused database option. It is:\n");
1300:     } else {
1301:       PetscPrintf(PETSC_COMM_WORLD,"There are %D unused database options. They are:\n",nopt);
1302:     }
1303:   }
1304: #if defined(PETSC_USE_DEBUG)
1305:   if (nopt && !flg3 && !flg1) {
1306:     PetscPrintf(PETSC_COMM_WORLD,"WARNING! There are options you set that were not used!\n");
1307:     PetscPrintf(PETSC_COMM_WORLD,"WARNING! could be spelling mistake, etc!\n");
1308:     PetscOptionsLeft(NULL);
1309:   } else if (nopt && flg3) {
1310: #else
1311:   if (nopt && flg3) {
1312: #endif
1313:     PetscOptionsLeft(NULL);
1314:   }

1316: #if defined(PETSC_HAVE_SAWS)
1317:   if (!PetscGlobalRank) {
1318:     PetscStackSAWsViewOff();
1319:     PetscStackCallSAWs(SAWs_Finalize,());
1320:   }
1321: #endif

1323: #if defined(PETSC_USE_LOG)
1324:   /*
1325:        List all objects the user may have forgot to free
1326:   */
1327:   if (PetscObjectsLog) {
1328:     PetscOptionsHasName(NULL,NULL,"-objects_dump",&flg1);
1329:     if (flg1) {
1330:       MPI_Comm local_comm;
1331:       char     string[64];

1333:       PetscOptionsGetString(NULL,NULL,"-objects_dump",string,64,NULL);
1334:       MPI_Comm_dup(MPI_COMM_WORLD,&local_comm);
1335:       PetscSequentialPhaseBegin_Private(local_comm,1);
1336:       PetscObjectsDump(stdout,(string[0] == 'a') ? PETSC_TRUE : PETSC_FALSE);
1337:       PetscSequentialPhaseEnd_Private(local_comm,1);
1338:       MPI_Comm_free(&local_comm);
1339:     }
1340:   }
1341: #endif

1343: #if defined(PETSC_USE_LOG)
1344:   PetscObjectsCounts    = 0;
1345:   PetscObjectsMaxCounts = 0;
1346:   PetscFree(PetscObjects);
1347: #endif

1349:   /*
1350:      Destroy any packages that registered a finalize
1351:   */
1352:   PetscRegisterFinalizeAll();

1354: #if defined(PETSC_USE_LOG)
1355:   PetscLogDestroy();
1356: #endif

1358:   /*
1359:      Print PetscFunctionLists that have not been properly freed

1361:   PetscFunctionListPrintAll();
1362:   */

1364:   if (petsc_history) {
1365:     PetscCloseHistoryFile(&petsc_history);
1366:     petsc_history = 0;
1367:   }
1368:   PetscOptionsHelpPrintedDestroy(&PetscOptionsHelpPrintedSingleton);

1370:   PetscInfoAllow(PETSC_FALSE,NULL);

1372: #if !defined(PETSC_HAVE_THREADSAFETY)
1373:   {
1374:     char fname[PETSC_MAX_PATH_LEN];
1375:     FILE *fd;
1376:     int  err;

1378:     fname[0] = 0;

1380:     PetscOptionsGetString(NULL,NULL,"-malloc_dump",fname,250,&flg1);
1381:     flg2 = PETSC_FALSE;
1382:     PetscOptionsGetBool(NULL,NULL,"-malloc_test",&flg2,NULL);
1383: #if defined(PETSC_USE_DEBUG)
1384:     if (PETSC_RUNNING_ON_VALGRIND) flg2 = PETSC_FALSE;
1385: #else
1386:     flg2 = PETSC_FALSE;         /* Skip reporting for optimized builds regardless of -malloc_test */
1387: #endif
1388:     if (flg1 && fname[0]) {
1389:       char sname[PETSC_MAX_PATH_LEN];

1391:       PetscSNPrintf(sname,PETSC_MAX_PATH_LEN,"%s_%d",fname,rank);
1392:       fd   = fopen(sname,"w"); if (!fd) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_FILE_OPEN,"Cannot open log file: %s",sname);
1393:       PetscMallocDump(fd);
1394:       err  = fclose(fd);
1395:       if (err) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SYS,"fclose() failed on file");
1396:     } else if (flg1 || flg2) {
1397:       MPI_Comm local_comm;

1399:       MPI_Comm_dup(MPI_COMM_WORLD,&local_comm);
1400:       PetscSequentialPhaseBegin_Private(local_comm,1);
1401:       PetscMallocDump(stdout);
1402:       PetscSequentialPhaseEnd_Private(local_comm,1);
1403:       MPI_Comm_free(&local_comm);
1404:     }
1405:   }

1407:   {
1408:     char fname[PETSC_MAX_PATH_LEN];
1409:     FILE *fd = NULL;

1411:     fname[0] = 0;

1413:     PetscOptionsGetString(NULL,NULL,"-malloc_log",fname,250,&flg1);
1414:     PetscOptionsHasName(NULL,NULL,"-malloc_log_threshold",&flg2);
1415:     if (flg1 && fname[0]) {
1416:       int err;

1418:       if (!rank) {
1419:         fd = fopen(fname,"w");
1420:         if (!fd) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_FILE_OPEN,"Cannot open log file: %s",fname);
1421:       }
1422:       PetscMallocDumpLog(fd);
1423:       if (fd) {
1424:         err = fclose(fd);
1425:         if (err) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SYS,"fclose() failed on file");
1426:       }
1427:     } else if (flg1 || flg2) {
1428:       PetscMallocDumpLog(stdout);
1429:     }
1430:   }
1431: #endif

1433:   /*
1434:      Close any open dynamic libraries
1435:   */
1436:   PetscFinalize_DynamicLibraries();

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

1441:   PetscGlobalArgc = 0;
1442:   PetscGlobalArgs = 0;

1444:   PetscFreeMPIResources();

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

1450:      If all PETSc objects were not destroyed those left over objects will have hanging references to
1451:      the MPI_Comms that were freed; but that is ok because those PETSc objects will never be used again
1452:  */
1453:   {
1454:     PetscCommCounter *counter;
1455:     PetscMPIInt      flg;
1456:     MPI_Comm         icomm;
1457:     union {MPI_Comm comm; void *ptr;} ucomm;
1458:     MPI_Comm_get_attr(PETSC_COMM_SELF,Petsc_InnerComm_keyval,&ucomm,&flg);
1459:     if (flg) {
1460:       icomm = ucomm.comm;
1461:       MPI_Comm_get_attr(icomm,Petsc_Counter_keyval,&counter,&flg);
1462:       if (!flg) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_CORRUPT,"Inner MPI_Comm does not have expected tag/name counter, problem with corrupted memory");

1464:       MPI_Comm_delete_attr(PETSC_COMM_SELF,Petsc_InnerComm_keyval);
1465:       MPI_Comm_delete_attr(icomm,Petsc_Counter_keyval);
1466:       MPI_Comm_free(&icomm);
1467:     }
1468:     MPI_Comm_get_attr(PETSC_COMM_WORLD,Petsc_InnerComm_keyval,&ucomm,&flg);
1469:     if (flg) {
1470:       icomm = ucomm.comm;
1471:       MPI_Comm_get_attr(icomm,Petsc_Counter_keyval,&counter,&flg);
1472:       if (!flg) SETERRQ(PETSC_COMM_WORLD,PETSC_ERR_ARG_CORRUPT,"Inner MPI_Comm does not have expected tag/name counter, problem with corrupted memory");

1474:       MPI_Comm_delete_attr(PETSC_COMM_WORLD,Petsc_InnerComm_keyval);
1475:       MPI_Comm_delete_attr(icomm,Petsc_Counter_keyval);
1476:       MPI_Comm_free(&icomm);
1477:     }
1478:   }

1480:   MPI_Comm_free_keyval(&Petsc_Counter_keyval);
1481:   MPI_Comm_free_keyval(&Petsc_InnerComm_keyval);
1482:   MPI_Comm_free_keyval(&Petsc_OuterComm_keyval);
1483:   MPI_Comm_free_keyval(&Petsc_Shared_keyval);

1485:   PetscSpinlockDestroy(&PetscViewerASCIISpinLockOpen);
1486:   PetscSpinlockDestroy(&PetscViewerASCIISpinLockStdout);
1487:   PetscSpinlockDestroy(&PetscViewerASCIISpinLockStderr);
1488:   PetscSpinlockDestroy(&PetscCommSpinLock);

1490:   if (PetscBeganMPI) {
1491: #if defined(PETSC_HAVE_MPI_FINALIZED)
1492:     PetscMPIInt flag;
1493:     MPI_Finalized(&flag);
1494:     if (flag) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_LIB,"MPI_Finalize() has already been called, even though MPI_Init() was called by PetscInitialize()");
1495: #endif
1496:     MPI_Finalize();
1497:   }
1498: /*

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

1508: */
1509:   PetscMallocClear();

1511:   PetscInitializeCalled = PETSC_FALSE;
1512:   PetscFinalizeCalled   = PETSC_TRUE;
1513:   return(0);
1514: }

1516: #if defined(PETSC_MISSING_LAPACK_lsame_)
1517: PETSC_EXTERN int lsame_(char *a,char *b)
1518: {
1519:   if (*a == *b) return 1;
1520:   if (*a + 32 == *b) return 1;
1521:   if (*a - 32 == *b) return 1;
1522:   return 0;
1523: }
1524: #endif

1526: #if defined(PETSC_MISSING_LAPACK_lsame)
1527: PETSC_EXTERN int lsame(char *a,char *b)
1528: {
1529:   if (*a == *b) return 1;
1530:   if (*a + 32 == *b) return 1;
1531:   if (*a - 32 == *b) return 1;
1532:   return 0;
1533: }
1534: #endif