Skip to content

Commit

Permalink
Improved type hints in documentation (#662)
Browse files Browse the repository at this point in the history
  • Loading branch information
JonathanWenger committed Mar 23, 2022
1 parent 0f19c11 commit d24b6b0
Show file tree
Hide file tree
Showing 40 changed files with 318 additions and 230 deletions.
3 changes: 3 additions & 0 deletions docs/source/api.rst
Expand Up @@ -25,6 +25,8 @@ API Reference
+-------------------------------------------------+--------------------------------------------------------------+
| :mod:`~probnum.randvars` | Random variables representing uncertain values. |
+-------------------------------------------------+--------------------------------------------------------------+
| :mod:`~probnum.typing` | Type aliases. |
+-------------------------------------------------+--------------------------------------------------------------+
| :mod:`~probnum.utils` | Utility functions. |
+-------------------------------------------------+--------------------------------------------------------------+

Expand All @@ -43,4 +45,5 @@ API Reference
api/quad
api/randprocs
api/randvars
api/typing
api/utils
8 changes: 8 additions & 0 deletions docs/source/api/typing.rst
@@ -0,0 +1,8 @@
**************
probnum.typing
**************

.. automodapi:: probnum.typing
:no-heading:
:headings: "="
:include-all-objects:
24 changes: 13 additions & 11 deletions docs/source/conf.py
Expand Up @@ -12,14 +12,15 @@
#
# All configuration values have a default; values that are commented out
# serve to show the default.

from datetime import datetime
import os
from pathlib import Path
import sys

from pkg_resources import DistributionNotFound, get_distribution

import probnum

# 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.
Expand All @@ -28,13 +29,11 @@

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

# If your documentation needs a minimal Sphinx version, state it here.
needs_sphinx = "3.0"

# 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.napoleon",
"sphinx.ext.doctest",
"sphinx.ext.intersphinx",
Expand All @@ -43,8 +42,6 @@
"sphinx.ext.mathjax",
"sphinx.ext.viewcode",
"sphinx_automodapi.automodapi",
"sphinx_autodoc_typehints",
"sphinxcontrib.bibtex",
"sphinx_gallery.load_style",
"myst_parser",
"nbsphinx",
Expand All @@ -54,22 +51,27 @@
# Add any paths that contain templates here, relative to this directory.
templates_path = ["_templates"]

# Settings for autodoc
autodoc_typehints = "description"
autodoc_typehints_description_target = "all"
autodoc_typehints_format = "short"
autodoc_type_aliases = {
type_alias: f"typing.{type_alias}" for type_alias in probnum.typing.__all__
} # Ensures type aliases are correctly displayed and linked in the documentation

# Settings for napoleon
napoleon_use_param = True

# Remove possible duplicate methods when using 'automodapi'
# autodoc_default_flags = ['no-members']
numpydoc_show_class_members = True


# Settings for automodapi
automodapi_toctreedirnm = "api/automod"
automodapi_writereprocessed = False
automodsumm_inherited_members = True

# Settings for autodoc_typehints
typehints_fully_qualified = False
typehints_document_rtype = True

# The suffix(es) of source filenames.
# You can specify multiple suffixes as a list of strings:
source_suffix = [".rst", ".md", ".ipynb"]
Expand Down Expand Up @@ -145,7 +147,7 @@
"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/", None),
"matplotlib": ("https://matplotlib.org/stable/", None),
}

