xref: /petsc/src/sys/error/err.c (revision 92f119d60f7d2a2cf41595d5d0552580c733cbde)
1 
2 /*
3       Code that allows one to set the error handlers
4 */
5 #include <petsc/private/petscimpl.h>           /*I "petscsys.h" I*/
6 #include <petscviewer.h>
7 
8 typedef struct _EH *EH;
9 struct _EH {
10   PetscErrorCode (*handler)(MPI_Comm,int,const char*,const char*,PetscErrorCode,PetscErrorType,const char*,void*);
11   void           *ctx;
12   EH             previous;
13 };
14 
15 static EH eh = 0;
16 
17 /*@C
18    PetscEmacsClientErrorHandler - Error handler that uses the emacsclient program to
19     load the file where the error occured. Then calls the "previous" error handler.
20 
21    Not Collective
22 
23    Input Parameters:
24 +  comm - communicator over which error occured
25 .  line - the line number of the error (indicated by __LINE__)
26 .  file - the file in which the error was detected (indicated by __FILE__)
27 .  mess - an error text string, usually just printed to the screen
28 .  n - the generic error number
29 .  p - specific error number
30 -  ctx - error handler context
31 
32    Options Database Key:
33 .   -on_error_emacs <machinename>
34 
35    Level: developer
36 
37    Notes:
38    You must put (server-start) in your .emacs file for the emacsclient software to work
39 
40    Most users need not directly employ this routine and the other error
41    handlers, but can instead use the simplified interface SETERRQ, which has
42    the calling sequence
43 $     SETERRQ(PETSC_COMM_SELF,number,p,mess)
44 
45    Notes for experienced users:
46    Use PetscPushErrorHandler() to set the desired error handler.
47 
48    Developer Note:
49    Since this is an error handler it cannot call CHKERRQ(); thus we just return if an error is detected.
50 
51 
52 .seealso:  PetscPushErrorHandler(), PetscAttachDebuggerErrorHandler(),
53           PetscAbortErrorHandler()
54  @*/
55 PetscErrorCode  PetscEmacsClientErrorHandler(MPI_Comm comm,int line,const char *fun,const char *file,PetscErrorCode n,PetscErrorType p,const char *mess,void *ctx)
56 {
57   PetscErrorCode ierr;
58   char           command[PETSC_MAX_PATH_LEN];
59   const char     *pdir;
60   FILE           *fp;
61 
62   PetscFunctionBegin;
63   ierr = PetscGetPetscDir(&pdir);if (ierr) PetscFunctionReturn(ierr);
64   sprintf(command,"cd %s; emacsclient --no-wait +%d %s\n",pdir,line,file);
65 #if defined(PETSC_HAVE_POPEN)
66   ierr = PetscPOpen(MPI_COMM_WORLD,(char*)ctx,command,"r",&fp);if (ierr) PetscFunctionReturn(ierr);
67   ierr = PetscPClose(MPI_COMM_WORLD,fp);if (ierr) PetscFunctionReturn(ierr);
68 #else
69   SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP_SYS,"Cannot run external programs on this machine");
70 #endif
71   ierr = PetscPopErrorHandler();if (ierr) PetscFunctionReturn(ierr); /* remove this handler from the stack of handlers */
72   if (!eh) {
73     ierr = PetscTraceBackErrorHandler(comm,line,fun,file,n,p,mess,0);if (ierr) PetscFunctionReturn(ierr);
74   } else {
75     ierr = (*eh->handler)(comm,line,fun,file,n,p,mess,eh->ctx);if (ierr) PetscFunctionReturn(ierr);
76   }
77   PetscFunctionReturn(ierr);
78 }
79 
80 /*@C
81    PetscPushErrorHandler - Sets a routine to be called on detection of errors.
82 
83    Not Collective
84 
85    Input Parameters:
86 +  handler - error handler routine
87 -  ctx - optional handler context that contains information needed by the handler (for
88          example file pointers for error messages etc.)
89 
90    Calling sequence of handler:
91 $    int handler(MPI_Comm comm,int line,char *func,char *file,PetscErrorCode n,int p,char *mess,void *ctx);
92 
93 +  comm - communicator over which error occured
94 .  line - the line number of the error (indicated by __LINE__)
95 .  file - the file in which the error was detected (indicated by __FILE__)
96 .  n - the generic error number (see list defined in include/petscerror.h)
97 .  p - PETSC_ERROR_INITIAL if error just detected, otherwise PETSC_ERROR_REPEAT
98 .  mess - an error text string, usually just printed to the screen
99 -  ctx - the error handler context
100 
101    Options Database Keys:
102 +   -on_error_attach_debugger <noxterm,gdb or dbx>
103 -   -on_error_abort
104 
105    Level: intermediate
106 
107    Notes:
108    The currently available PETSc error handlers include PetscTraceBackErrorHandler(),
109    PetscAttachDebuggerErrorHandler(), PetscAbortErrorHandler(), and PetscMPIAbortErrorHandler(), PetscReturnErrorHandler().
110 
111    Fortran Notes:
112     You can only push one error handler from Fortran before poping it.
113 
114 .seealso: PetscPopErrorHandler(), PetscAttachDebuggerErrorHandler(), PetscAbortErrorHandler(), PetscTraceBackErrorHandler(), PetscPushSignalHandler()
115 
116 @*/
117 PetscErrorCode  PetscPushErrorHandler(PetscErrorCode (*handler)(MPI_Comm comm,int,const char*,const char*,PetscErrorCode,PetscErrorType,const char*,void*),void *ctx)
118 {
119   EH             neweh;
120   PetscErrorCode ierr;
121 
122   PetscFunctionBegin;
123   ierr = PetscNew(&neweh);CHKERRQ(ierr);
124   if (eh) neweh->previous = eh;
125   else    neweh->previous = 0;
126   neweh->handler = handler;
127   neweh->ctx     = ctx;
128   eh             = neweh;
129   PetscFunctionReturn(0);
130 }
131 
132 /*@
133    PetscPopErrorHandler - Removes the latest error handler that was
134    pushed with PetscPushErrorHandler().
135 
136    Not Collective
137 
138    Level: intermediate
139 
140 .seealso: PetscPushErrorHandler()
141 @*/
142 PetscErrorCode  PetscPopErrorHandler(void)
143 {
144   EH             tmp;
145   PetscErrorCode ierr;
146 
147   PetscFunctionBegin;
148   if (!eh) PetscFunctionReturn(0);
149   tmp  = eh;
150   eh   = eh->previous;
151   ierr = PetscFree(tmp);CHKERRQ(ierr);
152   PetscFunctionReturn(0);
153 }
154 
155 /*@C
156   PetscReturnErrorHandler - Error handler that causes a return to the current
157   level.
158 
159    Not Collective
160 
161    Input Parameters:
162 +  comm - communicator over which error occurred
163 .  line - the line number of the error (indicated by __LINE__)
164 .  file - the file in which the error was detected (indicated by __FILE__)
165 .  mess - an error text string, usually just printed to the screen
166 .  n - the generic error number
167 .  p - specific error number
168 -  ctx - error handler context
169 
170    Level: developer
171 
172    Notes:
173    Most users need not directly employ this routine and the other error
174    handlers, but can instead use the simplified interface SETERRQ, which has
175    the calling sequence
176 $     SETERRQ(comm,number,mess)
177 
178    Notes for experienced users:
179    This routine is good for catching errors such as zero pivots in preconditioners
180    or breakdown of iterative methods. It is not appropriate for memory violations
181    and similar errors.
182 
183    Use PetscPushErrorHandler() to set the desired error handler.  The
184    currently available PETSc error handlers include PetscTraceBackErrorHandler(),
185    PetscAttachDebuggerErrorHandler(), PetscAbortErrorHandler(), and PetscAbortErrorHandler()
186 
187 .seealso:  PetscPushErrorHandler(), PetscPopErrorHandler().
188  @*/
189 
190 PetscErrorCode  PetscReturnErrorHandler(MPI_Comm comm,int line,const char *fun,const char *file,PetscErrorCode n,PetscErrorType p,const char *mess,void *ctx)
191 {
192   PetscFunctionBegin;
193   PetscFunctionReturn(n);
194 }
195 
196 static char PetscErrorBaseMessage[1024];
197 /*
198        The numerical values for these are defined in include/petscerror.h; any changes
199    there must also be made here
200 */
201 static const char *PetscErrorStrings[] = {
202   /*55 */ "Out of memory",
203           "No support for this operation for this object type",
204           "No support for this operation on this system",
205   /*58 */ "Operation done in wrong order",
206   /*59 */ "Signal received",
207   /*60 */ "Nonconforming object sizes",
208           "Argument aliasing not permitted",
209           "Invalid argument",
210   /*63 */ "Argument out of range",
211           "Corrupt argument: https://www.mcs.anl.gov/petsc/documentation/faq.html#valgrind",
212           "Unable to open file",
213           "Read from file failed",
214           "Write to file failed",
215           "Invalid pointer",
216   /*69 */ "Arguments must have same type",
217   /*70 */ "Attempt to use a pointer that does not point to a valid accessible location",
218   /*71 */ "Zero pivot in LU factorization: https://www.mcs.anl.gov/petsc/documentation/faq.html#zeropivot",
219   /*72 */ "Floating point exception",
220   /*73 */ "Object is in wrong state",
221           "Corrupted Petsc object",
222           "Arguments are incompatible",
223           "Error in external library",
224   /*77 */ "Petsc has generated inconsistent data",
225           "Memory corruption: https://www.mcs.anl.gov/petsc/documentation/installation.html#valgrind",
226           "Unexpected data in file",
227   /*80 */ "Arguments must have same communicators",
228   /*81 */ "Zero pivot in Cholesky factorization: https://www.mcs.anl.gov/petsc/documentation/faq.html#zeropivot",
229           "  ",
230           "  ",
231           "Overflow in integer operation: https://www.mcs.anl.gov/petsc/documentation/faq.html#64-bit-indices",
232   /*85 */ "Null argument, when expecting valid pointer",
233   /*86 */ "Unknown type. Check for miss-spelling or missing package: https://www.mcs.anl.gov/petsc/documentation/installation.html#external",
234   /*87 */ "MPI library at runtime is not compatible with MPI used at compile time",
235   /*88 */ "Error in system call",
236   /*89 */ "Object Type not set: https://www.mcs.anl.gov/petsc/documentation/faq.html#objecttypenotset",
237   /*90 */ "  ",
238   /*   */ "  ",
239   /*92 */ "See https://www.mcs.anl.gov/petsc/documentation/linearsolvertable.html for possible LU and Cholesky solvers",
240   /*93 */ "You cannot overwrite this option since that will conflict with other previously set options",
241 };
242 
243 /*@C
244    PetscErrorMessage - returns the text string associated with a PETSc error code.
245 
246    Not Collective
247 
248    Input Parameter:
249 .   errnum - the error code
250 
251    Output Parameter:
252 +  text - the error message (NULL if not desired)
253 -  specific - the specific error message that was set with SETERRxxx() or PetscError().  (NULL if not desired)
254 
255    Level: developer
256 
257 .seealso:  PetscPushErrorHandler(), PetscAttachDebuggerErrorHandler(), PetscError(), SETERRQ(), CHKERRQ()
258           PetscAbortErrorHandler(), PetscTraceBackErrorHandler()
259  @*/
260 PetscErrorCode  PetscErrorMessage(int errnum,const char *text[],char **specific)
261 {
262   PetscFunctionBegin;
263   if (text && errnum > PETSC_ERR_MIN_VALUE && errnum < PETSC_ERR_MAX_VALUE) *text = PetscErrorStrings[errnum-PETSC_ERR_MIN_VALUE-1];
264   else if (text) *text = 0;
265 
266   if (specific) *specific = PetscErrorBaseMessage;
267   PetscFunctionReturn(0);
268 }
269 
270 #if defined(PETSC_CLANGUAGE_CXX)
271 /* C++ exceptions are formally not allowed to propagate through extern "C" code. In practice, far too much software
272  * would be broken if implementations did not handle it it some common cases. However, keep in mind
273  *
274  *   Rule 62. Don't allow exceptions to propagate across module boundaries
275  *
276  * in "C++ Coding Standards" by Sutter and Alexandrescu. (This accounts for part of the ongoing C++ binary interface
277  * instability.) Having PETSc raise errors as C++ exceptions was probably misguided and should eventually be removed.
278  *
279  * Here is the problem: You have a C++ function call a PETSc function, and you would like to maintain the error message
280  * and stack information from the PETSc error. You could make everyone write exactly this code in their C++, but that
281  * seems crazy to me.
282  */
283 #include <sstream>
284 #include <stdexcept>
285 static void PetscCxxErrorThrow() {
286   const char *str;
287   if (eh && eh->ctx) {
288     std::ostringstream *msg;
289     msg = (std::ostringstream*) eh->ctx;
290     str = msg->str().c_str();
291   } else str = "Error detected in C PETSc";
292 
293   throw std::runtime_error(str);
294 }
295 #endif
296 
297 /*@C
298    PetscError - Routine that is called when an error has been detected,
299    usually called through the macro SETERRQ(PETSC_COMM_SELF,).
300 
301    Not Collective
302 
303    Input Parameters:
304 +  comm - communicator over which error occurred.  ALL ranks of this communicator MUST call this routine
305 .  line - the line number of the error (indicated by __LINE__)
306 .  func - the function name in which the error was detected
307 .  file - the file in which the error was detected (indicated by __FILE__)
308 .  n - the generic error number
309 .  p - PETSC_ERROR_INITIAL indicates the error was initially detected, PETSC_ERROR_REPEAT indicates this is a traceback from a previously detected error
310 -  mess - formatted message string - aka printf
311 
312   Level: intermediate
313 
314    Notes:
315    Most users need not directly use this routine and the error handlers, but
316    can instead use the simplified interface SETERRQ, which has the calling
317    sequence
318 $     SETERRQ(comm,n,mess)
319 
320    Fortran Note:
321    This routine is used differently from Fortran
322 $    PetscError(MPI_Comm comm,PetscErrorCode n,PetscErrorType p,char *message)
323 
324    Experienced users can set the error handler with PetscPushErrorHandler().
325 
326    Developer Note: Since this is called after an error condition it should not be calling any error handlers (currently it ignores any error codes)
327    BUT this routine does call regular PETSc functions that may call error handlers, this is problematic and could be fixed by never calling other PETSc routines
328    but this annoying.
329 
330 .seealso: PetscTraceBackErrorHandler(), PetscPushErrorHandler(), SETERRQ(), CHKERRQ(), CHKMEMQ, SETERRQ1(), SETERRQ2(), PetscErrorMessage()
331 @*/
332 PetscErrorCode PetscError(MPI_Comm comm,int line,const char *func,const char *file,PetscErrorCode n,PetscErrorType p,const char *mess,...)
333 {
334   va_list        Argp;
335   size_t         fullLength;
336   char           buf[2048],*lbuf = 0;
337   PetscBool      ismain;
338   PetscErrorCode ierr;
339 
340   PetscFunctionBegin;
341   if (!func) func = "User provided function";
342   if (!file) file = "User file";
343   if (comm == MPI_COMM_NULL) comm = PETSC_COMM_SELF;
344 
345   /* Compose the message evaluating the print format */
346   if (mess) {
347     va_start(Argp,mess);
348     PetscVSNPrintf(buf,2048,mess,&fullLength,Argp);
349     va_end(Argp);
350     lbuf = buf;
351     if (p == PETSC_ERROR_INITIAL) PetscStrncpy(PetscErrorBaseMessage,lbuf,1023);
352   }
353 
354   if (!eh) ierr = PetscTraceBackErrorHandler(comm,line,func,file,n,p,lbuf,0);
355   else     ierr = (*eh->handler)(comm,line,func,file,n,p,lbuf,eh->ctx);
356 
357   /*
358       If this is called from the main() routine we call MPI_Abort() instead of
359     return to allow the parallel program to be properly shutdown.
360 
361     Since this is in the error handler we don't check the errors below. Of course,
362     PetscStrncmp() does its own error checking which is problamatic
363   */
364   PetscStrncmp(func,"main",4,&ismain);
365   if (ismain) MPI_Abort(PETSC_COMM_WORLD,(int)ierr);
366 
367 #if defined(PETSC_CLANGUAGE_CXX)
368   if (p == PETSC_ERROR_IN_CXX) {
369     PetscCxxErrorThrow();
370   }
371 #endif
372   PetscFunctionReturn(ierr);
373 }
374 
375 /* -------------------------------------------------------------------------*/
376 
377 /*@C
378     PetscIntView - Prints an array of integers; useful for debugging.
379 
380     Collective on PetscViewer
381 
382     Input Parameters:
383 +   N - number of integers in array
384 .   idx - array of integers
385 -   viewer - location to print array,  PETSC_VIEWER_STDOUT_WORLD, PETSC_VIEWER_STDOUT_SELF or 0
386 
387   Level: intermediate
388 
389     Developer Notes:
390     idx cannot be const because may be passed to binary viewer where byte swapping is done
391 
392 .seealso: PetscRealView()
393 @*/
394 PetscErrorCode  PetscIntView(PetscInt N,const PetscInt idx[],PetscViewer viewer)
395 {
396   PetscErrorCode ierr;
397   PetscInt       j,i,n = N/20,p = N % 20;
398   PetscBool      iascii,isbinary;
399   MPI_Comm       comm;
400 
401   PetscFunctionBegin;
402   if (!viewer) viewer = PETSC_VIEWER_STDOUT_SELF;
403   PetscValidHeaderSpecific(viewer,PETSC_VIEWER_CLASSID,3);
404   if (N) PetscValidIntPointer(idx,2);
405   ierr = PetscObjectGetComm((PetscObject)viewer,&comm);CHKERRQ(ierr);
406 
407   ierr = PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&iascii);CHKERRQ(ierr);
408   ierr = PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERBINARY,&isbinary);CHKERRQ(ierr);
409   if (iascii) {
410     ierr = PetscViewerASCIIPushSynchronized(viewer);CHKERRQ(ierr);
411     for (i=0; i<n; i++) {
412       ierr = PetscViewerASCIISynchronizedPrintf(viewer,"%D:",20*i);CHKERRQ(ierr);
413       for (j=0; j<20; j++) {
414         ierr = PetscViewerASCIISynchronizedPrintf(viewer," %D",idx[i*20+j]);CHKERRQ(ierr);
415       }
416       ierr = PetscViewerASCIISynchronizedPrintf(viewer,"\n");CHKERRQ(ierr);
417     }
418     if (p) {
419       ierr = PetscViewerASCIISynchronizedPrintf(viewer,"%D:",20*n);CHKERRQ(ierr);
420       for (i=0; i<p; i++) { ierr = PetscViewerASCIISynchronizedPrintf(viewer," %D",idx[20*n+i]);CHKERRQ(ierr);}
421       ierr = PetscViewerASCIISynchronizedPrintf(viewer,"\n");CHKERRQ(ierr);
422     }
423     ierr = PetscViewerFlush(viewer);CHKERRQ(ierr);
424     ierr = PetscViewerASCIIPopSynchronized(viewer);CHKERRQ(ierr);
425   } else if (isbinary) {
426     PetscMPIInt rank,size,*sizes,Ntotal,*displs,NN;
427     PetscInt    *array;
428 
429     ierr = PetscMPIIntCast(N,&NN);CHKERRQ(ierr);
430     ierr = MPI_Comm_rank(comm,&rank);CHKERRQ(ierr);
431     ierr = MPI_Comm_size(comm,&size);CHKERRQ(ierr);
432 
433     if (size > 1) {
434       if (rank) {
435         ierr = MPI_Gather(&NN,1,MPI_INT,0,0,MPI_INT,0,comm);CHKERRQ(ierr);
436         ierr = MPI_Gatherv((void*)idx,NN,MPIU_INT,0,0,0,MPIU_INT,0,comm);CHKERRQ(ierr);
437       } else {
438         ierr      = PetscMalloc1(size,&sizes);CHKERRQ(ierr);
439         ierr      = MPI_Gather(&NN,1,MPI_INT,sizes,1,MPI_INT,0,comm);CHKERRQ(ierr);
440         Ntotal    = sizes[0];
441         ierr      = PetscMalloc1(size,&displs);CHKERRQ(ierr);
442         displs[0] = 0;
443         for (i=1; i<size; i++) {
444           Ntotal   += sizes[i];
445           displs[i] =  displs[i-1] + sizes[i-1];
446         }
447         ierr = PetscMalloc1(Ntotal,&array);CHKERRQ(ierr);
448         ierr = MPI_Gatherv((void*)idx,NN,MPIU_INT,array,sizes,displs,MPIU_INT,0,comm);CHKERRQ(ierr);
449         ierr = PetscViewerBinaryWrite(viewer,array,Ntotal,PETSC_INT,PETSC_TRUE);CHKERRQ(ierr);
450         ierr = PetscFree(sizes);CHKERRQ(ierr);
451         ierr = PetscFree(displs);CHKERRQ(ierr);
452         ierr = PetscFree(array);CHKERRQ(ierr);
453       }
454     } else {
455       ierr = PetscViewerBinaryWrite(viewer,(void*) idx,N,PETSC_INT,PETSC_FALSE);CHKERRQ(ierr);
456     }
457   } else {
458     const char *tname;
459     ierr = PetscObjectGetName((PetscObject)viewer,&tname);CHKERRQ(ierr);
460     SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Cannot handle that PetscViewer of type %s",tname);
461   }
462   PetscFunctionReturn(0);
463 }
464 
465 /*@C
466     PetscRealView - Prints an array of doubles; useful for debugging.
467 
468     Collective on PetscViewer
469 
470     Input Parameters:
471 +   N - number of PetscReal in array
472 .   idx - array of PetscReal
473 -   viewer - location to print array,  PETSC_VIEWER_STDOUT_WORLD, PETSC_VIEWER_STDOUT_SELF or 0
474 
475   Level: intermediate
476 
477     Developer Notes:
478     idx cannot be const because may be passed to binary viewer where byte swapping is done
479 
480 .seealso: PetscIntView()
481 @*/
482 PetscErrorCode  PetscRealView(PetscInt N,const PetscReal idx[],PetscViewer viewer)
483 {
484   PetscErrorCode ierr;
485   PetscInt       j,i,n = N/5,p = N % 5;
486   PetscBool      iascii,isbinary;
487   MPI_Comm       comm;
488 
489   PetscFunctionBegin;
490   if (!viewer) viewer = PETSC_VIEWER_STDOUT_SELF;
491   PetscValidHeaderSpecific(viewer,PETSC_VIEWER_CLASSID,3);
492   PetscValidScalarPointer(idx,2);
493   ierr = PetscObjectGetComm((PetscObject)viewer,&comm);CHKERRQ(ierr);
494 
495   ierr = PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&iascii);CHKERRQ(ierr);
496   ierr = PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERBINARY,&isbinary);CHKERRQ(ierr);
497   if (iascii) {
498     ierr = PetscViewerASCIIPushSynchronized(viewer);CHKERRQ(ierr);
499     for (i=0; i<n; i++) {
500       ierr = PetscViewerASCIISynchronizedPrintf(viewer,"%2d:",(int)5*i);CHKERRQ(ierr);
501       for (j=0; j<5; j++) {
502         ierr = PetscViewerASCIISynchronizedPrintf(viewer," %12.4e",(double)idx[i*5+j]);CHKERRQ(ierr);
503       }
504       ierr = PetscViewerASCIISynchronizedPrintf(viewer,"\n");CHKERRQ(ierr);
505     }
506     if (p) {
507       ierr = PetscViewerASCIISynchronizedPrintf(viewer,"%2d:",(int)5*n);CHKERRQ(ierr);
508       for (i=0; i<p; i++) { PetscViewerASCIISynchronizedPrintf(viewer," %12.4e",(double)idx[5*n+i]);CHKERRQ(ierr);}
509       ierr = PetscViewerASCIISynchronizedPrintf(viewer,"\n");CHKERRQ(ierr);
510     }
511     ierr = PetscViewerFlush(viewer);CHKERRQ(ierr);
512     ierr = PetscViewerASCIIPopSynchronized(viewer);CHKERRQ(ierr);
513   } else if (isbinary) {
514     PetscMPIInt rank,size,*sizes,*displs, Ntotal,NN;
515     PetscReal   *array;
516 
517     ierr = PetscMPIIntCast(N,&NN);CHKERRQ(ierr);
518     ierr = MPI_Comm_rank(comm,&rank);CHKERRQ(ierr);
519     ierr = MPI_Comm_size(comm,&size);CHKERRQ(ierr);
520 
521     if (size > 1) {
522       if (rank) {
523         ierr = MPI_Gather(&NN,1,MPI_INT,0,0,MPI_INT,0,comm);CHKERRQ(ierr);
524         ierr = MPI_Gatherv((PetscReal*)idx,NN,MPIU_REAL,0,0,0,MPIU_REAL,0,comm);CHKERRQ(ierr);
525       } else {
526         ierr      = PetscMalloc1(size,&sizes);CHKERRQ(ierr);
527         ierr      = MPI_Gather(&NN,1,MPI_INT,sizes,1,MPI_INT,0,comm);CHKERRQ(ierr);
528         Ntotal    = sizes[0];
529         ierr      = PetscMalloc1(size,&displs);CHKERRQ(ierr);
530         displs[0] = 0;
531         for (i=1; i<size; i++) {
532           Ntotal   += sizes[i];
533           displs[i] =  displs[i-1] + sizes[i-1];
534         }
535         ierr = PetscMalloc1(Ntotal,&array);CHKERRQ(ierr);
536         ierr = MPI_Gatherv((PetscReal*)idx,NN,MPIU_REAL,array,sizes,displs,MPIU_REAL,0,comm);CHKERRQ(ierr);
537         ierr = PetscViewerBinaryWrite(viewer,array,Ntotal,PETSC_REAL,PETSC_TRUE);CHKERRQ(ierr);
538         ierr = PetscFree(sizes);CHKERRQ(ierr);
539         ierr = PetscFree(displs);CHKERRQ(ierr);
540         ierr = PetscFree(array);CHKERRQ(ierr);
541       }
542     } else {
543       ierr = PetscViewerBinaryWrite(viewer,(void*) idx,N,PETSC_REAL,PETSC_FALSE);CHKERRQ(ierr);
544     }
545   } else {
546     const char *tname;
547     ierr = PetscObjectGetName((PetscObject)viewer,&tname);CHKERRQ(ierr);
548     SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Cannot handle that PetscViewer of type %s",tname);
549   }
550   PetscFunctionReturn(0);
551 }
552 
553 /*@C
554     PetscScalarView - Prints an array of scalars; useful for debugging.
555 
556     Collective on PetscViewer
557 
558     Input Parameters:
559 +   N - number of scalars in array
560 .   idx - array of scalars
561 -   viewer - location to print array,  PETSC_VIEWER_STDOUT_WORLD, PETSC_VIEWER_STDOUT_SELF or 0
562 
563   Level: intermediate
564 
565     Developer Notes:
566     idx cannot be const because may be passed to binary viewer where byte swapping is done
567 
568 .seealso: PetscIntView(), PetscRealView()
569 @*/
570 PetscErrorCode  PetscScalarView(PetscInt N,const PetscScalar idx[],PetscViewer viewer)
571 {
572   PetscErrorCode ierr;
573   PetscInt       j,i,n = N/3,p = N % 3;
574   PetscBool      iascii,isbinary;
575   MPI_Comm       comm;
576 
577   PetscFunctionBegin;
578   if (!viewer) viewer = PETSC_VIEWER_STDOUT_SELF;
579   PetscValidHeader(viewer,3);
580   if (N) PetscValidScalarPointer(idx,2);
581   ierr = PetscObjectGetComm((PetscObject)viewer,&comm);CHKERRQ(ierr);
582 
583   ierr = PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&iascii);CHKERRQ(ierr);
584   ierr = PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERBINARY,&isbinary);CHKERRQ(ierr);
585   if (iascii) {
586     ierr = PetscViewerASCIIPushSynchronized(viewer);CHKERRQ(ierr);
587     for (i=0; i<n; i++) {
588       ierr = PetscViewerASCIISynchronizedPrintf(viewer,"%2d:",3*i);CHKERRQ(ierr);
589       for (j=0; j<3; j++) {
590 #if defined(PETSC_USE_COMPLEX)
591         ierr = PetscViewerASCIISynchronizedPrintf(viewer," (%12.4e,%12.4e)", (double)PetscRealPart(idx[i*3+j]),(double)PetscImaginaryPart(idx[i*3+j]));CHKERRQ(ierr);
592 #else
593         ierr = PetscViewerASCIISynchronizedPrintf(viewer," %12.4e",(double)idx[i*3+j]);CHKERRQ(ierr);
594 #endif
595       }
596       ierr = PetscViewerASCIISynchronizedPrintf(viewer,"\n");CHKERRQ(ierr);
597     }
598     if (p) {
599       ierr = PetscViewerASCIISynchronizedPrintf(viewer,"%2d:",3*n);CHKERRQ(ierr);
600       for (i=0; i<p; i++) {
601 #if defined(PETSC_USE_COMPLEX)
602         ierr = PetscViewerASCIISynchronizedPrintf(viewer," (%12.4e,%12.4e)", (double)PetscRealPart(idx[n*3+i]),(double)PetscImaginaryPart(idx[n*3+i]));CHKERRQ(ierr);
603 #else
604         ierr = PetscViewerASCIISynchronizedPrintf(viewer," %12.4e",(double)idx[3*n+i]);CHKERRQ(ierr);
605 #endif
606       }
607       ierr = PetscViewerASCIISynchronizedPrintf(viewer,"\n");CHKERRQ(ierr);
608     }
609     ierr = PetscViewerFlush(viewer);CHKERRQ(ierr);
610     ierr = PetscViewerASCIIPopSynchronized(viewer);CHKERRQ(ierr);
611   } else if (isbinary) {
612     PetscMPIInt size,rank,*sizes,Ntotal,*displs,NN;
613     PetscScalar *array;
614 
615     ierr = PetscMPIIntCast(N,&NN);CHKERRQ(ierr);
616     ierr = MPI_Comm_rank(comm,&rank);CHKERRQ(ierr);
617     ierr = MPI_Comm_size(comm,&size);CHKERRQ(ierr);
618 
619     if (size > 1) {
620       if (rank) {
621         ierr = MPI_Gather(&NN,1,MPI_INT,0,0,MPI_INT,0,comm);CHKERRQ(ierr);
622         ierr = MPI_Gatherv((void*)idx,NN,MPIU_SCALAR,0,0,0,MPIU_SCALAR,0,comm);CHKERRQ(ierr);
623       } else {
624         ierr      = PetscMalloc1(size,&sizes);CHKERRQ(ierr);
625         ierr      = MPI_Gather(&NN,1,MPI_INT,sizes,1,MPI_INT,0,comm);CHKERRQ(ierr);
626         Ntotal    = sizes[0];
627         ierr      = PetscMalloc1(size,&displs);CHKERRQ(ierr);
628         displs[0] = 0;
629         for (i=1; i<size; i++) {
630           Ntotal   += sizes[i];
631           displs[i] =  displs[i-1] + sizes[i-1];
632         }
633         ierr = PetscMalloc1(Ntotal,&array);CHKERRQ(ierr);
634         ierr = MPI_Gatherv((void*)idx,NN,MPIU_SCALAR,array,sizes,displs,MPIU_SCALAR,0,comm);CHKERRQ(ierr);
635         ierr = PetscViewerBinaryWrite(viewer,array,Ntotal,PETSC_SCALAR,PETSC_TRUE);CHKERRQ(ierr);
636         ierr = PetscFree(sizes);CHKERRQ(ierr);
637         ierr = PetscFree(displs);CHKERRQ(ierr);
638         ierr = PetscFree(array);CHKERRQ(ierr);
639       }
640     } else {
641       ierr = PetscViewerBinaryWrite(viewer,(void*) idx,N,PETSC_SCALAR,PETSC_FALSE);CHKERRQ(ierr);
642     }
643   } else {
644     const char *tname;
645     ierr = PetscObjectGetName((PetscObject)viewer,&tname);CHKERRQ(ierr);
646     SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Cannot handle that PetscViewer of type %s",tname);
647   }
648   PetscFunctionReturn(0);
649 }
650 
651 
652 
653 
654