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