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