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