xref: /petsc/src/sys/objects/pinit.c (revision 3116ef58e11bc77b08297b681ddd79bc46c3f215)
1 
2 /*
3    This file defines the initialization of PETSc, including PetscInitialize()
4 */
5 
6 #include <petscsys.h>        /*I  "petscsys.h"   I*/
7 
8 #if defined(PETSC_HAVE_CUSP)
9 #include <cublas.h>
10 #endif
11 
12 #if defined(PETSC_USE_LOG)
13 extern PetscErrorCode PetscLogBegin_Private(void);
14 #endif
15 extern PetscBool  PetscHMPIWorker;
16 
17 /* -----------------------------------------------------------------------------------------*/
18 
19 extern FILE *petsc_history;
20 
21 extern PetscErrorCode PetscInitialize_DynamicLibraries(void);
22 extern PetscErrorCode PetscFinalize_DynamicLibraries(void);
23 extern PetscErrorCode PetscFListDestroyAll(void);
24 extern PetscErrorCode PetscSequentialPhaseBegin_Private(MPI_Comm,int);
25 extern PetscErrorCode PetscSequentialPhaseEnd_Private(MPI_Comm,int);
26 extern PetscErrorCode PetscCloseHistoryFile(FILE **);
27 
28 #if defined(PETSC_HAVE_PTHREADCLASSES)
29 extern int* ThreadCoreAffinity;
30 extern PetscErrorCode (*PetscThreadFinalize)(void);
31 extern PetscErrorCode (*PetscThreadInitialize)(PetscInt);
32 extern PetscMPIInt PetscMaxThreads;
33 #endif
34 
35 /* this is used by the _, __, and ___ macros (see include/petscerror.h) */
36 PetscErrorCode __gierr = 0;
37 
38 /* user may set this BEFORE calling PetscInitialize() */
39 MPI_Comm PETSC_COMM_WORLD = MPI_COMM_NULL;
40 
41 PetscMPIInt Petsc_Counter_keyval   = MPI_KEYVAL_INVALID;
42 PetscMPIInt Petsc_InnerComm_keyval = MPI_KEYVAL_INVALID;
43 PetscMPIInt Petsc_OuterComm_keyval = MPI_KEYVAL_INVALID;
44 
45 /*
46      Declare and set all the string names of the PETSc enums
47 */
48 const char *PetscBools[]     = {"FALSE","TRUE","PetscBool","PETSC_",0};
49 const char *PetscCopyModes[] = {"COPY_VALUES","OWN_POINTER","USE_POINTER","PetscCopyMode","PETSC_",0};
50 const char *PetscDataTypes[] = {"INT","DOUBLE","COMPLEX","LONG","SHORT","FLOAT",
51                                 "CHAR","LOGICAL","ENUM","BOOL","LONGDOUBLE","PetscDataType","PETSC_",0};
52 
53 PetscBool  PetscPreLoadingUsed = PETSC_FALSE;
54 PetscBool  PetscPreLoadingOn   = PETSC_FALSE;
55 
56 /*
57        Checks the options database for initializations related to the
58     PETSc components
59 */
60 #undef __FUNCT__
61 #define __FUNCT__ "PetscOptionsCheckInitial_Components"
62 PetscErrorCode  PetscOptionsCheckInitial_Components(void)
63 {
64   PetscBool  flg1;
65   PetscErrorCode ierr;
66 
67   PetscFunctionBegin;
68   ierr = PetscOptionsHasName(PETSC_NULL,"-help",&flg1);CHKERRQ(ierr);
69   if (flg1) {
70 #if defined (PETSC_USE_LOG)
71     MPI_Comm   comm = PETSC_COMM_WORLD;
72     ierr = (*PetscHelpPrintf)(comm,"------Additional PETSc component options--------\n");CHKERRQ(ierr);
73     ierr = (*PetscHelpPrintf)(comm," -log_summary_exclude: <vec,mat,pc.ksp,snes>\n");CHKERRQ(ierr);
74     ierr = (*PetscHelpPrintf)(comm," -info_exclude: <null,vec,mat,pc,ksp,snes,ts>\n");CHKERRQ(ierr);
75     ierr = (*PetscHelpPrintf)(comm,"-----------------------------------------------\n");CHKERRQ(ierr);
76 #endif
77   }
78   PetscFunctionReturn(0);
79 }
80 
81 #if defined(PETSC_HAVE_MATLAB_ENGINE)
82 extern PetscBool PetscBeganMPI;
83 
84 #undef __FUNCT__
85 #define __FUNCT__ "PetscInitializeMatlab"
86 /*
87       PetscInitializeMatlab - Calls PetscInitialize() from C/C++ without the pointers to argc and args
88 
89    Collective
90 
91    Level: advanced
92 
93     Notes: this is called only by the PETSc MATLAB interface. Even though it might start MPI it sets the flag to
94      indicate that it did NOT start MPI so that the PetscFinalize() does not end MPI, thus allowing PetscInitialize() to
95      be called multiple times from MATLAB without the problem of trying to initialize MPI more than once.
96 
97      Turns off PETSc signal handling because that can interact with MATLAB's signal handling causing random crashes.
98 
99 .seealso: PetscInitialize(), PetscInitializeFortran(), PetscInitializeNoArguments()
100 */
101 PetscErrorCode  PetscInitializeMatlab(int argc,char **args,const char *filename,const char *help)
102 {
103   PetscErrorCode ierr;
104   int            myargc = argc;
105   char           **myargs = args;
106 
107   PetscFunctionBegin;
108   ierr = PetscInitialize(&myargc,&myargs,filename,help);
109   ierr = PetscPopSignalHandler();CHKERRQ(ierr);
110   PetscBeganMPI = PETSC_FALSE;
111   PetscFunctionReturn(ierr);
112 }
113 
114 #undef __FUNCT__
115 #define __FUNCT__ "PetscInitializedMatlab"
116 /*
117       PetscInitializedMatlab - Has PETSc been initialized already?
118 
119    Not Collective
120 
121    Level: advanced
122 
123     Notes: this is called only by the PETSc MATLAB interface.
124 
125 .seealso: PetscInitialize(), PetscInitializeFortran(), PetscInitializeNoArguments()
126 */
127 int  PetscInitializedMatlab(void)
128 {
129   PetscBool flg;
130 
131   PetscInitialized(&flg);
132   if (flg) return 1;
133   else return 0;
134 }
135 
136 #undef __FUNCT__
137 #define __FUNCT__ "PetscGetPETSC_COMM_SELFMatlab"
138 /*
139       Used by MATLAB interface to get communicator
140 */
141 PetscErrorCode  PetscGetPETSC_COMM_SELFMatlab(MPI_Comm *comm)
142 {
143   PetscFunctionBegin;
144   *comm = PETSC_COMM_SELF;
145   PetscFunctionReturn(0);
146 }
147 #endif
148 
149 #undef __FUNCT__
150 #define __FUNCT__ "PetscInitializeNoArguments"
151 /*@C
152       PetscInitializeNoArguments - Calls PetscInitialize() from C/C++ without
153         the command line arguments.
154 
155    Collective
156 
157    Level: advanced
158 
159 .seealso: PetscInitialize(), PetscInitializeFortran()
160 @*/
161 PetscErrorCode  PetscInitializeNoArguments(void)
162 {
163   PetscErrorCode ierr;
164   int            argc = 0;
165   char           **args = 0;
166 
167   PetscFunctionBegin;
168   ierr = PetscInitialize(&argc,&args,PETSC_NULL,PETSC_NULL);
169   PetscFunctionReturn(ierr);
170 }
171 
172 #undef __FUNCT__
173 #define __FUNCT__ "PetscInitialized"
174 /*@
175       PetscInitialized - Determine whether PETSc is initialized.
176 
177 7   Level: beginner
178 
179 .seealso: PetscInitialize(), PetscInitializeNoArguments(), PetscInitializeFortran()
180 @*/
181 PetscErrorCode  PetscInitialized(PetscBool  *isInitialized)
182 {
183   PetscFunctionBegin;
184   PetscValidPointer(isInitialized, 1);
185   *isInitialized = PetscInitializeCalled;
186   PetscFunctionReturn(0);
187 }
188 
189 #undef __FUNCT__
190 #define __FUNCT__ "PetscFinalized"
191 /*@
192       PetscFinalized - Determine whether PetscFinalize() has been called yet
193 
194    Level: developer
195 
196 .seealso: PetscInitialize(), PetscInitializeNoArguments(), PetscInitializeFortran()
197 @*/
198 PetscErrorCode  PetscFinalized(PetscBool  *isFinalized)
199 {
200   PetscFunctionBegin;
201   PetscValidPointer(isFinalized, 1);
202   *isFinalized = PetscFinalizeCalled;
203   PetscFunctionReturn(0);
204 }
205 
206 extern PetscErrorCode        PetscOptionsCheckInitial_Private(void);
207 extern PetscBool  PetscBeganMPI;
208 
209 /*
210        This function is the MPI reduction operation used to compute the sum of the
211    first half of the datatype and the max of the second half.
212 */
213 MPI_Op PetscMaxSum_Op = 0;
214 
215 EXTERN_C_BEGIN
216 #undef __FUNCT__
217 #define __FUNCT__ "PetscMaxSum_Local"
218 void  MPIAPI PetscMaxSum_Local(void *in,void *out,int *cnt,MPI_Datatype *datatype)
219 {
220   PetscInt *xin = (PetscInt*)in,*xout = (PetscInt*)out,i,count = *cnt;
221 
222   PetscFunctionBegin;
223   if (*datatype != MPIU_2INT) {
224     (*PetscErrorPrintf)("Can only handle MPIU_2INT data types");
225     MPI_Abort(MPI_COMM_WORLD,1);
226   }
227 
228   for (i=0; i<count; i++) {
229     xout[2*i]    = PetscMax(xout[2*i],xin[2*i]);
230     xout[2*i+1] += xin[2*i+1];
231   }
232   PetscFunctionReturnVoid();
233 }
234 EXTERN_C_END
235 
236 /*
237     Returns the max of the first entry owned by this processor and the
238 sum of the second entry.
239 
240     The reason nprocs[2*i] contains lengths nprocs[2*i+1] contains flag of 1 if length is nonzero
241 is so that the PetscMaxSum_Op() can set TWO values, if we passed in only nprocs[i] with lengths
242 there would be no place to store the both needed results.
243 */
244 #undef __FUNCT__
245 #define __FUNCT__ "PetscMaxSum"
246 PetscErrorCode  PetscMaxSum(MPI_Comm comm,const PetscInt nprocs[],PetscInt *max,PetscInt *sum)
247 {
248   PetscMPIInt    size,rank;
249   PetscInt       *work;
250   PetscErrorCode ierr;
251 
252   PetscFunctionBegin;
253   ierr   = MPI_Comm_size(comm,&size);CHKERRQ(ierr);
254   ierr   = MPI_Comm_rank(comm,&rank);CHKERRQ(ierr);
255   ierr   = PetscMalloc(2*size*sizeof(PetscInt),&work);CHKERRQ(ierr);
256   ierr   = MPI_Allreduce((void*)nprocs,work,size,MPIU_2INT,PetscMaxSum_Op,comm);CHKERRQ(ierr);
257   *max   = work[2*rank];
258   *sum   = work[2*rank+1];
259   ierr   = PetscFree(work);CHKERRQ(ierr);
260   PetscFunctionReturn(0);
261 }
262 
263 /* ----------------------------------------------------------------------------*/
264 MPI_Op  PetscADMax_Op = 0;
265 
266 EXTERN_C_BEGIN
267 #undef __FUNCT__
268 #define __FUNCT__ "PetscADMax_Local"
269 void  MPIAPI PetscADMax_Local(void *in,void *out,PetscMPIInt *cnt,MPI_Datatype *datatype)
270 {
271   PetscScalar *xin = (PetscScalar *)in,*xout = (PetscScalar*)out;
272   PetscInt    i,count = *cnt;
273 
274   PetscFunctionBegin;
275   if (*datatype != MPIU_2SCALAR) {
276     (*PetscErrorPrintf)("Can only handle MPIU_2SCALAR data (i.e. double or complex) types");
277     MPI_Abort(MPI_COMM_WORLD,1);
278   }
279 
280   for (i=0; i<count; i++) {
281     if (PetscRealPart(xout[2*i]) < PetscRealPart(xin[2*i])) {
282       xout[2*i]   = xin[2*i];
283       xout[2*i+1] = xin[2*i+1];
284     }
285   }
286   PetscFunctionReturnVoid();
287 }
288 EXTERN_C_END
289 
290 MPI_Op  PetscADMin_Op = 0;
291 
292 EXTERN_C_BEGIN
293 #undef __FUNCT__
294 #define __FUNCT__ "PetscADMin_Local"
295 void  MPIAPI PetscADMin_Local(void *in,void *out,PetscMPIInt *cnt,MPI_Datatype *datatype)
296 {
297   PetscScalar *xin = (PetscScalar *)in,*xout = (PetscScalar*)out;
298   PetscInt    i,count = *cnt;
299 
300   PetscFunctionBegin;
301   if (*datatype != MPIU_2SCALAR) {
302     (*PetscErrorPrintf)("Can only handle MPIU_2SCALAR data (i.e. double or complex) types");
303     MPI_Abort(MPI_COMM_WORLD,1);
304   }
305 
306   for (i=0; i<count; i++) {
307     if (PetscRealPart(xout[2*i]) > PetscRealPart(xin[2*i])) {
308       xout[2*i]   = xin[2*i];
309       xout[2*i+1] = xin[2*i+1];
310     }
311   }
312   PetscFunctionReturnVoid();
313 }
314 EXTERN_C_END
315 /* ---------------------------------------------------------------------------------------*/
316 
317 #if (defined(PETSC_USE_COMPLEX) && !defined(PETSC_HAVE_MPI_C_DOUBLE_COMPLEX)) || defined(PETSC_USE_REAL___FLOAT128)
318 MPI_Op MPIU_SUM = 0;
319 
320 EXTERN_C_BEGIN
321 #undef __FUNCT__
322 #define __FUNCT__ "PetscSum_Local"
323 void  PetscSum_Local(void *in,void *out,PetscMPIInt *cnt,MPI_Datatype *datatype)
324 {
325   PetscInt    i,count = *cnt;
326 
327   PetscFunctionBegin;
328   if (*datatype == MPIU_SCALAR) {
329     PetscScalar *xin = (PetscScalar *)in,*xout = (PetscScalar*)out;
330     for (i=0; i<count; i++) {
331       xout[i] += xin[i];
332     }
333   } else if (*datatype == MPIU_REAL) {
334     PetscReal *xin = (PetscReal *)in,*xout = (PetscReal*)out;
335     for (i=0; i<count; i++) {
336       xout[i] += xin[i];
337     }
338   } else {
339     (*PetscErrorPrintf)("Can only handle MPIU_REAL or MPIU_SCALAR data (i.e. double or complex) types");
340     MPI_Abort(MPI_COMM_WORLD,1);
341   }
342   PetscFunctionReturnVoid();
343 }
344 EXTERN_C_END
345 #endif
346 
347 #if defined(PETSC_USE_REAL___FLOAT128)
348 MPI_Op MPIU_MAX = 0;
349 MPI_Op MPIU_MIN = 0;
350 
351 EXTERN_C_BEGIN
352 #undef __FUNCT__
353 #define __FUNCT__ "PetscMax_Local"
354 void  PetscMax_Local(void *in,void *out,PetscMPIInt *cnt,MPI_Datatype *datatype)
355 {
356   PetscScalar *xin = (PetscScalar *)in,*xout = (PetscScalar*)out;
357   PetscInt    i,count = *cnt;
358 
359   PetscFunctionBegin;
360   if (*datatype != MPIU_SCALAR) {
361     (*PetscErrorPrintf)("Can only handle MPIU_SCALAR data (i.e. double or complex) types");
362     MPI_Abort(MPI_COMM_WORLD,1);
363   }
364 
365   for (i=0; i<count; i++) {
366     xout[i] = PetscMax(xout[i],xin[i]);
367   }
368   PetscFunctionReturnVoid();
369 }
370 EXTERN_C_END
371 
372 EXTERN_C_BEGIN
373 #undef __FUNCT__
374 #define __FUNCT__ "PetscMin_Local"
375 void  PetscMin_Local(void *in,void *out,PetscMPIInt *cnt,MPI_Datatype *datatype)
376 {
377   PetscScalar *xin = (PetscScalar *)in,*xout = (PetscScalar*)out;
378   PetscInt    i,count = *cnt;
379 
380   PetscFunctionBegin;
381   if (*datatype != MPIU_SCALAR) {
382     (*PetscErrorPrintf)("Can only handle MPIU_SCALAR data (i.e. double or complex) types");
383     MPI_Abort(MPI_COMM_WORLD,1);
384   }
385 
386   for (i=0; i<count; i++) {
387     xout[i] = PetscMin(xout[i],xin[i]);
388   }
389   PetscFunctionReturnVoid();
390 }
391 EXTERN_C_END
392 #endif
393 
394 EXTERN_C_BEGIN
395 #undef __FUNCT__
396 #define __FUNCT__ "Petsc_DelCounter"
397 /*
398    Private routine to delete internal tag/name counter storage when a communicator is freed.
399 
400    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.
401 
402    Note: this is declared extern "C" because it is passed to MPI_Keyval_create()
403 
404 */
405 PetscMPIInt  MPIAPI Petsc_DelCounter(MPI_Comm comm,PetscMPIInt keyval,void *count_val,void *extra_state)
406 {
407   PetscErrorCode ierr;
408 
409   PetscFunctionBegin;
410   ierr = PetscInfo1(0,"Deleting counter data in an MPI_Comm %ld\n",(long)comm);if (ierr) PetscFunctionReturn((PetscMPIInt)ierr);
411   ierr = PetscFree(count_val);if (ierr) PetscFunctionReturn((PetscMPIInt)ierr);
412   PetscFunctionReturn(MPI_SUCCESS);
413 }
414 EXTERN_C_END
415 
416 EXTERN_C_BEGIN
417 #undef __FUNCT__
418 #define __FUNCT__ "Petsc_DelComm"
419 /*
420   This does not actually free anything, it simply marks when a reference count to an internal or external MPI_Comm reaches zero and the
421   the external MPI_Comm drops its reference to the internal or external MPI_Comm
422 
423   This is called by MPI, not by users. This is called when MPI_Comm_free() is called on the communicator.
424 
425   Note: this is declared extern "C" because it is passed to MPI_Keyval_create()
426 
427 */
428 PetscMPIInt  MPIAPI Petsc_DelComm(MPI_Comm comm,PetscMPIInt keyval,void *attr_val,void *extra_state)
429 {
430   PetscErrorCode   ierr;
431   PetscMPIInt      flg;
432   MPI_Comm         icomm;
433   void             *ptr;
434 
435   PetscFunctionBegin;
436   ierr  = MPI_Attr_get(comm,Petsc_InnerComm_keyval,&ptr,&flg);CHKERRQ(ierr);
437   if (flg) {
438     /*  Use PetscMemcpy() because casting from pointer to integer of different size is not allowed with some compilers  */
439     ierr = PetscMemcpy(&icomm,&ptr,sizeof(MPI_Comm));CHKERRQ(ierr);
440     ierr = MPI_Attr_get(icomm,Petsc_OuterComm_keyval,&ptr,&flg);CHKERRQ(ierr);
441     if (!flg) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_CORRUPT,"Inner MPI_Comm does not have expected reference to outer comm");
442     ierr = MPI_Attr_delete(icomm,Petsc_OuterComm_keyval);CHKERRQ(ierr);
443     ierr = PetscInfo1(0,"User MPI_Comm m %ld is being freed, removing reference from inner PETSc comm to this outer comm\n",(long)comm);if (ierr) PetscFunctionReturn((PetscMPIInt)ierr);
444   } else {
445     ierr = PetscInfo1(0,"Removing reference to PETSc communicator imbedded in a user MPI_Comm m %ld\n",(long)comm);if (ierr) PetscFunctionReturn((PetscMPIInt)ierr);
446   }
447   PetscFunctionReturn(MPI_SUCCESS);
448 }
449 EXTERN_C_END
450 
451 #if defined(PETSC_USE_PETSC_MPI_EXTERNAL32)
452 #if !defined(PETSC_WORDS_BIGENDIAN)
453 EXTERN_C_BEGIN
454 extern PetscMPIInt PetscDataRep_extent_fn(MPI_Datatype,MPI_Aint*,void*);
455 extern PetscMPIInt PetscDataRep_read_conv_fn(void*, MPI_Datatype,PetscMPIInt,void*,MPI_Offset,void*);
456 extern PetscMPIInt PetscDataRep_write_conv_fn(void*, MPI_Datatype,PetscMPIInt,void*,MPI_Offset,void*);
457 EXTERN_C_END
458 #endif
459 #endif
460 
461 int  PetscGlobalArgc   = 0;
462 char **PetscGlobalArgs = 0;
463 
464 #undef __FUNCT__
465 #define __FUNCT__ "PetscGetArgs"
466 /*@C
467    PetscGetArgs - Allows you to access the raw command line arguments anywhere
468      after PetscInitialize() is called but before PetscFinalize().
469 
470    Not Collective
471 
472    Output Parameters:
473 +  argc - count of number of command line arguments
474 -  args - the command line arguments
475 
476    Level: intermediate
477 
478    Notes:
479       This is usually used to pass the command line arguments into other libraries
480    that are called internally deep in PETSc or the application.
481 
482       The first argument contains the program name as is normal for C arguments.
483 
484    Concepts: command line arguments
485 
486 .seealso: PetscFinalize(), PetscInitializeFortran(), PetscGetArguments()
487 
488 @*/
489 PetscErrorCode  PetscGetArgs(int *argc,char ***args)
490 {
491   PetscFunctionBegin;
492   if (!PetscInitializeCalled && PetscFinalizeCalled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ORDER,"You must call after PetscInitialize() but before PetscFinalize()");
493   *argc = PetscGlobalArgc;
494   *args = PetscGlobalArgs;
495   PetscFunctionReturn(0);
496 }
497 
498 #undef __FUNCT__
499 #define __FUNCT__ "PetscGetArguments"
500 /*@C
501    PetscGetArguments - Allows you to access the  command line arguments anywhere
502      after PetscInitialize() is called but before PetscFinalize().
503 
504    Not Collective
505 
506    Output Parameters:
507 .  args - the command line arguments
508 
509    Level: intermediate
510 
511    Notes:
512       This does NOT start with the program name and IS null terminated (final arg is void)
513 
514    Concepts: command line arguments
515 
516 .seealso: PetscFinalize(), PetscInitializeFortran(), PetscGetArgs(), PetscFreeArguments()
517 
518 @*/
519 PetscErrorCode  PetscGetArguments(char ***args)
520 {
521   PetscInt       i,argc = PetscGlobalArgc;
522   PetscErrorCode ierr;
523 
524   PetscFunctionBegin;
525   if (!PetscInitializeCalled && PetscFinalizeCalled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ORDER,"You must call after PetscInitialize() but before PetscFinalize()");
526   if (!argc) {*args = 0; PetscFunctionReturn(0);}
527   ierr = PetscMalloc(argc*sizeof(char*),args);CHKERRQ(ierr);
528   for (i=0; i<argc-1; i++) {
529     ierr = PetscStrallocpy(PetscGlobalArgs[i+1],&(*args)[i]);CHKERRQ(ierr);
530   }
531   (*args)[argc-1] = 0;
532   PetscFunctionReturn(0);
533 }
534 
535 #undef __FUNCT__
536 #define __FUNCT__ "PetscFreeArguments"
537 /*@C
538    PetscFreeArguments - Frees the memory obtained with PetscGetArguments()
539 
540    Not Collective
541 
542    Output Parameters:
543 .  args - the command line arguments
544 
545    Level: intermediate
546 
547    Concepts: command line arguments
548 
549 .seealso: PetscFinalize(), PetscInitializeFortran(), PetscGetArgs(), PetscGetArguments()
550 
551 @*/
552 PetscErrorCode  PetscFreeArguments(char **args)
553 {
554   PetscInt       i = 0;
555   PetscErrorCode ierr;
556 
557   PetscFunctionBegin;
558   if (!args) {PetscFunctionReturn(0);}
559   while (args[i]) {
560     ierr = PetscFree(args[i]);CHKERRQ(ierr);
561     i++;
562   }
563   ierr = PetscFree(args);CHKERRQ(ierr);
564   PetscFunctionReturn(0);
565 }
566 
567 #undef __FUNCT__
568 #define __FUNCT__ "PetscInitialize"
569 /*@C
570    PetscInitialize - Initializes the PETSc database and MPI.
571    PetscInitialize() calls MPI_Init() if that has yet to be called,
572    so this routine should always be called near the beginning of
573    your program -- usually the very first line!
574 
575    Collective on MPI_COMM_WORLD or PETSC_COMM_WORLD if it has been set
576 
577    Input Parameters:
578 +  argc - count of number of command line arguments
579 .  args - the command line arguments
580 .  file - [optional] PETSc database file, also checks ~username/.petscrc and .petscrc use PETSC_NULL to not check for
581           code specific file. Use -skip_petscrc in the code specific file to skip the .petscrc files
582 -  help - [optional] Help message to print, use PETSC_NULL for no message
583 
584    If you wish PETSc code to run ONLY on a subcommunicator of MPI_COMM_WORLD, create that
585    communicator first and assign it to PETSC_COMM_WORLD BEFORE calling PetscInitialize(). Thus if you are running a
586    four process job and two processes will run PETSc and have PetscInitialize() and PetscFinalize() and two process will not,
587    then do this. If ALL processes in the job are using PetscInitialize() and PetscFinalize() then you don't need to do this, even
588    if different subcommunicators of the job are doing different things with PETSc.
589 
590    Options Database Keys:
591 +  -start_in_debugger [noxterm,dbx,xdb,gdb,...] - Starts program in debugger
592 .  -on_error_attach_debugger [noxterm,dbx,xdb,gdb,...] - Starts debugger when error detected
593 .  -on_error_emacs <machinename> causes emacsclient to jump to error file
594 .  -on_error_abort calls abort() when error detected (no traceback)
595 .  -on_error_mpiabort calls MPI_abort() when error detected
596 .  -error_output_stderr prints error messages to stderr instead of the default stdout
597 .  -error_output_none does not print the error messages (but handles errors in the same way as if this was not called)
598 .  -debugger_nodes [node1,node2,...] - Indicates nodes to start in debugger
599 .  -debugger_pause [sleeptime] (in seconds) - Pauses debugger
600 .  -stop_for_debugger - Print message on how to attach debugger manually to
601                         process and wait (-debugger_pause) seconds for attachment
602 .  -malloc - Indicates use of PETSc error-checking malloc (on by default for debug version of libraries)
603 .  -malloc no - Indicates not to use error-checking malloc
604 .  -malloc_debug - check for memory corruption at EVERY malloc or free
605 .  -fp_trap - Stops on floating point exceptions (Note that on the
606               IBM RS6000 this slows code by at least a factor of 10.)
607 .  -no_signal_handler - Indicates not to trap error signals
608 .  -shared_tmp - indicates /tmp directory is shared by all processors
609 .  -not_shared_tmp - each processor has own /tmp
610 .  -tmp - alternative name of /tmp directory
611 .  -get_total_flops - returns total flops done by all processors
612 .  -memory_info - Print memory usage at end of run
613 -  -server <port> - start PETSc webserver (default port is 8080)
614 
615    Options Database Keys for Profiling:
616    See the <a href="../../docs/manual.pdf#nameddest=ch_profiling">profiling chapter of the users manual</a> for details.
617 +  -log_trace [filename] - Print traces of all PETSc calls
618         to the screen (useful to determine where a program
619         hangs without running in the debugger).  See PetscLogTraceBegin().
620 .  -info <optional filename> - Prints verbose information to the screen
621 -  -info_exclude <null,vec,mat,pc,ksp,snes,ts> - Excludes some of the verbose messages
622 
623    Environmental Variables:
624 +   PETSC_TMP - alternative tmp directory
625 .   PETSC_SHARED_TMP - tmp is shared by all processes
626 .   PETSC_NOT_SHARED_TMP - each process has its own private tmp
627 .   PETSC_VIEWER_SOCKET_PORT - socket number to use for socket viewer
628 -   PETSC_VIEWER_SOCKET_MACHINE - machine to use for socket viewer to connect to
629 
630 
631    Level: beginner
632 
633    Notes:
634    If for some reason you must call MPI_Init() separately, call
635    it before PetscInitialize().
636 
637    Fortran Version:
638    In Fortran this routine has the format
639 $       call PetscInitialize(file,ierr)
640 
641 +   ierr - error return code
642 -  file - [optional] PETSc database file, also checks ~username/.petscrc and .petscrc use PETSC_NULL_CHARACTER to not check for
643           code specific file. Use -skip_petscrc in the code specific file to skip the .petscrc files
644 
645    Important Fortran Note:
646    In Fortran, you MUST use PETSC_NULL_CHARACTER to indicate a
647    null character string; you CANNOT just use PETSC_NULL as
648    in the C version. See the <a href="../../docs/manual.pdf">users manual</a> for details.
649 
650    If your main program is C but you call Fortran code that also uses PETSc you need to call PetscInitializeFortran() soon after
651    calling PetscInitialize().
652 
653    Concepts: initializing PETSc
654 
655 .seealso: PetscFinalize(), PetscInitializeFortran(), PetscGetArgs(), PetscInitializeNoArguments()
656 
657 @*/
658 PetscErrorCode  PetscInitialize(int *argc,char ***args,const char file[],const char help[])
659 {
660   PetscErrorCode ierr;
661   PetscMPIInt    flag, size;
662   PetscInt       nodesize;
663   PetscBool      flg;
664   char           hostname[256];
665 
666   PetscFunctionBegin;
667   if (PetscInitializeCalled) PetscFunctionReturn(0);
668 
669   /* these must be initialized in a routine, not as a constant declaration*/
670   PETSC_STDOUT = stdout;
671   PETSC_STDERR = stderr;
672 
673   ierr = PetscOptionsCreate();CHKERRQ(ierr);
674 
675   /*
676      We initialize the program name here (before MPI_Init()) because MPICH has a bug in
677      it that it sets args[0] on all processors to be args[0] on the first processor.
678   */
679   if (argc && *argc) {
680     ierr = PetscSetProgramName(**args);CHKERRQ(ierr);
681   } else {
682     ierr = PetscSetProgramName("Unknown Name");CHKERRQ(ierr);
683   }
684 
685   ierr = MPI_Initialized(&flag);CHKERRQ(ierr);
686   if (!flag) {
687     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");
688     ierr          = MPI_Init(argc,args);CHKERRQ(ierr);
689     PetscBeganMPI = PETSC_TRUE;
690   }
691   if (argc && args) {
692     PetscGlobalArgc = *argc;
693     PetscGlobalArgs = *args;
694   }
695   PetscFinalizeCalled   = PETSC_FALSE;
696 
697   if (PETSC_COMM_WORLD == MPI_COMM_NULL) {
698     PETSC_COMM_WORLD = MPI_COMM_WORLD;
699   }
700   ierr = MPI_Errhandler_set(PETSC_COMM_WORLD,MPI_ERRORS_RETURN);CHKERRQ(ierr);
701 
702   /* Done after init due to a bug in MPICH-GM? */
703   ierr = PetscErrorPrintfInitialize();CHKERRQ(ierr);
704 
705   ierr = MPI_Comm_rank(MPI_COMM_WORLD,&PetscGlobalRank);CHKERRQ(ierr);
706   ierr = MPI_Comm_size(MPI_COMM_WORLD,&PetscGlobalSize);CHKERRQ(ierr);
707 
708 #if defined(PETSC_USE_COMPLEX)
709   /*
710      Initialized the global complex variable; this is because with
711      shared libraries the constructors for global variables
712      are not called; at least on IRIX.
713   */
714   {
715 #if defined(PETSC_CLANGUAGE_CXX)
716     PetscScalar ic(0.0,1.0);
717     PETSC_i = ic;
718 #else
719     PETSC_i = I;
720 #endif
721   }
722 
723 #if !defined(PETSC_HAVE_MPI_C_DOUBLE_COMPLEX)
724   ierr = MPI_Type_contiguous(2,MPIU_REAL,&MPIU_C_DOUBLE_COMPLEX);CHKERRQ(ierr);
725   ierr = MPI_Type_commit(&MPIU_C_DOUBLE_COMPLEX);CHKERRQ(ierr);
726   ierr = MPI_Type_contiguous(2,MPI_FLOAT,&MPIU_C_COMPLEX);CHKERRQ(ierr);
727   ierr = MPI_Type_commit(&MPIU_C_COMPLEX);CHKERRQ(ierr);
728   ierr = MPI_Op_create(PetscSum_Local,1,&MPIU_SUM);CHKERRQ(ierr);
729 #endif
730 #endif
731 
732   /*
733      Create the PETSc MPI reduction operator that sums of the first
734      half of the entries and maxes the second half.
735   */
736   ierr = MPI_Op_create(PetscMaxSum_Local,1,&PetscMaxSum_Op);CHKERRQ(ierr);
737 
738 #if defined(PETSC_USE_REAL___FLOAT128)
739   ierr = MPI_Type_contiguous(2,MPI_DOUBLE,&MPIU___FLOAT128);CHKERRQ(ierr);
740   ierr = MPI_Type_commit(&MPIU___FLOAT128);CHKERRQ(ierr);
741   ierr = MPI_Op_create(PetscSum_Local,1,&MPIU_SUM);CHKERRQ(ierr);
742   ierr = MPI_Op_create(PetscMax_Local,1,&MPIU_MAX);CHKERRQ(ierr);
743   ierr = MPI_Op_create(PetscMin_Local,1,&MPIU_MIN);CHKERRQ(ierr);
744 #endif
745 
746   ierr = MPI_Type_contiguous(2,MPIU_SCALAR,&MPIU_2SCALAR);CHKERRQ(ierr);
747   ierr = MPI_Type_commit(&MPIU_2SCALAR);CHKERRQ(ierr);
748   ierr = MPI_Op_create(PetscADMax_Local,1,&PetscADMax_Op);CHKERRQ(ierr);
749   ierr = MPI_Op_create(PetscADMin_Local,1,&PetscADMin_Op);CHKERRQ(ierr);
750 
751   ierr = MPI_Type_contiguous(2,MPIU_INT,&MPIU_2INT);CHKERRQ(ierr);
752   ierr = MPI_Type_commit(&MPIU_2INT);CHKERRQ(ierr);
753 
754   /*
755      Attributes to be set on PETSc communicators
756   */
757   ierr = MPI_Keyval_create(MPI_NULL_COPY_FN,Petsc_DelCounter,&Petsc_Counter_keyval,(void*)0);CHKERRQ(ierr);
758   ierr = MPI_Keyval_create(MPI_NULL_COPY_FN,Petsc_DelComm,&Petsc_InnerComm_keyval,(void*)0);CHKERRQ(ierr);
759   ierr = MPI_Keyval_create(MPI_NULL_COPY_FN,Petsc_DelComm,&Petsc_OuterComm_keyval,(void*)0);CHKERRQ(ierr);
760 
761   /*
762      Build the options database
763   */
764   ierr = PetscOptionsInsert(argc,args,file);CHKERRQ(ierr);
765 
766 
767   /*
768      Print main application help message
769   */
770   ierr = PetscOptionsHasName(PETSC_NULL,"-help",&flg);CHKERRQ(ierr);
771   if (help && flg) {
772     ierr = PetscPrintf(PETSC_COMM_WORLD,help);CHKERRQ(ierr);
773   }
774   ierr = PetscOptionsCheckInitial_Private();CHKERRQ(ierr);
775 
776   /* SHOULD PUT IN GUARDS: Make sure logging is initialized, even if we do not print it out */
777 #if defined(PETSC_USE_LOG)
778   ierr = PetscLogBegin_Private();CHKERRQ(ierr);
779 #endif
780 
781   /*
782      Load the dynamic libraries (on machines that support them), this registers all
783      the solvers etc. (On non-dynamic machines this initializes the PetscDraw and PetscViewer classes)
784   */
785   ierr = PetscInitialize_DynamicLibraries();CHKERRQ(ierr);
786 
787   ierr = MPI_Comm_size(PETSC_COMM_WORLD,&size);CHKERRQ(ierr);
788   ierr = PetscInfo1(0,"PETSc successfully started: number of processors = %d\n",size);CHKERRQ(ierr);
789   ierr = PetscGetHostName(hostname,256);CHKERRQ(ierr);
790   ierr = PetscInfo1(0,"Running on machine: %s\n",hostname);CHKERRQ(ierr);
791 
792   ierr = PetscOptionsCheckInitial_Components();CHKERRQ(ierr);
793   /* Check the options database for options related to the options database itself */
794   ierr = PetscOptionsSetFromOptions();CHKERRQ(ierr);
795 
796 #if defined(PETSC_USE_PETSC_MPI_EXTERNAL32)
797   /*
798       Tell MPI about our own data representation converter, this would/should be used if extern32 is not supported by the MPI
799 
800       Currently not used because it is not supported by MPICH.
801   */
802 #if !defined(PETSC_WORDS_BIGENDIAN)
803   ierr = MPI_Register_datarep((char *)"petsc",PetscDataRep_read_conv_fn,PetscDataRep_write_conv_fn,PetscDataRep_extent_fn,PETSC_NULL);CHKERRQ(ierr);
804 #endif
805 #endif
806 
807   ierr = PetscOptionsGetInt(PETSC_NULL,"-hmpi_spawn_size",&nodesize,&flg);CHKERRQ(ierr);
808   if (flg) {
809 #if defined(PETSC_HAVE_MPI_COMM_SPAWN)
810     ierr = PetscHMPISpawn((PetscMPIInt) nodesize);CHKERRQ(ierr); /* worker nodes never return from here; they go directly to PetscEnd() */
811 #else
812     SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"PETSc built without MPI 2 (MPI_Comm_spawn) support, use -hmpi_merge_size instead");
813 #endif
814   } else {
815     ierr = PetscOptionsGetInt(PETSC_NULL,"-hmpi_merge_size",&nodesize,&flg);CHKERRQ(ierr);
816     if (flg) {
817       ierr = PetscHMPIMerge((PetscMPIInt) nodesize,PETSC_NULL,PETSC_NULL);CHKERRQ(ierr);
818       if (PetscHMPIWorker) { /* if worker then never enter user code */
819         PetscInitializeCalled = PETSC_TRUE;
820         ierr = PetscEnd();
821       }
822     }
823   }
824 
825 #if defined(PETSC_HAVE_CUDA)
826   cublasInit();
827 #endif
828 
829 #if defined(PETSC_HAVE_PTHREADCLASSES)
830   if(PetscThreadInitialize)
831     ierr = (*PetscThreadInitialize)(PetscMaxThreads);CHKERRQ(ierr);
832 #endif
833 
834 #if defined(PETSC_HAVE_AMS)
835   ierr = PetscOptionsHasName(PETSC_NULL,"-ams_publish_objects",&flg);CHKERRQ(ierr);
836   if (flg) {
837     PetscAMSPublishAll = PETSC_TRUE;
838   }
839 #endif
840 
841   ierr = PetscOptionsHasName(PETSC_NULL,"-python",&flg);CHKERRQ(ierr);
842   if (flg) {
843     PetscInitializeCalled = PETSC_TRUE;
844     ierr = PetscPythonInitialize(PETSC_NULL,PETSC_NULL);CHKERRQ(ierr);
845   }
846 
847   /*
848       Once we are completedly initialized then we can set this variables
849   */
850   PetscInitializeCalled = PETSC_TRUE;
851   PetscFunctionReturn(0);
852 }
853 
854 extern PetscObject *PetscObjects;
855 extern PetscInt    PetscObjectsCounts, PetscObjectsMaxCounts;
856 
857 #undef __FUNCT__
858 #define __FUNCT__ "PetscFinalize"
859 /*@C
860    PetscFinalize - Checks for options to be called at the conclusion
861    of the program. MPI_Finalize() is called only if the user had not
862    called MPI_Init() before calling PetscInitialize().
863 
864    Collective on PETSC_COMM_WORLD
865 
866    Options Database Keys:
867 +  -options_table - Calls PetscOptionsView()
868 .  -options_left - Prints unused options that remain in the database
869 .  -objects_left  - Prints list of all objects that have not been freed
870 .  -mpidump - Calls PetscMPIDump()
871 .  -malloc_dump - Calls PetscMallocDump()
872 .  -malloc_info - Prints total memory usage
873 -  -malloc_log - Prints summary of memory usage
874 
875    Options Database Keys for Profiling:
876    See the <a href="../../docs/manual.pdf#nameddest=ch_profiling">profiling chapter of the users manual</a> for details.
877 +  -log_summary [filename] - Prints summary of flop and timing
878         information to screen. If the filename is specified the
879         summary is written to the file.  See PetscLogView().
880 .  -log_summary_python [filename] - Prints data on of flop and timing usage to a file or screen.
881         See PetscLogPrintSViewPython().
882 .  -log_all [filename] - Logs extensive profiling information
883         See PetscLogDump().
884 .  -log [filename] - Logs basic profiline information  See PetscLogDump().
885 .  -log_sync - Log the synchronization in scatters, inner products
886         and norms
887 -  -log_mpe [filename] - Creates a logfile viewable by the
888       utility Upshot/Nupshot (in MPICH distribution)
889 
890    Level: beginner
891 
892    Note:
893    See PetscInitialize() for more general runtime options.
894 
895 .seealso: PetscInitialize(), PetscOptionsView(), PetscMallocDump(), PetscMPIDump(), PetscEnd()
896 @*/
897 PetscErrorCode  PetscFinalize(void)
898 {
899   PetscErrorCode ierr;
900   PetscMPIInt    rank;
901   PetscInt       i,nopt;
902   PetscBool      flg1 = PETSC_FALSE,flg2 = PETSC_FALSE,flg3 = PETSC_FALSE,objects_left = PETSC_FALSE;
903 #if defined(PETSC_HAVE_AMS)
904   PetscBool      flg = PETSC_FALSE;
905 #endif
906 #if defined(PETSC_USE_LOG)
907   char           mname[PETSC_MAX_PATH_LEN];
908 #endif
909 
910   PetscFunctionBegin;
911 
912   if (!PetscInitializeCalled) {
913     printf("PetscInitialize() must be called before PetscFinalize()\n");
914     PetscFunctionReturn(PETSC_ERR_ARG_WRONGSTATE);
915   }
916   ierr = PetscInfo(PETSC_NULL,"PetscFinalize() called\n");
917 
918 #if defined(PETSC_HAVE_AMS)
919   ierr = PetscOptionsGetBool(PETSC_NULL,"-options_gui",&flg,PETSC_NULL);CHKERRQ(ierr);
920   if (flg) {
921     ierr = PetscOptionsAMSDestroy();CHKERRQ(ierr);
922   }
923 #endif
924 
925   ierr = PetscHMPIFinalize();CHKERRQ(ierr);
926 #if defined(PETSC_HAVE_PTHREADCLASSES)
927   if (PetscThreadFinalize) {
928     /* thread pool case */
929     ierr = (*PetscThreadFinalize)();CHKERRQ(ierr);
930   }
931   free(ThreadCoreAffinity);
932 #endif
933 
934   ierr = MPI_Comm_rank(PETSC_COMM_WORLD,&rank);CHKERRQ(ierr);
935   ierr = PetscOptionsGetBool(PETSC_NULL,"-malloc_info",&flg2,PETSC_NULL);CHKERRQ(ierr);
936   if (!flg2) {
937     flg2 = PETSC_FALSE;
938     ierr = PetscOptionsGetBool(PETSC_NULL,"-memory_info",&flg2,PETSC_NULL);CHKERRQ(ierr);
939   }
940   if (flg2) {
941     ierr = PetscMemoryShowUsage(PETSC_VIEWER_STDOUT_WORLD,"Summary of Memory Usage in PETSc\n");CHKERRQ(ierr);
942   }
943 
944 #if defined(PETSC_USE_LOG)
945   flg1 = PETSC_FALSE;
946   ierr = PetscOptionsGetBool(PETSC_NULL,"-get_total_flops",&flg1,PETSC_NULL);CHKERRQ(ierr);
947   if (flg1) {
948     PetscLogDouble flops = 0;
949     ierr = MPI_Reduce(&_TotalFlops,&flops,1,MPI_DOUBLE,MPI_SUM,0,PETSC_COMM_WORLD);CHKERRQ(ierr);
950     ierr = PetscPrintf(PETSC_COMM_WORLD,"Total flops over all processors %g\n",flops);CHKERRQ(ierr);
951   }
952 #endif
953 
954 
955 #if defined(PETSC_USE_LOG)
956 #if defined(PETSC_HAVE_MPE)
957   mname[0] = 0;
958   ierr = PetscOptionsGetString(PETSC_NULL,"-log_mpe",mname,PETSC_MAX_PATH_LEN,&flg1);CHKERRQ(ierr);
959   if (flg1){
960     if (mname[0]) {ierr = PetscLogMPEDump(mname);CHKERRQ(ierr);}
961     else          {ierr = PetscLogMPEDump(0);CHKERRQ(ierr);}
962   }
963 #endif
964   mname[0] = 0;
965   ierr = PetscOptionsGetString(PETSC_NULL,"-log_summary",mname,PETSC_MAX_PATH_LEN,&flg1);CHKERRQ(ierr);
966   if (flg1) {
967     PetscViewer viewer;
968     if (mname[0])  {
969       ierr = PetscViewerASCIIOpen(PETSC_COMM_WORLD,mname,&viewer);CHKERRQ(ierr);
970       ierr = PetscLogView(viewer);CHKERRQ(ierr);
971       ierr = PetscViewerDestroy(&viewer);CHKERRQ(ierr);
972     } else {
973       viewer = PETSC_VIEWER_STDOUT_WORLD;
974       ierr = PetscLogView(viewer);CHKERRQ(ierr);
975     }
976   }
977 
978   mname[0] = 0;
979   ierr = PetscOptionsGetString(PETSC_NULL,"-log_summary_python",mname,PETSC_MAX_PATH_LEN,&flg1);CHKERRQ(ierr);
980   if (flg1) {
981     PetscViewer viewer;
982     if (mname[0])  {
983       ierr = PetscViewerASCIIOpen(PETSC_COMM_WORLD,mname,&viewer);CHKERRQ(ierr);
984       ierr = PetscLogViewPython(viewer);CHKERRQ(ierr);
985       ierr = PetscViewerDestroy(&viewer);CHKERRQ(ierr);
986     } else {
987       viewer = PETSC_VIEWER_STDOUT_WORLD;
988       ierr = PetscLogViewPython(viewer);CHKERRQ(ierr);
989     }
990   }
991 
992   ierr = PetscOptionsGetString(PETSC_NULL,"-log_detailed",mname,PETSC_MAX_PATH_LEN,&flg1);CHKERRQ(ierr);
993   if (flg1) {
994     if (mname[0])  {ierr = PetscLogPrintDetailed(PETSC_COMM_WORLD,mname);CHKERRQ(ierr);}
995     else           {ierr = PetscLogPrintDetailed(PETSC_COMM_WORLD,0);CHKERRQ(ierr);}
996   }
997 
998   mname[0] = 0;
999   ierr = PetscOptionsGetString(PETSC_NULL,"-log_all",mname,PETSC_MAX_PATH_LEN,&flg1);CHKERRQ(ierr);
1000   ierr = PetscOptionsGetString(PETSC_NULL,"-log",mname,PETSC_MAX_PATH_LEN,&flg2);CHKERRQ(ierr);
1001   if (flg1 || flg2){
1002     if (mname[0]) PetscLogDump(mname);
1003     else          PetscLogDump(0);
1004   }
1005 #endif
1006 
1007 #if defined(PETSC_USE_DEBUG) && !defined(PETSC_USE_PTHREAD)
1008   if (PetscStackActive) {
1009     ierr = PetscStackDestroy();CHKERRQ(ierr);
1010   }
1011 #endif
1012 
1013   flg1 = PETSC_FALSE;
1014   ierr = PetscOptionsGetBool(PETSC_NULL,"-no_signal_handler",&flg1,PETSC_NULL);CHKERRQ(ierr);
1015   if (!flg1) { ierr = PetscPopSignalHandler();CHKERRQ(ierr);}
1016   flg1 = PETSC_FALSE;
1017   ierr = PetscOptionsGetBool(PETSC_NULL,"-mpidump",&flg1,PETSC_NULL);CHKERRQ(ierr);
1018   if (flg1) {
1019     ierr = PetscMPIDump(stdout);CHKERRQ(ierr);
1020   }
1021   flg1 = PETSC_FALSE;
1022   flg2 = PETSC_FALSE;
1023   /* preemptive call to avoid listing this option in options table as unused */
1024   ierr = PetscOptionsHasName(PETSC_NULL,"-malloc_dump",&flg1);CHKERRQ(ierr);
1025   ierr = PetscOptionsGetBool(PETSC_NULL,"-options_table",&flg2,PETSC_NULL);CHKERRQ(ierr);
1026 
1027   if (flg2) {
1028     ierr = PetscOptionsView(PETSC_VIEWER_STDOUT_WORLD);CHKERRQ(ierr);
1029   }
1030 
1031   /* to prevent PETSc -options_left from warning */
1032   ierr = PetscOptionsHasName(PETSC_NULL,"-nox",&flg1);CHKERRQ(ierr);
1033   ierr = PetscOptionsHasName(PETSC_NULL,"-nox_warning",&flg1);CHKERRQ(ierr);
1034   ierr = PetscOptionsGetBool(PETSC_NULL,"-objects_left",&objects_left,PETSC_NULL);CHKERRQ(ierr);
1035 
1036   if (!PetscHMPIWorker) { /* worker processes skip this because they do not usually process options */
1037     flg3 = PETSC_FALSE; /* default value is required */
1038     ierr = PetscOptionsGetBool(PETSC_NULL,"-options_left",&flg3,&flg1);CHKERRQ(ierr);
1039     ierr = PetscOptionsAllUsed(&nopt);CHKERRQ(ierr);
1040     if (flg3) {
1041       if (!flg2) { /* have not yet printed the options */
1042 	ierr = PetscOptionsView(PETSC_VIEWER_STDOUT_WORLD);CHKERRQ(ierr);
1043       }
1044       if (!nopt) {
1045 	ierr = PetscPrintf(PETSC_COMM_WORLD,"There are no unused options.\n");CHKERRQ(ierr);
1046       } else if (nopt == 1) {
1047 	ierr = PetscPrintf(PETSC_COMM_WORLD,"There is one unused database option. It is:\n");CHKERRQ(ierr);
1048       } else {
1049 	ierr = PetscPrintf(PETSC_COMM_WORLD,"There are %D unused database options. They are:\n",nopt);CHKERRQ(ierr);
1050       }
1051     }
1052 #if defined(PETSC_USE_DEBUG)
1053     if (nopt && !flg3 && !flg1) {
1054       ierr = PetscPrintf(PETSC_COMM_WORLD,"WARNING! There are options you set that were not used!\n");CHKERRQ(ierr);
1055       ierr = PetscPrintf(PETSC_COMM_WORLD,"WARNING! could be spelling mistake, etc!\n");CHKERRQ(ierr);
1056       ierr = PetscOptionsLeft();CHKERRQ(ierr);
1057     } else if (nopt && flg3) {
1058 #else
1059     if (nopt && flg3) {
1060 #endif
1061       ierr = PetscOptionsLeft();CHKERRQ(ierr);
1062     }
1063   }
1064 
1065   /*
1066      Free all objects registered with PetscObjectRegisterDestroy() such as PETSC_VIEWER_XXX_().
1067   */
1068   ierr = PetscObjectRegisterDestroyAll();CHKERRQ(ierr);
1069 
1070   /*
1071        List all objects the user may have forgot to free
1072   */
1073   if (objects_left && PetscObjectsCounts) {
1074     ierr = PetscPrintf(PETSC_COMM_WORLD,"The following objects %D were never freed\n",PetscObjectsCounts);
1075   }
1076   for (i=0; i<PetscObjectsMaxCounts; i++) {
1077     if (PetscObjects[i]) {
1078       if (objects_left) {
1079         ierr = PetscPrintf(PETSC_COMM_WORLD,"  %s %s %s\n",PetscObjects[i]->class_name,PetscObjects[i]->type_name,PetscObjects[i]->name);CHKERRQ(ierr);
1080       }
1081     }
1082   }
1083   /* cannot actually destroy the left over objects, but destroy the list */
1084   PetscObjectsCounts    = 0;
1085   PetscObjectsMaxCounts = 0;
1086   ierr = PetscFree(PetscObjects);CHKERRQ(ierr);
1087 
1088 
1089 #if defined(PETSC_USE_LOG)
1090   ierr = PetscLogDestroy();CHKERRQ(ierr);
1091 #endif
1092 
1093   /*
1094        Free all the registered create functions, such as KSPList, VecList, SNESList, etc
1095   */
1096   ierr = PetscFListDestroyAll();CHKERRQ(ierr);
1097 
1098   /*
1099      Destroy any packages that registered a finalize
1100   */
1101   ierr = PetscRegisterFinalizeAll();CHKERRQ(ierr);
1102 
1103   /*
1104      Destroy all the function registration lists created
1105   */
1106   ierr = PetscFinalize_DynamicLibraries();CHKERRQ(ierr);
1107 
1108   if (petsc_history) {
1109     ierr = PetscCloseHistoryFile(&petsc_history);CHKERRQ(ierr);
1110     petsc_history = 0;
1111   }
1112 
1113   ierr = PetscInfoAllow(PETSC_FALSE,PETSC_NULL);CHKERRQ(ierr);
1114 
1115   {
1116     char fname[PETSC_MAX_PATH_LEN];
1117     FILE *fd;
1118     int  err;
1119 
1120     fname[0] = 0;
1121     ierr = PetscOptionsGetString(PETSC_NULL,"-malloc_dump",fname,250,&flg1);CHKERRQ(ierr);
1122     if (flg1 && fname[0]) {
1123       char sname[PETSC_MAX_PATH_LEN];
1124 
1125       sprintf(sname,"%s_%d",fname,rank);
1126       fd   = fopen(sname,"w"); if (!fd) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_FILE_OPEN,"Cannot open log file: %s",sname);
1127       ierr = PetscMallocDump(fd);CHKERRQ(ierr);
1128       err = fclose(fd);
1129       if (err) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SYS,"fclose() failed on file");
1130     } else if (flg1) {
1131       MPI_Comm local_comm;
1132 
1133       ierr = MPI_Comm_dup(MPI_COMM_WORLD,&local_comm);CHKERRQ(ierr);
1134       ierr = PetscSequentialPhaseBegin_Private(local_comm,1);CHKERRQ(ierr);
1135         ierr = PetscMallocDump(stdout);CHKERRQ(ierr);
1136       ierr = PetscSequentialPhaseEnd_Private(local_comm,1);CHKERRQ(ierr);
1137       ierr = MPI_Comm_free(&local_comm);CHKERRQ(ierr);
1138     }
1139   }
1140   {
1141     char fname[PETSC_MAX_PATH_LEN];
1142     FILE *fd;
1143 
1144     fname[0] = 0;
1145     ierr = PetscOptionsGetString(PETSC_NULL,"-malloc_log",fname,250,&flg1);CHKERRQ(ierr);
1146     if (flg1 && fname[0]) {
1147       char sname[PETSC_MAX_PATH_LEN];
1148       int  err;
1149 
1150       sprintf(sname,"%s_%d",fname,rank);
1151       fd   = fopen(sname,"w"); if (!fd) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_FILE_OPEN,"Cannot open log file: %s",sname);
1152       ierr = PetscMallocDumpLog(fd);CHKERRQ(ierr);
1153       err = fclose(fd);
1154       if (err) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SYS,"fclose() failed on file");
1155     } else if (flg1) {
1156       ierr = PetscMallocDumpLog(stdout);CHKERRQ(ierr);
1157     }
1158   }
1159   /* Can be destroyed only after all the options are used */
1160   ierr = PetscOptionsDestroy();CHKERRQ(ierr);
1161 
1162   PetscGlobalArgc = 0;
1163   PetscGlobalArgs = 0;
1164 
1165 #if defined(PETSC_USE_REAL___FLOAT128)
1166   ierr = MPI_Type_free(&MPIU___FLOAT128);CHKERRQ(ierr);
1167   ierr = MPI_Op_free(&MPIU_SUM);CHKERRQ(ierr);
1168   ierr = MPI_Op_free(&MPIU_MAX);CHKERRQ(ierr);
1169   ierr = MPI_Op_free(&MPIU_MIN);CHKERRQ(ierr);
1170 #endif
1171 
1172 #if defined(PETSC_USE_COMPLEX)
1173 #if !defined(PETSC_HAVE_MPI_C_DOUBLE_COMPLEX)
1174   ierr = MPI_Op_free(&MPIU_SUM);CHKERRQ(ierr);
1175   ierr = MPI_Type_free(&MPIU_C_DOUBLE_COMPLEX);CHKERRQ(ierr);
1176   ierr = MPI_Type_free(&MPIU_C_COMPLEX);CHKERRQ(ierr);
1177 #endif
1178 #endif
1179   ierr = MPI_Type_free(&MPIU_2SCALAR);CHKERRQ(ierr);
1180   ierr = MPI_Type_free(&MPIU_2INT);CHKERRQ(ierr);
1181   ierr = MPI_Op_free(&PetscMaxSum_Op);CHKERRQ(ierr);
1182   ierr = MPI_Op_free(&PetscADMax_Op);CHKERRQ(ierr);
1183   ierr = MPI_Op_free(&PetscADMin_Op);CHKERRQ(ierr);
1184 
1185   /*
1186      Destroy any known inner MPI_Comm's and attributes pointing to them
1187      Note this will not destroy any new communicators the user has created.
1188 
1189      If all PETSc objects were not destroyed those left over objects will have hanging references to
1190      the MPI_Comms that were freed; but that is ok because those PETSc objects will never be used again
1191  */
1192   {
1193     PetscCommCounter *counter;
1194     PetscMPIInt      flg;
1195     MPI_Comm         icomm;
1196     void             *ptr;
1197     ierr  = MPI_Attr_get(PETSC_COMM_SELF,Petsc_InnerComm_keyval,&ptr,&flg);CHKERRQ(ierr);
1198     if (flg) {
1199       /*  Use PetscMemcpy() because casting from pointer to integer of different size is not allowed with some compilers  */
1200       ierr = PetscMemcpy(&icomm,&ptr,sizeof(MPI_Comm));CHKERRQ(ierr);
1201       ierr = MPI_Attr_get(icomm,Petsc_Counter_keyval,&counter,&flg);CHKERRQ(ierr);
1202       if (!flg) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_CORRUPT,"Inner MPI_Comm does not have expected tag/name counter, problem with corrupted memory");
1203 
1204       ierr = MPI_Attr_delete(PETSC_COMM_SELF,Petsc_InnerComm_keyval);CHKERRQ(ierr);
1205       ierr = MPI_Attr_delete(icomm,Petsc_Counter_keyval);CHKERRQ(ierr);
1206       ierr = MPI_Comm_free(&icomm);CHKERRQ(ierr);
1207     }
1208     ierr  = MPI_Attr_get(PETSC_COMM_WORLD,Petsc_InnerComm_keyval,&ptr,&flg);CHKERRQ(ierr);
1209     if (flg) {
1210       /*  Use PetscMemcpy() because casting from pointer to integer of different size is not allowed with some compilers  */
1211       ierr = PetscMemcpy(&icomm,&ptr,sizeof(MPI_Comm));CHKERRQ(ierr);
1212       ierr = MPI_Attr_get(icomm,Petsc_Counter_keyval,&counter,&flg);CHKERRQ(ierr);
1213       if (!flg) SETERRQ(PETSC_COMM_WORLD,PETSC_ERR_ARG_CORRUPT,"Inner MPI_Comm does not have expected tag/name counter, problem with corrupted memory");
1214 
1215       ierr = MPI_Attr_delete(PETSC_COMM_WORLD,Petsc_InnerComm_keyval);CHKERRQ(ierr);
1216       ierr = MPI_Attr_delete(icomm,Petsc_Counter_keyval);CHKERRQ(ierr);
1217       ierr = MPI_Comm_free(&icomm);CHKERRQ(ierr);
1218     }
1219   }
1220 
1221   ierr = MPI_Keyval_free(&Petsc_Counter_keyval);CHKERRQ(ierr);
1222   ierr = MPI_Keyval_free(&Petsc_InnerComm_keyval);CHKERRQ(ierr);
1223   ierr = MPI_Keyval_free(&Petsc_OuterComm_keyval);CHKERRQ(ierr);
1224 
1225   ierr = PetscInfo(0,"PETSc successfully ended!\n");CHKERRQ(ierr);
1226   if (PetscBeganMPI) {
1227 #if defined(PETSC_HAVE_MPI_FINALIZED)
1228     PetscMPIInt flag;
1229     ierr = MPI_Finalized(&flag);CHKERRQ(ierr);
1230     if (flag) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_LIB,"MPI_Finalize() has already been called, even though MPI_Init() was called by PetscInitialize()");
1231 #endif
1232     ierr = MPI_Finalize();CHKERRQ(ierr);
1233   }
1234 
1235   if (PETSC_ZOPEFD){
1236     if (PETSC_ZOPEFD != PETSC_STDOUT) fprintf(PETSC_ZOPEFD, "<<<end>>>");
1237     else fprintf(PETSC_STDOUT, "<<<end>>>");
1238   }
1239 
1240 #if defined(PETSC_HAVE_CUDA)
1241   cublasShutdown();
1242 #endif
1243 /*
1244 
1245      Note: In certain cases PETSC_COMM_WORLD is never MPI_Comm_free()ed because
1246    the communicator has some outstanding requests on it. Specifically if the
1247    flag PETSC_HAVE_BROKEN_REQUEST_FREE is set (for IBM MPI implementation). See
1248    src/vec/utils/vpscat.c. Due to this the memory allocated in PetscCommDuplicate()
1249    is never freed as it should be. Thus one may obtain messages of the form
1250    [ 1] 8 bytes PetscCommDuplicate() line 645 in src/sys/mpiu.c indicating the
1251    memory was not freed.
1252 
1253 */
1254   ierr = PetscMallocClear();CHKERRQ(ierr);
1255   PetscInitializeCalled = PETSC_FALSE;
1256   PetscFinalizeCalled   = PETSC_TRUE;
1257   PetscFunctionReturn(ierr);
1258 }
1259 
1260