File: fortran.rst.txt

package info (click to toggle)
petsc 3.22.5%2Bdfsg1-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 516,740 kB
  • sloc: ansic: 814,333; cpp: 50,948; python: 37,416; f90: 17,187; javascript: 3,493; makefile: 3,198; sh: 1,502; xml: 619; objc: 445; java: 13; csh: 1
file content (489 lines) | stat: -rw-r--r-- 15,414 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
.. _ch_fortran:

PETSc for Fortran Users
-----------------------

Make sure the suffix of your Fortran files is .F90, not .f or .f90.

Basic Fortran API Differences
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. _sec_fortran_includes:

Modules and Include Files
^^^^^^^^^^^^^^^^^^^^^^^^^

You must use both PETSc include files and modules.
At the beginning of every function and module definition you need something like

.. code-block:: fortran

  #include "petsc/finclude/petscXXX.h"
           use petscXXX

The Fortran include files for PETSc are located in the directory
``$PETSC_DIR/include/petsc/finclude`` and the module files are located in ``$PETSC_DIR/$PETSC_ARCH/include``

Declaring PETSc Object Variables
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

You can declare PETSc object variables using either of the following:

.. code-block:: fortran

    XXX variablename


.. code-block:: fortran

    type(tXXX) variablename

For example,

.. code-block:: fortran

  #include "petsc/finclude/petscvec.h"
           use petscvec

      Vec b
      type(tVec) x

PETSc types like ``PetscInt`` and ``PetscReal`` are simply aliases for basic Fortran types and cannot be written as ``type(tPetscInt)``

PETSc objects are always automatically initialized when declared so you do not need to (and should not) do

.. code-block:: fortran

    type(tXXX) x = PETSC_NULL_XXX
    XXX x = PETSC_NULL_XXX
 

Calling Sequences
^^^^^^^^^^^^^^^^^

PETSc Fortran routines have the
same names as the corresponding C versions except for a few that use allocatable array arguments and end with ``F90()``,
see :any:`sec_fortranarrays`.

The calling sequences for the Fortran version are in most cases
identical to the C version, except for the error checking variable
discussed in :any:`sec_fortran_errors` and a few routines
listed in :any:`sec_fortran_exceptions`.

When passing floating point numbers into PETSc Fortran subroutines, always
make sure you have them marked as double precision (e.g., pass in ``10.d0``
instead of ``10.0`` or declare them as PETSc variables, e.g.
``PetscScalar one = 1.0``). Otherwise, the compiler interprets the input as a single
precision number, which can cause crashes or other mysterious problems.
We **highly** recommend using the ``implicit none``
option at the beginning of each Fortran subroutine and declaring all variables.

.. _sec_fortran_errors:

Error Checking
^^^^^^^^^^^^^^

In the Fortran version, each PETSc routine has as its final argument an
integer error variable. The error code is
nonzero if an error has been detected; otherwise, it is zero. For
example, the Fortran and C variants of ``KSPSolve()`` are given,
respectively, below, where ``ierr`` denotes the ``PetscErrorCode`` error variable:

.. code-block:: fortran

   call KSPSolve(ksp, b, x, ierr) ! Fortran
   ierr = KSPSolve(ksp, b, x);    // C

For proper error handling one should not use the above syntax instead one should use

.. code-block:: fortran

   PetscCall(KSPSolve(ksp, b, x, ierr))   ! Fortran subroutines
   PetscCallA(KSPSolve(ksp, b, x, ierr))  ! Fortran main program
   PetscCall(KSPSolve(ksp, b, x))         // C

Passing Arrays
^^^^^^^^^^^^^^

Many PETSc functions take arrays as arguments; in Fortran they must be passed as arrays even if the "array"
is of length one (unlike Fortran 77 where one can pass scalars to functions expecting arrays). When passing
a single value one can use the Fortran [] notation to pass the scalar as an array, for example

.. code-block:: fortran

   PetscCall(VecSetValues(v, one, [i], [val], ierr))

This trick can only be used for arrays used to pass data into a PETSc routine, it cannot be used
for arrays used to receive data from a PETSc routine. For example,

.. code-block:: fortran

   PetscCall(VecGetValues(v, one, idx, [val], ierr))

is invalid and will not set ``val`` with the correct value.

For PETSc routine arguments that return a character string, you should pass a string long enough to hold the
result. For example,

