xref: /petsc/src/binding/petsc4py/src/petsc4py/PETSc/Options.pyx (revision 1acb5306efbd6b897a796cf04de7b7f73041d5b3)
1# --------------------------------------------------------------------
2
3cdef class Options:
4    """The options database object.
5
6    A dictionary-like object to store and operate with
7    command line options.
8
9    Parameters
10    ----------
11    prefix : str, optional
12        Optional string to prepend to all the options.
13
14    Examples
15    --------
16    Create an option database and operate with it.
17
18    >>> from petsc4py import PETSc
19    >>> opts = PETSc.Options()
20    >>> opts['a'] = 1 # insert the command-line option '-a 1'
21    >>> if 'a' in opts: # if the option is present
22    >>>     val = opts['a'] # return the option value as 'str'
23    >>> a_int = opts.getInt('a') # return the option value as 'int'
24    >>> a_bool = opts.getBool('a') # return the option value as 'bool'
25
26    Read command line and use default values.
27
28    >>> from petsc4py import PETSc
29    >>> opts = PETSc.Options()
30    >>> b_float = opts.getReal('b', 1) # return the value or 1.0 if not present
31
32    Read command line options prepended with a prefix.
33
34    >>> from petsc4py import PETSc
35    >>> opts = PETSc.Options('prefix_')
36    >>> opts.getString('b', 'some_default_string') # read -prefix_b xxx
37
38    See Also
39    --------
40    petsc_options
41
42    """
43
44    cdef PetscOptions opt
45    cdef object       _prefix
46
47    def __init__(self, prefix = None):
48        self.opt = NULL
49        self.prefix = prefix
50
51    def __dealloc__(self):
52        if self.opt == NULL: return
53        CHKERR(PetscOptionsDestroy(&self.opt))
54
55    def __contains__(self, item):
56        return self.hasName(item)
57
58    def __getitem__(self, item):
59        return self.getString(item)
60
61    def __setitem__(self, item, value):
62        self.setValue(item, value)
63
64    def __delitem__(self, item):
65        self.delValue(item)
66
67    property prefix:
68        """Prefix for options."""
69        def __get__(self) -> str:
70            return self._prefix
71
72        def __set__(self, prefix):
73            self._prefix = getprefix(prefix)
74
75        def __del__(self):
76            self._prefix = None
77    #
78
79    def create(self) -> Self:
80        """Create an options database."""
81        if self.opt != NULL: return
82        CHKERR(PetscOptionsCreate(&self.opt))
83        return self
84
85    def destroy(self) -> Self:
86        """Destroy an options database."""
87        if self.opt == NULL: return
88        CHKERR(PetscOptionsDestroy(&self.opt))
89        return self
90
91    def clear(self) -> Self:
92        """Clear an options database."""
93        if self.opt == NULL: return
94        CHKERR(PetscOptionsClear(self.opt))
95        return self
96
97    def view(self, Viewer viewer=None) -> None:
98        """View the options database.
99
100        Collective.
101
102        Parameters
103        ----------
104        viewer
105            A `Viewer` instance or `None` for the default viewer.
106
107        See Also
108        --------
109        Viewer, petsc.PetscOptionsView
110
111        """
112        cdef PetscViewer vwr = NULL
113        if viewer is not None: vwr = viewer.vwr
114        CHKERR(PetscOptionsView(self.opt, vwr))
115
116    def prefixPush(self, prefix: str | Options | Object | None) -> None:
117        """Push a prefix for the options database.
118
119        Logically collective.
120
121        See Also
122        --------
123        prefixPop, petsc.PetscOptionsPrefixPush
124
125        """
126        prefix = getprefix(prefix)
127        cdef const char *cprefix = NULL
128        prefix = str2bytes(prefix, &cprefix)
129        CHKERR(PetscOptionsPrefixPush(self.opt, cprefix))
130
131    def prefixPop(self) -> None:
132        """Pop a prefix for the options database.
133
134        Logically collective.
135
136        See Also
137        --------
138        prefixPush, petsc.PetscOptionsPrefixPop
139
140        """
141        CHKERR(PetscOptionsPrefixPop(self.opt))
142    #
143
144    def hasName(self, name: str) -> bool:
145        """Return the boolean indicating if the option is in the database."""
146        cdef const char *pr = NULL
147        cdef const char *nm = NULL
148        cdef object unused = getpair(self.prefix, name, &pr, &nm)
149        cdef PetscBool flag = PETSC_FALSE
150        CHKERR(PetscOptionsHasName(self.opt, pr, nm, &flag))
151        return toBool(flag)
152
153    def used(self, name: str) -> bool:
154        """Return the boolean indicating if the option was queried from the database."""
155        cdef const char *key = NULL
156        cdef PetscBool flag = PETSC_FALSE
157        name = str2bytes(name, &key)
158        CHKERR(PetscOptionsUsed(self.opt, key, &flag))
159        return toBool(flag)
160
161    def setValue(self, name: str,
162                 value: bool | int | float | Scalar | Sequence[bool] | Sequence[int] | Sequence[float] | Sequence[Scalar] | str) -> None:
163        """Set a value for an option.
164
165        Logically collective.
166
167        Parameters
168        ----------
169        name
170            The string identifying the option.
171        value
172            The option value.
173
174        See Also
175        --------
176        delValue, petsc.PetscOptionsSetValue
177
178        """
179        cdef const char *pr = NULL
180        cdef const char *nm = NULL
181        cdef object unused = getpair(self.prefix, name, &pr, &nm)
182        if pr == NULL:
183            option = bytes2str(nm)
184        else:
185            option = '-%s%s' % (bytes2str(pr), bytes2str(&nm[1]))
186
187        if isinstance(value, ndarray):
188            value = value.tolist()
189        if isinstance(value, (tuple, list)):
190            value = str(value).replace(' ', '').\
191                    replace('(', '').replace(')', '').\
192                    replace('[', '').replace(']', '')
193        elif isinstance(value, bool):
194            value = str(value).lower()
195        elif value is not None:
196            value = str(value)
197        cdef const char *key = NULL
198        cdef const char *val = NULL
199        option = str2bytes(option, &key)
200        value  = str2bytes(value,  &val)
201        CHKERR(PetscOptionsSetValue(self.opt, key, val))
202
203    def delValue(self, name: str) -> None:
204        """Delete an option from the database.
205
206        Logically collective.
207
208        See Also
209        --------
210        setValue, petsc.PetscOptionsClearValue
211
212        """
213        cdef const char *pr = NULL
214        cdef const char *nm = NULL
215        cdef object unused = getpair(self.prefix, name, &pr, &nm)
216        if pr == NULL:
217            option = bytes2str(nm)
218        else:
219            option = '-%s%s' % (bytes2str(pr), bytes2str(&nm[1]))
220        cdef const char *key = NULL
221        option = str2bytes(option, &key)
222        CHKERR(PetscOptionsClearValue(self.opt, key))
223
224    #
225
226    def getBool(self, name: str, default=None) -> bool:
227        """Return the boolean value associated with the option.
228
229        Not collective.
230
231        Parameters
232        ----------
233        name
234            The option name.
235        default
236            The default value.
237            If `None`, it raises a `KeyError` if the option is not found.
238
239        See Also
240        --------
241        getBoolArray, petsc.PetscOptionsGetBool
242
243        """
244        return getopt(self.opt, OPT_BOOL, self.prefix, name, default)
245
246    def getBoolArray(self, name: str, default=None) -> ArrayBool:
247        """Return the boolean values associated with the option.
248
249        Not collective.
250
251        Parameters
252        ----------
253        name
254            The option name.
255        default
256            The default value.
257            If `None`, it raises a `KeyError` if the option is not found.
258
259        See Also
260        --------
261        getBool, petsc.PetscOptionsGetBoolArray
262
263        """
264        return getopt(self.opt, OPT_BOOLARRAY, self.prefix, name, default)
265
266    def getInt(self, name: str, default=None) -> int:
267        """Return the integer value associated with the option.
268
269        Not collective.
270
271        Parameters
272        ----------
273        name
274            The option name.
275        default
276            The default value.
277            If `None`, it raises a `KeyError` if the option is not found.
278
279        See Also
280        --------
281        getIntArray, petsc.PetscOptionsGetInt
282
283        """
284        return getopt(self.opt, OPT_INT, self.prefix, name, default)
285
286    def getIntArray(self, name: str, default=None) -> ArrayInt:
287        """Return the integer array associated with the option.
288
289        Not collective.
290
291        Parameters
292        ----------
293        name
294            The option name.
295        default
296            The default value.
297            If `None`, it raises a `KeyError` if the option is not found.
298
299        See Also
300        --------
301        getInt, petsc.PetscOptionsGetIntArray
302
303        """
304        return getopt(self.opt, OPT_INTARRAY, self.prefix, name, default)
305
306    def getReal(self, name: str, default=None) -> float:
307        """Return the real value associated with the option.
308
309        Not collective.
310
311        Parameters
312        ----------
313        name
314            The option name.
315        default
316            The default value.
317            If `None`, it raises a `KeyError` if the option is not found.
318
319        See Also
320        --------
321        getRealArray, petsc.PetscOptionsGetReal
322
323        """
324        return getopt(self.opt, OPT_REAL, self.prefix, name, default)
325
326    def getRealArray(self, name: str, default=None) -> ArrayReal:
327        """Return the real array associated with the option.
328
329        Not collective.
330
331        Parameters
332        ----------
333        name
334            The option name.
335        default
336            The default value.
337            If `None`, it raises a `KeyError` if the option is not found.
338
339        See Also
340        --------
341        getReal, petsc.PetscOptionsGetRealArray
342
343        """
344        return getopt(self.opt, OPT_REALARRAY, self.prefix, name, default)
345
346    def getScalar(self, name: str, default=None) -> Scalar:
347        """Return the scalar value associated with the option.
348
349        Not collective.
350
351        Parameters
352        ----------
353        name
354            The option name.
355        default
356            The default value.
357            If `None`, it raises a `KeyError` if the option is not found.
358
359        See Also
360        --------
361        getScalarArray, petsc.PetscOptionsGetScalar
362
363        """
364        return getopt(self.opt, OPT_SCALAR, self.prefix, name, default)
365
366    def getScalarArray(self, name: str, default=None) -> ArrayScalar:
367        """Return the scalar array associated with the option.
368
369        Not collective.
370
371        Parameters
372        ----------
373        name
374            The option name.
375        default
376            The default value.
377            If `None`, it raises a `KeyError` if the option is not found.
378
379        See Also
380        --------
381        getScalar, petsc.PetscOptionsGetScalarArray
382
383        """
384        return getopt(self.opt, OPT_SCALARARRAY, self.prefix, name, default)
385
386    def getString(self, name: str, default=None) -> str:
387        """Return the string associated with the option.
388
389        Not collective.
390
391        Parameters
392        ----------
393        name
394            The option name.
395        default
396            The default value.
397            If `None`, it raises a `KeyError` if the option is not found.
398
399        See Also
400        --------
401        petsc.PetscOptionsGetString
402
403        """
404        return getopt(self.opt, OPT_STRING, self.prefix, name, default)
405
406    #
407
408    def insertString(self, string: str) -> None:
409        """Insert a string in the options database.
410
411        Logically collective.
412
413        See Also
414        --------
415        petsc.PetscOptionsInsertString
416
417        """
418        cdef const char *cstring = NULL
419        string = str2bytes(string, &cstring)
420        CHKERR(PetscOptionsInsertString(self.opt, cstring))
421
422    def getAll(self) -> dict[str, str]:
423        """Return all the options and their values.
424
425        Not collective.
426
427        See Also
428        --------
429        petsc.PetscOptionsGetAll
430
431        """
432        cdef char *allopts = NULL
433        CHKERR(PetscOptionsGetAll(self.opt, &allopts))
434        options = bytes2str(allopts)
435        CHKERR(PetscFree(allopts))
436        return parseopt(options, self.prefix)
437
438# --------------------------------------------------------------------
439