# -- Options for HTML output ----------------------------------------------
Expand Down
22 changes: 11 additions & 11 deletions docs/source/development/adding_to_the_api_documentation.ipynb
Expand Up @@ -97,23 +97,23 @@
"\n",
" Parameters\n",
" ----------\n",
" A :\n",
" A\n",
" *shape=(n, n)* -- A square linear operator (or matrix). Only matrix-vector\n",
" products :math:`v \\mapsto Av` are used internally.\n",
" b :\n",
" b\n",
" *shape=(n, ) or (n, nrhs)* -- Right-hand side vector, matrix or random\n",
" variable in :math:`A x = b`.\n",
" A0 :\n",
" A0\n",
" *shape=(n, n)* -- A square matrix, linear operator or random variable\n",
" representing the prior belief about the linear operator :math:`A`.\n",
" Ainv0 :\n",
" Ainv0\n",
" *shape=(n, n)* -- A square matrix, linear operator or random variable\n",
" representing the prior belief about the inverse :math:`H=A^{-1}`. This can be\n",
" viewed as a preconditioner.\n",
" x0 :\n",
" x0\n",
" *shape=(n, ) or (n, nrhs)* -- Prior belief for the solution of the linear\n",
" system. Will be ignored if ``Ainv0`` is given.\n",
" assume_A :\n",
" assume_A\n",
" Assumptions on the linear operator which can influence solver choice and\n",
" behavior. The available options are (combinations of)\n",
"\n",
Expand All @@ -124,19 +124,19 @@
" (additive) noise ``noise``\n",
" ==================== =========\n",
"\n",
" maxiter :\n",
" maxiter\n",
" Maximum number of iterations. Defaults to :math:`10n`, where :math:`n` is the\n",
" dimension of :math:`A`.\n",
" atol :\n",
" atol\n",
" Absolute convergence tolerance.\n",
" rtol :\n",
" rtol\n",
" Relative convergence tolerance.\n",
" callback :\n",
" callback\n",
" User-supplied function called after each iteration of the linear solver. It is\n",
" called as ``callback(xk, Ak, Ainvk, sk, yk, alphak, resid, **kwargs)`` and can\n",
" be used to return quantities from the iteration. Note that depending on the\n",
" function supplied, this can slow down the solver considerably.\n",
" kwargs : optional\n",
" kwargs\n",
" Optional keyword arguments passed onto the solver iteration.\n",
"\n",
" Returns\n",
Expand Down
1 change: 0 additions & 1 deletion docs/sphinx-requirements.txt
Expand Up @@ -7,7 +7,6 @@ Pygments>=2.6.1
# Sphinx extensions
pydata-sphinx-theme>=0.6.0
sphinx-automodapi
sphinx-autodoc-typehints
sphinx-gallery
sphinxcontrib-bibtex

Expand Down
8 changes: 6 additions & 2 deletions src/probnum/_function.py
@@ -1,5 +1,7 @@
"""Function class defining a Callable with fixed in- and output shapes."""

from __future__ import annotations

import abc
from typing import Callable

Expand Down Expand Up @@ -41,7 +43,8 @@ def __init__(self, input_shape: ShapeLike, output_shape: ShapeLike = ()) -> None
def input_shape(self) -> ShapeType:
"""Shape of the function's input.
For a scalar-input function, this is an empty tuple."""
For a scalar-input function, this is an empty tuple.
"""
return self._input_shape

@property
Expand All @@ -53,7 +56,8 @@ def input_ndim(self) -> int:
def output_shape(self) -> ShapeType:
"""Shape of the function's output.
For scalar-valued function, this is an empty tuple."""
For scalar-valued function, this is an empty tuple.
"""
return self._output_shape

@property
Expand Down
2 changes: 2 additions & 0 deletions src/probnum/diffeq/_odesolver.py
@@ -1,5 +1,7 @@
"""ODE solver interface."""

from __future__ import annotations

from abc import ABC, abstractmethod
from collections import abc
import dataclasses
Expand Down
3 changes: 3 additions & 0 deletions src/probnum/diffeq/_perturbsolve_ivp.py
@@ -1,4 +1,7 @@
"""Perturbation-based probabilistic ODE solver."""

from __future__ import annotations

from typing import Callable, Optional

import numpy as np
Expand Down
2 changes: 2 additions & 0 deletions src/probnum/diffeq/_probsolve_ivp.py
Expand Up @@ -8,6 +8,8 @@
.. [4] https://arxiv.org/pdf/2004.00623.pdf
"""

from __future__ import annotations

from typing import Callable, Optional

import numpy as np
Expand Down
2 changes: 2 additions & 0 deletions src/probnum/filtsmooth/_kalman_filter_smoother.py
@@ -1,5 +1,7 @@
"""Convenience functions for filtering and smoothing."""

from __future__ import annotations

import numpy as np

from probnum import problems, randprocs, randvars
Expand Down
2 changes: 2 additions & 0 deletions src/probnum/filtsmooth/_timeseriesposterior.py
@@ -1,5 +1,7 @@
"""Abstract Base Class for posteriors over states after applying filtering/smoothing."""

from __future__ import annotations

import abc
from typing import Iterable, Optional, Union

Expand Down
3 changes: 3 additions & 0 deletions src/probnum/filtsmooth/gaussian/_kalmanposterior.py
Expand Up @@ -3,6 +3,9 @@
Contains the discrete time and function outputs. Provides dense output by being
callable. Can function values can also be accessed by indexing.
"""

from __future__ import annotations

import abc
from typing import Iterable, Optional, Union

