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