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