xref: /petsc/src/binding/petsc4py/docs/source/petsc_options.rst (revision b11d9968bc79904c690b122f9399be46447eb113)
1.. _petsc_options:
2
3Working with PETSc options
4==========================
5
6A very powerful feature of PETSc is that objects can be configured via command-line options.
7In this way, one can choose the method to be used or set different parameters without changing the source code.
8See the PETSc `manual <the_options_database>` for additional information.
9
10In order to use command-line options in a petsc4py program, it is important to initialize the module as follows:
11
12.. code-block:: python
13
14  # We first import petsc4py and sys to initialize PETSc
15  import sys, petsc4py
16  petsc4py.init(sys.argv)
17
18  # Import the PETSc module
19  from petsc4py import PETSc
20
21Then one can provide command-line options when running a script:
22
23.. code-block:: console
24
25  $ python foo.py -ksp_type gmres -ksp_gmres_restart 100 -ksp_view
26
27When the above initialization method is not possible, PETSc options can be also specified via environment variables or configuration files, e.g.:
28
29.. code-block:: console
30
31  $ PETSC_OPTIONS='-ksp_type gmres -ksp_gmres_restart 100 -ksp_view' python foo.py
32
33Command-line options can be read via an instance of the ``Options`` class. For instance:
34
35.. code-block:: python
36
37  OptDB = PETSc.Options()
38  n     = OptDB.getInt('n', 16)
39  eta   = OptDB.getReal('eta', 0.014)
40  alpha = OptDB.getScalar('alpha', -12.3)
41
42In this way, if the script is run with
43
44.. code-block:: console
45
46  $ python foo.py -n 50 -alpha 8.8
47
48the options, ``n`` and ``alpha`` will get the values ``50`` and ``8.8``, respectively, while ``eta`` will be assigned the value specified as default, ``0.014``.
49
50The options database is accessible also as a Python dictionary, so that one can for instance override, insert or delete an option:
51
52.. code-block:: python
53
54  OptDB['draw_pause'] = 1
55  del OptDB['draw_pause']
56