.. code-block:: fortran

   character(80)  str
   PetscCall(KSPGetType(ksp,str,ierr))

The result is copied into ``str``.

For PETSc routine arguments that return an array of ``PetscInt``, ``PetscScalar``, ``PetscReal`` or of PETSc objects,
there are two possibilities. In the first, the Fortran routine must pass in an array of sufficient size to hold the result. For example,


.. code-block:: fortran

   PetscInt lx(64)
   DMDAGetOwnershipRanges(a, lx, PETSC_NULL_INTEGER_ARRAY, PETSC_NULL_INTEGER_ARRAY);

In the second form one passes in a pointer to an array and the PETSc routine returns an array containing the values.

.. code-block:: fortran

   PetscScalar, pointer :: array(:)
   PetscCall(VecGetArrayF90(v, array, ierr))

In this second form the PETSc routine often has a name that ends with ``F90``.

The information for which form to use is documented in the manual page of the routine.

Passing Null Pointers
^^^^^^^^^^^^^^^^^^^^^

Many PETSc C functions have the option of passing a ``NULL``
argument (for example, the fifth argument of ``MatCreateSeqAIJ()``).
From Fortran, users *must* pass ``PETSC_NULL_XXX`` to indicate a null
argument (where ``XXX`` is ``INTEGER``, ``DOUBLE``, ``CHARACTER``,
``SCALAR``, ``VEC``, ``MAT``, etc depending on the argument type); passing a literal 0 from
Fortran in this case will crash the code.  For example, when no options prefix is desired
in the routine ``PetscOptionsGetInt()``, one must use the following
command in Fortran:

.. code-block:: fortran

   PetscCall(PetscOptionsGetInt(PETSC_NULL_OPTIONS, PETSC_NULL_CHARACTER, PETSC_NULL_CHARACTER, '-name', N, flg, ierr))

Where the code expects an array, then use ``PETSC_NULL_XXX_ARRAY``. For example:

.. code-block:: fortran

   PetscCall(MatCreateSeqDense(comm, m, n, PETSC_NULL_SCALAR_ARRAY, A))

Finally, when a subroutine returns a ``PetscObject`` through an argument to check if it is ``NULL`` you must use:

.. code-block:: fortran

   if (PetscObjectIsNull(dm)) then
   if (.not. PetscObjectIsNull(dm)) then

you cannot use

.. code-block:: fortran

   if (dm .eq. PETSC_NULL_DM) then

Note that

.. code-block:: fortran

   if (PetscObjectIsNull(PETSC_NULL_VEC)) then

will always return true, for any PETSc object.

These specializations are required because of Fortran's strict type checking system and lack of a concept of ``NULL``.

Matrix, Vector and IS Indices
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

All matrices, vectors and ``IS`` in PETSc use zero-based indexing in the PETSc API
regardless of whether C or Fortran is being used. For example,
``MatSetValues()`` and ``VecSetValues()`` always use
zero indexing. See :any:`sec_matoptions` for further
details.

Indexing into Fortran arrays, for example obtained with ``VecGetArrayF90()``, uses the Fortran
convention and generally begin with 1 except for special routines such as ``DMDAVecGetArrayF90()`` which uses the ranges
provided by ``DMDAGetCorners()``.

Setting Routines and Contexts
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Some PETSc functions take as arguments user-functions and contexts for the function. For example

.. code-block:: fortran

   external func
   SNESSetFunction(snes, r, func, ctx, ierr)
   SNES snes
   Vec r
   PetscErrorCode ierr

where ``func`` has the calling sequence

.. code-block:: fortran

   subroutine func(snes, x, f, ctx, ierr)
   SNES snes
   Vec x,f
   PetscErrorCode ierr

and ``ctx`` can be almost anything (represented as ``void *`` in C).

It can be a Fortran derived type as in

.. code-block:: fortran

   subroutine func(snes, x, f, ctx, ierr)
   SNES snes
   Vec x,f
   type (userctx)   ctx
   PetscErrorCode ierr
   ...

   external func
   SNESSetFunction(snes, r, func, ctx, ierr)
   SNES snes
   Vec r
   PetscErrorCode ierr
   type (userctx)   ctx

or a PETSc object

.. code-block:: fortran

   subroutine func(snes, x, f, ctx, ierr)
   SNES snes
   Vec x,f
   Vec ctx
   PetscErrorCode ierr
   ...

   external func
   SNESSetFunction(snes, r, func, ctx, ierr)
   SNES snes
   Vec r
   PetscErrorCode ierr
   Vec ctx

