xref: /petsc/doc/manual/fortran.md (revision b2ccae6bdc8edea944f1c160ca3b2eb32c69ecb2)
1(ch_fortran)=
2
3# PETSc for Fortran Users
4
5Make sure the suffix of your Fortran files is .F90, not .f or .f90.
6
7## Basic Fortran API Differences
8
9(sec_fortran_includes)=
10
11### Modules and Include Files
12
13You must use both PETSc include files and modules.
14At the beginning of every function and module definition you need something like
15
16```fortran
17#include "petsc/finclude/petscXXX.h"
18   use petscXXX
19```
20
21The Fortran include files for PETSc are located in the directory
22`$PETSC_DIR/include/petsc/finclude` and the module files are located in `$PETSC_DIR/$PETSC_ARCH/include`
23
24The include files are nested, that is, for example, `petsc/finclude/petscmat.h` automatically includes
25`petsc/finclude/petscvec.h` and so on. Except for `petscsys` which is nested in the other modules,
26modules are **not** nested. Thus if your routine uses, for example, both
27`Mat` and `Vec` operations you need
28
29```c
30use petscvec
31use petscmat
32```
33
34The reason they are not nested is that they are very large and including all of them slows down the compile time.
35One can use
36
37```c
38use petsc
39```
40
41to include all of them. In addition, if you have a routine that does not have function calls for an object, but has
42the object as an argument you can use, for example,
43
44```c
45subroutine FormFunction(snes,x,f,dummy,ierr)
46  use petscvec
47  use petscsnesdef
48  implicit none
49```
50
51### Declaring PETSc Object Variables
52
53You can declare PETSc object variables using either of the following:
54
55```fortran
56XXX variablename
57```
58
59```fortran
60type(tXXX) variablename
61```
62
63For example,
64
65```fortran
66#include "petsc/finclude/petscvec.h"
67  use petscvec
68
69  Vec b
70  type(tVec) x
71```
72
73PETSc types like `PetscInt` and `PetscReal` are simply aliases for basic Fortran types and cannot be written as `type(tPetscInt)`
74
75PETSc objects are always automatically initialized when declared so you do not need to (and should not) do
76
77```fortran
78type(tXXX) x = PETSC_NULL_XXX
79XXX x = PETSC_NULL_XXX
80```
81
82To make a variable no longer point to its previously assigned PETSc object use, for example,
83
84```fortran
85   Vec x, y
86   PetscInt one = 1
87   PetscCallA(VecCreateMPI(PETSC_COMM_WORLD, one, PETSC_DETERMINE, x, ierr))
88   y = x
89   PetscCallA(VecDestroy(x, ierr))
90   PetscObjectNullify(y)
91```
92
93Otherwise `y` will be a dangling pointer whose access will cause a crash.
94
95
96### Calling Sequences
97
98The calling sequences for the Fortran version are in most cases
99identical to the C version, except for the error checking variable
100discussed in {any}`sec_fortran_errors`.
101
102The key differences in handling arguments when calling PETSc functions from Fortran are
103
104- One cannot pass a scalar variable to a function expecting an array, {any}`sec_passarray`.
105- One must use type specific `PETSC_NULL` arguments, such as `PETSC_NULL_INTEGER`, {any}`sec_nullptr`.
106- One must pass pointers to arrays for arguments that output an array, for example `PetscScalar, pointer \:\: a(\:)`,
107  {any}`sec_fortranarrays`.
108- `PETSC_DECIDE` and friends need to match the argument type, for example `PETSC_DECIDE_INTEGER`.
109
110When passing floating point numbers into PETSc Fortran subroutines, always
111make sure you have them marked as double precision (e.g., pass in `10.d0`
112instead of `10.0` or declare them as PETSc variables, e.g.
113`PetscScalar one = 1.0`). Otherwise, the compiler interprets the input as a single
114precision number, which can cause crashes or other mysterious problems.
115We **highly** recommend using the `implicit none`
116option at the beginning of each Fortran subroutine and declaring all variables.
117
118(sec_fortran_errors)=
119
120### Error Checking
121
122In the Fortran version, each PETSc routine has as its final argument an
123integer error variable. The error code is
124nonzero if an error has been detected; otherwise, it is zero. For
125example, the Fortran and C variants of `KSPSolve()` are given,
126respectively, below, where `ierr` denotes the `PetscErrorCode` error variable:
127
128```fortran
129call KSPSolve(ksp, b, x, ierr) ! Fortran
130ierr = KSPSolve(ksp, b, x);    // C
131```
132
133For proper error handling one should not use the above syntax instead one should use
134
135```fortran
136PetscCall(KSPSolve(ksp, b, x, ierr))   ! Fortran subroutines
137PetscCallA(KSPSolve(ksp, b, x, ierr))  ! Fortran main program
138PetscCall(KSPSolve(ksp, b, x))         // C
139```
140
141(sec_passarray)=
142
143### Passing Arrays To PETSc Functions
144
145Many PETSc functions take arrays as arguments; in Fortran they must be passed as arrays even if the "array"
146is of length one (unlike Fortran 77 where one can pass scalars to functions expecting arrays). When passing
147a single value one can use the Fortran [] notation to pass the scalar as an array, for example
148
149```fortran
150PetscCall(VecSetValues(v, one, [i], [val], ierr))
151```
152
153This trick can only be used for arrays used to pass data into a PETSc routine, it cannot be used
154for arrays used to receive data from a PETSc routine. For example,
155
156```fortran
157PetscCall(VecGetValues(v, one, idx, [val], ierr))
158```
159
160is invalid and will not set `val` with the correct value.
161
162(sec_nullptr)=
163
164### Passing null pointers to PETSc functions
165
166Many PETSc C functions have the option of passing a `NULL`
167argument (for example, the fifth argument of `MatCreateSeqAIJ()`).
168From Fortran, users *must* pass `PETSC_NULL_XXX` to indicate a null
169argument (where `XXX` is `INTEGER`, `DOUBLE`, `CHARACTER`,
170`SCALAR`, `VEC`, `MAT`, etc depending on the argument type). For example, when no options prefix is desired
171in the routine `PetscOptionsGetInt()`, one must use the following
172command in Fortran:
173
174```fortran
175PetscCall(PetscOptionsGetInt(PETSC_NULL_OPTIONS, PETSC_NULL_CHARACTER, PETSC_NULL_CHARACTER, '-name', N, flg, ierr))
176```
177
178Where the code expects an array, then use `PETSC_NULL_XXX_ARRAY`. For example:
179
180```fortran
181PetscCall(MatCreateSeqDense(comm, m, n, PETSC_NULL_SCALAR_ARRAY, A))
182```
183
184When a PETSc function returns multiple arrays, such as `DMDAGetOwnershipRanges()` and the user does not need
185certain arrays they must pass `PETSC_NULL_XXX_POINTER` as the argument. For example,
186
187```fortran
188PetscInt, pointer :: lx(:), ly(:)
189PetscCallA(DMDAGetOwnershipRanges(da, lx, ly, PETSC_NULL_INTEGER_POINTER, ierr))
190PetscCallA(DMDARestoreOwnershipRanges(da, lx, ly, PETSC_NULL_INTEGER_POINTER, ierr))
191```
192
193Arguments that are fully defined Fortran derived types (C structs), such as `MatFactorInfo` or `PetscSFNode`,
194cannot be passed as null from Fortran. A properly defined variable must be passed in for those arguments.
195
196Finally when a subroutine returns a `PetscObject` through an argument, to check if it is `NULL` you must use:
197
198```fortran
199if (PetscObjectIsNull(dm)) then
200if (.not. PetscObjectIsNull(dm)) then
201```
202
203you cannot use
204
205```fortran
206if (dm .eq. PETSC_NULL_DM) then
207```
208
209Note that
210
211```fortran
212if (PetscObjectIsNull(PETSC_NULL_VEC)) then
213```
214
215will always return true, for any PETSc object.
216
217These specializations with `NULL` types are required because of Fortran's strict type checking system and lack of a concept of `NULL`,
218the Fortran compiler will often warn you if the wrong `NULL` type is passed.
219
220(sec_fortranarrays)=
221
222### Output Arrays from PETSc functions
223
224For PETSc routine arguments that return an array of `PetscInt`, `PetscScalar`, `PetscReal` or of PETSc objects,
225one passes in a pointer to an array and the PETSc routine returns an array containing the values. For example,
226
227```c
228PetscScalar *a;
229Vec         v;
230VecGetArray(v, &a);
231```
232
233is in Fortran,
234
235```fortran
236PetscScalar, pointer :: a(:)
237Vec,         v
238VecGetArray(v, a, ierr)
239```
240
241For PETSc routine arguments that return a character string (array), e.g. `const char *str[]` pass a string long enough to hold the
242result. For example,
243
244```fortran
245character*(80)  str
246PetscCall(KSPGetType(ksp,str,ierr))
247```
248
249The result is copied into `str`.
250
251Similarly, for PETSc routines where the user provides a character array (to be filled) followed by the array's length, e.g. `char name[], size_t nlen`.
252In Fortran pass a string long enough to hold the result, but not the separate length argument. For example,
253
254```fortran
255character*(80)  str
256PetscCall(PetscGetHostName(name,ierr))
257```
258
259### Matrix, Vector and IS Indices
260
261All matrices, vectors and `IS` in PETSc use zero-based indexing in the PETSc API
262regardless of whether C or Fortran is being used. For example,
263`MatSetValues()` and `VecSetValues()` always use
264zero indexing. See {any}`sec_matoptions` for further
265details.
266
267Indexing into Fortran arrays, for example obtained with `VecGetArray()`, uses the Fortran
268convention and generally begin with 1 except for special routines such as `DMDAVecGetArray()` which uses the ranges
269provided by `DMDAGetCorners()`.
270
271### Setting Routines and Contexts
272
273Some PETSc functions take as arguments user-functions and contexts for the function. For example
274
275```fortran
276external func
277SNESSetFunction(snes, r, func, ctx, ierr)
278SNES snes
279Vec r
280PetscErrorCode ierr
281```
282
283where `func` has the calling sequence
284
285```fortran
286subroutine func(snes, x, f, ctx, ierr)
287SNES snes
288Vec x,f
289PetscErrorCode ierr
290```
291
292and `ctx` can be almost anything (represented as `void *` in C).
293
294It can be a Fortran derived type as in
295
296```fortran
297subroutine func(snes, x, f, ctx, ierr)
298SNES snes
299Vec x,f
300type (userctx)   ctx
301PetscErrorCode ierr
302...
303
304external func
305SNESSetFunction(snes, r, func, ctx, ierr)
306SNES snes
307Vec r
308PetscErrorCode ierr
309type (userctx)   ctx
310```
311
312or a PETSc object
313
314```fortran
315subroutine func(snes, x, f, ctx, ierr)
316SNES snes
317Vec x,f
318Vec ctx
319PetscErrorCode ierr
320...
321
322external func
323SNESSetFunction(snes, r, func, ctx, ierr)
324SNES snes
325Vec r
326PetscErrorCode ierr
327Vec ctx
328```
329
330or nothing
331
332```fortran
333subroutine func(snes, x, f, dummy, ierr)
334SNES snes
335Vec x,f
336integer dummy(*)
337PetscErrorCode ierr
338...
339
340external func
341SNESSetFunction(snes, r, func, 0, ierr)
342SNES snes
343Vec r
344PetscErrorCode ierr
345```
346
347When a function pointer (declared as external in Fortran) is passed as an argument to a PETSc function,
348it is assumed that this
349function references a routine written in the same language as the PETSc
350interface function that was called. For instance, if
351`SNESSetFunction()` is called from C, the function must be a C function. Likewise, if it is called from Fortran, the
352function must be (a subroutine) written in Fortran.
353
354If you are using Fortran classes that have bound functions (methods) as in
355<a href="PETSC_DOC_OUT_ROOT_PLACEHOLDER/src/snes/tests/ex18f90.F90.html">src/snes/tests/ex18f90.F90</a>, the context cannot be passed
356to function pointer setting routines, such as `SNESSetFunction()`. Instead, one must use `SNESSetFunctionNoInterface()`,
357and define the interface directly in the user code, see
358<a href="PETSC_DOC_OUT_ROOT_PLACEHOLDER/src/snes/tests/ex18f90.F90.html">ex18f90.F90</a>
359for a full demonstration.
360
361(sec_fortcompile)=
362
363### Compiling and Linking Fortran Programs
364
365See {any}`sec_writing_application_codes`.
366
367### Duplicating Multiple Vectors
368
369The Fortran interface to `VecDuplicateVecs()` differs slightly from
370the C/C++ variant. To create `n` vectors of the same
371format as an existing vector, the user must declare a vector array,
372`v_new` of size `n`. Then, after `VecDuplicateVecs()` has been
373called, `v_new` will contain (pointers to) the new PETSc vector
374objects. When finished with the vectors, the user should destroy them by
375calling `VecDestroyVecs()`. For example, the following code fragment
376duplicates `v_old` to form two new vectors, `v_new(1)` and
377`v_new(2)`.
378
379```fortran
380Vec          v_old, v_new(2)
381PetscInt     ierr
382PetscScalar  alpha
383....
384PetscCall(VecDuplicateVecs(v_old, 2, v_new, ierr))
385alpha = 4.3
386PetscCall(VecSet(v_new(1), alpha, ierr))
387alpha = 6.0
388PetscCall(VecSet(v_new(2), alpha, ierr))
389....
390PetscCall(VecDestroyVecs(2, v_new, ierr))
391```
392
393(sec_fortran_examples)=
394
395## Sample Fortran Programs
396
397Sample programs that illustrate the PETSc interface for Fortran are
398given below, corresponding to
399<a href="PETSC_DOC_OUT_ROOT_PLACEHOLDER/src/vec/vec/tests/ex19f.F90.html">Vec Test ex19f</a>,
400<a href="PETSC_DOC_OUT_ROOT_PLACEHOLDER/src/vec/vec/tutorials/ex4f.F90.html">Vec Tutorial ex4f</a>,
401<a href="PETSC_DOC_OUT_ROOT_PLACEHOLDER/src/sys/classes/draw/tests/ex5f.F90.html">Draw Test ex5f</a>,
402and
403<a href="PETSC_DOC_OUT_ROOT_PLACEHOLDER/src/snes/tutorials/ex1f.F90.html">SNES Tutorial ex1f</a>,
404respectively. We also refer Fortran programmers to the C examples listed
405throughout the manual, since PETSc usage within the two languages
406differs only slightly.
407
408:::{admonition} Listing: `src/vec/vec/tests/ex19f.F90`
409:name: vec-test-ex19f
410
411```{literalinclude} /../src/vec/vec/tests/ex19f.F90
412:end-at: end
413:language: fortran
414```
415:::
416
417(listing_vec_ex4f)=
418
419:::{admonition} Listing: `src/vec/vec/tutorials/ex4f.F90`
420:name: vec-ex4f
421
422```{literalinclude} /../src/vec/vec/tutorials/ex4f.F90
423:end-before: '!/*TEST'
424:language: fortran
425```
426:::
427
428:::{admonition} Listing: `src/sys/classes/draw/tests/ex5f.F90`
429:name: draw-test-ex5f
430
431```{literalinclude} /../src/sys/classes/draw/tests/ex5f.F90
432:end-at: end
433:language: fortran
434```
435:::
436
437:::{admonition} Listing: `src/snes/tutorials/ex1f.F90`
438:name: snes-ex1f
439
440```{literalinclude} /../src/snes/tutorials/ex1f.F90
441:end-before: '!/*TEST'
442:language: fortran
443```
444:::
445
446### Calling Fortran Routines from C (and C Routines from Fortran)
447
448The information here applies only if you plan to call your **own**
449C functions from Fortran or Fortran functions from C.
450Different compilers have different methods of naming Fortran routines
451called from C (or C routines called from Fortran). Most Fortran
452compilers change the capital letters in Fortran routines to
453all lowercase. With some compilers, the Fortran compiler appends an underscore
454to the end of each Fortran routine name; for example, the Fortran
455routine `Dabsc()` would be called from C with `dabsc_()`. Other
456compilers change all the letters in Fortran routine names to capitals.
457
458PETSc provides two macros (defined in C/C++) to help write portable code
459that mixes C/C++ and Fortran. They are `PETSC_HAVE_FORTRAN_UNDERSCORE`
460and `PETSC_HAVE_FORTRAN_CAPS` , which will be defined in the file
461`$PETSC_DIR/$PETSC_ARCH/include/petscconf.h` based on the compilers
462conventions. The macros are used,
463for example, as follows:
464
465```fortran
466#if defined(PETSC_HAVE_FORTRAN_CAPS)
467#define dabsc_ DABSC
468#elif !defined(PETSC_HAVE_FORTRAN_UNDERSCORE)
469#define dabsc_ dabsc
470#endif
471.....
472dabsc_( &n,x,y); /* call the Fortran function */
473```
474