File: conf.py

package info (click to toggle)
slepc4py 3.24.0-1exp1
  • links: PTS, VCS
  • area: main
  • in suites: experimental
  • size: 2,384 kB
  • sloc: python: 6,364; makefile: 126; ansic: 98; sh: 46
file content (545 lines) | stat: -rw-r--r-- 17,963 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
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
# Configuration file for the Sphinx documentation builder.
#
# For the full list of built-in configuration values, see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html

# -- Path setup --------------------------------------------------------------

# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.

import re
import os
import shutil
import sys
import subprocess
import typing
import datetime
import importlib
import sphobjinv
import functools
#import pylit
from sphinx.ext.napoleon.docstring import NumpyDocstring

# apidoc
sys.path.insert(0, os.path.abspath('.'))
_today = datetime.datetime.now()

# FIXME: allow building from build?

# -- Project information -----------------------------------------------------
# https://www.sphinx-doc.org/en/master/usage/configuration.html#project-information

package = 'slepc4py'

docdir = os.path.abspath(os.path.dirname(__file__))
topdir = os.path.abspath(os.path.join(docdir, *[os.path.pardir] * 2))


def pkg_version():
    with open(os.path.join(topdir, 'src', package, '__init__.py')) as f:
        m = re.search(r"__version__\s*=\s*'(.*)'", f.read())
        return m.groups()[0]


def get_doc_branch():
    release = 1
    if topdir.endswith(os.path.join(os.path.sep, 'src', 'binding', package)):
        rootdir = os.path.abspath(os.path.join(topdir, *[os.path.pardir] * 3))
        rootname = package.replace('4py', '')
        version_h = os.path.join(rootdir, 'include', f'{rootname}version.h')
        if os.path.exists(version_h) and os.path.isfile(version_h):
            release_macro = f'{rootname.upper()}_VERSION_RELEASE'
            version_re = re.compile(rf'#define\s+{release_macro}\s+([-]*\d+)')
            with open(version_h, 'r') as f:
                release = int(version_re.search(f.read()).groups()[0])
    return 'release' if release else 'main'


__project__ = 'SLEPc for Python'
__author__ = 'Lisandro Dalcin'
__copyright__ = f'{_today.year}, {__author__}'

release = pkg_version()
version = release.rsplit('.', 1)[0]


# -- General configuration ---------------------------------------------------
# https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration

extensions = [
    'sphinx.ext.autodoc',
    'sphinx.ext.autosummary',
    'sphinx.ext.intersphinx',
    'sphinx.ext.napoleon',
    'sphinx.ext.extlinks',
]

templates_path = ['_templates']
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']

default_role = 'any'

pygments_style = 'tango'

nitpicky = True
nitpick_ignore = [
    ('envvar', 'NUMPY_INCLUDE'),
    ('envvar', 'SLEPC_DIR'),
    ('envvar', 'PETSC_DIR'),
    ('envvar', 'PETSC_ARCH'),
    ('envvar', 'MACOSX_DEPLOYMENT_TARGET'),
    ('envvar', 'SDKROOT'),
    ('envvar', 'ARCHFLAGS'),
    ('py:class', 'ndarray'),  # FIXME
    ('py:class', 'typing_extensions.Self'),
]
nitpick_ignore_regex = [
    (r'c:.*', r'MPI_.*'),
    (r'c:.*', r'Slepc.*'),
    (r'envvar', r'(LD_LIBRARY_)?PATH'),
    (r'envvar', r'(MPICH|OMPI|MPIEXEC)_.*'),
]

toc_object_entries = False
toc_object_entries_show_parents = 'hide'
# python_use_unqualified_type_names = True

autodoc_class_signature = 'separated'
autodoc_typehints = 'description'
autodoc_typehints_format = 'short'
autodoc_mock_imports = []
autodoc_type_aliases = {}

autosummary_context = {
    'synopsis': {},
    'autotype': {},
}

# Links depends on the actual branch -> release or main
www = f'https://gitlab.com/slepc/slepc/-/tree/{get_doc_branch()}'
#extlinks = {'sources': (f'{www}/src/binding/slepc4py/src/%s', '%s')}

napoleon_preprocess_types = True

try:
    import sphinx_rtd_theme

    if 'sphinx_rtd_theme' not in extensions:
        extensions.append('sphinx_rtd_theme')
except ImportError:
    sphinx_rtd_theme = None

