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