Belle II Software development
conf.py
1#!/usr/bin/env python3
2#
3# basf2 documentation build configuration file, created by
4# sphinx-quickstart on Mon May 23 17:26:16 2016.
5#
6# This file is execfile()d with the current directory set to its
7# containing dir.
8#
9# Note that not all possible configuration values are present in this
10# autogenerated file.
11#
12# All configuration values have a default; values that are commented out
13# serve to show the default.
14
15import sys
16import os
17import re
18import subprocess
19
20sys.path.insert(0, os.path.abspath("extensions"))
21
22# If extensions (or modules to document with autodoc) are in another directory,
23# add these directories to sys.path here. If the directory is relative to the
24# documentation root, use os.path.abspath to make it absolute, like shown here.
25# sys.path.insert(0, os.path.abspath('....'))
26
27# -- General configuration ------------------------------------------------
28
29# If your documentation needs a minimal Sphinx version, state it here.
30# needs_sphinx = '1.0'
31
32# Add any Sphinx extension module names here, as strings. They can be
33# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
34# ones.
35extensions = [
36 'sphinx.ext.intersphinx',
37 'sphinx.ext.autodoc',
38 # 'sphinx.ext.autosummary',
39 'sphinx.ext.mathjax',
40 'sphinx.ext.napoleon',
41 'sphinx.ext.viewcode',
42 'sphinx.ext.autosectionlabel',
43 'sphinx_codeautolink',
44 'sphinxarg.ext',
45 'basf2ext',
46 'nbsphinx',
47 'sphinxcontrib.programoutput',
48 'IPython.sphinxext.ipython_console_highlighting',
49]
50
51# Codeautolink warnings for compilation. Turned off due to conflicts with line
52# numbering.
53codeautolink_warn_on_missing_inventory = False
54codeautolink_warn_on_failed_resolve = False
55
56basf2_doxygen_xml_dir = f"{os.environ.get('BELLE2_RELEASE_DIR', os.environ.get('BELLE2_LOCAL_DIR'))}/build/doxygen/xml"
57
58nbsphinx_allow_errors = True
59
60# autosummary_generate = True
61
62# prefix each section with the name of the document it is in followed by a
63# colon
64autosectionlabel_prefix_document = True
65suppress_warnings = ['autosectionlabel.*', 'codeautolink.*']
66
67# Add any paths that contain templates here, relative to this directory.
68templates_path = ['_sphinxtemplates']
69
70# The suffix(es) of source filenames.
71# You can specify multiple suffix as a list of string:
72# source_suffix = ['.rst', '.md']
73source_suffix = '.rst'
74
75# The encoding of source files.
76# source_encoding = 'utf-8-sig'
77
78# The master toctree document.
79master_doc = 'index'
80
81# General information about the project.
82project = 'basf2'
83copyright = 'Belle II Collaboration'
84author = 'Belle II Software Group'
85
86# The version info for the project you're documenting, acts as replacement for
87# |version| and |release|, also used in various other places throughout the
88# built documents.
89#
90# The short X.Y version.
91version = subprocess.check_output(["git", "rev-parse", "--short", "HEAD"]).decode().strip()
92# Used for links to the repository
93basf2_repository = "https://gitlab.desy.de/belle2/software/basf2/"
94basf2_commitid = subprocess.check_output(["git", "rev-parse", "HEAD"]).decode().strip()
95basf2_issues = "https://gitlab.desy.de/belle2/software/basf2/-/issues/"
96
97# The full version, including alpha/beta/rc tags.
98release = os.environ.get('BELLE2_RELEASE', 'development')
99if release == 'head':
100 release = 'development'
101
102# Add warnings in the code if this is not a release
103keep_warnings = release == "development"
104nitpicky = keep_warnings
105
106# Mask false warnings
107nitpick_ignore = []
108for entry in ['cppyy.gbl.TObject', 'cppyy.gbl.TFile', 'ROOT.TFile']:
109 nitpick_ignore.append(('py:class', entry))
110for entry in ['int', 'bool', 'list', 'str', 'object', 'None', 'LogConfig', 'ProcessStatistics.ModuleStatistics']:
111 nitpick_ignore.append(('py:class', entry + ' :'))
112
113basf2_doxygen_baseurl = f"https://software.belle2.org/{release}/doxygen/"
114
115# The language for content autogenerated by Sphinx. Refer to documentation
116# for a list of supported languages.
117#
118# This is also used if you do content translation via gettext catalogs.
119# Usually you set "language" from the command line for these cases.
120language = 'en'
121
122# There are two options for replacing |today|: either, you set today to some
123# non-false value, then it is used:
124# today = ''
125# Else, today_fmt is used as the format for a strftime call.
126# today_fmt = '%B %d, %Y'
127
128# List of patterns, relative to source directory, that match files and
129# directories to ignore when looking for source files.
130# This patterns also effect to html_static_path and html_extra_path
131exclude_patterns = ['.*', '_sphinxbuild', 'Thumbs.db', 'build', 'include', 'lib', 'bin', 'modules', 'data', 'site_scons']
132# If we want to create the light release documentation then we need to exclude anything not in the light release.
133if tags.has('light'): # noqa
134 light_packages = {entry.strip('/') for entry in open('../../.light').read().split() if entry.endswith('/')}
135 for entry in os.listdir("../../"):
136 if entry.find('.') > -1 or os.path.isfile(entry) or entry in exclude_patterns or entry in light_packages:
137 continue
138 exclude_patterns.append(entry)
139 del light_packages
140
141# now we need to exclude everything in the build dir except for the tools_doc
142# sub dir but there's no negative exclusion pattern so do it manually
143exclude_patterns.remove("build")
144exclude_patterns += ['build/html', 'build/latex', 'build/json', 'build/Linux*', 'build/belle2_tools']
145# Ignore jupyter notebooks by default, we only want the ones meant for documentation
146exclude_patterns += ['**/*.ipynb', '*.ipynb']
147
148# The reST default role (used for this markup: `text`) to use for all
149# documents. :any: allows easy linking to functions/classes/modules
150default_role = 'any'
151
152# If true, '()' will be appended to :func: etc. cross-reference text.
153# add_function_parentheses = True
154
155# If true, the current module name will be prepended to all description
156# unit titles (such as .. function::).
157# add_module_names = True
158
159# If true, sectionauthor and moduleauthor directives will be shown in the
160# output. They are ignored by default.
161# show_authors = False
162
163# The name of the Pygments (syntax highlighting) style to use.
164pygments_style = 'sphinx'
165
166# A list of ignored prefixes for module index sorting.
167# modindex_common_prefix = []
168
169# If true, keep warnings as "system message" paragraphs in the built documents.
170# keep_warnings = False
171
172# If true, `todo` and `todoList` produce output, else they produce nothing.
173todo_include_todos = False
174
175# If true, figures with captions automatically get figure numbers included at the start of the caption.
176# Also the :numref: role is allowed for figures. Referencing figures/sections etc in this way
177# will insert a reference to the reference number instead of the reference text/caption.
178numfig = True
179
180# -- Options for HTML output ----------------------------------------------
181
182# The theme to use for HTML and HTML Help pages. See the documentation for
183# a list of builtin themes.
184html_theme = 'sphinx_book_theme'
185
186# Theme options are theme-specific and customize the look and feel of a theme
187# further. For a list of options available for each theme, see the
188# documentation.
189# html_theme_options = {'stickysidebar': True}
190
191# Add any paths that contain custom themes here, relative to this directory.
192html_theme_path = ["_themes", ]
193
194# The name for this set of Sphinx documents.
195# "<project> v<release> documentation" by default.
196# html_title = 'basf2 vhead'
197
198# A shorter title for the navigation bar. Default is the same as html_title.
199# html_short_title = None
200
201# The name of an image file (relative to this directory) to place at the top
202# of the sidebar.
203html_logo = "b2logo.svg"
204
205# The name of an image file (relative to this directory) to use as a favicon of
206# the docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
207# pixels large.
208# html_favicon = None
209
210# Add any paths that contain custom static files (such as style sheets) here,
211# relative to this directory. They are copied after the builtin static files,
212# so a file named "default.css" will overwrite the builtin "default.css".
213html_static_path = ['_sphinxstatic']
214
215# Add any extra paths that contain custom files (such as robots.txt or
216# .htaccess) here, relative to this directory. These files are copied
217# directly to the root of the documentation.
218# html_extra_path = []
219
220# If not None, a 'Last updated on:' timestamp is inserted at every page
221# bottom, using the given strftime format.
222# The empty string is equivalent to '%b %d, %Y'.
223# html_last_updated_fmt = None
224
225# If true, SmartyPants will be used to convert quotes and dashes to
226# typographically correct entities.
227# html_use_smartypants = True
228
229# Custom sidebar templates, maps document names to template names.
230# html_sidebars = {}
231
232# Additional templates that should be rendered to pages, maps page names to
233# template names.
234# html_additional_pages = {}
235
236# If false, no module index is generated.
237# html_domain_indices = True
238
239# If false, no index is generated.
240# html_use_index = True
241
242# If true, the index is split into individual pages for each letter.
243# html_split_index = False
244
245# If true, links to the reST sources are added to the pages.
246# html_show_sourcelink = True
247
248# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
249# html_show_sphinx = True
250
251# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
252# html_show_copyright = True
253
254# If true, an OpenSearch description file will be output, and all pages will
255# contain a <link> tag referring to it. The value of this option must be the
256# base URL from which the finished HTML is served.
257# html_use_opensearch = ''
258
259# This is the file name suffix for HTML files (e.g. ".xhtml").
260# html_file_suffix = None
261
262# Language to be used for generating the HTML full-text search index.
263# Sphinx supports the following languages:
264# 'da', 'de', 'en', 'es', 'fi', 'fr', 'h', 'it', 'ja'
265# 'nl', 'no', 'pt', 'ro', 'r', 'sv', 'tr', 'zh'
266# html_search_language = 'en'
267
268# A dictionary with options for the search language support, empty by default.
269# 'ja' uses this config value.
270# 'zh' user can custom change `jieba` dictionary path.
271# html_search_options = {'type': 'default'}
272
273# The name of a javascript file (relative to the configuration directory) that
274# implements a search results scorer. If empty, the default will be used.
275# html_search_scorer = 'scorer.js'
276
277# Output file base name for HTML help builder.
278htmlhelp_basename = 'basf2doc'
279
280# -- Options for LaTeX output ---------------------------------------------
281
282latex_elements = {
283 # The paper size ('letterpaper' or 'a4paper').
284 'papersize': 'a4paper',
285
286 # The font size ('10pt', '11pt' or '12pt').
287 'pointsize': '10pt',
288
289 # Additional stuff for the LaTeX preamble.
290 'preamble': '\\setcounter{tocdepth}{2}',
291
292 # Latex figure (float) alignment
293 # 'figure_align': 'htbp',
294}
295
296# Grouping the document tree into LaTeX files. List of tuples
297# (source start file, target name, title,
298# author, documentclass [howto, manual, or own class]).
299latex_documents = [
300 (master_doc, 'basf2.tex', 'Belle II Software Documentation',
301 author, 'manual'),
302]
303
304# The name of an image file (relative to this directory) to place at the top of
305# the title page.
306latex_logo = "belle2-logo.pdf"
307
308# For "manual" documents, if this is true, then toplevel headings are parts,
309# not chapters.
310latex_use_parts = True
311latex_show_urls = 'footnote'
312latex_show_pagerefs = True
313
314# If true, show page references after internal links.
315# latex_show_pagerefs = False
316
317# If true, show URL addresses after external links.
318# latex_show_urls = False
319
320# Documents to append as an appendix to all manuals.
321# latex_appendices = []
322
323# If false, no module index is generated.
324# latex_domain_indices = True
325
326
327# -- Options for manual page output ---------------------------------------
328
329# One entry per manual page. List of tuples
330# (source start file, name, description, authors, manual section).
331man_pages = [
332 (master_doc, 'basf2', 'basf2 Documentation',
333 [author], 1)
334]
335
336# If true, show URL addresses after external links.
337# man_show_urls = False
338
339
340# -- Options for Texinfo output -------------------------------------------
341
342# Grouping the document tree into Texinfo files. List of tuples
343# (source start file, target name, title, author,
344# dir menu entry, description, category)
345texinfo_documents = [
346 (master_doc, 'basf2', 'basf2 Documentation',
347 author, 'basf2', 'One line description of project.',
348 'Miscellaneous'),
349]
350
351# Documents to append as an appendix to all manuals.
352# texinfo_appendices = []
353
354# If false, no module index is generated.
355# texinfo_domain_indices = True
356
357# How to display URL addresses: 'footnote', 'no', or 'inline'.
358# texinfo_show_urls = 'footnote'
359
360# If true, do not generate a @detailmenu in the "Top" node's menu.
361# texinfo_no_detailmenu = False
362
363# allow to have links to python documentation
364intersphinx_mapping = {'python': ('https://docs.python.org/3.11/', None),
365 'numpy': ('https://numpy.org/doc/stable/', None),
366 'scipy': ('https://docs.scipy.org/doc/scipy/', None),
367 'pandas': ('https://pandas.pydata.org/docs/', None),
368 'matplotlib': ('https://matplotlib.org/stable/', None),
369 'b2luigi': ('https://b2luigi.belle2.org/', None),
370 'gbasf2': ('https://gbasf2.belle2.org/', None),
371 'uproot': ('https://uproot.readthedocs.io/en/stable/', None)}
372
373
374def process_sig(app, what, name, obj, options, signature, return_annotation):
375 """
376 remove unhelpful 'self' arguments from methods.
377 """
378 if what == 'method' and signature:
379 reg = re.compile('^\\( \\(.*\\)arg1')
380 signature = reg.sub('(', signature)
381 return (signature, return_annotation)
382
383
384def improve_docstring(obj):
385 """
386 Enhances docstrings of PyROOT objects/classes.
387
388 >>> improve_docstring(Belle2.Variable.Manager)
389
390 or
391
392 >>> variables = ROOT.Belle2.Variable.Manager
393 >>> improve_docstring(variables)
394 """
395 try:
396 # is this a ..._meta object?
397 classname = obj.__name__
398 pyclass = obj
399 except AttributeError:
400 classname = obj.__class__.__name__
401 pyclass = obj.__class__
402
403 if '::' not in classname:
404 return # not a ROOT class?
405 pos = classname.find('Belle2::')
406 classname = classname[pos:]
407 if pyclass.__doc__ is None:
408 pyclass.__doc__ = ''
409
410 pyclass.__name__ = 'Belle2.' + classname
411
412 from ROOT import TClass
413 tclass = TClass(classname)
414 # if tclass:
415 # pyclass.__doc__ += '\n' + tclass.GetTitle()
416
417 doxygen_url = f'{basf2_doxygen_baseurl}/class'
418 doxygen_url += '_1_1'.join(classname.split('::'))
419 doxygen_url += '.html'
420 pyclass.__doc__ += f'\n`Doxygen page for {classname} <{doxygen_url}>`_'
421
422 # TODO put this into the member docstrings directly? (sadly, readonly)
423 members = tclass.GetListOfMethods()
424 if members.GetEntries() > 0:
425 pyclass.__doc__ += '\n\nMember functions:'
426 for f in members:
427 # getattr(pyclass, f.GetName()).__doc__ = "test"
428 pyclass.__doc__ += f'\n * {f.GetReturnTypeName()} {f.GetName()}{f.GetSignature()}'
429 title = f.GetTitle()
430 if title:
431 pyclass.__doc__ += f' ({title})'
432
433 members = tclass.GetListOfAllPublicDataMembers()
434 if members.GetEntries() > 0:
435 pyclass.__doc__ += '\n\nPublic data members'
436 for f in members:
437 pyclass.__doc__ += f'\n * {f.GetName()}'
438 title = f.GetTitle()
439 if title:
440 pyclass.__doc__ += f' ({title})'
441
442
443def skipmember(app, what, name, obj, skip, options):
444 """
445 This is executed before docstring processing,
446 so try improving them a bit.
447 """
448 try:
449 improve_docstring(obj)
450 except AttributeError:
451 pass
452 return skip
453
454
455def process_docstring(app, what, name, obj, options, lines):
456 """
457 convert doxygen syntax to sphinx
458 """
459 substitutions = {
460 re.compile(r'^( *)@param (.*?):? '): r':param \2: ',
461 re.compile(r'^( *)@returns? '): r':return: ',
462 }
463 newlines = []
464 for line in lines:
465 new = line
466 for reg, sub in substitutions.items():
467 new = reg.sub(sub, new)
468 if new != line:
469 # Sphinx wants a new paragraph before these, so let's add one
470 newlines += ['']
471 newlines += [new]
472 lines[:] = newlines
473
474
475def setup(app):
476 """
477 Install some event handlers to improve output.
478 """
479 app.connect('autodoc-process-signature', process_sig)
480 app.connect('autodoc-process-docstring', process_docstring)
481 app.connect('autodoc-skip-member', skipmember)
482 app.add_css_file('css/custom.css')