Expand Down
26 changes: 14 additions & 12 deletions src/probnum/linalg/_problinsolve.py
Expand Up @@ -6,6 +6,8 @@
posterior distribution.
"""

from __future__ import annotations

from typing import Callable, Dict, Optional, Tuple, Union
import warnings

Expand Down Expand Up @@ -44,7 +46,7 @@ def problinsolve(
atol: float = 10**-6,
rtol: float = 10**-6,
callback: Optional[Callable] = None,
**kwargs
**kwargs,
) -> Tuple[
"randvars.RandomVariable[np.ndarray]",
"randvars.RandomVariable[linops.LinearOperator]",
Expand All @@ -67,23 +69,23 @@ def problinsolve(
Parameters
----------
A :
A
*shape=(n, n)* -- A square linear operator (or matrix). Only matrix-vector
products :math:`v \mapsto Av` are used internally.
b :
b
*shape=(n, ) or (n, nrhs)* -- Right-hand side vector, matrix or random
variable in :math:`A x = b`.
A0 :
A0
*shape=(n, n)* -- A square matrix, linear operator or random variable
representing the prior belief about the linear operator :math:`A`.
Ainv0 :
Ainv0
*shape=(n, n)* -- A square matrix, linear operator or random variable
representing the prior belief about the inverse :math:`H=A^{-1}`. This can be
viewed as a preconditioner.
x0 :
x0
*shape=(n, ) or (n, nrhs)* -- Prior belief for the solution of the linear
system. Will be ignored if ``Ainv0`` is given.
assume_A :
assume_A
Assumptions on the linear operator which can influence solver choice and
behavior. The available options are (combinations of)
Expand All @@ -94,19 +96,19 @@ def problinsolve(
(additive) noise ``noise``
==================== =========
maxiter :
maxiter
Maximum number of iterations. Defaults to :math:`10n`, where :math:`n` is the
dimension of :math:`A`.
atol :
atol
Absolute convergence tolerance.
rtol :
rtol
Relative convergence tolerance.
callback :
callback
User-supplied function called after each iteration of the linear solver. It is
called as ``callback(xk, Ak, Ainvk, sk, yk, alphak, resid, **kwargs)`` and can
be used to return quantities from the iteration. Note that depending on the
function supplied, this can slow down the solver considerably.
kwargs : optional
kwargs
Optional keyword arguments passed onto the solver iteration.
Returns
Expand Down
2 changes: 2 additions & 0 deletions src/probnum/linalg/solvers/_probabilistic_linear_solver.py
Expand Up @@ -3,6 +3,8 @@
Iterative probabilistic numerical methods solving linear systems :math:`Ax = b`.
"""

from __future__ import annotations

from typing import Generator, Optional, Tuple

import numpy as np
Expand Down
3 changes: 3 additions & 0 deletions src/probnum/linalg/solvers/_state.py
@@ -1,4 +1,7 @@
"""State of a probabilistic linear solver."""

from __future__ import annotations

from collections import defaultdict
import dataclasses
from typing import Any, DefaultDict, List, Optional, Tuple
Expand Down
20 changes: 15 additions & 5 deletions src/probnum/linops/_kronecker.py
Expand Up @@ -5,7 +5,7 @@

import numpy as np

from probnum.typing import DTypeLike, NotImplementedType
from probnum.typing import DTypeLike, LinearOperatorLike, NotImplementedType

from . import _linear_operator, _utils

Expand Down Expand Up @@ -102,7 +102,7 @@ class Kronecker(_linear_operator.LinearOperator):
"""

# todo: extend this to list of operators
def __init__(self, A: _utils.LinearOperatorLike, B: _utils.LinearOperatorLike):
def __init__(self, A: LinearOperatorLike, B: LinearOperatorLike):
self.A = _utils.aslinop(A)
self.B = _utils.aslinop(B)

Expand Down Expand Up @@ -317,8 +317,8 @@ class SymmetricKronecker(_linear_operator.LinearOperator):

def __init__(
self,
A: _utils.LinearOperatorLike,
B: Optional[_utils.LinearOperatorLike] = None,
A: LinearOperatorLike,
B: Optional[LinearOperatorLike] = None,
):
self.A = _utils.aslinop(A)

Expand Down Expand Up @@ -496,7 +496,17 @@ def _symmetrize(self) -> SymmetricKronecker:


class IdentityKronecker(_linear_operator.LinearOperator):
def __init__(self, num_blocks: int, B: _utils.LinearOperatorLike):
"""Block-diagonal linear operator.
Parameters
----------
num_blocks :
Number of blocks.
B :
Block.
"""

def __init__(self, num_blocks: int, B: LinearOperatorLike):
self._num_blocks = num_blocks
self.A = _linear_operator.Identity(num_blocks)
self.B = _utils.aslinop(B)
Expand Down

0 comments on commit d24b6b0

Please sign in to comment.