or nothing

.. code-block:: fortran

   subroutine func(snes, x, f, dummy, ierr)
   SNES snes
   Vec x,f
   integer dummy(*)
   PetscErrorCode ierr
   ...

   external func
   SNESSetFunction(snes, r, func, 0, ierr)
   SNES snes
   Vec r
   PetscErrorCode ierr

When a function pointer (declared as external in Fortran) is passed as an argument to a PETSc function,
it is assumed that this
function references a routine written in the same language as the PETSc
interface function that was called. For instance, if
``SNESSetFunction()`` is called from C, the function must be a C function. Likewise, if it is called from Fortran, the
function must be (a subroutine) written in Fortran.

If you are using Fortran classes that have bound functions (methods) as in
`src/snes/tests/ex18f90.F90 <PETSC_DOC_OUT_ROOT_PLACEHOLDER/src/snes/tests/ex18f90.F90.html>`__, the context cannot be passed
to function pointer setting routines, such as ``SNESSetFunction()``. Instead, one must use ``SNESSetFunctionNoInterface()``,
and define the interface directly in the user code, see
`ex18f90.F90 <PETSC_DOC_OUT_ROOT_PLACEHOLDER/src/snes/tests/ex18f90.F90.html>`__
for a full demonstration.


.. _sec_fortcompile:

Compiling and Linking Fortran Programs
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

See :any:`sec_writing_application_codes`.

.. _sec_fortran_exceptions:

Routines with Different Fortran Interfaces
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

The following Fortran routines differ slightly from their C
counterparts; see the manual pages and previous discussion in this
chapter for details:

.. code-block:: fortran

   PetscInitialize()
   PetscOptionsGetString()

The following functions are not supported in Fortran:

.. code-block:: fortran

   PetscFClose(), PetscFOpen(), PetscFPrintf(), PetscPrintf(),
   PetscPopErrorHandler(), PetscPushErrorHandler(), PetscInfo(),
   PetscSetDebugger(), VecGetArrays(), VecRestoreArrays(),
   PetscViewerASCIIGetPointer(), PetscViewerBinaryGetDescriptor(),
   PetscViewerStringOpen(), PetscViewerStringSPrintf(),
   PetscOptionsGetStringArray()

.. _sec_fortranarrays:

Routines that Return Fortran Allocatable Arrays
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Many PETSc functions that return an array of values in C in an argument (such as ``ISGetIndices()``)
return an allocatable array in Fortran. The Fortran function names for these are suffixed with ``F90`` as indicated below.
A few routines, such as ``VecDuplicateVecs()`` discussed above, do not return a Fortran allocatable array;
a large enough array must be explicitly declared before use and passed into the routine.

.. list-table::

   * - C-API
   * - ``ISGetIndices()``
   * - ``ISRestoreIndices()``
   * - ``ISLocalToGlobalMappingGetIndices()``
   * - ``ISLocalToGlobalMappingRestoreIndices()``
   * - ``VecGetArray()``
   * - ``VecRestoreArray()``
   * - ``VecGetArrayRead()``
   * - ``VecRestoreArrayRead()``
   * - ``VecDuplicateVecs()``
   * - ``VecDestroyVecs()``
   * - ``DMDAVecGetArray()``
   * - ``DMDAVecRestoreArray()``
   * - ``DMDAVecGetArrayRead()``
   * - ``DMDAVecRestoreArrayRead()``
   * - ``DMDAVecGetArrayWrite()``
   * - ``DMDAVecRestoreArrayWrite()``
   * - ``MatGetRowIJ()``
   * - ``MatRestoreRowIJ()``
   * - ``MatSeqAIJGetArray()``
   * - ``MatSeqAIJRestoreArray()``
   * - ``MatMPIAIJGetSeqAIJ()``
   * - ``MatDenseGetArray()``
   * - ``MatDenseRestoreArray()``

The array arguments to these Fortran functions should be declared with forms such as

.. code-block:: fortran

   PetscScalar, pointer :: x(:)
   PetscInt, pointer :: idx(:)

See the manual pages for details and pointers to example programs.

.. _sec_fortvecd:

Duplicating Multiple Vectors
^^^^^^^^^^^^^^^^^^^^^^^^^^^^