intersphinx_mapping = {
    'python': ('https://docs.python.org/3/', ('/usr/share/doc/python3/html/objects.inv', None)),
    'numpy': ('https://numpy.org/doc/stable/', ('/usr/share/doc/python-numpy/html/objects.inv', None)),
    'numpydoc': ('https://numpydoc.readthedocs.io/en/latest/', None),
    'mpi4py': ('https://mpi4py.readthedocs.io/en/stable/', ('/usr/share/doc/python-mpi4py-doc/html/objects.inv', None)),
    'pyopencl': ('https://documen.tician.de/pyopencl/', ('/usr/share/doc/python-pyopencl-doc/html/objects.inv', None)),
    'dlpack': ('https://dmlc.github.io/dlpack/latest/', None),
    'petsc': ('https://petsc.org/release/', ('/usr/share/doc/petsc3.24-doc/docs/objects.inv', None)),
    'petsc4py': ('https://petsc.org/release/petsc4py/', ('/usr/share/doc/python-petsc4py-doc/html/objects.inv', None)),
    'slepc': ('https://slepc.upv.es/release/', ('/usr/share/doc/slepc3.24-doc/docs/objects.inv', None)),
}

intersphinx_resolve_self = 'slepc'

def _mangle_petsc_intersphinx():
    """Preprocess the keys in PETSc's intersphinx inventory.

    PETSc have intersphinx keys of the form:

        manualpages/Vec/VecShift

    instead of:

        petsc.VecShift

    This function downloads their object inventory and strips the leading path
    elements so that references to PETSc names actually resolve."""

    website = intersphinx_mapping['petsc'][0].partition('/release/')[0]
    branch = get_doc_branch()
    doc_url = f'{website}/{branch}/'
    inventory_url = None
    if 'LOC_PETSC' in os.environ:
        inventory_file = os.path.join(os.environ['LOC_PETSC'], 'objects.inv')
        inventory_url = 'file://' + inventory_file
        if not os.path.isfile(inventory_file):
            print('PETSC inventory not found at ' + inventory_url)
            print('Check code for errors')
            inventory_url = None
    if inventory_url is None:
        inventory_url = f'{doc_url}objects.inv'
    print('Using PETSC inventory from ' + inventory_url)
    inventory = sphobjinv.Inventory(url=inventory_url)
    print(inventory)

    for obj in inventory.objects:
        if obj.name.startswith('manualpages'):
            obj.name = 'petsc.' + '/'.join(obj.name.split('/')[2:])
            obj.role = 'class'
            obj.domain = 'py'

    new_inventory_filename = 'petsc_objects.inv'
    sphobjinv.writebytes(
        new_inventory_filename, sphobjinv.compress(inventory.data_file(contract=True))
    )
    intersphinx_mapping['petsc'] = (doc_url, new_inventory_filename)

def _mangle_slepc_intersphinx():
    """Preprocess the keys in SLEPc's intersphinx inventory.

    SLEPc have intersphinx keys of the form:

        manualpages/BV/BVGetSizes

    instead of:

        slepc.BVGetSizes

    This function downloads their object inventory and strips the leading path
    elements so that references to SLEPc names actually resolve."""

    website = intersphinx_mapping['slepc'][0].partition('/release/')[0]
    branch = get_doc_branch()
    doc_url = f'{website}/{branch}/'
    inventory_url = None
    if 'LOC' in os.environ:
        inventory_file = os.path.join(os.environ['LOC'], 'objects.inv')
        inventory_url = 'file://' + inventory_file
        if not os.path.isfile(inventory_file):
            print('SLEPC inventory not found at ' + inventory_url)
            print('Check code for errors')
            inventory_url = None
    if inventory_url is None:
        inventory_url = f'{doc_url}objects.inv'
    print('Using SLEPC inventory from ' + inventory_url)
    inventory = sphobjinv.Inventory(url=inventory_url)
    print(inventory)

    for obj in inventory.objects:
        if obj.name.startswith('manualpages'):
            obj.name = 'slepc.' + '/'.join(obj.name.split('/')[2:])
            obj.role = 'class'
            obj.domain = 'py'

    new_inventory_filename = 'slepc_objects.inv'
    sphobjinv.writebytes(
        new_inventory_filename, sphobjinv.compress(inventory.data_file(contract=True))
    )
    intersphinx_mapping['slepc'] = (doc_url, new_inventory_filename)


_mangle_petsc_intersphinx()
_mangle_slepc_intersphinx()


def _setup_mpi4py_typing():
    pkg = type(sys)('mpi4py')
    mod = type(sys)('mpi4py.MPI')
    mod.__package__ = pkg.__name__
    sys.modules[pkg.__name__] = pkg
    sys.modules[mod.__name__] = mod
    for clsname in (
        'Intracomm',
        'Datatype',
        'Op',
    ):
        cls = type(clsname, (), {})
        cls.__module__ = mod.__name__
        setattr(mod, clsname, cls)


