# -*- coding: utf-8 -*-
#
# FiPy documentation build configuration file, created by
# sphinx-quickstart on Sat Aug 29 21:50:21 2009.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.

import sys, os

# 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 pathlib
import sys
sys.path.insert(0, pathlib.Path(__file__).parents[2].resolve().as_posix())
sys.path.append(pathlib.Path('sphinxext').resolve().as_posix())
sys.path.append(pathlib.Path('tutorial').resolve().as_posix())

# -- General configuration -----------------------------------------------------

# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = ['sphinx.ext.autodoc',
              'sphinx.ext.doctest',
              'sphinx.ext.intersphinx',
              'sphinx.ext.todo',
              'sphinx.ext.coverage',
              'sphinx.ext.ifconfig',
              'sphinx.ext.autosummary',
              'sphinx.ext.imgconverter',
              'sphinx.ext.napoleon',
              'sphinx_readme',
              'sphinxcontrib.bibtex',
              'matplotlib.sphinxext.plot_directive']

# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']

# The suffix of source filenames.
source_suffix = '.rst'

# The encoding of source files.
#source_encoding = 'utf-8'

# The root toctree document.
root_doc = 'contents'

bibtex_bibfiles = ['refs.bib']

# General information about the project.
project = u'FiPy'
copyright = u'works of NIST employees are not not subject to copyright protection in the United States'

# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#

import fipy

# The short X.Y version.
version = fipy.__version__
# The full version, including alpha/beta/rc tags.
release = fipy.__version__

# Without this import, get metric craptons of
#   TypeError("'>' not supported between instances of 'size' and 'int'")
import fipy

# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None

# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'

# List of documents that shouldn't be included in the build.
unused_docs = ['RESOURCES',
               'TODOLIST',
               'VERSION']

# List of directories, relative to source directory, that shouldn't be searched
# for source files.
exclude_patterns = ['_build',
                    '_templates',
                    'sphinxext',]

# The reST default role (used for this markup: `text`) to use for all documents.
#default_role = None

# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True

# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True

# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False

# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'

# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []

autoclass_content = "both"

autodoc_default_options = {
    'member-order': 'alphabetical',
    'special-members': True,
    'inherited-members': True,
    'show-inheritance': True,
    'exclude-members': '__annotations__, __dict__, __init__, __module__, __weakref__'
}

autodoc_mock_imports = ['pyamg', 'pyamgx', 'pysvn', 'PyTrilinos.NOX',
                        'PyTrilinos', 'petsc4py', 'mpi4py',
                        'mayavi', 'enthought']

napoleon_numpy_docstring = True
#
# [@MadPhysicist](https://stackoverflow.com/users/2988730/mad-physicist)
# [CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/)
# https://stackoverflow.com/a/66182779
# Corrected for https://github.com/sphinx-doc/sphinx/issues/10963
napoleon_preprocess_types = True
napoleon_type_aliases = {
    'array-like': ':term:`array-like <array_like>`',
    'array_like': ':term:`array_like`'
}

autosummary_generate = True

# ~~enable~~ disable :numref:
#
# note: :numref: doesn't work with .. plot::
# https://github.com/matplotlib/matplotlib/issues/9346
#
# There's a workaround, but it's gross
# https://github.com/sfstoolbox/theory/issues/5
#
# Figure numbers skip by 2? Another .. plot:: glitch?
numfig = False

# numpydoc_show_class_members = False

# -- Options for HTML output ---------------------------------------------------

# The theme to use for HTML and HTML Help pages.  Major themes that come with
# Sphinx are currently 'default' and 'sphinxdoc'.
html_theme = 'nist'

# Theme options are theme-specific and customize the look and feel of a theme
# further.  For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}

# Add any paths that contain custom themes here, relative to this directory.
html_theme_path = ['_themes']

# The name for this set of Sphinx documents.  If None, it defaults to
# "<project> v<release> documentation".
#html_title = None

# A shorter title for the navigation bar.  Default is the same as html_title.
#html_short_title = None

# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
html_logo = '_static/logo.png'

# The name of an image file (within the static path) to use as favicon of the
# docs.  This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
html_favicon = '_static/favicon.ico'

# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']

# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
html_last_updated_fmt = '%b %d, %Y'

# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True

# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
html_sidebars = {'index': ['indexsidebar.html', 'searchbox.html', 'contact.html'],
                 '**': ['localtoc.html', 'relations.html', 'sourcelink.html', 'searchbox.html', 'contact.html']}

# Additional templates that should be rendered to pages, maps page names to
# template names.
html_additional_pages = {
    'index': 'index.html',
}

# If false, no module index is generated.
#html_use_modindex = True

# If false, no index is generated.
#html_use_index = True

# If true, the index is split into individual pages for each letter.
#html_split_index = False

# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True

# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
html_show_copyright = False

# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it.  The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''

# If nonempty, this is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = ''

# Output file base name for HTML help builder.
htmlhelp_basename = 'FiPydoc'