The Fortran interface to ``VecDuplicateVecs()`` differs slightly from
the C/C++ variant. To create ``n`` vectors of the same
format as an existing vector, the user must declare a vector array,
``v_new`` of size ``n``. Then, after ``VecDuplicateVecs()`` has been
called, ``v_new`` will contain (pointers to) the new PETSc vector
objects. When finished with the vectors, the user should destroy them by
calling ``VecDestroyVecs()``. For example, the following code fragment
duplicates ``v_old`` to form two new vectors, ``v_new(1)`` and
``v_new(2)``.

.. code-block:: fortran

   Vec          v_old, v_new(2)
   PetscInt     ierr
   PetscScalar  alpha
   ....
   PetscCall(VecDuplicateVecs(v_old, 2, v_new, ierr))
   alpha = 4.3
   PetscCall(VecSet(v_new(1), alpha, ierr))
   alpha = 6.0
   PetscCall(VecSet(v_new(2), alpha, ierr))
   ....
   PetscCall(VecDestroyVecs(2, v_new, ierr))

.. _sec_fortran-examples:

Sample Fortran Programs
~~~~~~~~~~~~~~~~~~~~~~~

Sample programs that illustrate the PETSc interface for Fortran are
given below, corresponding to
`Vec Test ex19f <PETSC_DOC_OUT_ROOT_PLACEHOLDER/src/vec/vec/tests/ex19f.F90.html>`__,
`Vec Tutorial ex4f <PETSC_DOC_OUT_ROOT_PLACEHOLDER/src/vec/vec/tutorials/ex4f.F90.html>`__,
`Draw Test ex5f <PETSC_DOC_OUT_ROOT_PLACEHOLDER/src/sys/classes/draw/tests/ex5f.F90.html>`__,
and
`SNES Tutorial ex1f <PETSC_DOC_OUT_ROOT_PLACEHOLDER/src/snes/tutorials/ex1f.F90.html>`__,
respectively. We also refer Fortran programmers to the C examples listed
throughout the manual, since PETSc usage within the two languages
differs only slightly.


.. admonition:: Listing: ``src/vec/vec/tests/ex19f.F90``
   :name: vec-test-ex19f

   .. literalinclude:: /../src/vec/vec/tests/ex19f.F90
      :language: fortran
      :end-at: end

.. _listing_vec_ex4f:

.. admonition:: Listing: ``src/vec/vec/tutorials/ex4f.F90``
   :name: vec-ex4f

   .. literalinclude:: /../src/vec/vec/tutorials/ex4f.F90
      :language: fortran
      :end-before: !/*TEST

.. admonition:: Listing: ``src/sys/classes/draw/tests/ex5f.F90``
   :name: draw-test-ex5f

   .. literalinclude:: /../src/sys/classes/draw/tests/ex5f.F90
      :language: fortran
      :end-at: end

.. admonition:: Listing: ``src/snes/tutorials/ex1f.F90``
   :name: snes-ex1f

   .. literalinclude:: /../src/snes/tutorials/ex1f.F90
      :language: fortran
      :end-before: !/*TEST

Calling Fortran Routines from C (and C Routines from Fortran)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

The information here applies only if you plan to call your **own**
C functions from Fortran or Fortran functions from C.
Different compilers have different methods of naming Fortran routines
called from C (or C routines called from Fortran). Most Fortran
compilers change the capital letters in Fortran routines to
all lowercase. With some compilers, the Fortran compiler appends an underscore
to the end of each Fortran routine name; for example, the Fortran
routine ``Dabsc()`` would be called from C with ``dabsc_()``. Other
compilers change all the letters in Fortran routine names to capitals.

PETSc provides two macros (defined in C/C++) to help write portable code
that mixes C/C++ and Fortran. They are ``PETSC_HAVE_FORTRAN_UNDERSCORE``
and ``PETSC_HAVE_FORTRAN_CAPS`` , which will be defined in the file
``$PETSC_DIR/$PETSC_ARCH/include/petscconf.h`` based on the compilers
conventions. The macros are used,
for example, as follows:

.. code-block:: fortran

   #if defined(PETSC_HAVE_FORTRAN_CAPS)
   #define dabsc_ DABSC
   #elif !defined(PETSC_HAVE_FORTRAN_UNDERSCORE)
   #define dabsc_ dabsc
   #endif
   .....
   dabsc_( &n,x,y); /* call the Fortran function */