def _patch_domain_python():
    from sphinx.domains.python import PythonDomain

    PythonDomain.object_types['data'].roles += ('class',)


def _setup_autodoc(app):
    from sphinx.ext import autodoc
    from sphinx.util import inspect
    from sphinx.util import typing

    #

    def stringify_annotation(annotation, mode='fully-qualified-except-typing'):
        qualname = getattr(annotation, '__qualname__', '')
        module = getattr(annotation, '__module__', '')
        args = getattr(annotation, '__args__', None)
        if module == 'builtins' and qualname and args is not None:
            args = ', '.join(stringify_annotation(a, mode) for a in args)
            return f'{qualname}[{args}]'
        return stringify_annotation_orig(annotation, mode)

    try:
        stringify_annotation_orig = typing.stringify_annotation
        inspect.stringify_annotation = stringify_annotation
        typing.stringify_annotation = stringify_annotation
        autodoc.stringify_annotation = stringify_annotation
        autodoc.typehints.stringify_annotation = stringify_annotation
    except AttributeError:
        stringify_annotation_orig = typing.stringify
        inspect.stringify_annotation = stringify_annotation
        typing.stringify = stringify_annotation
        autodoc.stringify_typehint = stringify_annotation

    #

    class ClassDocumenterMixin:
        def __init__(self, *args, **kwargs):
            super().__init__(*args, **kwargs)
            if self.config.autodoc_class_signature == 'separated':
                members = self.options.members
                special_members = self.options.special_members
                if special_members is not None:
                    for name in ('__new__', '__init__'):
                        if name in members:
                            members.remove(name)
                        if name in special_members:
                            special_members.remove(name)

    class ClassDocumenter(
        ClassDocumenterMixin,
        autodoc.ClassDocumenter,
    ):
        pass

    class ExceptionDocumenter(
        ClassDocumenterMixin,
        autodoc.ExceptionDocumenter,
    ):
        pass

    app.add_autodocumenter(ClassDocumenter, override=True)
    app.add_autodocumenter(ExceptionDocumenter, override=True)


def _monkey_patch_returns():
    """Rewrite the role of names in "Returns" sections.

    This is needed because Napoleon uses ``:class:`` for the return types
    and this does not work with type aliases like ``ArrayScalar``. To resolve
    this we swap ``:class:`` for ``:any:``.

    """
    _parse_returns_section = NumpyDocstring._parse_returns_section

    @functools.wraps(NumpyDocstring._parse_returns_section)
    def wrapper(*args, **kwargs):
        out = _parse_returns_section(*args, **kwargs)
        return [line.replace(':class:', ':any:') for line in out]

    NumpyDocstring._parse_returns_section = wrapper


def _monkey_patch_see_also():
    """Rewrite the role of names in "see also" sections.

    Napoleon uses :obj: for all names found in "see also" sections but we
    need :all: so that references to labels work."""

    _parse_numpydoc_see_also_section = NumpyDocstring._parse_numpydoc_see_also_section

    @functools.wraps(NumpyDocstring._parse_numpydoc_see_also_section)
    def wrapper(*args, **kwargs):
        out = _parse_numpydoc_see_also_section(*args, **kwargs)
        return [line.replace(':obj:', ':any:') for line in out]

    NumpyDocstring._parse_numpydoc_see_also_section = wrapper


def _apply_monkey_patches():
    """Modify Napoleon types after parsing to make references work."""
    _monkey_patch_returns()
    _monkey_patch_see_also()


_apply_monkey_patches()


def _process_demos(*demos):
    # Convert demo .py files to rst. Also copy the .py file so it can be
    # linked from the demo rst file.
    try:
        os.mkdir('demo')
    except FileExistsError:
        pass
    for demo in demos:
        demo_dir = os.path.join('demo', os.path.dirname(demo))
        demo_src = os.path.join(os.pardir, os.pardir, 'demo', demo)
        try:
            os.mkdir(demo_dir)
        except FileExistsError:
            pass
        with open(demo_src, 'r') as infile:
            with open(
                os.path.join(os.path.join('demo', os.path.splitext(demo)[0] + '.rst')),
                'w',
            ) as outfile:
                converter = pylit.Code2Text(infile)
                outfile.write(str(converter))
        demo_copy_name = os.path.join(demo_dir, os.path.basename(demo))
        shutil.copyfile(demo_src, demo_copy_name)
        html_static_path.append(demo_copy_name)
    with open(os.path.join('demo', 'demo.rst'), 'w') as demofile:
        demofile.write("""
slepc4py demos
==============

.. toctree::

""")
        for demo in demos:
            demofile.write('    ' + os.path.splitext(demo)[0] + '\n')
        demofile.write('\n')