mathjax3_config = {
  "loader": {"load": ['[tex]/textmacros']},
  "tex": {"packages": {'[+]': ['textmacros']}}
}

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

latex_elements = {
    'fncychap': r"\usepackage[PetersLenny]{fncychap}",
    'preamble': r"""
        \usepackage{nist}

        \usepackage[amssymb]{SIunits}
        \usepackage{changepage}

        \DeclareMathOperator{\erf}{erf}
        \DeclareMathOperator{\Ei}{ei}
        \providecommand{\abs}[1]{\lvert#1\rvert}


        \authoraddress{Materials Science and Engineering Division \\
        and the Center for Theoretical and Computational Materials Science \\
        Material Measurement Laboratory}

        \definecolor{redish}{rgb}{0.894,0.122,0.122}
        \definecolor{bluish}{rgb}{0.216,0.188,0.533}

        \newcommand{\fipylogo}{\scalebox{10}{\rotatebox{4}{\textcolor{redish}{\( \varphi \)}}\kern-.70em\raisebox{-.15em}{\textcolor{bluish}{\( \pi\)}}}}

        \usepackage{pdflscape}
    """,
    'printindex': r'\footnotesize\raggedright\printindex',
}

# The paper size ('letter' or 'a4').
#latex_paper_size = 'letter'

# The font size ('10pt', '11pt' or '12pt').
#latex_font_size = '10pt'

# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
  ('manual', 'fipy.tex', 'FiPy Manual',
   r'Jonathan E. Guyer \\ Daniel Wheeler \\ James A. Warren', 'manual'),
]

# The name of an image file (relative to this directory) to place at the top of
# the title page.
# latex_logo = None

# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
latex_toplevel_sectioning = 'part'

# Goofy `.tex.txt` suffix required to keep files from being submitted to
# PDF build process
# https://www.sphinx-doc.org/en/master/latex.html#the-latex-elements-configuration-setting
latex_additional_files = [
    'nist.sty',
    'figures/nistident_flright_vec.pdf',
    'LICENSE.tex.txt',
    'DISCLAIMER.tex.txt'
]

# Documents to append as an appendix to all manuals.
# latex_appendices = ['docs/source/refs.bib_cited']

# If false, no module index is generated.
#latex_use_modindex = True

# --------------------------------------------------------

# refer to Python, NumPy, SciPy, matplotlib
intersphinx_mapping = {
    'python': ('https://docs.python.org/3/', None),
    'numpy': ('https://numpy.org/doc/stable/', None),
    'scipy': ('https://docs.scipy.org/doc/scipy/', None),
    'matplotlib': ('https://matplotlib.org/stable/', None),
    'mayavi': ('http://docs.enthought.com/mayavi/mayavi', None),
    'steppyngstounes': ('https://pages.nist.gov/steppyngstounes/en/stable/', None),
}

def skip_numpy_not_numerix(app, what, name, obj, skip, options):
    import types
    import numpy

    screen_types = [types.FunctionType,
                     types.BuiltinFunctionType,
                     type(numpy.dtype),
                     type]

    try:
        # NumPy 1.25 changed how dispatching works
        # which makes many numpy functions not Python functions
        # https://github.com/numpy/numpy/pull/23020
        screen_types.append(numpy.core._multiarray_umath._ArrayFunctionDispatcher)
    except:
        pass

    if type(obj) in screen_types:
        module = getattr(obj, "__module__", "")
        if module is None:
            module = ""
        if not (module.startswith("fipy")
                or module.startswith("package")):
            skip = True
    return skip

def skip_mayavi_baseclass(app, what, name, obj, skip, options):
    return True if name in ["trait_property_changed",
                            "trait_items_event"] else None

def autodoc_skip_member(app, what, name, obj, skip, options):
    return (skip_numpy_not_numerix(app, what, name, obj, skip, options)
            or skip_mayavi_baseclass(app, what, name, obj, skip, options))

def setup(app):
    app.connect('autodoc-skip-member', autodoc_skip_member)
    app.add_css_file('widetable.css')
    
# lifted from astropy/astropy@e68ca1a1

# Enable nitpicky mode - which ensures that all references in the docs
# resolve.

# Lots of things aren't defined, though
# https://stackoverflow.com/a/30624034/2019542

nitpicky = True
nitpick_ignore = []

for line in open('nitpick-exceptions'):
    if line.strip() == "" or line.startswith("#"):
        continue
    dtype, target = line.split(None, 1)
    target = target.strip()
    nitpick_ignore.append((dtype, target))


# sphinx-readme options
# See https://sphinx-readme.readthedocs.io/en/latest/configuration/configuring.html
html_context = {
    'display_github': True,
    'github_user': 'usnistgov',
    'github_repo': 'fipy',
}

html_baseurl = "https://pages.nist.gov/fipy/en/latest/"

readme_src_files = [
    "CHANGELOG.rst",
    "INSTALLATION.rst",
    "README.rst",
]
readme_docs_url_type = "code"

readme_raw_directive = False
