xref: /petsc/src/sys/objects/pinit.c (revision d89683f4717475c39c51567414f4d9e0fb47aeb9)
1 #define PETSC_DLL
2 /*
3    This file defines the initialization of PETSc, including PetscInitialize()
4 */
5 
6 #include "petsc.h"        /*I  "petsc.h"   I*/
7 #include "petscsys.h"
8 #include "zope.h"
9 
10 #if defined(PETSC_USE_LOG)
11 EXTERN PetscErrorCode PetscLogBegin_Private(void);
12 #endif
13 
14 /* -----------------------------------------------------------------------------------------*/
15 
16 extern FILE *petsc_history;
17 
18 EXTERN PetscErrorCode PetscInitialize_DynamicLibraries(void);
19 EXTERN PetscErrorCode PetscFinalize_DynamicLibraries(void);
20 EXTERN PetscErrorCode PetscFListDestroyAll(void);
21 EXTERN PetscErrorCode PetscSequentialPhaseBegin_Private(MPI_Comm,int);
22 EXTERN PetscErrorCode PetscSequentialPhaseEnd_Private(MPI_Comm,int);
23 EXTERN PetscErrorCode PetscLogCloseHistoryFile(FILE **);
24 EXTERN PetscErrorCode PetscOptionsHelpDestroyList(void);
25 
26 /* this is used by the _, __, and ___ macros (see include/petscerror.h) */
27 PetscErrorCode __gierr = 0;
28 
29 /* user may set this BEFORE calling PetscInitialize() */
30 MPI_Comm PETSC_COMM_WORLD = 0;
31 
32 /*
33      Declare and set all the string names of the PETSc enums
34 */
35 const char *PetscTruths[]    = {"FALSE","TRUE","PetscTruth","PETSC_",0};
36 const char *PetscDataTypes[] = {"INT", "DOUBLE", "COMPLEX",
37                                 "LONG","SHORT",  "FLOAT",
38                                 "CHAR","LOGICAL","ENUM","TRUTH","LONGDOUBLE","PetscDataType","PETSC_",0};
39 
40 PetscCookie PETSC_LARGEST_COOKIE = PETSC_SMALLEST_COOKIE;
41 PetscCookie PETSC_OBJECT_COOKIE = 0;
42 
43 PetscTruth PetscPreLoadingUsed = PETSC_FALSE;
44 PetscTruth PetscPreLoadingOn   = PETSC_FALSE;
45 
46 PetscErrorCode PETSC_DLLEXPORT PetscCookieRegister(PetscCookie *cookie)
47 {
48   *cookie = ++PETSC_LARGEST_COOKIE;
49   return 0;
50 }
51 
52 /*
53        Checks the options database for initializations related to the
54     PETSc components
55 */
56 #undef __FUNCT__
57 #define __FUNCT__ "PetscOptionsCheckInitial_Components"
58 PetscErrorCode PETSC_DLLEXPORT PetscOptionsCheckInitial_Components(void)
59 {
60   PetscTruth flg1;
61   PetscErrorCode ierr;
62 
63   PetscFunctionBegin;
64   ierr = PetscOptionsHasName(PETSC_NULL,"-help",&flg1);CHKERRQ(ierr);
65   if (flg1) {
66 #if defined (PETSC_USE_LOG)
67     MPI_Comm   comm = PETSC_COMM_WORLD;
68     ierr = (*PetscHelpPrintf)(comm,"------Additional PETSc component options--------\n");CHKERRQ(ierr);
69     ierr = (*PetscHelpPrintf)(comm," -log_summary_exclude: <vec,mat,pc.ksp,snes>\n");CHKERRQ(ierr);
70     ierr = (*PetscHelpPrintf)(comm," -info_exclude: <null,vec,mat,pc,ksp,snes,ts>\n");CHKERRQ(ierr);
71     ierr = (*PetscHelpPrintf)(comm,"-----------------------------------------------\n");CHKERRQ(ierr);
72 #endif
73   }
74   PetscFunctionReturn(0);
75 }
76 
77 #undef __FUNCT__
78 #define __FUNCT__ "PetscInitializeNoArguments"
79 /*@C
80       PetscInitializeNoArguments - Calls PetscInitialize() from C/C++ without
81         the command line arguments.
82 
83    Collective
84 
85    Level: advanced
86 
87 .seealso: PetscInitialize(), PetscInitializeFortran()
88 @*/
89 PetscErrorCode PETSC_DLLEXPORT PetscInitializeNoArguments(void)
90 {
91   PetscErrorCode ierr;
92   int            argc = 0;
93   char           **args = 0;
94 
95   PetscFunctionBegin;
96   ierr = PetscInitialize(&argc,&args,PETSC_NULL,PETSC_NULL);
97   PetscFunctionReturn(ierr);
98 }
99 
100 #undef __FUNCT__
101 #define __FUNCT__ "PetscInitialized"
102 /*@
103       PetscInitialized - Determine whether PETSc is initialized.
104 
105 7   Level: beginner
106 
107 .seealso: PetscInitialize(), PetscInitializeNoArguments(), PetscInitializeFortran()
108 @*/
109 PetscErrorCode PETSC_DLLEXPORT PetscInitialized(PetscTruth *isInitialized)
110 {
111   PetscFunctionBegin;
112   PetscValidPointer(isInitialized, 1);
113   *isInitialized = PetscInitializeCalled;
114   PetscFunctionReturn(0);
115 }
116 
117 #undef __FUNCT__
118 #define __FUNCT__ "PetscFinalized"
119 /*@
120       PetscFinalized - Determine whether PetscFinalize() has been called yet
121 
122    Level: developer
123 
124 .seealso: PetscInitialize(), PetscInitializeNoArguments(), PetscInitializeFortran()
125 @*/
126 PetscErrorCode PETSC_DLLEXPORT PetscFinalized(PetscTruth *isFinalized)
127 {
128   PetscFunctionBegin;
129   PetscValidPointer(isFinalized, 1);
130   *isFinalized = PetscFinalizeCalled;
131   PetscFunctionReturn(0);
132 }
133 
134 EXTERN PetscErrorCode        PetscOptionsCheckInitial_Private(void);
135 extern PetscTruth PetscBeganMPI;
136 
137 /*
138        This function is the MPI reduction operation used to compute the sum of the
139    first half of the datatype and the max of the second half.
140 */
141 MPI_Op PetscMaxSum_Op = 0;
142 
143 EXTERN_C_BEGIN
144 #undef __FUNCT__
145 #define __FUNCT__ "PetscMaxSum_Local"
146 void PETSC_DLLEXPORT PetscMaxSum_Local(void *in,void *out,int *cnt,MPI_Datatype *datatype)
147 {
148   PetscInt *xin = (PetscInt*)in,*xout = (PetscInt*)out,i,count = *cnt;
149 
150   PetscFunctionBegin;
151   if (*datatype != MPIU_2INT) {
152     (*PetscErrorPrintf)("Can only handle MPIU_2INT data types");
153     MPI_Abort(MPI_COMM_WORLD,1);
154   }
155 
156   for (i=0; i<count; i++) {
157     xout[2*i]    = PetscMax(xout[2*i],xin[2*i]);
158     xout[2*i+1] += xin[2*i+1];
159   }
160   PetscStackPop;
161   return;
162 }
163 EXTERN_C_END
164 
165 /*
166     Returns the max of the first entry owned by this processor and the
167 sum of the second entry.
168 */
169 #undef __FUNCT__
170 #define __FUNCT__ "PetscMaxSum"
171 PetscErrorCode PETSC_DLLEXPORT PetscMaxSum(MPI_Comm comm,const PetscInt nprocs[],PetscInt *max,PetscInt *sum)
172 {
173   PetscMPIInt    size,rank;
174   PetscInt       *work;
175   PetscErrorCode ierr;
176 
177   PetscFunctionBegin;
178   ierr   = MPI_Comm_size(comm,&size);CHKERRQ(ierr);
179   ierr   = MPI_Comm_rank(comm,&rank);CHKERRQ(ierr);
180   ierr   = PetscMalloc(2*size*sizeof(PetscInt),&work);CHKERRQ(ierr);
181   ierr   = MPI_Allreduce((void*)nprocs,work,size,MPIU_2INT,PetscMaxSum_Op,comm);CHKERRQ(ierr);
182   *max   = work[2*rank];
183   *sum   = work[2*rank+1];
184   ierr   = PetscFree(work);CHKERRQ(ierr);
185   PetscFunctionReturn(0);
186 }
187 
188 /* ----------------------------------------------------------------------------*/
189 MPI_Op PETSC_DLLEXPORT PetscADMax_Op = 0;
190 
191 EXTERN_C_BEGIN
192 #undef __FUNCT__
193 #define __FUNCT__ "PetscADMax_Local"
194 void PETSC_DLLEXPORT PetscADMax_Local(void *in,void *out,PetscMPIInt *cnt,MPI_Datatype *datatype)
195 {
196   PetscScalar *xin = (PetscScalar *)in,*xout = (PetscScalar*)out;
197   PetscInt    i,count = *cnt;
198 
199   PetscFunctionBegin;
200   if (*datatype != MPIU_2SCALAR) {
201     (*PetscErrorPrintf)("Can only handle MPIU_2SCALAR data (i.e. double or complex) types");
202     MPI_Abort(MPI_COMM_WORLD,1);
203   }
204 
205   for (i=0; i<count; i++) {
206     if (PetscRealPart(xout[2*i]) < PetscRealPart(xin[2*i])) {
207       xout[2*i]   = xin[2*i];
208       xout[2*i+1] = xin[2*i+1];
209     }
210   }
211 
212   PetscStackPop;
213   return;
214 }
215 EXTERN_C_END
216 
217 MPI_Op PETSC_DLLEXPORT PetscADMin_Op = 0;
218 
219 EXTERN_C_BEGIN
220 #undef __FUNCT__
221 #define __FUNCT__ "PetscADMin_Local"
222 void PETSC_DLLEXPORT PetscADMin_Local(void *in,void *out,PetscMPIInt *cnt,MPI_Datatype *datatype)
223 {
224   PetscScalar *xin = (PetscScalar *)in,*xout = (PetscScalar*)out;
225   PetscInt    i,count = *cnt;
226 
227   PetscFunctionBegin;
228   if (*datatype != MPIU_2SCALAR) {
229     (*PetscErrorPrintf)("Can only handle MPIU_2SCALAR data (i.e. double or complex) types");
230     MPI_Abort(MPI_COMM_WORLD,1);
231   }
232 
233   for (i=0; i<count; i++) {
234     if (PetscRealPart(xout[2*i]) > PetscRealPart(xin[2*i])) {
235       xout[2*i]   = xin[2*i];
236       xout[2*i+1] = xin[2*i+1];
237     }
238   }
239 
240   PetscStackPop;
241   return;
242 }
243 EXTERN_C_END
244 /* ---------------------------------------------------------------------------------------*/
245 
246 #if defined(PETSC_USE_COMPLEX)
247 MPI_Op PetscSum_Op = 0;
248 
249 EXTERN_C_BEGIN
250 #undef __FUNCT__
251 #define __FUNCT__ "PetscSum_Local"
252 void PETSC_DLLEXPORT PetscSum_Local(void *in,void *out,PetscMPIInt *cnt,MPI_Datatype *datatype)
253 {
254   PetscScalar *xin = (PetscScalar *)in,*xout = (PetscScalar*)out;
255   PetscInt         i,count = *cnt;
256 
257   PetscFunctionBegin;
258   if (*datatype != MPIU_SCALAR) {
259     (*PetscErrorPrintf)("Can only handle MPIU_SCALAR data (i.e. double or complex) types");
260     MPI_Abort(MPI_COMM_WORLD,1);
261   }
262 
263   for (i=0; i<count; i++) {
264     xout[i] += xin[i];
265   }
266 
267   PetscStackPop;
268   return;
269 }
270 EXTERN_C_END
271 #endif
272 
273 static int  PetscGlobalArgc   = 0;
274 static char **PetscGlobalArgs = 0;
275 
276 #undef __FUNCT__
277 #define __FUNCT__ "PetscGetArgs"
278 /*@C
279    PetscGetArgs - Allows you to access the raw command line arguments anywhere
280      after PetscInitialize() is called but before PetscFinalize().
281 
282    Not Collective
283 
284    Output Parameters:
285 +  argc - count of number of command line arguments
286 -  args - the command line arguments
287 
288    Level: intermediate
289 
290    Notes:
291       This is usually used to pass the command line arguments into other libraries
292    that are called internally deep in PETSc or the application.
293 
294    Concepts: command line arguments
295 
296 .seealso: PetscFinalize(), PetscInitializeFortran(), PetscGetArguments()
297 
298 @*/
299 PetscErrorCode PETSC_DLLEXPORT PetscGetArgs(int *argc,char ***args)
300 {
301   PetscFunctionBegin;
302   if (!PetscGlobalArgs) {
303     SETERRQ(PETSC_ERR_ORDER,"You must call after PetscInitialize() but before PetscFinalize()");
304   }
305   *argc = PetscGlobalArgc;
306   *args = PetscGlobalArgs;
307   PetscFunctionReturn(0);
308 }
309 
310 #undef __FUNCT__
311 #define __FUNCT__ "PetscGetArguments"
312 /*@C
313    PetscGetArguments - Allows you to access the  command line arguments anywhere
314      after PetscInitialize() is called but before PetscFinalize().
315 
316    Not Collective
317 
318    Output Parameters:
319 .  args - the command line arguments
320 
321    Level: intermediate
322 
323    Notes:
324       This does NOT start with the program name and IS null terminated (final arg is void)
325 
326    Concepts: command line arguments
327 
328 .seealso: PetscFinalize(), PetscInitializeFortran(), PetscGetArgs(), PetscFreeArguments()
329 
330 @*/
331 PetscErrorCode PETSC_DLLEXPORT PetscGetArguments(char ***args)
332 {
333   PetscInt       i,argc = PetscGlobalArgc;
334   PetscErrorCode ierr;
335 
336   PetscFunctionBegin;
337   if (!PetscGlobalArgs) {
338     SETERRQ(PETSC_ERR_ORDER,"You must call after PetscInitialize() but before PetscFinalize()");
339   }
340   ierr = PetscMalloc(argc*sizeof(char*),args);CHKERRQ(ierr);
341   for (i=0; i<argc-1; i++) {
342     ierr = PetscStrallocpy(PetscGlobalArgs[i+1],&(*args)[i]);CHKERRQ(ierr);
343   }
344   (*args)[argc-1] = 0;
345   PetscFunctionReturn(0);
346 }
347 
348 #undef __FUNCT__
349 #define __FUNCT__ "PetscFreeArguments"
350 /*@C
351    PetscFreeArguments - Frees the memory obtained with PetscGetArguments()
352 
353    Not Collective
354 
355    Output Parameters:
356 .  args - the command line arguments
357 
358    Level: intermediate
359 
360    Concepts: command line arguments
361 
362 .seealso: PetscFinalize(), PetscInitializeFortran(), PetscGetArgs(), PetscGetArguments()
363 
364 @*/
365 PetscErrorCode PETSC_DLLEXPORT PetscFreeArguments(char **args)
366 {
367   PetscInt       i = 0;
368   PetscErrorCode ierr;
369 
370   PetscFunctionBegin;
371   while (args[i]) {
372     ierr = PetscFree(args[i]);CHKERRQ(ierr);
373     i++;
374   }
375   ierr = PetscFree(args);CHKERRQ(ierr);
376   PetscFunctionReturn(0);
377 }
378 
379 #undef __FUNCT__
380 #define __FUNCT__ "PetscInitialize"
381 /*@C
382    PetscInitialize - Initializes the PETSc database and MPI.
383    PetscInitialize() calls MPI_Init() if that has yet to be called,
384    so this routine should always be called near the beginning of
385    your program -- usually the very first line!
386 
387    Collective on MPI_COMM_WORLD or PETSC_COMM_WORLD if it has been set
388 
389    Input Parameters:
390 +  argc - count of number of command line arguments
391 .  args - the command line arguments
392 .  file - [optional] PETSc database file, also checks ~username/.petscrc and .petscrc use PETSC_NULL to not check for
393           code specific file. Use -skip_petscrc in the code specific file to skip the .petscrc files
394 -  help - [optional] Help message to print, use PETSC_NULL for no message
395 
396    If you wish PETSc to run on a subcommunicator of MPI_COMM_WORLD, create that
397    communicator first and assign it to PETSC_COMM_WORLD BEFORE calling PetscInitialize()
398 
399    Options Database Keys:
400 +  -start_in_debugger [noxterm,dbx,xdb,gdb,...] - Starts program in debugger
401 .  -on_error_attach_debugger [noxterm,dbx,xdb,gdb,...] - Starts debugger when error detected
402 .  -on_error_emacs <machinename> causes emacsclient to jump to error file
403 .  -on_error_abort calls abort() when error detected (no traceback)
404 .  -on_error_mpiabort calls MPI_abort() when error detected
405 .  -error_output_stderr prints error messages to stderr instead of the default stdout
406 .  -error_output_none does not print the error messages (but handles errors in the same way as if this was not called)
407 .  -debugger_nodes [node1,node2,...] - Indicates nodes to start in debugger
408 .  -debugger_pause [sleeptime] (in seconds) - Pauses debugger
409 .  -stop_for_debugger - Print message on how to attach debugger manually to
410                         process and wait (-debugger_pause) seconds for attachment
411 .  -malloc - Indicates use of PETSc error-checking malloc (on by default for debug version of libraries)
412 .  -malloc no - Indicates not to use error-checking malloc
413 .  -malloc_debug - check for memory corruption at EVERY malloc or free
414 .  -fp_trap - Stops on floating point exceptions (Note that on the
415               IBM RS6000 this slows code by at least a factor of 10.)
416 .  -no_signal_handler - Indicates not to trap error signals
417 .  -shared_tmp - indicates /tmp directory is shared by all processors
418 .  -not_shared_tmp - each processor has own /tmp
419 .  -tmp - alternative name of /tmp directory
420 .  -get_total_flops - returns total flops done by all processors
421 -  -memory_info - Print memory usage at end of run
422 
423    Options Database Keys for Profiling:
424    See the Profiling chapter of the users manual for details.
425 +  -log_trace [filename] - Print traces of all PETSc calls
426         to the screen (useful to determine where a program
427         hangs without running in the debugger).  See PetscLogTraceBegin().
428 .  -info <optional filename> - Prints verbose information to the screen
429 -  -info_exclude <null,vec,mat,pc,ksp,snes,ts> - Excludes some of the verbose messages
430 
431    Environmental Variables:
432 +   PETSC_TMP - alternative tmp directory
433 .   PETSC_SHARED_TMP - tmp is shared by all processes
434 .   PETSC_NOT_SHARED_TMP - each process has its own private tmp
435 .   PETSC_VIEWER_SOCKET_PORT - socket number to use for socket viewer
436 -   PETSC_VIEWER_SOCKET_MACHINE - machine to use for socket viewer to connect to
437 
438 
439    Level: beginner
440 
441    Notes:
442    If for some reason you must call MPI_Init() separately, call
443    it before PetscInitialize().
444 
445    Fortran Version:
446    In Fortran this routine has the format
447 $       call PetscInitialize(file,ierr)
448 
449 +   ierr - error return code
450 -  file - [optional] PETSc database file, also checks ~username/.petscrc and .petscrc use PETSC_CHARACTER_NULL to not check for
451           code specific file. Use -skip_petscrc in the code specific file to skip the .petscrc files
452 
453    Important Fortran Note:
454    In Fortran, you MUST use PETSC_NULL_CHARACTER to indicate a
455    null character string; you CANNOT just use PETSC_NULL as
456    in the C version.  See the users manual for details.
457 
458 
459    Concepts: initializing PETSc
460 
461 .seealso: PetscFinalize(), PetscInitializeFortran(), PetscGetArgs()
462 
463 @*/
464 PetscErrorCode PETSC_DLLEXPORT PetscInitialize(int *argc,char ***args,const char file[],const char help[])
465 {
466   PetscErrorCode ierr;
467   PetscMPIInt    flag, size,nodesize;
468   PetscTruth     flg;
469   char           hostname[256];
470 
471   PetscFunctionBegin;
472   if (PetscInitializeCalled) PetscFunctionReturn(0);
473 
474   /* these must be initialized in a routine, not as a constant declaration*/
475   PETSC_STDOUT = stdout;
476   PETSC_STDERR = stderr;
477 
478   ierr = PetscOptionsCreate();CHKERRQ(ierr);
479 
480   /*
481      We initialize the program name here (before MPI_Init()) because MPICH has a bug in
482      it that it sets args[0] on all processors to be args[0] on the first processor.
483   */
484   if (argc && *argc) {
485     ierr = PetscSetProgramName(**args);CHKERRQ(ierr);
486   } else {
487     ierr = PetscSetProgramName("Unknown Name");CHKERRQ(ierr);
488   }
489 
490   ierr = MPI_Initialized(&flag);CHKERRQ(ierr);
491   if (!flag) {
492     if (PETSC_COMM_WORLD) SETERRQ(PETSC_ERR_SUP,"You cannot set PETSC_COMM_WORLD if you have not initialized MPI first");
493     ierr          = MPI_Init(argc,args);CHKERRQ(ierr);
494     PetscBeganMPI = PETSC_TRUE;
495   }
496   if (argc && args) {
497     PetscGlobalArgc = *argc;
498     PetscGlobalArgs = *args;
499   }
500   PetscInitializeCalled = PETSC_TRUE;
501   PetscFinalizeCalled   = PETSC_FALSE;
502 
503   if (!PETSC_COMM_WORLD) {
504     PETSC_COMM_WORLD = MPI_COMM_WORLD;
505   }
506 
507   /* Done after init due to a bug in MPICH-GM? */
508   ierr = PetscErrorPrintfInitialize();CHKERRQ(ierr);
509 
510   ierr = MPI_Comm_rank(MPI_COMM_WORLD,&PetscGlobalRank);CHKERRQ(ierr);
511   ierr = MPI_Comm_size(MPI_COMM_WORLD,&PetscGlobalSize);CHKERRQ(ierr);
512 
513 #if defined(PETSC_USE_COMPLEX)
514   /*
515      Initialized the global complex variable; this is because with
516      shared libraries the constructors for global variables
517      are not called; at least on IRIX.
518   */
519   {
520 #if defined(PETSC_CLANGUAGE_CXX)
521     PetscScalar ic(0.0,1.0);
522     PETSC_i = ic;
523 #else
524     PetscScalar ic;
525     ic = 1.I;
526     PETSC_i = ic;
527 #endif
528   }
529 
530   ierr = MPI_Type_contiguous(2,MPIU_REAL,&MPIU_COMPLEX);CHKERRQ(ierr);
531   ierr = MPI_Type_commit(&MPIU_COMPLEX);CHKERRQ(ierr);
532   ierr = MPI_Op_create(PetscSum_Local,1,&PetscSum_Op);CHKERRQ(ierr);
533 #endif
534 
535   /*
536      Create the PETSc MPI reduction operator that sums of the first
537      half of the entries and maxes the second half.
538   */
539   ierr = MPI_Op_create(PetscMaxSum_Local,1,&PetscMaxSum_Op);CHKERRQ(ierr);
540 
541   ierr = MPI_Type_contiguous(2,MPIU_SCALAR,&MPIU_2SCALAR);CHKERRQ(ierr);
542   ierr = MPI_Type_commit(&MPIU_2SCALAR);CHKERRQ(ierr);
543   ierr = MPI_Op_create(PetscADMax_Local,1,&PetscADMax_Op);CHKERRQ(ierr);
544   ierr = MPI_Op_create(PetscADMin_Local,1,&PetscADMin_Op);CHKERRQ(ierr);
545 
546   ierr = MPI_Type_contiguous(2,MPIU_INT,&MPIU_2INT);CHKERRQ(ierr);
547   ierr = MPI_Type_commit(&MPIU_2INT);CHKERRQ(ierr);
548 
549 
550   /*
551      Build the options database
552   */
553   ierr = PetscOptionsInsert(argc,args,file);CHKERRQ(ierr);
554 
555 
556   /*
557      Print main application help message
558   */
559   ierr = PetscOptionsHasName(PETSC_NULL,"-help",&flg);CHKERRQ(ierr);
560   if (help && flg) {
561     ierr = PetscPrintf(PETSC_COMM_WORLD,help);CHKERRQ(ierr);
562   }
563   ierr = PetscOptionsCheckInitial_Private();CHKERRQ(ierr);
564 
565   /* SHOULD PUT IN GUARDS: Make sure logging is initialized, even if we do not print it out */
566 #if defined(PETSC_USE_LOG)
567   ierr = PetscLogBegin_Private();CHKERRQ(ierr);
568 #endif
569 
570   /*
571      Load the dynamic libraries (on machines that support them), this registers all
572      the solvers etc. (On non-dynamic machines this initializes the PetscDraw and PetscViewer classes)
573   */
574   ierr = PetscInitialize_DynamicLibraries();CHKERRQ(ierr);
575 
576   ierr = MPI_Comm_size(PETSC_COMM_WORLD,&size);CHKERRQ(ierr);
577   ierr = PetscInfo1(0,"PETSc successfully started: number of processors = %d\n",size);CHKERRQ(ierr);
578   ierr = PetscGetHostName(hostname,256);CHKERRQ(ierr);
579   ierr = PetscInfo1(0,"Running on machine: %s\n",hostname);CHKERRQ(ierr);
580 
581   ierr = PetscOptionsCheckInitial_Components();CHKERRQ(ierr);
582   /* Check the options database for options related to the options database itself */
583   ierr = PetscOptionsSetFromOptions(); CHKERRQ(ierr);
584 
585   ierr = PetscOptionsGetInt(PETSC_NULL,"-openmp_spawn_size",&nodesize,&flg);CHKERRQ(ierr);
586   if (flg) {
587 #if defined(PETSC_HAVE_MPI_COMM_SPAWN)
588     ierr = PetscOpenMPSpawn(nodesize);CHKERRQ(ierr);
589 #else
590     SETERRQ(PETSC_ERR_SUP,"PETSc built without MPI 2 (MPI_Comm_spawn) support, use -openmp_merge_size instead");
591 #endif
592   } else {
593     ierr = PetscOptionsGetInt(PETSC_NULL,"-openmp_merge_size",&nodesize,&flg);CHKERRQ(ierr);
594     if (flg) {
595       ierr = PetscOpenMPMerge(nodesize);CHKERRQ(ierr);
596     }
597   }
598 
599   PetscFunctionReturn(ierr);
600 }
601 
602 
603 #undef __FUNCT__
604 #define __FUNCT__ "PetscFinalize"
605 /*@C
606    PetscFinalize - Checks for options to be called at the conclusion
607    of the program. MPI_Finalize() is called only if the user had not
608    called MPI_Init() before calling PetscInitialize().
609 
610    Collective on PETSC_COMM_WORLD
611 
612    Options Database Keys:
613 +  -options_table - Calls PetscOptionsPrint()
614 .  -options_left - Prints unused options that remain in the database
615 .  -options_left no - Does not print unused options that remain in the database
616 .  -mpidump - Calls PetscMPIDump()
617 .  -malloc_dump - Calls PetscMallocDump()
618 .  -malloc_info - Prints total memory usage
619 -  -malloc_log - Prints summary of memory usage
620 
621    Options Database Keys for Profiling:
622    See the Profiling chapter of the users manual for details.
623 +  -log_summary [filename] - Prints summary of flop and timing
624         information to screen. If the filename is specified the
625         summary is written to the file. (for code compiled with
626         PETSC_USE_LOG).  See PetscLogPrintSummary().
627 .  -log_all [filename] - Logs extensive profiling information
628         (for code compiled with PETSC_USE_LOG). See PetscLogDump().
629 .  -log [filename] - Logs basic profiline information (for
630         code compiled with PETSC_USE_LOG).  See PetscLogDump().
631 .  -log_sync - Log the synchronization in scatters, inner products
632         and norms
633 -  -log_mpe [filename] - Creates a logfile viewable by the
634       utility Upshot/Nupshot (in MPICH distribution)
635 
636    Level: beginner
637 
638    Note:
639    See PetscInitialize() for more general runtime options.
640 
641 .seealso: PetscInitialize(), PetscOptionsPrint(), PetscMallocDump(), PetscMPIDump(), PetscEnd()
642 @*/
643 PetscErrorCode PETSC_DLLEXPORT PetscFinalize(void)
644 {
645   PetscErrorCode ierr;
646   PetscMPIInt    rank;
647   int            nopt;
648   PetscTruth     flg1,flg2,flg3;
649 
650   PetscFunctionBegin;
651 
652   if (!PetscInitializeCalled) {
653     (*PetscErrorPrintf)("PetscInitialize() must be called before PetscFinalize()\n");
654     PetscFunctionReturn(0);
655   }
656   ierr = PetscOpenMPFinalize();CHKERRQ(ierr);
657 
658   ierr = MPI_Comm_rank(PETSC_COMM_WORLD,&rank);CHKERRQ(ierr);
659   ierr = PetscOptionsHasName(PETSC_NULL,"-malloc_info",&flg2);CHKERRQ(ierr);
660   if (!flg2) {
661     ierr = PetscOptionsHasName(PETSC_NULL,"-memory_info",&flg2);CHKERRQ(ierr);
662   }
663   if (flg2) {
664     ierr = PetscMemoryShowUsage(PETSC_VIEWER_STDOUT_WORLD,"Summary of Memory Usage in PETSc\n");CHKERRQ(ierr);
665   }
666 
667   /* Destroy auxiliary packages */
668 #if defined(PETSC_HAVE_MATHEMATICA)
669   ierr = PetscViewerMathematicaFinalizePackage();CHKERRQ(ierr);
670 #endif
671 #if defined(PETSC_USE_DYNAMIC_LIBRARIES)
672 #if defined(PETSC_HAVE_SIEVE)
673   {
674     PetscErrorCode (*func)(void);
675     char lib[PETSC_MAX_PATH_LEN];
676 
677     ierr = PetscStrcpy(lib,PETSC_LIB_DIR);CHKERRQ(ierr);
678     ierr = PetscStrcat(lib,"/libpetscdm");CHKERRQ(ierr);
679     ierr = PetscDLLibrarySym(PETSC_COMM_WORLD,&DLLibrariesLoaded,lib,"DMFinalizePackage",(void **) &func);CHKERRQ(ierr);
680     if (func) {
681       ierr = (*func)();CHKERRQ(ierr);
682     }
683   }
684 #endif
685 #endif
686 
687   /*
688      Destroy all the function registration lists created
689   */
690   ierr = PetscFinalize_DynamicLibraries();CHKERRQ(ierr);
691 
692 #if defined(PETSC_USE_LOG)
693   ierr = PetscOptionsHasName(PETSC_NULL,"-get_total_flops",&flg1);CHKERRQ(ierr);
694   if (flg1) {
695     PetscLogDouble flops = 0;
696     ierr = MPI_Reduce(&_TotalFlops,&flops,1,MPI_DOUBLE,MPI_SUM,0,PETSC_COMM_WORLD);CHKERRQ(ierr);
697     ierr = PetscPrintf(PETSC_COMM_WORLD,"Total flops over all processors %g\n",flops);CHKERRQ(ierr);
698   }
699 #endif
700 
701   /*
702      Free all objects registered with PetscObjectRegisterDestroy() such ast
703     PETSC_VIEWER_XXX_().
704   */
705   ierr = PetscObjectRegisterDestroyAll();CHKERRQ(ierr);
706   ierr = PetscOptionsHelpDestroyList();CHKERRQ(ierr);
707 
708 #if defined(PETSC_USE_DEBUG)
709   if (PetscStackActive) {
710     ierr = PetscStackDestroy();CHKERRQ(ierr);
711   }
712 #endif
713 
714 #if defined(PETSC_USE_LOG)
715   {
716     char mname[PETSC_MAX_PATH_LEN];
717 #if defined(PETSC_HAVE_MPE)
718     mname[0] = 0;
719     ierr = PetscOptionsGetString(PETSC_NULL,"-log_mpe",mname,PETSC_MAX_PATH_LEN,&flg1);CHKERRQ(ierr);
720     if (flg1){
721       if (mname[0]) {ierr = PetscLogMPEDump(mname);CHKERRQ(ierr);}
722       else          {ierr = PetscLogMPEDump(0);CHKERRQ(ierr);}
723     }
724 #endif
725     mname[0] = 0;
726     ierr = PetscOptionsGetString(PETSC_NULL,"-log_summary",mname,PETSC_MAX_PATH_LEN,&flg1);CHKERRQ(ierr);
727     if (flg1) {
728       if (mname[0])  {ierr = PetscLogPrintSummary(PETSC_COMM_WORLD,mname);CHKERRQ(ierr);}
729       else           {ierr = PetscLogPrintSummary(PETSC_COMM_WORLD,0);CHKERRQ(ierr);}
730     }
731 
732     ierr = PetscOptionsGetString(PETSC_NULL,"-log_detailed",mname,PETSC_MAX_PATH_LEN,&flg1);CHKERRQ(ierr);
733     if (flg1) {
734       if (mname[0])  {ierr = PetscLogPrintDetailed(PETSC_COMM_WORLD,mname);CHKERRQ(ierr);}
735       else           {ierr = PetscLogPrintDetailed(PETSC_COMM_WORLD,0);CHKERRQ(ierr);}
736     }
737 
738     mname[0] = 0;
739     ierr = PetscOptionsGetString(PETSC_NULL,"-log_all",mname,PETSC_MAX_PATH_LEN,&flg1);CHKERRQ(ierr);
740     ierr = PetscOptionsGetString(PETSC_NULL,"-log",mname,PETSC_MAX_PATH_LEN,&flg2);CHKERRQ(ierr);
741     if (flg1 || flg2){
742       if (mname[0]) PetscLogDump(mname);
743       else          PetscLogDump(0);
744     }
745     ierr = PetscLogDestroy();CHKERRQ(ierr);
746   }
747 #endif
748   ierr = PetscOptionsHasName(PETSC_NULL,"-no_signal_handler",&flg1);CHKERRQ(ierr);
749   if (!flg1) { ierr = PetscPopSignalHandler();CHKERRQ(ierr);}
750   ierr = PetscOptionsHasName(PETSC_NULL,"-mpidump",&flg1);CHKERRQ(ierr);
751   if (flg1) {
752     ierr = PetscMPIDump(stdout);CHKERRQ(ierr);
753   }
754   ierr = PetscOptionsHasName(PETSC_NULL,"-malloc_dump",&flg1);CHKERRQ(ierr);
755   ierr = PetscOptionsHasName(PETSC_NULL,"-options_table",&flg2);CHKERRQ(ierr);
756   if (flg2) {
757     if (!rank) {ierr = PetscOptionsPrint(stdout);CHKERRQ(ierr);}
758   }
759 
760   /* to prevent PETSc -options_left from warning */
761   ierr = PetscOptionsHasName(PETSC_NULL,"-nox",&flg1);CHKERRQ(ierr)
762   ierr = PetscOptionsHasName(PETSC_NULL,"-nox_warning",&flg1);CHKERRQ(ierr)
763 
764   flg3 = PETSC_FALSE; /* default value is required */
765   ierr = PetscOptionsGetTruth(PETSC_NULL,"-options_left",&flg3,&flg1);CHKERRQ(ierr);
766   ierr = PetscOptionsAllUsed(&nopt);CHKERRQ(ierr);
767   if (flg3) {
768     if (!flg2) { /* have not yet printed the options */
769       ierr = PetscOptionsPrint(stdout);CHKERRQ(ierr);
770     }
771     if (!nopt) {
772       ierr = PetscPrintf(PETSC_COMM_WORLD,"There are no unused options.\n");CHKERRQ(ierr);
773     } else if (nopt == 1) {
774       ierr = PetscPrintf(PETSC_COMM_WORLD,"There is one unused database option. It is:\n");CHKERRQ(ierr);
775     } else {
776       ierr = PetscPrintf(PETSC_COMM_WORLD,"There are %d unused database options. They are:\n",nopt);CHKERRQ(ierr);
777     }
778   }
779 #if defined(PETSC_USE_DEBUG)
780   if (nopt && !flg3 && !flg1) {
781     ierr = PetscPrintf(PETSC_COMM_WORLD,"WARNING! There are options you set that were not used!\n");CHKERRQ(ierr);
782     ierr = PetscPrintf(PETSC_COMM_WORLD,"WARNING! could be spelling mistake, etc!\n");CHKERRQ(ierr);
783     ierr = PetscOptionsLeft();CHKERRQ(ierr);
784   } else if (nopt && flg3) {
785 #else
786   if (nopt && flg3) {
787 #endif
788     ierr = PetscOptionsLeft();CHKERRQ(ierr);
789   }
790 
791   ierr = PetscOptionsHasName(PETSC_NULL,"-log_history",&flg1);CHKERRQ(ierr);
792   if (flg1) {
793     ierr = PetscLogCloseHistoryFile(&petsc_history);CHKERRQ(ierr);
794     petsc_history = 0;
795   }
796 
797   ierr = PetscInfoAllow(PETSC_FALSE,PETSC_NULL);CHKERRQ(ierr);
798 
799   /*
800        Free all the registered create functions, such as KSPList, VecList, SNESList, etc
801   */
802   ierr = PetscFListDestroyAll();CHKERRQ(ierr);
803 
804   ierr = PetscOptionsHasName(PETSC_NULL,"-malloc_dump",&flg1);CHKERRQ(ierr);
805   ierr = PetscOptionsHasName(PETSC_NULL,"-malloc_log",&flg3);CHKERRQ(ierr);
806   if (flg1) {
807     char fname[PETSC_MAX_PATH_LEN];
808     FILE *fd;
809 
810     fname[0] = 0;
811     ierr = PetscOptionsGetString(PETSC_NULL,"-malloc_dump",fname,250,&flg1);CHKERRQ(ierr);
812     if (flg1 && fname[0]) {
813       char sname[PETSC_MAX_PATH_LEN];
814 
815       sprintf(sname,"%s_%d",fname,rank);
816       fd   = fopen(sname,"w"); if (!fd) SETERRQ1(PETSC_ERR_FILE_OPEN,"Cannot open log file: %s",sname);
817       ierr = PetscMallocDump(fd);CHKERRQ(ierr);
818       fclose(fd);
819     } else {
820       MPI_Comm local_comm;
821 
822       ierr = MPI_Comm_dup(MPI_COMM_WORLD,&local_comm);CHKERRQ(ierr);
823       ierr = PetscSequentialPhaseBegin_Private(local_comm,1);CHKERRQ(ierr);
824         ierr = PetscMallocDump(stdout);CHKERRQ(ierr);
825       ierr = PetscSequentialPhaseEnd_Private(local_comm,1);CHKERRQ(ierr);
826       ierr = MPI_Comm_free(&local_comm);CHKERRQ(ierr);
827     }
828   }
829   if (flg3) {
830     char fname[PETSC_MAX_PATH_LEN];
831     FILE *fd;
832 
833     fname[0] = 0;
834     ierr = PetscOptionsGetString(PETSC_NULL,"-malloc_log",fname,250,&flg1);CHKERRQ(ierr);
835     if (flg1 && fname[0]) {
836       char sname[PETSC_MAX_PATH_LEN];
837 
838       sprintf(sname,"%s_%d",fname,rank);
839       fd   = fopen(sname,"w"); if (!fd) SETERRQ1(PETSC_ERR_FILE_OPEN,"Cannot open log file: %s",sname);
840       ierr = PetscMallocDumpLog(fd);CHKERRQ(ierr);
841       fclose(fd);
842     } else {
843       ierr = PetscMallocDumpLog(stdout);CHKERRQ(ierr);
844     }
845   }
846   /* Can be destroyed only after all the options are used */
847   ierr = PetscOptionsDestroy();CHKERRQ(ierr);
848 
849   PetscGlobalArgc = 0;
850   PetscGlobalArgs = 0;
851 
852 #if defined(PETSC_USE_COMPLEX)
853   ierr = MPI_Op_free(&PetscSum_Op);CHKERRQ(ierr);
854   ierr = MPI_Type_free(&MPIU_COMPLEX);CHKERRQ(ierr);
855 #endif
856   ierr = MPI_Type_free(&MPIU_2SCALAR);CHKERRQ(ierr);
857   ierr = MPI_Type_free(&MPIU_2INT);CHKERRQ(ierr);
858   ierr = MPI_Op_free(&PetscMaxSum_Op);CHKERRQ(ierr);
859   ierr = MPI_Op_free(&PetscADMax_Op);CHKERRQ(ierr);
860   ierr = MPI_Op_free(&PetscADMin_Op);CHKERRQ(ierr);
861 
862   ierr = PetscInfo(0,"PETSc successfully ended!\n");CHKERRQ(ierr);
863   if (PetscBeganMPI) {
864     ierr = MPI_Finalize();CHKERRQ(ierr);
865   }
866 
867   if(PETSC_LISTEN_CHECK){
868     PETSC_LISTEN_CHECK = 0;
869     extern FILE * PETSC_STDOUT;
870     fprintf(PETSC_STDOUT, "<<<end>>>");
871     close(PETSC_LISTENFD);}
872 
873 /*
874 
875      Note: In certain cases PETSC_COMM_WORLD is never MPI_Comm_free()ed because
876    the communicator has some outstanding requests on it. Specifically if the
877    flag PETSC_HAVE_BROKEN_REQUEST_FREE is set (for IBM MPI implementation). See
878    src/vec/utils/vpscat.c. Due to this the memory allocated in PetscCommDuplicate()
879    is never freed as it should be. Thus one may obtain messages of the form
880    [ 1] 8 bytes PetscCommDuplicate() line 645 in src/sys/mpiu.c indicating the
881    memory was not freed.
882 
883 */
884   ierr = PetscClearMalloc();CHKERRQ(ierr);
885   PetscInitializeCalled = PETSC_FALSE;
886   PetscFinalizeCalled   = PETSC_TRUE;
887   PetscFunctionReturn(ierr);
888 }
889 
890 /*
891      These may be used in code that ADIC is to be used on
892 */
893 
894 #undef __FUNCT__
895 #define __FUNCT__ "PetscGlobalMax"
896 /*@C
897       PetscGlobalMax - Computes the maximum value over several processors
898 
899      Collective on MPI_Comm
900 
901    Input Parameters:
902 +   local - the local value
903 -   comm - the processors that find the maximum
904 
905    Output Parameter:
906 .   result - the maximum value
907 
908    Level: intermediate
909 
910    Notes:
911      These functions are to be used inside user functions that are to be processed with
912    ADIC. PETSc will automatically provide differentiated versions of these functions
913 
914 .seealso: PetscGlobalMin(), PetscGlobalSum()
915 @*/
916 PetscErrorCode PETSC_DLLEXPORT PetscGlobalMax(PetscReal* local,PetscReal* result,MPI_Comm comm)
917 {
918   return MPI_Allreduce(local,result,1,MPIU_REAL,MPI_MAX,comm);
919 }
920 
921 #undef __FUNCT__
922 #define __FUNCT__ "PetscGlobalMin"
923 /*@C
924       PetscGlobalMin - Computes the minimum value over several processors
925 
926      Collective on MPI_Comm
927 
928    Input Parameters:
929 +   local - the local value
930 -   comm - the processors that find the minimum
931 
932    Output Parameter:
933 .   result - the minimum value
934 
935    Level: intermediate
936 
937    Notes:
938      These functions are to be used inside user functions that are to be processed with
939    ADIC. PETSc will automatically provide differentiated versions of these functions
940 
941 .seealso: PetscGlobalMax(), PetscGlobalSum()
942 @*/
943 PetscErrorCode PETSC_DLLEXPORT PetscGlobalMin(PetscReal* local,PetscReal* result,MPI_Comm comm)
944 {
945   return MPI_Allreduce(local,result,1,MPIU_REAL,MPI_MIN,comm);
946 }
947 
948 #undef __FUNCT__
949 #define __FUNCT__ "PetscGlobalSum"
950 /*@C
951       PetscGlobalSum - Computes the sum over sever processors
952 
953      Collective on MPI_Comm
954 
955    Input Parameters:
956 +   local - the local value
957 -   comm - the processors that find the sum
958 
959    Output Parameter:
960 .   result - the sum
961 
962    Level: intermediate
963 
964    Notes:
965      These functions are to be used inside user functions that are to be processed with
966    ADIC. PETSc will automatically provide differentiated versions of these functions
967 
968 .seealso: PetscGlobalMin(), PetscGlobalMax()
969 @*/
970 PetscErrorCode PETSC_DLLEXPORT PetscGlobalSum(PetscScalar* local,PetscScalar* result,MPI_Comm comm)
971 {
972   return MPI_Allreduce(local,result,1,MPIU_SCALAR,PetscSum_Op,comm);
973 }
974 
975 
976