html_static_path = ['_static']
html_css_files = [ # relative to the html_static_path
                  'css/slepc.css',
                  ]
#_process_demos('ex1.py')


def setup(app):

    if 'PETSC_DIR' not in os.environ:
        print('\nUnable to build the documentation, PETSC_DIR environment variable is not set')
        print('\nPlease configure PETSc and SLEPc before building the documentation')
        raise Exception('PETSC_DIR not set')
    if 'PETSC_ARCH' not in os.environ:
        print('\nUnable to build the documentation, PETSC_ARCH environment variable is not set')
        print('\nPlease configure PETSc and SLEPc before building the documentation')
        raise Exception('PETSC_ARCH not set')
    else:
        # We know where we are, don't we?
        app.slepc_dir = os.path.abspath('../../../')
        app.petsc_dir = os.path.abspath(os.environ['PETSC_DIR'])
        app.petsc_arch = os.environ['PETSC_ARCH']

    sys.path.insert(0, os.path.abspath(app.petsc_dir
                                       +'/'
                                       +os.environ['PETSC_ARCH']
                                       +'/lib'))

    sys.path.insert(0, os.path.abspath(app.slepc_dir
                                       +'/'
                                       +os.environ['PETSC_ARCH']
                                       +'/lib'))
    print(sys.path)

    _setup_mpi4py_typing()
    _patch_domain_python()
    _monkey_patch_returns()
    _monkey_patch_see_also()
    #_setup_autodoc(app)

    try:
        from slepc4py import SLEPc
    except ImportError as e:
        print('ImportError: slepc4py '+str(e))
        autodoc_mock_imports.append('SLEPc')
        return

    sys_dwb = sys.dont_write_bytecode
    sys.dont_write_bytecode = True
    import apidoc

    sys.dont_write_bytecode = sys_dwb

    name = SLEPc.__name__
    here = os.path.abspath(os.path.dirname(__file__))
    outdir = os.path.join(here, apidoc.OUTDIR)
    source = os.path.join(outdir, f'{name}.py')
    print('source: {}'.format(source))
    getmtime = os.path.getmtime
    generate = (
        not os.path.exists(source)
        or getmtime(source) < getmtime(SLEPc.__file__)
        or getmtime(source) < getmtime(apidoc.__file__)
    )
    if generate:
        apidoc.generate(source)
    module = apidoc.load_module(source)
    apidoc.replace_module(module)

    modules = [
        'slepc4py',
    ]
    typing_overload = typing.overload
    typing.overload = lambda arg: arg
    for name in modules:
        mod = importlib.import_module(name)
        ann = apidoc.load_module(f'{mod.__file__}i', name)
        apidoc.annotate(mod, ann)
    typing.overload = typing_overload

    from slepc4py import typing as tp

    for attr in tp.__all__:
        autodoc_type_aliases[attr] = f'~slepc4py.typing.{attr}'


# -- Options for HTML output -------------------------------------------------
# https://www.sphinx-doc.org/en/master/usage/configuration.html#options-for-html-output

# The theme to use for HTML and HTML Help pages.  See the documentation for
# a list of builtin themes.
html_theme = 'pydata_sphinx_theme'

html_theme_options = {
    'navigation_with_keys': True,
    "footer_end": ["theme-version", "last-updated"],
}
git_describe_version = subprocess.check_output(['git', 'describe', '--always']).strip().decode('utf-8') # noqa: S603, S607
html_last_updated_fmt = r'%Y-%m-%dT%H:%M:%S%z (' + git_describe_version + ')'

# -- Options for HTMLHelp output ------------------------------------------

# Output file base name for HTML help builder.
htmlhelp_basename = f'{package}-man'


# -- Options for LaTeX output ---------------------------------------------

# (source start file, target name, title,
#  author, documentclass [howto, manual, or own class]).
latex_documents = [
    ('index', f'{package}.tex', __project__, __author__, 'howto'),
]

latex_elements = {
    'papersize': 'a4',
}


# -- Options for manual page output ---------------------------------------

# (source start file, name, description, authors, manual section).
man_pages = [('index', package, __project__, [__author__], 3)]


# -- Options for Texinfo output -------------------------------------------

# (source start file, target name, title, author,
#  dir menu entry, description, category)
texinfo_documents = [
    (
        'index',
        package,
        __project__,
        __author__,
        package,
        f'{__project__}.',
        'Miscellaneous',
    ),
]


# -- Options for Epub output ----------------------------------------------

# Output file base name for ePub builder.
epub_basename = package