xref: /petsc/src/sys/objects/pinit.c (revision 8cda6cd7047ed8bb2d68b8e371c012553cb590ce)
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 
9 #if defined(PETSC_USE_LOG)
10 EXTERN PetscErrorCode PetscLogBegin_Private(void);
11 #endif
12 extern PetscTruth PetscOpenMPWorker;
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_NULL_CHARACTER 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;
468   PetscInt       nodesize;
469   PetscTruth     flg;
470   char           hostname[256];
471 
472   PetscFunctionBegin;
473   if (PetscInitializeCalled) PetscFunctionReturn(0);
474 
475   /* these must be initialized in a routine, not as a constant declaration*/
476   PETSC_STDOUT = stdout;
477   PETSC_STDERR = stderr;
478 
479   ierr = PetscOptionsCreate();CHKERRQ(ierr);
480 
481   /*
482      We initialize the program name here (before MPI_Init()) because MPICH has a bug in
483      it that it sets args[0] on all processors to be args[0] on the first processor.
484   */
485   if (argc && *argc) {
486     ierr = PetscSetProgramName(**args);CHKERRQ(ierr);
487   } else {
488     ierr = PetscSetProgramName("Unknown Name");CHKERRQ(ierr);
489   }
490 
491   ierr = MPI_Initialized(&flag);CHKERRQ(ierr);
492   if (!flag) {
493     if (PETSC_COMM_WORLD) SETERRQ(PETSC_ERR_SUP,"You cannot set PETSC_COMM_WORLD if you have not initialized MPI first");
494     ierr          = MPI_Init(argc,args);CHKERRQ(ierr);
495     PetscBeganMPI = PETSC_TRUE;
496   }
497   if (argc && args) {
498     PetscGlobalArgc = *argc;
499     PetscGlobalArgs = *args;
500   }
501   PetscInitializeCalled = PETSC_TRUE;
502   PetscFinalizeCalled   = PETSC_FALSE;
503 
504   if (!PETSC_COMM_WORLD) {
505     PETSC_COMM_WORLD = MPI_COMM_WORLD;
506   }
507 
508   /* Done after init due to a bug in MPICH-GM? */
509   ierr = PetscErrorPrintfInitialize();CHKERRQ(ierr);
510 
511   ierr = MPI_Comm_rank(MPI_COMM_WORLD,&PetscGlobalRank);CHKERRQ(ierr);
512   ierr = MPI_Comm_size(MPI_COMM_WORLD,&PetscGlobalSize);CHKERRQ(ierr);
513 
514 #if defined(PETSC_USE_COMPLEX)
515   /*
516      Initialized the global complex variable; this is because with
517      shared libraries the constructors for global variables
518      are not called; at least on IRIX.
519   */
520   {
521 #if defined(PETSC_CLANGUAGE_CXX)
522     PetscScalar ic(0.0,1.0);
523     PETSC_i = ic;
524 #else
525     PETSC_i = I;
526 #endif
527   }
528 
529   ierr = MPI_Type_contiguous(2,MPIU_REAL,&MPIU_COMPLEX);CHKERRQ(ierr);
530   ierr = MPI_Type_commit(&MPIU_COMPLEX);CHKERRQ(ierr);
531   ierr = MPI_Op_create(PetscSum_Local,1,&PetscSum_Op);CHKERRQ(ierr);
532 #endif
533 
534   /*
535      Create the PETSc MPI reduction operator that sums of the first
536      half of the entries and maxes the second half.
537   */
538   ierr = MPI_Op_create(PetscMaxSum_Local,1,&PetscMaxSum_Op);CHKERRQ(ierr);
539 
540   ierr = MPI_Type_contiguous(2,MPIU_SCALAR,&MPIU_2SCALAR);CHKERRQ(ierr);
541   ierr = MPI_Type_commit(&MPIU_2SCALAR);CHKERRQ(ierr);
542   ierr = MPI_Op_create(PetscADMax_Local,1,&PetscADMax_Op);CHKERRQ(ierr);
543   ierr = MPI_Op_create(PetscADMin_Local,1,&PetscADMin_Op);CHKERRQ(ierr);
544 
545   ierr = MPI_Type_contiguous(2,MPIU_INT,&MPIU_2INT);CHKERRQ(ierr);
546   ierr = MPI_Type_commit(&MPIU_2INT);CHKERRQ(ierr);
547 
548 
549   /*
550      Build the options database
551   */
552   ierr = PetscOptionsInsert(argc,args,file);CHKERRQ(ierr);
553 
554 
555   /*
556      Print main application help message
557   */
558   ierr = PetscOptionsHasName(PETSC_NULL,"-help",&flg);CHKERRQ(ierr);
559   if (help && flg) {
560     ierr = PetscPrintf(PETSC_COMM_WORLD,help);CHKERRQ(ierr);
561   }
562   ierr = PetscOptionsCheckInitial_Private();CHKERRQ(ierr);
563 
564   /* SHOULD PUT IN GUARDS: Make sure logging is initialized, even if we do not print it out */
565 #if defined(PETSC_USE_LOG)
566   ierr = PetscLogBegin_Private();CHKERRQ(ierr);
567 #endif
568 
569   /*
570      Load the dynamic libraries (on machines that support them), this registers all
571      the solvers etc. (On non-dynamic machines this initializes the PetscDraw and PetscViewer classes)
572   */
573   ierr = PetscInitialize_DynamicLibraries();CHKERRQ(ierr);
574 
575   ierr = MPI_Comm_size(PETSC_COMM_WORLD,&size);CHKERRQ(ierr);
576   ierr = PetscInfo1(0,"PETSc successfully started: number of processors = %d\n",size);CHKERRQ(ierr);
577   ierr = PetscGetHostName(hostname,256);CHKERRQ(ierr);
578   ierr = PetscInfo1(0,"Running on machine: %s\n",hostname);CHKERRQ(ierr);
579 
580   ierr = PetscOptionsCheckInitial_Components();CHKERRQ(ierr);
581   /* Check the options database for options related to the options database itself */
582   ierr = PetscOptionsSetFromOptions(); CHKERRQ(ierr);
583 
584   ierr = PetscOptionsGetInt(PETSC_NULL,"-openmp_spawn_size",&nodesize,&flg);CHKERRQ(ierr);
585   if (flg) {
586 #if defined(PETSC_HAVE_MPI_COMM_SPAWN)
587     ierr = PetscOpenMPSpawn((PetscMPIInt) nodesize);CHKERRQ(ierr);
588 #else
589     SETERRQ(PETSC_ERR_SUP,"PETSc built without MPI 2 (MPI_Comm_spawn) support, use -openmp_merge_size instead");
590 #endif
591   } else {
592     ierr = PetscOptionsGetInt(PETSC_NULL,"-openmp_merge_size",&nodesize,&flg);CHKERRQ(ierr);
593     if (flg) {
594       ierr = PetscOpenMPMerge((PetscMPIInt) nodesize);CHKERRQ(ierr);
595     }
596   }
597 
598   PetscFunctionReturn(ierr);
599 }
600 
601 
602 #undef __FUNCT__
603 #define __FUNCT__ "PetscFinalize"
604 /*@C
605    PetscFinalize - Checks for options to be called at the conclusion
606    of the program. MPI_Finalize() is called only if the user had not
607    called MPI_Init() before calling PetscInitialize().
608 
609    Collective on PETSC_COMM_WORLD
610 
611    Options Database Keys:
612 +  -options_table - Calls PetscOptionsPrint()
613 .  -options_left - Prints unused options that remain in the database
614 .  -options_left no - Does not print unused options that remain in the database
615 .  -mpidump - Calls PetscMPIDump()
616 .  -malloc_dump - Calls PetscMallocDump()
617 .  -malloc_info - Prints total memory usage
618 -  -malloc_log - Prints summary of memory usage
619 
620    Options Database Keys for Profiling:
621    See the Profiling chapter of the users manual for details.
622 +  -log_summary [filename] - Prints summary of flop and timing
623         information to screen. If the filename is specified the
624         summary is written to the file. (for code compiled with
625         PETSC_USE_LOG).  See PetscLogPrintSummary().
626 .  -log_all [filename] - Logs extensive profiling information
627         (for code compiled with PETSC_USE_LOG). See PetscLogDump().
628 .  -log [filename] - Logs basic profiline information (for
629         code compiled with PETSC_USE_LOG).  See PetscLogDump().
630 .  -log_sync - Log the synchronization in scatters, inner products
631         and norms
632 -  -log_mpe [filename] - Creates a logfile viewable by the
633       utility Upshot/Nupshot (in MPICH distribution)
634 
635    Level: beginner
636 
637    Note:
638    See PetscInitialize() for more general runtime options.
639 
640 .seealso: PetscInitialize(), PetscOptionsPrint(), PetscMallocDump(), PetscMPIDump(), PetscEnd()
641 @*/
642 PetscErrorCode PETSC_DLLEXPORT PetscFinalize(void)
643 {
644   PetscErrorCode ierr;
645   PetscMPIInt    rank;
646   int            nopt;
647   PetscTruth     flg1,flg2,flg3;
648   extern FILE   *PETSC_ZOPEFD;
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 any packages that registered a finalize */
668   ierr = PetscRegisterFinalizeAll();CHKERRQ(ierr);
669 
670   /*
671      Destroy all the function registration lists created
672   */
673   ierr = PetscFinalize_DynamicLibraries();CHKERRQ(ierr);
674 
675 #if defined(PETSC_USE_LOG)
676   ierr = PetscOptionsHasName(PETSC_NULL,"-get_total_flops",&flg1);CHKERRQ(ierr);
677   if (flg1) {
678     PetscLogDouble flops = 0;
679     ierr = MPI_Reduce(&_TotalFlops,&flops,1,MPI_DOUBLE,MPI_SUM,0,PETSC_COMM_WORLD);CHKERRQ(ierr);
680     ierr = PetscPrintf(PETSC_COMM_WORLD,"Total flops over all processors %g\n",flops);CHKERRQ(ierr);
681   }
682 #endif
683 
684   /*
685      Free all objects registered with PetscObjectRegisterDestroy() such ast
686     PETSC_VIEWER_XXX_().
687   */
688   ierr = PetscObjectRegisterDestroyAll();CHKERRQ(ierr);
689   ierr = PetscOptionsHelpDestroyList();CHKERRQ(ierr);
690 
691 #if defined(PETSC_USE_DEBUG)
692   if (PetscStackActive) {
693     ierr = PetscStackDestroy();CHKERRQ(ierr);
694   }
695 #endif
696 
697 #if defined(PETSC_USE_LOG)
698   {
699     char mname[PETSC_MAX_PATH_LEN];
700 #if defined(PETSC_HAVE_MPE)
701     mname[0] = 0;
702     ierr = PetscOptionsGetString(PETSC_NULL,"-log_mpe",mname,PETSC_MAX_PATH_LEN,&flg1);CHKERRQ(ierr);
703     if (flg1){
704       if (mname[0]) {ierr = PetscLogMPEDump(mname);CHKERRQ(ierr);}
705       else          {ierr = PetscLogMPEDump(0);CHKERRQ(ierr);}
706     }
707 #endif
708     mname[0] = 0;
709     ierr = PetscOptionsGetString(PETSC_NULL,"-log_summary",mname,PETSC_MAX_PATH_LEN,&flg1);CHKERRQ(ierr);
710     if (flg1) {
711       if (mname[0])  {ierr = PetscLogPrintSummary(PETSC_COMM_WORLD,mname);CHKERRQ(ierr);}
712       else           {ierr = PetscLogPrintSummary(PETSC_COMM_WORLD,0);CHKERRQ(ierr);}
713     }
714 
715     ierr = PetscOptionsGetString(PETSC_NULL,"-log_detailed",mname,PETSC_MAX_PATH_LEN,&flg1);CHKERRQ(ierr);
716     if (flg1) {
717       if (mname[0])  {ierr = PetscLogPrintDetailed(PETSC_COMM_WORLD,mname);CHKERRQ(ierr);}
718       else           {ierr = PetscLogPrintDetailed(PETSC_COMM_WORLD,0);CHKERRQ(ierr);}
719     }
720 
721     mname[0] = 0;
722     ierr = PetscOptionsGetString(PETSC_NULL,"-log_all",mname,PETSC_MAX_PATH_LEN,&flg1);CHKERRQ(ierr);
723     ierr = PetscOptionsGetString(PETSC_NULL,"-log",mname,PETSC_MAX_PATH_LEN,&flg2);CHKERRQ(ierr);
724     if (flg1 || flg2){
725       if (mname[0]) PetscLogDump(mname);
726       else          PetscLogDump(0);
727     }
728     ierr = PetscLogDestroy();CHKERRQ(ierr);
729   }
730 #endif
731   ierr = PetscOptionsHasName(PETSC_NULL,"-no_signal_handler",&flg1);CHKERRQ(ierr);
732   if (!flg1) { ierr = PetscPopSignalHandler();CHKERRQ(ierr);}
733   ierr = PetscOptionsHasName(PETSC_NULL,"-mpidump",&flg1);CHKERRQ(ierr);
734   if (flg1) {
735     ierr = PetscMPIDump(stdout);CHKERRQ(ierr);
736   }
737   ierr = PetscOptionsHasName(PETSC_NULL,"-malloc_dump",&flg1);CHKERRQ(ierr);
738   ierr = PetscOptionsHasName(PETSC_NULL,"-options_table",&flg2);CHKERRQ(ierr);
739   if (flg2) {
740     if (!rank) {ierr = PetscOptionsPrint(stdout);CHKERRQ(ierr);}
741   }
742 
743   /* to prevent PETSc -options_left from warning */
744   ierr = PetscOptionsHasName(PETSC_NULL,"-nox",&flg1);CHKERRQ(ierr)
745   ierr = PetscOptionsHasName(PETSC_NULL,"-nox_warning",&flg1);CHKERRQ(ierr)
746 
747   if (!PetscOpenMPWorker) { /* worker processes skip this because they do not usually process options */
748     flg3 = PETSC_FALSE; /* default value is required */
749     ierr = PetscOptionsGetTruth(PETSC_NULL,"-options_left",&flg3,&flg1);CHKERRQ(ierr);
750     ierr = PetscOptionsAllUsed(&nopt);CHKERRQ(ierr);
751     if (flg3) {
752       if (!flg2) { /* have not yet printed the options */
753 	ierr = PetscOptionsPrint(stdout);CHKERRQ(ierr);
754       }
755       if (!nopt) {
756 	ierr = PetscPrintf(PETSC_COMM_WORLD,"There are no unused options.\n");CHKERRQ(ierr);
757       } else if (nopt == 1) {
758 	ierr = PetscPrintf(PETSC_COMM_WORLD,"There is one unused database option. It is:\n");CHKERRQ(ierr);
759       } else {
760 	ierr = PetscPrintf(PETSC_COMM_WORLD,"There are %d unused database options. They are:\n",nopt);CHKERRQ(ierr);
761       }
762     }
763 #if defined(PETSC_USE_DEBUG)
764     if (nopt && !flg3 && !flg1) {
765       ierr = PetscPrintf(PETSC_COMM_WORLD,"WARNING! There are options you set that were not used!\n");CHKERRQ(ierr);
766       ierr = PetscPrintf(PETSC_COMM_WORLD,"WARNING! could be spelling mistake, etc!\n");CHKERRQ(ierr);
767       ierr = PetscOptionsLeft();CHKERRQ(ierr);
768     } else if (nopt && flg3) {
769 #else
770     if (nopt && flg3) {
771 #endif
772       ierr = PetscOptionsLeft();CHKERRQ(ierr);
773     }
774   }
775 
776   ierr = PetscOptionsHasName(PETSC_NULL,"-log_history",&flg1);CHKERRQ(ierr);
777   if (flg1) {
778     ierr = PetscLogCloseHistoryFile(&petsc_history);CHKERRQ(ierr);
779     petsc_history = 0;
780   }
781 
782   ierr = PetscInfoAllow(PETSC_FALSE,PETSC_NULL);CHKERRQ(ierr);
783 
784   /*
785        Free all the registered create functions, such as KSPList, VecList, SNESList, etc
786   */
787   ierr = PetscFListDestroyAll();CHKERRQ(ierr);
788 
789   ierr = PetscOptionsHasName(PETSC_NULL,"-malloc_dump",&flg1);CHKERRQ(ierr);
790   ierr = PetscOptionsHasName(PETSC_NULL,"-malloc_log",&flg3);CHKERRQ(ierr);
791   if (flg1) {
792     char fname[PETSC_MAX_PATH_LEN];
793     FILE *fd;
794     int  err;
795 
796     fname[0] = 0;
797     ierr = PetscOptionsGetString(PETSC_NULL,"-malloc_dump",fname,250,&flg1);CHKERRQ(ierr);
798     if (flg1 && fname[0]) {
799       char sname[PETSC_MAX_PATH_LEN];
800 
801       sprintf(sname,"%s_%d",fname,rank);
802       fd   = fopen(sname,"w"); if (!fd) SETERRQ1(PETSC_ERR_FILE_OPEN,"Cannot open log file: %s",sname);
803       ierr = PetscMallocDump(fd);CHKERRQ(ierr);
804       err = fclose(fd);
805       if (err) SETERRQ(PETSC_ERR_SYS,"fclose() failed on file");
806     } else {
807       MPI_Comm local_comm;
808 
809       ierr = MPI_Comm_dup(MPI_COMM_WORLD,&local_comm);CHKERRQ(ierr);
810       ierr = PetscSequentialPhaseBegin_Private(local_comm,1);CHKERRQ(ierr);
811         ierr = PetscMallocDump(stdout);CHKERRQ(ierr);
812       ierr = PetscSequentialPhaseEnd_Private(local_comm,1);CHKERRQ(ierr);
813       ierr = MPI_Comm_free(&local_comm);CHKERRQ(ierr);
814     }
815   }
816   if (flg3) {
817     char fname[PETSC_MAX_PATH_LEN];
818     FILE *fd;
819 
820     fname[0] = 0;
821     ierr = PetscOptionsGetString(PETSC_NULL,"-malloc_log",fname,250,&flg1);CHKERRQ(ierr);
822     if (flg1 && fname[0]) {
823       char sname[PETSC_MAX_PATH_LEN];
824       int  err;
825 
826       sprintf(sname,"%s_%d",fname,rank);
827       fd   = fopen(sname,"w"); if (!fd) SETERRQ1(PETSC_ERR_FILE_OPEN,"Cannot open log file: %s",sname);
828       ierr = PetscMallocDumpLog(fd);CHKERRQ(ierr);
829       err = fclose(fd);
830       if (err) SETERRQ(PETSC_ERR_SYS,"fclose() failed on file");
831     } else {
832       ierr = PetscMallocDumpLog(stdout);CHKERRQ(ierr);
833     }
834   }
835   /* Can be destroyed only after all the options are used */
836   ierr = PetscOptionsDestroy();CHKERRQ(ierr);
837 
838   PetscGlobalArgc = 0;
839   PetscGlobalArgs = 0;
840 
841 #if defined(PETSC_USE_COMPLEX)
842   ierr = MPI_Op_free(&PetscSum_Op);CHKERRQ(ierr);
843   ierr = MPI_Type_free(&MPIU_COMPLEX);CHKERRQ(ierr);
844 #endif
845   ierr = MPI_Type_free(&MPIU_2SCALAR);CHKERRQ(ierr);
846   ierr = MPI_Type_free(&MPIU_2INT);CHKERRQ(ierr);
847   ierr = MPI_Op_free(&PetscMaxSum_Op);CHKERRQ(ierr);
848   ierr = MPI_Op_free(&PetscADMax_Op);CHKERRQ(ierr);
849   ierr = MPI_Op_free(&PetscADMin_Op);CHKERRQ(ierr);
850 
851   ierr = PetscInfo(0,"PETSc successfully ended!\n");CHKERRQ(ierr);
852   if (PetscBeganMPI) {
853 #if defined(PETSC_HAVE_MPI_FINALIZED)
854     PetscMPIInt flag;
855     ierr = MPI_Finalized(&flag);CHKERRQ(ierr);
856     if (flag) SETERRQ(PETSC_ERR_LIB,"MPI_Finalize() has already been called, even though MPI_Init() was called by PetscInitialize()");
857 #endif
858     ierr = MPI_Finalize();CHKERRQ(ierr);
859   }
860 
861   if(PETSC_ZOPEFD != NULL){
862     if (PETSC_ZOPEFD != PETSC_STDOUT) fprintf(PETSC_ZOPEFD, "<<<end>>>");
863     else fprintf(PETSC_STDOUT, "<<<end>>>");}
864 
865 /*
866 
867      Note: In certain cases PETSC_COMM_WORLD is never MPI_Comm_free()ed because
868    the communicator has some outstanding requests on it. Specifically if the
869    flag PETSC_HAVE_BROKEN_REQUEST_FREE is set (for IBM MPI implementation). See
870    src/vec/utils/vpscat.c. Due to this the memory allocated in PetscCommDuplicate()
871    is never freed as it should be. Thus one may obtain messages of the form
872    [ 1] 8 bytes PetscCommDuplicate() line 645 in src/sys/mpiu.c indicating the
873    memory was not freed.
874 
875 */
876   ierr = PetscMallocClear();CHKERRQ(ierr);
877   PetscInitializeCalled = PETSC_FALSE;
878   PetscFinalizeCalled   = PETSC_TRUE;
879   PetscFunctionReturn(ierr);
880 }
881 
882 /*
883      These may be used in code that ADIC is to be used on
884 */
885 
886 #undef __FUNCT__
887 #define __FUNCT__ "PetscGlobalMax"
888 /*@C
889       PetscGlobalMax - Computes the maximum value over several processors
890 
891      Collective on MPI_Comm
892 
893    Input Parameters:
894 +   local - the local value
895 -   comm - the processors that find the maximum
896 
897    Output Parameter:
898 .   result - the maximum value
899 
900    Level: intermediate
901 
902    Notes:
903      These functions are to be used inside user functions that are to be processed with
904    ADIC. PETSc will automatically provide differentiated versions of these functions
905 
906 .seealso: PetscGlobalMin(), PetscGlobalSum()
907 @*/
908 PetscErrorCode PETSC_DLLEXPORT PetscGlobalMax(PetscReal* local,PetscReal* result,MPI_Comm comm)
909 {
910   return MPI_Allreduce(local,result,1,MPIU_REAL,MPI_MAX,comm);
911 }
912 
913 #undef __FUNCT__
914 #define __FUNCT__ "PetscGlobalMin"
915 /*@C
916       PetscGlobalMin - Computes the minimum value over several processors
917 
918      Collective on MPI_Comm
919 
920    Input Parameters:
921 +   local - the local value
922 -   comm - the processors that find the minimum
923 
924    Output Parameter:
925 .   result - the minimum value
926 
927    Level: intermediate
928 
929    Notes:
930      These functions are to be used inside user functions that are to be processed with
931    ADIC. PETSc will automatically provide differentiated versions of these functions
932 
933 .seealso: PetscGlobalMax(), PetscGlobalSum()
934 @*/
935 PetscErrorCode PETSC_DLLEXPORT PetscGlobalMin(PetscReal* local,PetscReal* result,MPI_Comm comm)
936 {
937   return MPI_Allreduce(local,result,1,MPIU_REAL,MPI_MIN,comm);
938 }
939 
940 #undef __FUNCT__
941 #define __FUNCT__ "PetscGlobalSum"
942 /*@C
943       PetscGlobalSum - Computes the sum over sever processors
944 
945      Collective on MPI_Comm
946 
947    Input Parameters:
948 +   local - the local value
949 -   comm - the processors that find the sum
950 
951    Output Parameter:
952 .   result - the sum
953 
954    Level: intermediate
955 
956    Notes:
957      These functions are to be used inside user functions that are to be processed with
958    ADIC. PETSc will automatically provide differentiated versions of these functions
959 
960 .seealso: PetscGlobalMin(), PetscGlobalMax()
961 @*/
962 PetscErrorCode PETSC_DLLEXPORT PetscGlobalSum(PetscScalar* local,PetscScalar* result,MPI_Comm comm)
963 {
964   return MPI_Allreduce(local,result,1,MPIU_SCALAR,PetscSum_Op,comm);
965 }
966 
967 
968