xref: /petsc/doc/manual/other.md (revision af0e4c05a9d095ddef457b485b531206e788d438)
1# Other PETSc Features
2
3## PETSc on a process subset
4
5Users who wish to employ PETSc on only a subset of MPI processes
6within a larger parallel job, or who wish to use a “manager” process to
7coordinate the work of “worker” PETSc processes, should specify an
8alternative communicator for `PETSC_COMM_WORLD` by directly setting
9its value, for example to use an existing MPI communicator `comm`,
10
11```
12PETSC_COMM_WORLD = comm; /* To use a previously-defined MPI_Comm */
13```
14
15*before* calling `PetscInitialize()`, but, obviously, after calling
16`MPI_Init()`.
17
18(sec_options)=
19
20## Runtime Options
21
22Allowing the user to modify parameters and options easily at runtime is
23very desirable for many applications. PETSc provides a simple mechanism
24to enable such customization. To print a list of available options for a
25given program, simply specify the option `-help` at
26runtime, e.g.,
27
28```console
29$ mpiexec -n 1 ./ex1 -help
30```
31
32Note that all runtime options correspond to particular PETSc routines
33that can be explicitly called from within a program to set compile-time
34defaults. For many applications it is natural to use a combination of
35compile-time and runtime choices. For example, when solving a linear
36system, one could explicitly specify use of the Krylov subspace
37solver BiCGStab by calling
38
39```
40KSPSetType(ksp, KSPBCGS);
41```
42
43One could then override this choice at runtime with the option
44
45```
46-ksp_type tfqmr
47```
48
49to select the Transpose-Free QMR algorithm. (See
50{any}`ch_ksp` for details.)
51
52The remainder of this section discusses details of runtime options.
53
54(the_options_database_1)=
55
56### The Options Database
57
58Each PETSc process maintains a database of option names and values
59(stored as text strings). This database is generated with the command
60`PetscInitialize()`, which is listed below in its C/C++ and Fortran
61variants, respectively:
62
63```
64PetscInitialize(int *argc, char ***args, const char *file, const char *help); // C
65```
66
67```fortran
68call PetscInitialize(integer ierr) ! Fortran
69```
70
71The arguments `argc` and `args` (in the C/C++ version only) are the
72addresses of the usual command line arguments, while the `file` is a name
73of an optional file that can contain additional options. By default this file is
74called `.petscrc` in the user’s home directory. The user can also
75specify options via the environmental variable `PETSC_OPTIONS`. The
76options are processed in the following order:
77
781. file
792. environmental variable
803. command line
81
82Thus, the command line options supersede the environmental variable
83options, which in turn supersede the options file.
84
85The file format for specifying options is
86
87```none
88-optionname possible_value
89-anotheroptionname possible_value
90...
91```
92
93All of the option names must begin with a dash (-) and have no
94intervening spaces. Note that the option values cannot have intervening
95spaces either, and tab characters cannot be used between the option
96names and values. For
97uniformity throughout PETSc, we employ the format
98`-[prefix_]package_option` (for instance, `-ksp_type`,
99`-mat_view ::info`, or `-mg_levels_ksp_type`).
100
101Users can specify an alias for any option name (to avoid typing the
102sometimes lengthy default name) by adding an alias to the `.petscrc`
103file in the format
104
105```none
106alias -newname -oldname
107```
108
109For example,
110
111```none
112alias -kspt -ksp_type
113alias -sd -start_in_debugger
114```
115
116Comments can be placed in the `.petscrc` file by using `#` in the
117first column of a line.
118
119### Options Prefixes
120
121Options prefixes allow specific objects to be controlled from the
122options database. For instance, `PCMG` gives prefixes to its nested
123`KSP` objects; one may control the coarse grid solver by adding the
124`mg_coarse` prefix, for example `-mg_coarse_ksp_type preonly`. One
125may also use `KSPSetOptionsPrefix()`,`DMSetOptionsPrefix()` ,
126`SNESSetOptionsPrefix()`, `TSSetOptionsPrefix()`, and similar
127functions to assign custom prefixes, useful for applications with
128multiple or nested solvers.
129
130### Adding options from a file
131
132PETSc can load additional options from a file using `PetscOptionsInsertFile()`,
133which can also be used from the command line, e.g. `-options_file my_options.opts`.
134
135One can also use YAML files with `PetscOptionsInsertFileYAML()`.
136For example, the following file:
137
138```{literalinclude} /../src/sys/tests/ex47-options.yaml
139:language: yaml
140```
141
142corresponds to the following PETSc options:
143
144```{literalinclude} /../src/sys/tests/output/ex47_3_options.out
145:end-before: '#End'
146:language: none
147:start-after: '#'
148```
149
150With `-options_file`, PETSc will parse the file as YAML if it ends in a standard
151YAML or JSON [^json] extension or if one uses a `:yaml` postfix,
152e.g. `-options_file my_options.yaml` or `-options_file my_options.txt:yaml`
153
154PETSc will also check the first line of the options file itself and
155parse the file as YAML if it matches certain criteria, for example.
156
157```{literalinclude} /../src/sys/tests/ex47-yaml_tag
158:language: yaml
159```
160
161and
162
163```{literalinclude} /../src/sys/tests/ex47-yaml_doc
164:language: yaml
165```
166
167both correspond to options
168
169```{literalinclude} /../src/sys/tests/output/ex47_2_auto.out
170:end-before: '#End'
171:language: none
172:start-after: '#'
173```
174
175### User-Defined PetscOptions
176
177Any subroutine in a PETSc program can add entries to the database with
178the command
179
180```
181PetscOptionsSetValue(PetscOptions options, char *name, char *value);
182```
183
184though this is rarely done. To locate options in the database, one
185should use the commands
186
187```
188PetscOptionsHasName(PetscOptions options, char *pre, char *name, PetscBool *flg);
189PetscOptionsGetInt(PetscOptions options, char *pre, char *name, PetscInt *value, PetscBool *flg);
190PetscOptionsGetReal(PetscOptions options, char *pre, char *name, PetscReal *value, PetscBool *flg);
191PetscOptionsGetString(PetscOptions options, char *pre, char *name, char *value, size_t maxlen, PetscBool  *flg);
192PetscOptionsGetStringArray(PetscOptions options, char *pre, char *name, char **values, PetscInt *nmax, PetscBool *flg);
193PetscOptionsGetIntArray(PetscOptions options, char *pre, char *name, PetscInt *value, PetscInt *nmax, PetscBool *flg);
194PetscOptionsGetRealArray(PetscOptions options, char *pre, char *name, PetscReal *value, PetscInt *nmax, PetscBool *flg);
195```
196
197All of these routines set `flg=PETSC_TRUE` if the corresponding option
198was found, `flg=PETSC_FALSE` if it was not found. The optional
199argument `pre` indicates that the true name of the option is the given
200name (with the dash “-” removed) prepended by the prefix `pre`.
201Usually `pre` should be set to `NULL` (or `PETSC_NULL_CHARACTER`
202for Fortran); its purpose is to allow someone to rename all the options
203in a package without knowing the names of the individual options. For
204example, when using block Jacobi preconditioning, the `KSP` and `PC`
205methods used on the individual blocks can be controlled via the options
206`-sub_ksp_type` and `-sub_pc_type`.
207
208### Keeping Track of Options
209
210One useful means of keeping track of user-specified runtime options is
211use of `-options_view`, which prints to `stdout` during
212`PetscFinalize()` a table of all runtime options that the user has
213specified. A related option is `-options_left`, which prints the
214options table and indicates any options that have *not* been requested
215upon a call to `PetscFinalize()`. This feature is useful to check
216whether an option has been activated for a particular PETSc object (such
217as a solver or matrix format), or whether an option name may have been
218accidentally misspelled.
219
220The option `-options_monitor` `<viewer>` turns on the default monitoring of options.
221`PetscOptionsMonitorSet()` can be used to provide custom monitors.
222The option `-options_monitor_cancel` prevents any monitoring by monitors set with `PetscOptionsMonitorSet()` (but not that set with `-options_monitor`).
223
224(sec_viewers)=
225
226## Viewers: Looking at PETSc Objects
227
228PETSc employs a consistent scheme for examining, printing, and saving
229objects through commands of the form
230
231```
232XXXView(XXX obj, PetscViewer viewer);
233```
234
235Here `obj` is a PETSc object of type `XXX`, where `XXX` is
236`Mat`, `Vec`, `SNES`, etc. There are several predefined viewers.
237
238- Passing in a zero (`0`) for the viewer causes the object to be
239  printed to the screen; this is useful when viewing an object in a
240  debugger but should be avoided in source code.
241- `PETSC_VIEWER_STDOUT_SELF` and `PETSC_VIEWER_STDOUT_WORLD` causes
242  the object to be printed to the screen.
243- `PETSC_VIEWER_DRAW_SELF` `PETSC_VIEWER_DRAW_WORLD` causes the
244  object to be drawn in a default X window.
245- Passing in a viewer obtained by `PetscViewerDrawOpen()` causes the
246  object to be displayed graphically. See
247  {any}`sec_graphics` for more on PETSc’s graphics support.
248- To save an object to a file in ASCII format, the user creates the
249  viewer object with the command
250  `PetscViewerASCIIOpen(MPI_Comm comm, char* file, PetscViewer *viewer)`.
251  This object is analogous to `PETSC_VIEWER_STDOUT_SELF` (for a
252  communicator of `MPI_COMM_SELF`) and `PETSC_VIEWER_STDOUT_WORLD`
253  (for a parallel communicator).
254- To save an object to a file in binary format, the user creates the
255  viewer object with the command
256  `PetscViewerBinaryOpen(MPI_Comm comm, char* file, PetscViewerBinaryType type, PetscViewer *viewer)`.
257  Details of binary I/O are discussed below.
258- Vector and matrix objects can be passed to a running MATLAB process
259  with a viewer created by
260  `PetscViewerSocketOpen(MPI_Comm comm, char *machine, int port, PetscViewer *viewer)`.
261  See {any}`sec_matlabsocket`.
262
263The user can control the format of ASCII printed objects with viewers
264created by `PetscViewerASCIIOpen()` by calling
265
266```
267PetscViewerPushFormat(PetscViewer viewer, PetscViewerFormat format);
268```
269
270Formats include `PETSC_VIEWER_DEFAULT`, `PETSC_VIEWER_ASCII_MATLAB`,
271and `PETSC_VIEWER_ASCII_IMPL`. The implementation-specific format,
272`PETSC_VIEWER_ASCII_IMPL`, displays the object in the most natural way
273for a particular implementation.
274
275The routines
276
277```
278PetscViewerPushFormat(PetscViewer viewer, PetscViewerFormat format);
279PetscViewerPopFormat(PetscViewer viewer);
280```
281
282allow one to temporarily change the format of a viewer.
283
284As discussed above, one can output PETSc objects in binary format by
285first opening a binary viewer with `PetscViewerBinaryOpen()` and then
286using `MatView()`, `VecView()`, etc. The corresponding routines for
287input of a binary object have the form `XXXLoad()`. In particular,
288matrix and vector binary input is handled by the following routines:
289
290```
291MatLoad(Mat newmat, PetscViewer viewer);
292VecLoad(Vec newvec, PetscViewer viewer);
293```
294
295These routines generate parallel matrices and vectors if the viewer’s
296communicator has more than one process. The particular matrix and vector
297formats are determined from the options database; see the manual pages
298for details.
299
300One can provide additional information about matrix data for matrices
301stored on disk by providing an optional file `matrixfilename.info`,
302where `matrixfilename` is the name of the file containing the matrix.
303The format of the optional file is the same as the `.petscrc` file and
304can (currently) contain the following:
305
306```none
307-matload_block_size <bs>
308```
309
310The block size indicates the size of blocks to use if the matrix is read
311into a block oriented data structure (for example, `MATMPIBAIJ`). The
312diagonal information `s1,s2,s3,...` indicates which (block) diagonals
313in the matrix have nonzero values. The info file is automatically created
314when `VecView()` or `MatView()` is used with a binary viewer; hence if you
315save a matrix with a given block size with `MatView()`, then a `MatLoad()`
316on that file will automatically use the saved block size.
317
318(sec_viewfromoptions)=
319
320### Viewing From Options
321
322Command-line options provide a particularly convenient way to view PETSc
323objects. All options of the form `-xxx_view` accept
324colon(`:`)-separated compound arguments which specify a viewer type,
325format, and/or destination (e.g. file name or socket) if appropriate.
326For example, to quickly export a binary file containing a matrix, one
327may use `-mat_view binary:matrix.out`, or to output to a
328MATLAB-compatible ASCII file, one may use
329`-mat_view ascii:matrix.m:ascii_matlab`. See the
330`PetscOptionsCreateViewer()` man page for full details, as well as the
331`XXXViewFromOptions()` man pages (for instance,
332`PetscDrawSetFromOptions()`) for many other convenient command-line
333options.
334
335### Using Viewers to Check Load Imbalance
336
337The `PetscViewer` format `PETSC_VIEWER_LOAD_BALANCE` will cause certain
338objects to display simple measures of their imbalance. For example
339
340```none
341-n 4 ./ex32 -ksp_view_mat ::load_balance
342```
343
344will display
345
346```none
347Nonzeros: Min 162  avg 168  max 174
348```
349
350indicating that one process has 162 nonzero entries in the matrix, the
351average number of nonzeros per process is 168 and the maximum number of
352nonzeros is 174. Similar for vectors one can see the load balancing
353with, for example,
354
355```none
356-n 4 ./ex32 -ksp_view_rhs ::load_balance
357```
358
359The measurements of load balancing can also be done within the program
360with calls to the appropriate object viewer with the viewer format
361`PETSC_VIEWER_LOAD_BALANCE`.
362
363(sec_saws)=
364
365## Using SAWs with PETSc
366
367The Scientific Application Web server, SAWs [^saws], allows one to monitor
368running PETSc applications from a browser. To use SAWs you must `configure` PETSc with
369the option `--download-saws`. Options to use SAWs include
370
371- `-saws_options` - allows setting values in the PETSc options
372  database via the browser (works only on one process).
373- `-stack_view saws` - allows monitoring the current stack frame that
374  PETSc is in; refresh to see the new location.
375- `-snes_monitor_saws, -ksp_monitor_saws` - monitor the solvers’
376  iterations from the web browser.
377
378For each of these you need to point your browser to
379`http://hostname:8080`, for example `http://localhost:8080`. Options
380that control behavior of SAWs include
381
382- `-saws_log filename` - log all SAWs actions in a file.
383- `-saws_https certfile` - use HTTPS instead of HTTP with a
384  certificate.
385- `-saws_port_auto_select` - have SAWs pick a port number instead of
386  using 8080.
387- `-saws_port port` - use `port` instead of 8080.
388- `-saws_root rootdirectory` - local directory to which the SAWs
389  browser will have read access.
390- `-saws_local` - use the local file system to obtain the SAWS
391  javascript files (they much be in `rootdirectory/js`).
392
393Also see the manual pages for `PetscSAWsBlock()`,
394`PetscObjectSAWsTakeAccess()`, `PetscObjectSAWsGrantAccess()`,
395`PetscObjectSAWsSetBlock()`, `PetscStackSAWsGrantAccess()`
396`PetscStackSAWsTakeAccess()`, `KSPMonitorSAWs()`, and
397`SNESMonitorSAWs()`.
398
399(sec_debugging)=
400
401## Debugging
402
403PETSc programs may be debugged using one of the two options below.
404
405- `-start_in_debugger` `[noxterm,dbx,xxgdb,xdb,xldb,lldb]`
406  `[-display name]` - start all processes in debugger
407- `-on_error_attach_debugger` `[noxterm,dbx,xxgdb,xdb,xldb,lldb]`
408  `[-display name]` - start debugger only on encountering an error
409
410Note that, in general, debugging MPI programs cannot be done in the
411usual manner of starting the programming in the debugger (because then
412it cannot set up the MPI communication and remote processes).
413
414By default on Linux systems the GNU debugger `gdb` is used, on macOS systems `lldb` is used
415
416By default, the debugger will be started in a new
417xterm (Apple Terminal on macOS), to enable running separate debuggers on each process, unless the
418option `noxterm` is used. In order to handle the MPI startup phase,
419the debugger command `cont` should be used to continue execution of
420the program within the debugger. Rerunning the program through the
421debugger requires terminating the first job and restarting the
422processor(s); the usual `run` option in the debugger will not
423correctly handle the MPI startup and should not be used. Not all
424debuggers work on all machines, the user may have to experiment to find
425one that works correctly.
426
427You can select a subset of the processes to be debugged (the rest just
428run without the debugger) with the option
429
430```none
431-debugger_ranks rank1,rank2,...
432```
433
434where you simply list the ranks you want the debugger to run with.
435
436(sec_errors)=
437
438## Error Handling
439
440Errors are handled through the routine `PetscError()`. This routine
441checks a stack of error handlers and calls the one on the top. If the
442stack is empty, it selects `PetscTraceBackErrorHandler()`, which tries
443to print a traceback. A new error handler can be put on the stack with
444
445```
446PetscPushErrorHandler(PetscErrorCode (*HandlerFunction)(int line, char *dir, char *file, char *message, int number, void*), void *HandlerContext)
447```
448
449The arguments to `HandlerFunction()` are the line number where the
450error occurred, the file in which the error was detected, the
451corresponding directory, the error message, the error integer, and the
452`HandlerContext.` The routine
453
454```
455PetscPopErrorHandler()
456```
457
458removes the last error handler and discards it.
459
460PETSc provides two additional error handlers besides
461`PetscTraceBackErrorHandler()`:
462
463```
464PetscAbortErrorHandler()
465PetscAttachDebuggerErrorHandler()
466```
467
468The function `PetscAbortErrorHandler()` calls abort on encountering an
469error, while `PetscAttachDebuggerErrorHandler()` attaches a debugger to the
470running process if an error is detected. At runtime, these error
471handlers can be set with the options `-on_error_abort` or
472`-on_error_attach_debugger` `[noxterm, dbx, xxgdb, xldb]`
473`[-display DISPLAY]`.
474
475All PETSc calls can be traced (useful for determining where a program is
476hanging without running in the debugger) with the option
477
478```none
479-log_trace [filename]
480```
481
482where `filename` is optional. By default the traces are printed to the
483screen. This can also be set with the command
484`PetscLogTraceBegin(FILE*)`.
485
486It is also possible to trap signals by using the command
487
488```
489PetscPushSignalHandler(PetscErrorCode (*Handler)(int, PetscCtx), PetscCtx ctx);
490```
491
492The default handler `PetscSignalHandlerDefault()` calls
493`PetscError()` and then terminates. In general, a signal in PETSc
494indicates a catastrophic failure. Any error handler that the user
495provides should try to clean up only before exiting. By default all
496PETSc programs turn on the default PETSc signal handler in `PetscInitialize()`,
497this can be prevented with the option `-no_signal_handler` that can be provided on the command line,
498in the ~./petscrc file, or with the call
499
500```
501PetscCall(PetscOptionsSetValue(NULL, "-no_signal_handler", "true"));
502```
503
504Once the first PETSc signal handler has been pushed it is impossible to go back to
505to a signal handler that was set directly by the user with the UNIX signal handler API or by
506the loader.
507
508Some Fortran compilers/loaders cause, by default, a traceback of the Fortran call stack when a
509segmentation violation occurs to be printed. This is handled by them setting a special signal handler
510when the program is started up. This feature is useful for debugging without needing to start up a debugger.
511If `PetscPushSignalHandler()` has been called this traceback will not occur, hence if the Fortran traceback
512is desired one should put
513
514```
515PetscCallA(PetscOptionsSetValue(PETSC_NULL_OPTIONS,"-no_signal_handler","true",ierr))
516```
517
518**before** the call to `PetscInitialize()`. This prevents PETSc from defaulting to using a signal handler.
519
520There is a separate signal handler for floating-point exceptions. The
521option `-fp_trap` turns on the floating-point trap at runtime, and the
522routine
523
524```
525PetscFPTrapPush(PetscFPTrap flag);
526```
527
528can be used within a program. A `flag` of `PETSC_FP_TRAP_ON` indicates that
529floating-point exceptions should be trapped, while a value of
530`PETSC_FP_TRAP_OFF` (the default) indicates that they should be
531ignored.
532
533```
534PetscFPTrapPop(void);
535```
536
537should be used to revert to the previous handling of floating point exceptions before the call to `PetscFPTrapPush()`.
538
539A small set of macros is used to make the error handling lightweight.
540These macros are used throughout the PETSc libraries and can be employed
541by the application programmer as well. When an error is first detected,
542one should set it by calling
543
544```
545SETERRQ(MPI_Comm comm, PetscErrorCode flag, char *message);
546```
547
548The user should check the return codes for all PETSc routines (and
549possibly user-defined routines as well) with
550
551```
552PetscCall(PetscRoutine(...));
553```
554
555Likewise, all memory allocations should be checked with
556
557```
558PetscCall(PetscMalloc1(n, &ptr));
559```
560
561If this procedure is followed throughout all of the user’s libraries and
562codes, any error will by default generate a clean traceback of the
563location of the error.
564
565Note that the macro `PETSC_FUNCTION_NAME` is used to keep track of
566routine names during error tracebacks. Users need not worry about this
567macro in their application codes; however, users can take advantage of
568this feature if desired by setting this macro before each user-defined
569routine that may call `SETERRQ()`, `PetscCall()`. A simple example of
570usage is given below.
571
572```
573PetscErrorCode MyRoutine1()
574{
575    /* Declarations Here */
576    PetscFunctionBeginUser;
577    /* code here */
578    PetscFunctionReturn(PETSC_SUCCESS);
579}
580```
581
582(sec_complex)=
583
584## Numbers
585
586PETSc supports the use of complex numbers in application programs
587written in C, C++, and Fortran. To do so, we employ either the C99
588`complex` type or the C++ versions of the PETSc libraries in which the
589basic “scalar” datatype, given in PETSc codes by `PetscScalar`, is
590defined as `complex` (or `complex<double>` for machines using
591templated complex class libraries). To work with complex numbers, the
592user should run `configure` with the additional option
593`--with-scalar-type=complex`. The
594{doc}`installation instructions </install/index>`
595provide detailed instructions for installing PETSc. You can use
596`--with-clanguage=c` (the default) to use the C99 complex numbers or
597`--with-clanguage=c++` to use the C++ complex type [^cxx-note].
598
599Recall that each configuration of the PETSc libraries is stored in a different
600directory, given by `$PETSC_DIR/$PETSC_ARCH`
601according to the architecture. Thus, the libraries for complex numbers
602are maintained separately from those for real numbers. When using any of
603the complex numbers versions of PETSc, *all* vector and matrix elements
604are treated as complex, even if their imaginary components are zero. Of
605course, one can elect to use only the real parts of the complex numbers
606when using the complex versions of the PETSc libraries; however, when
607working *only* with real numbers in a code, one should use a version of
608PETSc for real numbers for best efficiency.
609
610The program
611<a href="PETSC_DOC_OUT_ROOT_PLACEHOLDER/src/ksp/ksp/tutorials/ex11.c.html">KSP Tutorial ex11</a>
612solves a linear system with a complex coefficient matrix. Its Fortran
613counterpart is
614<a href="PETSC_DOC_OUT_ROOT_PLACEHOLDER/src/ksp/ksp/tutorials/ex11f.F90.html">KSP Tutorial ex11f</a>.
615
616## Parallel Communication
617
618When used in a message-passing environment, all communication within
619PETSc is done through MPI, the message-passing interface standard
620{cite}`mpi-final`. Any file that includes `petscsys.h` (or
621any other PETSc include file) can freely use any MPI routine.
622
623(sec_graphics)=
624
625## Graphics
626
627The PETSc graphics library is not intended to compete with high-quality
628graphics packages. Instead, it is intended to be easy to use
629interactively with PETSc programs. We urge users to generate their
630publication-quality graphics using a professional graphics package. If a
631user wants to hook certain packages into PETSc, he or she should send a
632message to
633[petsc-maint@mcs.anl.gov](mailto:petsc-maint@mcs.anl.gov); we
634will see whether it is reasonable to try to provide direct interfaces.
635
636### Windows as PetscViewers
637
638For drawing predefined PETSc objects such as matrices and vectors, one
639may first create a viewer using the command
640
641```
642PetscViewerDrawOpen(MPI_Comm comm, char *display, char *title, int x, int y, int w, int h, PetscViewer *viewer);
643```
644
645This viewer may be passed to any of the `XXXView()` routines.
646Alternately, one may use command-line options to quickly specify viewer
647formats, including `PetscDraw`-based ones; see
648{any}`sec_viewfromoptions`.
649
650To draw directly into the viewer, one must obtain the `PetscDraw`
651object with the command
652
653```
654PetscViewerDrawGetDraw(PetscViewer viewer, PetscDraw *draw);
655```
656
657Then one can call any of the `PetscDrawXXX()` commands on the `draw`
658object. If one obtains the `draw` object in this manner, one does not
659call the `PetscDrawOpenX()` command discussed below.
660
661Predefined viewers, `PETSC_VIEWER_DRAW_WORLD` and
662`PETSC_VIEWER_DRAW_SELF`, may be used at any time. Their initial use
663will cause the appropriate window to be created.
664
665Implementations using OpenGL, TikZ, and other formats may be selected
666with `PetscDrawSetType()`. PETSc can also produce movies; see
667`PetscDrawSetSaveMovie()`, and note that command-line options can also
668be convenient; see the `PetscDrawSetFromOptions()` man page.
669
670By default, PETSc drawing tools employ a private colormap, which
671remedies the problem of poor color choices for contour plots due to an
672external program’s mangling of the colormap. Unfortunately, this may
673cause flashing of colors as the mouse is moved between the PETSc windows
674and other windows. Alternatively, a shared colormap can be used via the
675option `-draw_x_shared_colormap`.
676
677### Simple PetscDrawing
678
679With the default format, one can open a window that is not associated
680with a viewer directly under the X11 Window System with the
681command
682
683```
684PetscDrawCreate(MPI_Comm comm, char *display, char *title, int x, int y, int w, int h, PetscDraw *win);
685PetscDrawSetFromOptions(win);
686```
687
688All drawing routines are performed relative to the window’s coordinate
689system and viewport. By default, the drawing coordinates are from
690`(0,0)` to `(1,1)`, where `(0,0)` indicates the lower left corner
691of the window. The application program can change the window coordinates
692with the command
693
694```
695PetscDrawSetCoordinates(PetscDraw win, PetscReal xl, PetscReal yl, PetscReal xr, PetscReal yr);
696```
697
698By default, graphics will be drawn in the entire window. To restrict the
699drawing to a portion of the window, one may use the command
700
701```
702PetscDrawSetViewPort(PetscDraw win, PetscReal xl, PetscReal yl, PetscReal xr, PetscReal yr);
703```
704
705These arguments, which indicate the fraction of the window in which the
706drawing should be done, must satisfy
707$0 \leq {\tt xl} \leq {\tt xr} \leq 1$ and
708$0 \leq {\tt yl} \leq {\tt yr} \leq 1.$
709
710To draw a line, one uses the command
711
712```
713PetscDrawLine(PetscDraw win, PetscReal xl, PetscReal yl, PetscReal xr, PetscReal yr, int cl);
714```
715
716The argument `cl` indicates the color (which is an integer between 0
717and 255) of the line. A list of predefined colors may be found in
718`include/petscdraw.h` and includes `PETSC_DRAW_BLACK`,
719`PETSC_DRAW_RED`, `PETSC_DRAW_BLUE` etc.
720
721To ensure that all graphics actually have been displayed, one should use
722the command
723
724```
725PetscDrawFlush(PetscDraw win);
726```
727
728When displaying by using double buffering, which is set with the command
729
730```
731PetscDrawSetDoubleBuffer(PetscDraw win);
732```
733
734*all* processes must call
735
736```
737PetscDrawFlush(PetscDraw win);
738```
739
740in order to swap the buffers. From the options database one may use
741`-draw_pause` `n`, which causes the PETSc application to pause `n`
742seconds at each `PetscDrawPause()`. A time of `-1` indicates that
743the application should pause until receiving mouse input from the user.
744
745Text can be drawn with commands
746
747```
748PetscDrawString(PetscDraw win, PetscReal x, PetscReal y, int color, char *text);
749PetscDrawStringVertical(PetscDraw win, PetscReal x, PetscReal y, int color, const char *text);
750PetscDrawStringCentered(PetscDraw win, PetscReal x, PetscReal y, int color, const char *text);
751PetscDrawStringBoxed(PetscDraw draw, PetscReal sxl, PetscReal syl, int sc, int bc, const char text[], PetscReal *w, PetscReal *h);
752```
753
754The user can set the text font size or determine it with the commands
755
756```
757PetscDrawStringSetSize(PetscDraw win, PetscReal width, PetscReal height);
758PetscDrawStringGetSize(PetscDraw win, PetscReal *width, PetscReal *height);
759```
760
761### Line Graphs
762
763PETSc includes a set of routines for manipulating simple two-dimensional
764graphs. These routines, which begin with `PetscDrawAxisDraw()`, are
765usually not used directly by the application programmer. Instead, the
766programmer employs the line graph routines to draw simple line graphs.
767As shown in the {ref}`listing below <listing_draw_test_ex3>`, line
768graphs are created with the command
769
770```
771PetscDrawLGCreate(PetscDraw win, PetscInt ncurves, PetscDrawLG *ctx);
772```
773
774The argument `ncurves` indicates how many curves are to be drawn.
775Points can be added to each of the curves with the command
776
777```
778PetscDrawLGAddPoint(PetscDrawLG ctx, PetscReal *x, PetscReal *y);
779```
780
781The arguments `x` and `y` are arrays containing the next point value
782for each curve. Several points for each curve may be added with
783
784```
785PetscDrawLGAddPoints(PetscDrawLG ctx, PetscInt n, PetscReal **x, PetscReal **y);
786```
787
788The line graph is drawn (or redrawn) with the command
789
790```
791PetscDrawLGDraw(PetscDrawLG ctx);
792```
793
794A line graph that is no longer needed can be destroyed with the command
795
796```
797PetscDrawLGDestroy(PetscDrawLG *ctx);
798```
799
800To plot new curves, one can reset a linegraph with the command
801
802```
803PetscDrawLGReset(PetscDrawLG ctx);
804```
805
806The line graph automatically determines the range of values to display
807on the two axes. The user can change these defaults with the command
808
809```
810PetscDrawLGSetLimits(PetscDrawLG ctx, PetscReal xmin, PetscReal xmax, PetscReal ymin, PetscReal ymax);
811```
812
813It is also possible to change the display of the axes and to label them.
814This procedure is done by first obtaining the axes context with the
815command
816
817```
818PetscDrawLGGetAxis(PetscDrawLG ctx, PetscDrawAxis *axis);
819```
820
821One can set the axes’ colors and labels, respectively, by using the
822commands
823
824```
825PetscDrawAxisSetColors(PetscDrawAxis axis, int axis_lines, int ticks, int text);
826PetscDrawAxisSetLabels(PetscDrawAxis axis, char *top, char *x, char *y);
827```
828
829It is possible to turn off all graphics with the option `-nox`. This
830will prevent any windows from being opened or any drawing actions to be
831done. This is useful for running large jobs when the graphics overhead
832is too large, or for timing.
833
834The full example, <a href="PETSC_DOC_OUT_ROOT_PLACEHOLDER/src/sys/classes/draw/tests/ex3.c.html">Draw Test ex3</a>,
835follows.
836
837(listing_draw_test_ex3)=
838
839:::{admonition} Listing: `src/classes/draw/tests/ex3.c`
840:name: snes-ex1
841
842```{literalinclude} /../src/sys/classes/draw/tests/ex3.c
843:end-before: /*TEST
844```
845:::
846
847### Graphical Convergence Monitor
848
849For both the linear and nonlinear solvers default routines allow one to
850graphically monitor convergence of the iterative method. These are
851accessed via the command line with `-ksp_monitor draw::draw_lg` and
852`-snes_monitor draw::draw_lg`. See also
853{any}`sec_kspmonitor` and {any}`sec_snesmonitor`.
854
855### Disabling Graphics at Compile Time
856
857To disable all X-window-based graphics, run `configure` with the
858additional option `--with-x=0`
859
860(sec_developer_environments)=
861
862# Developer Environments
863
864Coding styles for most editors or integrated development environments are defined with [EditorConfig](https://editorconfig.org') in `.editorconfig`.
865
866## Emacs Users
867
868Many PETSc developers use Emacs, which can be used as a "simple" text editor or a comprehensive development environment.
869For a more integrated development environment, we recommend using [lsp-mode](https://emacs-lsp.github.io/lsp-mode/) (or [eglot](https://github.com/joaotavora/eglot)) with [clangd](https://clangd.llvm.org/).
870The most convenient way to teach clangd what compilation flags to use is to install [Bear](https://github.com/rizsotto/Bear) ("build ear") and run:
871
872```
873bear make -B
874```
875
876which will do a complete rebuild (`-B`) of PETSc and capture the compilation commands in a file named `compile_commands.json`, which will be automatically picked up by clangd.
877You can use the same procedure when building examples or your own project.
878It can also be used with any other editor that supports clangd, including VS Code and Vim.
879When lsp-mode is accompanied by [flycheck](https://www.flycheck.org/en/latest/), Emacs will provide real-time feedback and syntax checking, along with refactoring tools provided by clangd.
880
881The easiest way to install packages in recent Emacs is to use the "Options" menu to select "Manage Emacs Packages".
882
883### Tags
884
885It is sometimes useful to cross-reference tags across projects.
886Regardless of whether you use lsp-mode, it can be useful to use [GNU Global](https://www.gnu.org/software/global/) (install `gtags`) to provide reverse lookups (e.g. find all call sites
887for a given function) across all projects you might work on/browse.
888Tags for PETSc can be generated by running `make allgtags` from `$PETSC_DIR`, or one can generate tags for all projects by running a command such as
889
890```none
891find $PETSC_DIR/{include,src,tutorials,$PETSC_ARCH/include} any/other/paths \
892   -regex '.*\.\(cc\|hh\|cpp\|cxx\|C\|hpp\|c\|h\|cu\)$' \
893   | grep -v ftn-auto | gtags -f -
894```
895
896from your home directory or wherever you keep source code. If you are
897making large changes, it is useful to either set this up to run as a
898cron job or to make a convenient alias so that refreshing is easy. Then
899add the following to `~/.emacs` to enable gtags and specify key bindings.
900
901```emacs
902(when (require 'gtags)
903  (global-set-key (kbd "C-c f") 'gtags-find-file)
904  (global-set-key (kbd "C-c .") 'gtags-find-tag)
905  (global-set-key (kbd "C-c r") 'gtags-find-rtag)
906  (global-set-key (kbd "C-c ,") 'gtags-pop-stack))
907(add-hook 'c-mode-common-hook
908          '(lambda () (gtags-mode t))) ; Or add to existing hook
909```
910
911A more basic alternative to the GNU Global (`gtags`) approach that does not require adding packages is to use
912the builtin `etags` feature. First, run `make etags` from the
913PETSc home directory to generate the file `$PETSC_DIR/TAGS`, and
914then from within Emacs, run
915
916```none
917M-x visit-tags-table
918```
919
920where `M` denotes the Emacs Meta key, and enter the name of the
921`TAGS` file. Then the command `M-.` will cause Emacs to find the
922file and line number where a desired PETSc function is defined. Any
923string in any of the PETSc files can be found with the command `M-x tags-search`.
924To find repeated occurrences, one can simply use `M-,` to find the next occurrence.
925
926## VS Code Users
927
928[VS Code](https://code.visualstudio.com/) (unlike {ref}`sec_visual_studio`, described below) is an open-source editor with a rich extension ecosystem.
929It has [excellent integration](https://marketplace.visualstudio.com/items?itemName=llvm-vs-code-extensions.vscode-clangd) with clangd and will automatically pick up `compile_commands.json`
930as produced by a command such as `bear make -B` (see {ref}`sec_developer_environments`).
931If you have no prior attachment to a specific code editor, we recommend trying VS Code.
932
933## Vi and Vim Users
934
935This section lists helpful Vim commands for PETSc. Ones that configure Vim can be placed
936in a `.vimrc` file in the top of the PETSc directory and will be loaded automatically.
937
938Vim has configurable keymaps: all of the "command mode" commands given that start with
939a colon (such as `:help`) can be assigned to short sequences in "normal mode," which
940is how most Vim users use their most frequently used commands.
941
942See the {ref}`sec_developer_environments` discussion above for configuration of clangd, which
943provides integrated development environment.
944
945### Tags
946
947The `tags` feature can be used to search PETSc files quickly and efficiently.
948To use this feature, one should first check if the file, `$PETSC_DIR/CTAGS`
949exists. If this file is not present, it should be generated by running `make
950etags` from the PETSc home directory. Once the file exists, from Vi/Vim the
951user should issue the command
952
953```none
954:set tags=CTAGS
955```
956
957from the `$PETSC_DIR` directory and enter the name of the `CTAGS` file. The
958command `:tag functionname` will cause Vi/Vim to open the file and line
959number where a desired PETSc function is defined in the current window.
960`<Ctrl-o>` will return the screen to your previous location.
961
962The command `:stag functionname` will split the current window and then open
963the file and line number for that function in one half. Some prefer this because
964it is easier to compare the file you are editing to the function definition this way.
965
966### Cscope and gtags
967
968Vim can also use the `cscope` utility to navigate source code. One useful thing
969it can do that the basic `tags` feature can't is search for references to a symbol,
970rather than its definition, which can be useful for refactoring. The command
971
972```none
973:cs find s functionname
974```
975
976opens a list of all of the places the function is called in PETSc, and opens
977the file and line that you choose. The variant `:scs find s functionname`
978does the same but splits the window like `stag`.
979
980The PETSc makefile does not have a command for building a cscope database, but
981GNU Global is cross-compatible with cscope: call `make allgtags` to make the
982gtags database, and run the commands
983
984```none
985:set csprg=gtags-cscope
986:cs add GTAGS
987```
988
989### Quickfix
990
991Rather than exiting editing a file to build the library and check for errors or
992warnings, calling `:make` runs the make command without leaving Vim and
993collects the errors and warnings in a "quickfix" window. Move the cursor to
994one of the errors or warnings in the quickfix window and press `<Enter>` and
995the main window will jump to the file and line with the error. The following
996commands filter lines of out PETSc's make output that can clutter the quickfix window:
997
998```none
999:set efm^=%-GStarting\ make\ run\ on\ %.%#
1000:set efm^=%-GMachine\ characteristics:\ %.%#
1001:set efm^=%-G#define\ PETSC%.%#
1002```
1003
1004### Autocompletion and snippets
1005
1006Autocompletion of long function names can be helpful when working with PETSc.
1007If you have a tags file, you can press `<Ctrl-N>` when you have partially
1008typed a word to bring up a list of potential completions that you can choose
1009from with `<Tab>`.
1010
1011More powerful autocompletion, such as completing the fieldname of a struct, is
1012available from external plugins that can be added to Vim, such as [SuperTab](https://github.com/ervandew/supertab), [VimCompletesMe](https://github.com/ackyshake/VimCompletesMe), or [YouCompleteMe](https://github.com/ycm-core/YouCompleteMe).
1013
1014Along the same lines, plugins can be added that fill in the boilerplate
1015associated with PETSc programming with code snippets. One such tool is
1016[UltiSnips](https://github.com/sirver/UltiSnips).
1017
1018### LSP for Vim
1019
1020Several plugins provide the equivalent of emacs' lsp-mode: YouCompleteMe,
1021mentioned above, is one; another popular one is [ale](https://github.com/dense-analysis/ale). These can check for syntax errors,
1022check for compilation errors in the background, and provide sophisticated tools
1023for refactoring. Like lsp-mode, they also rely on a compilation database, so
1024`bear -- make -B` should be used as well to generate the file
1025`compile_commands.json`.
1026
1027See [online tutorials](http://www.yolinux.com/TUTORIALS/LinuxTutorialAdvanced_vi.html)
1028for additional Vi/Vim options.
1029
1030## Eclipse Users
1031
1032If you are interested in developing code that uses PETSc from Eclipse or
1033developing PETSc in Eclipse and have knowledge of how to do indexing and
1034build libraries in Eclipse, please contact us at
1035[petsc-dev@mcs.anl.gov](mailto:petsc-dev@mcs.anl.gov).
1036
1037One way to index and build PETSc in Eclipse is as follows.
1038
10391. Open
1040   “File$\rightarrow$Import$\rightarrow$Git$\rightarrow$Projects
1041   from Git”. In the next two panels, you can either add your existing
1042   local repository or download PETSc from Bitbucket by providing the
1043   URL. Most Eclipse distributions come with Git support. If not,
1044   install the EGit plugin. When importing the project, select the
1045   wizard “Import as general project”.
10462. Right-click on the project (or the “File” menu on top) and select
1047   “New $\rightarrow$ Convert to a C/C++ Project (Adds C/C++
1048   Nature)”. In the setting window, choose “C Project” and specify the
1049   project type as “Shared Library”.
10503. Right-click on the C project and open the “Properties” panel. Under
1051   “C/C++ Build $\rightarrow$ Builder Settings”, set the Build
1052   directory to `$PETSC_DIR` and make sure “Generate Makefiles
1053   automatically” is unselected. Under the section “C/C++
1054   General$\rightarrow$Paths and Symbols”, add the PETSc paths
1055   to “Includes”.
1056
1057> ```none
1058>      $PETSC_DIR/include
1059>      $PETSC_DIR/$PETSC_ARCH/include
1060>
1061> Under the section “C/C++ General\ :math:`\rightarrow`\ index”, choose
1062> “Use active build configuration”.
1063> ```
1064
10651. Configure PETSc normally outside Eclipse to generate a makefile and
1066   then build the project in Eclipse. The source code will be parsed by
1067   Eclipse.
1068
1069If you launch Eclipse from the Dock on Mac OS X, `.bashrc` will not be
1070loaded (a known OS X behavior, for security reasons). This will be a
1071problem if you set the environment variables `$PETSC_DIR` and
1072`$PETSC_ARCH` in `.bashrc`. A solution which involves replacing the
1073executable can be found at
1074`` `/questions/829749/launch-mac-eclipse-with-environment-variables-set `` \</questions/829749/launch-mac-eclipse-with-environment-variables-set>\`\_\_.
1075Alternatively, you can add `$PETSC_DIR` and `$PETSC_ARCH` manually
1076under “Properties $\rightarrow$ C/C++ Build $\rightarrow$
1077Environment”.
1078
1079To allow an Eclipse code to compile with the PETSc include files and
1080link with the PETSc libraries, a PETSc user has suggested the following.
1081
10821. Right-click on your C project and select “Properties
1083   $\rightarrow$ C/C++ Build $\rightarrow$ Settings”
10842. A new window on the righthand side appears with various settings
1085   options. Select “Includes” and add the required PETSc paths,
1086
1087```none
1088$PETSC_DIR/include
1089$PETSC_DIR/$PETSC_ARCH/include
1090```
1091
10921. Select “Libraries” under the header Linker and set the library search
1093   path:
1094
1095```none
1096   $PETSC_DIR/$PETSC_ARCH/lib
1097
1098and the libraries, for example
1099```
1100
1101```none
1102m, petsc, stdc++, mpichxx, mpich, lapack, blas, gfortran, dl, rt,gcc_s, pthread, X11
1103```
1104
1105Another PETSc user has provided the following steps to build an Eclipse
1106index for PETSc that can be used with their own code, without compiling
1107PETSc source into their project.
1108
11091. In the user project source directory, create a symlink to the PETSc
1110   `src/` directory.
11112. Refresh the project explorer in Eclipse, so the new symlink is
1112   followed.
11133. Right-click on the project in the project explorer, and choose “Index
1114   $\rightarrow$ Rebuild”. The index should now be built.
11154. Right-click on the PETSc symlink in the project explorer, and choose
1116   “Exclude from build...” to make sure Eclipse does not try to compile
1117   PETSc with the project.
1118
1119For further examples of using Eclipse with a PETSc-based application,
1120see the documentation for LaMEM [^lamem].
1121
1122## Qt Creator Users
1123
1124This information was provided by Mohammad Mirzadeh. The Qt Creator IDE
1125is part of the Qt SDK, developed for cross-platform GUI programming
1126using C++. It is available under GPL v3, LGPL v2 and a commercial
1127license and may be obtained, either as part of the Qt SDK or as
1128stand-alone software. It supports
1129automatic makefile generation using cross-platform `qmake` and
1130CMake build systems as well as allowing one to import projects based
1131on existing, possibly hand-written, makefiles. Qt Creator has a visual
1132debugger using GDB and LLDB (on Linux and OS X) or Microsoft’s CDB (on
1133Microsoft Windows) as backends. It also has an interface to Valgrind’s “memcheck”
1134and “callgrind” tools to detect memory leaks and profile code. It has
1135built-in support for a variety of version control systems including git,
1136mercurial, and subversion. Finally, Qt Creator comes fully equipped with
1137auto-completion, function look-up, and code refactoring tools. This
1138enables one to easily browse source files, find relevant functions, and
1139refactor them across an entire project.
1140
1141### Creating a Project
1142
1143When using Qt Creator with `qmake`, one needs a `.pro` file. This
1144configuration file tells Qt Creator about all build/compile options and
1145locations of source files. One may start with a blank `.pro` file and
1146fill in configuration options as needed. For example:
1147
1148```none
1149# The name of the application executable
1150TARGET = ex1
1151
1152# There are two ways to add PETSc functionality
1153# 1-Manual: Set all include path and libs required by PETSc
1154PETSC_INCLUDE = path/to/petsc_includes # e.g. obtained via running `make getincludedirs'
1155PETSC_LIBS = path/to/petsc_libs # e.g. obtained via running `make getlinklibs'
1156
1157INCLUDEPATH += $$PETSC_INCLUDES
1158LIBS += $$PETSC_LIBS
1159
1160# 2-Automatic: Use the PKGCONFIG functionality
1161# NOTE: petsc.pc must be in the pkgconfig path. You might need to adjust PKG_CONFIG_PATH
1162CONFIG += link_pkgconfig
1163PKGCONFIG += PETSc
1164
1165# Set appropriate compiler and its flags
1166QMAKE_CC = path/to/mpicc
1167QMAKE_CXX = path/to/mpicxx # if this is a cpp project
1168QMAKE_LINK = path/to/mpicxx # if this is a cpp project
1169
1170QMAKE_CFLAGS   += -O3 # add extra flags here
1171QMAKE_CXXFLAGS += -O3
1172QMAKE_LFLAGS   += -O3
1173
1174# Add all files that must be compiled
1175SOURCES += ex1.c source1.c source2.cpp
1176
1177HEADERS += source1.h source2.h
1178
1179# OTHER_FILES are ignored during compilation but will be shown in file panel in Qt Creator
1180OTHER_FILES += \
1181    path/to/resource_file \
1182    path/to/another_file
1183```
1184
1185In this example, keywords include:
1186
1187- `TARGET`: The name of the application executable.
1188- `INCLUDEPATH`: Used at compile time to point to required include
1189  files. Essentially, it is used as an `-I \$\$INCLUDEPATH` flag for
1190  the compiler. This should include all application-specific header
1191  files and those related to PETSc (which may be found via
1192  `make getincludedirs`).
1193- `LIBS`: Defines all required external libraries to link with the
1194  application. To get PETSc’s linking libraries, use
1195  `make getlinklibs`.
1196- `CONFIG`: Configuration options to be used by `qmake`. Here, the
1197  option `link_pkgconfig` instructs `qmake` to internally use
1198  `pkgconfig` to resolve `INCLUDEPATH` and `LIBS` variables.
1199- `PKGCONFIG`: Name of the configuration file (the `.pc` file –
1200  here `petsc.pc`) to be passed to `pkgconfig`. Note that for this
1201  functionality to work, `petsc.pc` must be in path which might
1202  require adjusting the `PKG_CONFIG_PATH` environment variable. For
1203  more information see
1204  [the Qt Creator documentation](https://doc.qt.io/qtcreator/creator-build-settings.html).
1205- `QMAKE_CC` and `QMAKE_CXX`: Define which C/C++ compilers use.
1206- `QMAKE_LINK`: Defines the proper linker to be used. Relevant if
1207  compiling C++ projects.
1208- `QMAKE_CFLAGS`, `QMAKE_CXXFLAGS` and `QMAKE_LFLAGS`: Set the
1209  corresponding compile and linking flags.
1210- `SOURCES`: Source files to be compiled.
1211- `HEADERS`: Header files required by the application.
1212- `OTHER_FILES`: Other files to include (source, header, or any other
1213  extension). Note that none of the source files placed here are
1214  compiled.
1215
1216More options can be included in a `.pro` file; see
1217<https://doc.qt.io/qt-5/qmake-project-files.html>. Once the `.pro` file
1218is generated, the user can simply open it via Qt Creator. Upon opening,
1219one has the option to create two different build options, debug and
1220release, and switch between the two. For more information on using the
1221Qt Creator interface and other more advanced aspects of the IDE, refer
1222to <https://www.qt.io/qt-features-libraries-apis-tools-and-ide/>
1223
1224(sec_visual_studio)=
1225
1226## Visual Studio Users
1227
1228To use PETSc from Microsoft Visual Studio, one would have to compile a PETSc
1229example with its corresponding makefile and then transcribe all compiler
1230and linker options used in this build into a Visual Studio project file,
1231in the appropriate format in Visual Studio project settings.
1232
1233## Xcode IDE Users
1234
1235See {any}`doc_macos_install` for the standard Unix command line tools approach to development on macOS. The information
1236below is only if you plan to write code within the Xcode IDE.
1237
1238### Apple Xcode IDE for macOS Applications
1239
1240Follow the instructions in `$PETSC_DIR/systems/Apple/OSX/bin/makeall`
1241to build the PETSc framework and documentation suitable for use in
1242Xcode.
1243
1244You can then use the PETSc framework in
1245`$PETSC_DIR/arch-osx/PETSc.framework` in the usual manner for Apple
1246frameworks. See the examples in
1247`$PETSC_DIR/systems/Apple/OSX/examples`. When working in Xcode, things
1248like function name completion should work for all PETSc functions as
1249well as MPI functions. You must also link against the Apple
1250`Accelerate.framework`.
1251
1252### Apple Xcode IDE for iPhone/iPad iOS Applications
1253
1254Follow the instructions in
1255`$PETSC_DIR/systems/Apple/iOS/bin/iosbuilder.py` to build the PETSc
1256library for use on the iPhone/iPad.
1257
1258You can then use the PETSc static library in
1259`$PETSC_DIR/arch-osx/libPETSc.a` in the usual manner for Apple
1260libraries inside your iOS XCode projects; see the examples in
1261`$PETSC_DIR/systems/Apple/iOS/examples`. You must also link against
1262the Apple `Accelerate.framework`.
1263
1264A thorough discussion of the
1265procedure is given in [Comparison of Migration Techniques for High-Performance Code to Android and iOS](https://www.researchgate.net/publication/308973080_Comparison_of_Migration_Techniques_for_High-Performance_Code_to_Android_and_iOS).
1266
1267For Android, you must have your standalone bin folder in the path, so that the compilers
1268are visible.
1269
1270The installation process has not been tested for iOS or Android since 2017.
1271
1272```{rubric} Footnotes
1273```
1274
1275[^saws]: [Saws wiki on Bitbucket](https://bitbucket.org/saws/saws/wiki/Home)
1276
1277[^cxx-note]: Note that this option is not required to use PETSc with C++
1278
1279[^lamem]: See the `doc/` directory at <https://bitbucket.org/bkaus/lamem>
1280
1281[^json]: JSON is a subset of YAML
1282