π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
docs: docstring-style foundation β strict RTD build, style checks, kornia.geometry.depth as the worked example (#6359)
Dmytro Mishkinedc9f22e69a5
diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.ymlindex 72fb692d4..064c91298 100644--- a/.github/workflows/docs.yml+++ b/.github/workflows/docs.yml@@ -89,6 +89,13 @@ jobs:- name: Install docs dependenciesrun: pixi run -e ${{ steps.pixi-env.outputs.name }} install-docs+ - name: Check docstring references against the docs pages+ # These tests read every page under docs/source and the cached intersphinx inventories, but the PR test+ # workflow skips a change that touches only docs/, so a page edit that breaks them is caught here.+ run: >-+ pixi run -e ${{ steps.pixi-env.outputs.name }}+ uv run pytest tests/test_docstring_style.py tests/test_docstring_style_helpers.py+- name: Run doctest# Empty on direct pull_request events (the `inputs` context is empty there and# the workflow_call default does not apply), which is the intended PR behaviour:diff --git a/AGENTS.md b/AGENTS.mdindex 141c67052..deed0c94e 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -119,6 +119,7 @@ when more than one virtualenv is in play: name the interpreter explicitly rather- A `KORNIA_CHECK` message that formats a tensor size or an `int` argument specializes it under a dynamic-shape `torch.compile`, which then compiles a graph per value. Compare sizes with `KORNIA_CHECK_SAME_SIZE`, `KORNIA_CHECK_SIZES` or `KORNIA_CHECK_SHAPE`, or pass the message as `lambda: f"..."`. TorchScript rejects a `lambda`, so a function it compiles formats whole shapes instead, such as `{x.shape}`, which do not specialize. `tests/core/test_check_message_call_sites.py` enforces both and lists the functions TorchScript compiles.- Use `BaseTester` from `testing.base`, injected `device`/`dtype` fixtures, and `self.assert_close()` for tensor comparisons. Its dtype-specific tolerances are intentional.- Follow [TESTING.md](TESTING.md) for test mechanisms. Use `self.gradcheck()` for gradient checks and the injected `torch_optimizer` fixture for `torch.compile` coverage. Include smoke, exception, shape/cardinality, numerical, gradient, and compile tests when they apply; not every change needs every kind.+- Write docstrings in the style of [CONTRIBUTING.md](CONTRIBUTING.md#docstring-style): a unique task-word title line, a contract paragraph that starts from the call, `See Also:` with explanations, and shape literals instead of `:math:`. `tests/test_docstring_style.py` checks See Also, references, shape literals and catalogs for the modules listed in `testing/docstring_rollout.py`; `kornia/geometry/depth.py` is the worked example.- Keep numerical correctness tests self-contained. For expected values produced by an optional reference library, prefer a hardcoded literal plus the small generation snippet and source. Optional-dependency integration tests, including ONNX tests, may still use `pytest.importorskip`.- For a new algorithm, name the source that defines it, such as a paper or a reference implementation in PyTorch, OpenCV, or scikit-image.- Do not keep or copy a bug just because the original implementation has it. When a port differs from its reference, decide which behaviour is correct before changing anything: "the reference does it" is not a justification on its own. For example, a non-maxima suppression that keeps positions equal to their window maximum (`>=`), or that re-admits positions once their stronger neighbours are suppressed, is unstable and wrong in principle; kornia keeps strict maxima. When kornia departs from a reference on purpose, say so in the docstring and give the reason.diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 5d4054087..24d236afb 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -198,6 +198,31 @@ The rest of this guide contains practical and technical guidance so nobody has t4. Preview: `open docs/build/html/index.html`5. Submit a PR following the [Pull Request](#pull-request) guidelines+### Docstring style++A docstring is how a reader, human or agent, decides which function to call, so it states the choice before the details. `kornia/geometry/depth.py` is the worked example. Docstrings are reST: write literals with double backticks, as in ``` ``(B, 1, H, W)`` ```, and keep single backticks for roles such as `` :func:`name` ``.++- **Title line**: one physical line, in task words, imperative, naming what sets the function apart from its siblings (2D or 3D, channels first or last, the criterion, one call or module form). Aim for about 80 characters; 120 is the hard limit. Avoid markup that breaks reST, such as a bare `*`. No two unrelated public symbols may share one (`tests/test_docstring_first_lines.py`); a class and the function it wraps may.+- **Status words** come first when they apply: `Deprecated: use X.` or `Alias of X.`. Do not label a function "Legacy"; for a nearby better choice, write a neutral "for X, use Y" in the contract paragraph.+- **Contract paragraph** (2-5 sentences) starts from the call: ``` ``points = depth_to_3d(depth, camera_matrix)`` ``` takes ... and returns .... A callable module shows construction and invocation; a data class (`Boxes`, `PinholeCamera`) shows construction and its main method. Name inputs and output with shapes, frames and units, and end with "use X instead" when a nearby task is better served elsewhere.+- **Existing blocks** stay: `.. note::`, `Convention:`, `Args:`, `Return:`/`Returns:`, `Raises:`, trimmed where the paragraph already says the same. In a long class docstring, put whatever decides correct use in the first paragraph.+- **`See Also:`** goes after `Returns`/`Raises` and before `Example`.+ - Write each entry as `` - :func:`name`: how it differs. ``; the explanation is required.+ - Spell targets as Sphinx registers them: a short name for an object documented under the same module, the documented path (`~kornia.geometry.camera.perspective.unproject_points`) for the rest. A shorter import alias renders as plain text, with no warning.+ - List kornia objects only, with no self-links or private names; mention torch and Python functions in the contract paragraph instead. Link true siblings both ways (v1 and v2, 2D and 3D); reviewers check that, no test does.+- **Module docstrings** open with a title line, then the conventions the module's functions share, then "Which function to use", grouped by task, one line each, naming every entry of the `__all__` of the namespace users import from as a role (`` :func:`name` ``) or a literal (``` ``name`` ```). A namespace without `__all__` (`kornia.geometry`, `kornia.geometry.transform`) catalogs its subpackages and main entry points instead; a defining file without `__all__` gets no catalog.+- **Shapes** are literals such as ``` ``(B, 1, H, W)`` ```. Keep `:math:` for formulas.++What `tests/test_docstring_style.py` checks:++- every package of `kornia` is assigned to in scope or excluded (global);+- each public function and class of a converted module has a `See Also:` whose entries carry an explanation and name a kornia object, with no self-link or private target; an exception needs a non-empty reason;+- every Python-domain object role (`:func:`, `:class:`, `:meth:`, `:attr:`, `:data:`, `:const:`, `:exc:`, `:obj:`) in a converted object's docstring resolves as Sphinx resolves it. It must name either an object registered by the `.rst` pages under `docs/source`, or a torch, Python or NumPy object in the cached intersphinx inventories (`docs/source/_intersphinx`). Registered objects include the data attributes autodoc documents: enum members and dataclass fields under `:undoc-members:`, and variables with a `#:` comment or a docstring. An intersphinx object must be of a type the role links to: a function for `:func:`, a method for `:meth:`, an attribute or property for `:attr:`, and nothing for `:const:`. Only `:func:` and `:meth:` drop a trailing `()`. Roles in a catalog module docstring must import;+- no source file of a shape-checked module writes a shape tuple as `:math:`, comments included;+- a catalog namespace's module docstring names every export of its `__all__` inside a role or a double-backtick literal, where a qualified name must be a path to that export (`torch.nn.functional.normalize` does not catalog `kornia.enhance.normalize`); the same word in plain prose or in single backticks does not count.++Read the Docs builds with `fail_on_warning: true` (`readthedocs.yml`) and the docs dependencies pinned in `uv.lock`, the same versions as `pixi run build-docs`, so a Sphinx warning fails the docs check. A module joins these checks when it is added to the lists in `testing/docstring_rollout.py`: `DOCSTRING_MODULES` (defining-module prefixes: `See Also:` and references), `CATALOG_NAMESPACES` (namespaces whose `__all__` the module docstring must name) and `SHAPE_CHECK_MODULES` (source-file prefixes, or `None` for all of `kornia/`). An object that needs no `See Also:` goes into `SEE_ALSO_EXCEPTIONS` with a reason. The package inventory is `IN_SCOPE_PACKAGES` and `EXCLUDED_PACKAGES`. The helpers are in `testing/docstring_style.py`; its `sphinx_registry` raises on an autodoc option it does not model, so a docs page that adds one (`:no-index:`, `:exclude-members:`, `:inherited-members:`) needs the registry taught first.+## Coding Standards- **Write small incremental changes:**diff --git a/docs/source/geometry.depth.rst b/docs/source/geometry.depth.rstindex 11c477fcf..7d983febb 100644--- a/docs/source/geometry.depth.rst+++ b/docs/source/geometry.depth.rst@@ -4,6 +4,15 @@ kornia.geometry.depth.. meta:::description: The kornia.geometry.depth module provides functions for working with depth-related transformations in 3D vision tasks. Key functionalities include computing depth from disparity, converting depth maps to 3D points, obtaining surface normals from depth data, and unprojecting depth data from mesh grids. Additionally, the module supports depth-based image warping and working with depth through plane equations, enabling advanced geometric operations in computer vision.+:func:`~kornia.geometry.depth.depth_to_3d` (channels first) and+:func:`~kornia.geometry.depth.depth_to_3d_v2` (channels last, optionally reusing rays from+:func:`~kornia.geometry.depth.unproject_meshgrid`) turn a depth map into 3D points, and+:func:`~kornia.geometry.depth.depth_to_normals` into surface normals. Get depth from a stereo disparity map with+:func:`~kornia.geometry.depth.depth_from_disparity`, or for pixels on a known plane with+:func:`~kornia.geometry.depth.depth_from_plane_equation`. Render an image from another viewpoint by depth with+:func:`~kornia.geometry.depth.warp_frame_depth` (a 4x4 pose and one camera matrix), or with+:class:`~kornia.geometry.depth.DepthWarper` and :func:`~kornia.geometry.depth.depth_warp` (two pinhole camera models).+.. currentmodule:: kornia.geometry.depth.. autofunction:: depth_from_disparitydiff --git a/kornia/geometry/depth.py b/kornia/geometry/depth.pyindex ed7eccf17..f5ecc0fa5 100644--- a/kornia/geometry/depth.py+++ b/kornia/geometry/depth.py@@ -15,7 +15,24 @@# limitations under the License.#-"""nn.Module containing operators to work on RGB-Depth images."""+"""Depth maps: unproject them to 3D points and normals, get depth from stereo or planes, and warp images by depth.++Functions that take ``camera_matrix`` expect pixel intrinsics of shape ``(B, 3, 3)`` with integer pixel+centres, and read ``depth`` as the camera-frame ``z`` (the Euclidean ray length with ``normalize_points=True``).++Which function to use:++- 3D points from a depth map: :func:`depth_to_3d` returns ``(B, 3, H, W)``; :func:`depth_to_3d_v2` returns+ ``(*, H, W, 3)`` and can reuse the rays from :func:`unproject_meshgrid` for every frame of one camera.+- Surface normals from a depth map: :func:`depth_to_normals`.+- Depth from a rectified stereo disparity map: :func:`depth_from_disparity`. Depth of given pixels on a known+ plane: :func:`depth_from_plane_equation`.+- An image rendered from another viewpoint by depth: :func:`warp_frame_depth` (a 4x4 pose and one camera+ matrix), or :class:`DepthWarper` and :func:`depth_warp` (two :class:`~kornia.geometry.camera.pinhole.PinholeCamera`+ models).+- Selected pixels instead of whole maps: :func:`~kornia.geometry.camera.perspective.unproject_points` and+ :func:`~kornia.geometry.camera.perspective.project_points`.+"""from __future__ import annotations@@ -36,8 +53,6 @@ from .camera.pinhole import _embed_intrinsicsfrom .conversions import normalize_pixel_coordinates, normalize_points_with_intrinsicsfrom .linalg import convert_points_to_homogeneous, transform_points-"""nn.Module containing operators to work on RGB-Depth images."""-__all__ = ["DepthWarper","depth_from_disparity",@@ -81,34 +96,35 @@ def unproject_meshgrid(device: Optional[torch.device] = None,dtype: Optional[torch.dtype] = None,) -> torch.Tensor:- """Generate camera-frame rays through each pixel, with z = 1 by default, for caching in depth_to_3d_v2.+ """Compute the camera ray through every pixel, to reuse across frames with depth_to_3d_v2.- .. tip::-- This function should be used in conjunction with :py:func:`kornia.geometry.depth.depth_to_3d_v2` to cache- the meshgrid computation when warping multiple frames with the same camera intrinsics.+ ``rays = unproject_meshgrid(H, W, camera_matrix)`` returns the camera-frame ray of each pixel as a+ ``(B, H, W, 3)`` tensor, scaled so that ``z`` is 1 by default (unit length with ``normalize_points=True``). It+ takes no depth: multiply the rays by ``depth[..., None]`` for a ``(B, H, W)`` depth map, or pass them to+ :func:`depth_to_3d_v2` as ``xyz_grid``, to get the 3D points of many frames from one camera without rebuilding+ the grid each time.Convention:- - the result is the **camera-frame** ray through each pixel at depth 1, :math:`(B, H, W, 3)`, so- multiplying it by a :math:`(B, H, W)` depth map reproduces :func:`~kornia.geometry.depth.depth_to_3d_v2`- (its ``xyz_grid`` cache). Pixel centres are integers; see- :class:`~kornia.geometry.camera.pinhole.PinholeCamera`.- - ``camera_matrix`` must be :math:`(B, 3, 3)`; an unbatched matrix or extra leading dimensions raise+ - pixel centres are integers; see :class:`~kornia.geometry.camera.pinhole.PinholeCamera`.+ - ``camera_matrix`` must be ``(B, 3, 3)``; an unbatched matrix or extra leading dimensions raise``ShapeError``.- - ``normalize_points=True`` returns the unit ray instead of the ray whose ``z`` is 1.Args:height: height of image.width: width of image.- camera_matrix: tensor containing the camera intrinsics with shape :math:`(B, 3, 3)`.- normalize_points: whether to normalize the pointcloud. This must be set to `True` when the depth is+ camera_matrix: tensor containing the camera intrinsics with shape ``(B, 3, 3)``.+ normalize_points: whether to normalize the pointcloud. This must be set to ``True`` when the depth isrepresented as the Euclidean ray length from the camera position.device: device to place the result on.dtype: dtype of the pixel grid; the output dtype follows promotion with ``camera_matrix``.Return:the ray through each pixel, with ``z`` equal to 1 (or unit length with ``normalize_points=True``), with- shape :math:`(B, H, W, 3)`.+ shape ``(B, H, W, 3)``.++ See Also:+ - :func:`depth_to_3d_v2`: takes these rays as ``xyz_grid`` and scales them by a depth map.+ - :func:`~kornia.geometry.camera.perspective.unproject_points`: the camera-frame point of selected pixels."""KORNIA_CHECK_SHAPE(camera_matrix, ["B", "3", "3"])@@ -142,42 +158,49 @@ def depth_to_3d_v2() -> torch.Tensor:# NOTE: when this replaces the `depth_to_3d` behaviour, a deprecated function should be added here, instead# of just replace the other function.- """Unproject a ``(*, H, W)`` depth map to channels-last camera-frame 3D points, broadcast with the camera batch.-- .. note::-- This is an alternative implementation of :py:func:`kornia.geometry.depth.depth_to_3d` that can reuse a- grid from :py:func:`kornia.geometry.depth.unproject_meshgrid`, passed as ``xyz_grid``, instead of building- the meshgrid on every call.+ """Unproject a depth map to a 3D point per pixel, channels last.++ ``points = depth_to_3d_v2(depth, camera_matrix)`` takes a ``(*, H, W)`` map of camera-frame depths and+ ``(B, 3, 3)`` pixel intrinsics, and returns the camera-frame point of every pixel as a ``(*, H, W, 3)``+ tensor. The ``(B, H, W, 3)`` rays of the ``B`` cameras broadcast against ``depth`` by torch's rules, so the+ camera batch lines up with the axis of ``depth`` just before ``H``, not with its first axis: an ``(H, W)`` depth+ gives one map per camera, a ``(B, H, W)`` depth pairs camera ``b`` with ``depth[b]``, and a ``(B, T, H, W)``+ depth pairs camera ``t`` with ``depth[:, t]`` when ``T == B``. With ``T == 1`` it pairs every camera with every+ map and returns ``(B, B, H, W, 3)``, so pass ``depth[:, 0]``; any other ``T`` raises, unless there is a single+ camera, which then serves every map. For one camera per ``(B, T, H, W)`` batch element, pass+ ``xyz_grid=unproject_meshgrid(H, W, camera_matrix)[:, None]``; the same grid also saves rebuilding the pixel+ rays for many frames of one camera. For a channels-first ``(B, 3, H, W)`` result, use :func:`depth_to_3d`.Convention:- - ``depth`` is the camera-frame ``z`` of each pixel and the result the camera-frame point- ``((u - cx) z / fx, (v - cy) z / fy, z)``, channels-**last** :math:`(*, H, W, 3)`, with ``u`` the- column and ``v`` the row (integer pixel centres; see- :class:`~kornia.geometry.camera.pinhole.PinholeCamera`). It equals- :func:`~kornia.geometry.depth.depth_to_3d` after ``permute(0, 2, 3, 1)``.- - without ``xyz_grid``, ``camera_matrix`` must be exactly :math:`(B, 3, 3)` (another shape raises+ - pixel ``(u, v)``, with ``u`` the column and ``v`` the row, maps to ``((u - cx) z / fx, (v - cy) z / fy, z)``.+ Pixel centres are integers, as in :class:`~kornia.geometry.camera.pinhole.PinholeCamera`.+ ``depth_to_3d_v2(depth[:, 0], K)`` equals ``depth_to_3d(depth, K).permute(0, 2, 3, 1)``.+ - without ``xyz_grid``, ``camera_matrix`` must be exactly ``(B, 3, 3)`` (another shape raises``ShapeError``); with ``xyz_grid`` only its shape is checked.- - ``normalize_points=True`` reads ``depth`` as the Euclidean ray length instead of ``z``.- - ``xyz_grid`` replaces the grid construction; pass what :func:`~kornia.geometry.depth.unproject_meshgrid`- returns for the same camera.+ - ``normalize_points=True`` reads ``depth`` as the Euclidean ray length instead of ``z``. With ``xyz_grid`` it+ is ignored: build the grid with the same ``normalize_points``.- without ``xyz_grid``, the pixel grid is built in ``promote_types(depth.dtype, camera_matrix.dtype)``when either input is floating (the default floating dtype when both are integer), so half-precisiondepth does not round the pixel indices below the intrinsics' precision.Args:- depth: image tensor containing a depth value per pixel with shape :math:`(*, H, W)`.- camera_matrix: tensor containing the camera intrinsics with shape :math:`(B, 3, 3)`.- normalize_points: whether to normalise the pointcloud. This must be set to `True` when the depth is+ depth: image tensor containing a depth value per pixel with shape ``(*, H, W)``.+ camera_matrix: tensor containing the camera intrinsics with shape ``(B, 3, 3)``.+ normalize_points: whether to normalize the pointcloud. This must be set to ``True`` when the depth isrepresented as the Euclidean ray length from the camera position.xyz_grid: explicit xyz point values.Return:- tensor with a 3d point per pixel of the same resolution as the input, :math:`(*, H, W, 3)`, whose+ tensor with a 3d point per pixel of the same resolution as the input, ``(*, H, W, 3)``, whoseleading dimensions are the broadcast of ``depth``'s and the grid's: the Example broadcasts a- :math:`(4, 4)` depth against a :math:`(2, 3, 3)` camera to :math:`(2, 4, 4, 3)`, and a- :math:`(B, T, H, W)` depth with an ``xyz_grid`` of shape :math:`(B, 1, H, W, 3)` returns- :math:`(B, T, H, W, 3)`.+ ``(4, 4)`` depth against a ``(2, 3, 3)`` camera to ``(2, 4, 4, 3)``, and a+ ``(B, T, H, W)`` depth with an ``xyz_grid`` of shape ``(B, 1, H, W, 3)`` returns+ ``(B, T, H, W, 3)``.++ See Also:+ - :func:`depth_to_3d`: the same points channels first, ``(B, 3, H, W)``.+ - :func:`unproject_meshgrid`: the per-pixel rays to pass as ``xyz_grid``.+ - :func:`depth_to_normals`: per-pixel surface normals, from a ``(B, 1, H, W)`` depth.Example:>>> depth = torch.rand(4, 4)@@ -205,19 +228,18 @@ def depth_to_3d_v2(def depth_to_3d(depth: torch.Tensor, camera_matrix: torch.Tensor, normalize_points: bool = False) -> torch.Tensor:- """Unproject a (B, 1, H, W) depth map to camera-frame 3D points, returned channels-first as (B, 3, H, W).+ """Unproject a depth map to a 3D point per pixel, channels first.- .. note::-- :py:func:`kornia.geometry.depth.depth_to_3d_v2` computes the same points in the :math:`(B, H, W, 3)`- layout and can reuse a grid cached with :py:func:`kornia.geometry.depth.unproject_meshgrid`.+ ``points = depth_to_3d(depth, camera_matrix)`` takes a ``(B, 1, H, W)`` map of camera-frame depths and+ ``(B, 3, 3)`` pixel intrinsics, and returns the camera-frame point of every pixel as a ``(B, 3, H, W)``+ tensor. For a channels-last ``(*, H, W, 3)`` result, or to reuse the pixel rays across frames, use+ :func:`depth_to_3d_v2` on ``depth[:, 0]``. To unproject selected pixels rather than a whole map, use+ :func:`~kornia.geometry.camera.perspective.unproject_points`.Convention:- - ``depth`` is the camera-frame ``z`` of each pixel and the result the camera-frame point- ``((u - cx) z / fx, (v - cy) z / fy, z)``, channels-**first** :math:`(B, 3, H, W)`, with ``u`` the- column and ``v`` the row (integer pixel centres; see- :class:`~kornia.geometry.camera.pinhole.PinholeCamera`). It equals- :func:`~kornia.geometry.depth.depth_to_3d_v2` after ``permute(0, 2, 3, 1)``.+ - pixel ``(u, v)``, with ``u`` the column and ``v`` the row, maps to ``((u - cx) z / fx, (v - cy) z / fy, z)``.+ Pixel centres are integers, as in :class:`~kornia.geometry.camera.pinhole.PinholeCamera`.+ ``depth_to_3d(depth, K).permute(0, 2, 3, 1)`` equals ``depth_to_3d_v2(depth[:, 0], K)``.- ``normalize_points=True`` reads ``depth`` as the Euclidean ray length instead of ``z``.- an integer ``depth`` is not rejected; the result takes the floating dtype of ``camera_matrix``.The pixel grid is built in ``promote_types(depth.dtype, camera_matrix.dtype)`` when either input is@@ -225,13 +247,19 @@ def depth_to_3d(depth: torch.Tensor, camera_matrix: torch.Tensor, normalize_poinround the pixel indices below the intrinsics' precision.Args:- depth: image tensor containing a depth value per pixel with shape :math:`(B, 1, H, W)`.- camera_matrix: tensor containing the camera intrinsics with shape :math:`(B, 3, 3)`.- normalize_points: whether to normalise the pointcloud. This must be set to `True` when the depth is+ depth: image tensor containing a depth value per pixel with shape ``(B, 1, H, W)``.+ camera_matrix: tensor containing the camera intrinsics with shape ``(B, 3, 3)``.+ normalize_points: whether to normalize the pointcloud. This must be set to ``True`` when the depth isrepresented as the Euclidean ray length from the camera position.Return:- tensor with a 3d point per pixel of the same resolution as the input :math:`(B, 3, H, W)`.+ tensor with a 3d point per pixel of the same resolution as the input ``(B, 3, H, W)``.++ See Also:+ - :func:`depth_to_3d_v2`: the same points channels last, with an optional cached grid.+ - :func:`depth_to_normals`: per-pixel surface normals from the same inputs.+ - :func:`depth_from_disparity`: depth from a stereo disparity map, to feed this function.+ - :func:`~kornia.geometry.camera.perspective.unproject_points`: the camera-frame point of selected pixels.Example:>>> depth = torch.rand(1, 1, 4, 4)@@ -268,32 +296,37 @@ def depth_to_3d(depth: torch.Tensor, camera_matrix: torch.Tensor, normalize_poindef depth_to_normals(depth: torch.Tensor, camera_matrix: torch.Tensor, normalize_points: bool = False) -> torch.Tensor:- r"""Compute the normal surface per pixel.+ r"""Estimate a unit surface normal per pixel from a depth map.++ ``normals = depth_to_normals(depth, camera_matrix)`` takes the same ``(B, 1, H, W)`` depth map and+ ``(B, 3, 3)`` intrinsics as :func:`depth_to_3d`, differentiates the unprojected points with a Sobel+ :func:`~kornia.filters.spatial_gradient`, and returns the normalized cross product of the two tangents as a+ ``(B, 3, H, W)`` tensor. Normals point away from the camera: a fronto-parallel plane gets ``(0, 0, 1)``.Convention:- both spatial dimensions must be at least 2: a surface normal requires two tangent directions.- - the normal is the unit cross product ``d/dx`` x ``d/dy`` of the unprojected point cloud, so a- fronto-parallel plane gets ``(0, 0, 1)``, pointing **away** from the camera; a depth growing along- the columns tilts it towards ``-x``, one growing along the rows towards ``-y``.- - the arguments mean what they mean for :func:`~kornia.geometry.depth.depth_to_3d`, and the result- has its :math:`(B, 3, H, W)` layout.+ - a depth growing along the columns tilts the normal towards ``-x``, one growing along the rows towards+ ``-y``.- float16 and bfloat16 inputs are widened to float32 first. The result has the promoted dtype of ``depth`` and``camera_matrix``, or the default floating dtype when both are integer, and it does not follow anenclosing autocast region: its dtype and values are the same inside autocast as outside.Args:- depth: image tensor containing a depth value per pixel with shape :math:`(B, 1, H, W)`, with+ depth: image tensor containing a depth value per pixel with shape ``(B, 1, H, W)``, with:math:`H \geq 2` and :math:`W \geq 2`.- camera_matrix: tensor containing the camera intrinsics with shape :math:`(B, 3, 3)`.- normalize_points: whether to normalize the pointcloud. This must be set to `True` when the depth is- represented as the Euclidean ray length from the camera position.+ camera_matrix: tensor containing the camera intrinsics with shape ``(B, 3, 3)``.+ normalize_points: whether to normalize the pointcloud. This must be set to ``True`` when the depth is+ represented as the Euclidean ray length from the camera position.Return:- tensor with a normal surface vector per pixel of the same resolution as the input :math:`(B, 3, H, W)`.+ tensor with a normal surface vector per pixel of the same resolution as the input ``(B, 3, H, W)``.Raises:ShapeError: if either spatial dimension of ``depth`` is smaller than 2.+ See Also:+ - :func:`depth_to_3d`: the point map whose tangents give the normals.+Example:>>> depth = torch.rand(1, 1, 4, 4)>>> K = torch.eye(3)[None]@@ -347,15 +380,19 @@ def depth_from_plane_equation(camera_matrix: torch.Tensor,eps: float = 1e-8,) -> torch.Tensor:- r"""Compute depth values from plane equations and pixel coordinates.+ r"""Compute the depth of given pixels that lie on a known plane.++ ``depth = depth_from_plane_equation(plane_normals, plane_offsets, points_uv, camera_matrix)`` intersects the+ camera ray of each pixel in ``points_uv`` of shape ``(B, N, 2)`` with the camera-frame plane+ :math:`n \cdot X = d` and returns the ``z`` of each intersection as a ``(B, N)`` tensor: a list of depths,+ not a depth map.Convention:- - the plane is given in Hessian form :math:`n \cdot X = d`, with the normal ``plane_normals`` and the- offset ``plane_offsets`` in the **camera** frame: ``n = (0, 0, 1)`` with ``d = 2`` is the plane- ``z = 2``, and every pixel on it has depth 2.+ - the plane is in Hessian form, with the normal ``plane_normals`` of shape ``(B, 3)`` and+ the offset ``plane_offsets`` of shape ``(B, 1)``: ``n = (0, 0, 1)`` with ``d = 2`` is the plane ``z = 2``,+ and every pixel on it has depth 2.- ``points_uv`` are **pixels** (integer centres; see:class:`~kornia.geometry.camera.pinhole.PinholeCamera`), normalized here with ``camera_matrix``.- - the result is the camera-frame ``z`` of each pixel, :math:`(B, N)`: a list of depths, not a map.- a ray-plane dot product inside :math:`(-eps, eps)` is replaced by :math:`\pm` ``eps`` with its sign(``+eps`` for an exact zero), so a grazing ray returns the large signed depth ``d / eps`` rather than``inf``. In float16 a positive ``eps`` is floored at the smallest subnormal, ``2**-24``, because the@@ -363,14 +400,18 @@ def depth_from_plane_equation(about ``3.9e-3``, so pass a larger ``eps`` for a finite depth (``eps=1e-4`` keeps ``|d| <= 6.5`` finite).Args:- plane_normals (torch.Tensor): Plane normal vectors of shape (B, 3).- plane_offsets (torch.Tensor): Plane offsets of shape (B, 1).- points_uv (torch.Tensor): Pixel coordinates of shape (B, N, 2).- camera_matrix (torch.Tensor): Camera intrinsic matrix of shape (B, 3, 3).+ plane_normals (torch.Tensor): Plane normal vectors of shape ``(B, 3)``.+ plane_offsets (torch.Tensor): Plane offsets of shape ``(B, 1)``.+ points_uv (torch.Tensor): Pixel coordinates of shape ``(B, N, 2)``.+ camera_matrix (torch.Tensor): Camera intrinsic matrix of shape ``(B, 3, 3)``.eps: epsilon for numerical stability.Returns:- torch.Tensor: Computed depth values at the given pixels, shape (B, N).+ torch.Tensor: Computed depth values at the given pixels, shape ``(B, N)``.++ See Also:+ - :func:`~kornia.geometry.camera.perspective.unproject_points`: turn these pixels and depths into 3D points.+ - :func:`depth_from_disparity`: a whole depth map from a rectified stereo disparity map, not from a plane."""KORNIA_CHECK_SHAPE(plane_normals, ["B", "3"])@@ -417,34 +458,43 @@ def warp_frame_depth(camera_matrix: torch.Tensor,normalize_points: bool = False,) -> torch.Tensor:- """Warp a tensor from a source to destination frame by the depth in the destination.+ """Render an image from another viewpoint, given that viewpoint's depth map and the relative pose.- Compute 3d points from the depth, transform them using given transformation, then project the point cloud to an- image plane.+ ``image_dst = warp_frame_depth(image_src, depth_dst, src_trans_dst, camera_matrix)`` shows the source image+ ``(B, D, H, W)`` as the destination camera sees it. Each destination pixel is unprojected with its depth+ from ``depth_dst`` of shape ``(B, 1, H, W)``, moved into the source frame by the ``(B, 4, 4)`` pose+ ``src_trans_dst``, projected with the ``(B, 3, 3)`` intrinsics ``camera_matrix`` that both views share, and+ sampled bilinearly. :class:`DepthWarper` and :func:`depth_warp` do the same warp from two+ :class:`~kornia.geometry.camera.pinhole.PinholeCamera` models; for a planar scene,+ :func:`~kornia.geometry.transform.warp_perspective` with a homography needs no depth.Convention:- - the depth belongs to the **destination** frame (``depth_dst``) and the image to the **source** frame- (``image_src``), and ``src_trans_dst`` maps destination-frame points into the source frame. With- ``fx = fy = 1`` and a unit depth, a :math:`+1` translation in ``x`` samples ``image_src`` one pixel to- the right of each destination pixel.- - the unprojection is :func:`~kornia.geometry.depth.depth_to_3d_v2` and the reprojection+ - ``src_trans_dst`` maps destination-frame points into the source frame. With ``fx = fy = 1`` and a+ unit depth, a translation of 1 along ``x`` samples ``image_src`` one pixel to the right of each+ destination pixel.+ - the unprojection is :func:`depth_to_3d_v2` and the reprojection:func:`~kornia.geometry.camera.perspective.project_points`, whose conventions apply.- the sampling is bilinear ``grid_sample`` with a fixed ``align_corners=True`` and- ``padding_mode="zeros"``; the output is :math:`(B, D, H, W)` with ``image_src``'s channels.- - :class:`~kornia.geometry.depth.DepthWarper` and :func:`~kornia.geometry.depth.depth_warp` perform the- same warp under the opposite frame names: this function's ``dst`` (the frame holding the depth) is- their ``src``, and ``image_src`` is their ``patch_dst``. Both namings are kept.+ ``padding_mode="zeros"``; the output keeps ``image_src``'s channels.+ - :class:`DepthWarper` and :func:`depth_warp` name the frames the other way round: this function's+ ``dst`` (the frame holding the depth) is their ``src``, and ``image_src`` is their ``patch_dst``.Args:- image_src: image tensor in the source frame with shape :math:`(B,D,H,W)`.- depth_dst: depth tensor in the destination frame with shape :math:`(B,1,H,W)`.- src_trans_dst: transformation matrix from destination to source with shape :math:`(B,4,4)`.- camera_matrix: tensor containing the camera intrinsics with shape :math:`(B,3,3)`.+ image_src: image tensor in the source frame with shape ``(B, D, H, W)``.+ depth_dst: depth tensor in the destination frame with shape ``(B, 1, H, W)``.+ src_trans_dst: transformation matrix from destination to source with shape ``(B, 4, 4)``.+ camera_matrix: tensor containing the camera intrinsics with shape ``(B, 3, 3)``.normalize_points: whether to normalize the pointcloud. This must be set to ``True`` when the depthis represented as the Euclidean ray length from the camera position.Return:- ``image_src`` resampled onto the destination pixel grid, with shape :math:`(B,D,H,W)`.+ ``image_src`` resampled onto the destination pixel grid, with shape ``(B, D, H, W)``.++ See Also:+ - :class:`DepthWarper`, :func:`depth_warp`: the same warp from two pinhole camera models.+ - :func:`depth_to_3d_v2`, :func:`~kornia.geometry.camera.perspective.project_points`: the two halves of the+ warp.+ - :func:`~kornia.geometry.transform.warp_perspective`: warp by a homography, without depth."""KORNIA_CHECK_SHAPE(image_src, ["B", "D", "H", "W"])@@ -485,21 +535,25 @@ def warp_frame_depth(class DepthWarper(nn.Module):- r"""Warp a patch by depth.+ r"""Render an image from another viewpoint by depth, given two PinholeCamera models (module form).++ Build ``warper = DepthWarper(pinhole_dst, H, W)``, call ``warper.compute_projection_matrix(pinhole_src)``,+ then ``image = warper(depth_src, patch_dst)`` samples the destination image ``patch_dst`` of shape+ ``(B, C, H, W)`` at the pixels where the source-frame depth ``depth_src`` projects, so the ``(B, C, H, W)``+ result shows ``patch_dst`` as the source camera sees it. Calling the warper before+ :meth:`compute_projection_matrix` raises ``ValueError``.+ :func:`depth_warp` is the one-call form; :func:`warp_frame_depth` takes a 4x4 pose and one intrinsics+ matrix instead of two cameras... math::P_{src}^{\{dst\}} = K_{dst} * T_{src}^{\{dst\}}- I_{src} = \\omega(I_{dst}, P_{src}^{\{dst\}}, D_{src})+ I_{src} = \omega(I_{dst}, P_{src}^{\{dst\}}, D_{src})Convention:- - the depth lives in the **source** frame and the image in the **destination** frame:- :meth:`forward` takes ``(depth_src, patch_dst)``, samples ``patch_dst`` at the pixels the- source-frame depth projects to, and returns a :math:`(B, C, H, W)` tensor carrying ``patch_dst``'s- channel count.- - this is a two-step API: :meth:`compute_projection_matrix` has to be called first. Until it has- been, :meth:`warp_grid` and :meth:`forward` raise ``ValueError`` and :meth:`compute_subpixel_step`- raises ``RuntimeError``.+ - the depth lives in the **source** frame and the image in the **destination** frame.+ - until :meth:`compute_projection_matrix` has been called, :meth:`warp_grid` raises ``ValueError`` and+ :meth:`compute_subpixel_step` raises ``RuntimeError``.- :meth:`compute_projection_matrix` stores ``K_dst @ (E_dst @ inverse(E_src))``, the matrix above, fromthe constructor's ``pinhole_dst`` and that method's ``pinhole_src`` (both:class:`~kornia.geometry.camera.pinhole.PinholeCamera`, world-to-camera extrinsics).@@ -508,11 +562,12 @@ class DepthWarper(nn.Module):- the ``grid`` attribute is the homogeneous integer-centre pixel grid (pixel ``(0, 0)`` is``(0, 0, 1)``); :meth:`warp_grid` returns sampling positions in ``grid_sample``'s``align_corners=True`` normalized coordinates of the **destination** image.- - ``align_corners`` (default ``True``), ``mode`` and ``padding_mode`` are forwarded to ``grid_sample``.- :func:`~kornia.geometry.depth.depth_warp` is the functional form and exposes ``align_corners`` only.- - :func:`~kornia.geometry.depth.warp_frame_depth` performs the same warp under the opposite frame names:- this class's ``src`` (the frame holding the depth) is that function's ``dst``, and ``patch_dst`` is its- ``image_src``. Both namings are kept.+ - ``align_corners`` (default ``True``), ``mode`` and ``padding_mode`` are forwarded to ``grid_sample``,+ but :meth:`warp_grid` normalizes for ``align_corners=True`` whatever the flag, so ``False`` misaligns+ the warp and an identity warp no longer returns its input+ (`#6317 <https://github.com/kornia/kornia/issues/6317>`_).+ - :func:`warp_frame_depth` names the frames the other way round: its ``dst`` (the frame holding the depth)+ is this class's ``src``, and its ``image_src`` is ``patch_dst``... warning::The two warps agree to rounding for float32/float64 away from ``z = 0``, and split at ``z = 0``, where@@ -527,6 +582,10 @@ class DepthWarper(nn.Module):padding_mode: padding mode for outside grid values ``'zeros'`` | ``'border'`` | ``'reflection'``.align_corners: interpolation flag.+ See Also:+ - :func:`depth_warp`: this warp in one call.+ - :func:`warp_frame_depth`: the same warp from a 4x4 pose and one camera matrix.+"""# All per-instance, not global (thread safe, multiple warps)@@ -566,7 +625,7 @@ class DepthWarper(nn.Module):def compute_projection_matrix(self, pinhole_src: PinholeCamera) -> DepthWarper:"""Compute the projection matrix from the source to destination frame.- See the Convention block on :class:`~kornia.geometry.depth.DepthWarper`.+ See the Convention block on :class:`DepthWarper`."""# Inline type checks for faster fail-fastif type(self._pinhole_dst) is not PinholeCamera:@@ -625,7 +684,7 @@ class DepthWarper(nn.Module):def compute_subpixel_step(self) -> torch.Tensor:"""Compute the inverse depth step for sub pixel accurate sampling of the depth cost volume, per camera.- See the Convention block on :class:`~kornia.geometry.depth.DepthWarper`.+ See the Convention block on :class:`DepthWarper`.Szeliski, Richard, and Daniel Scharstein. "Symmetric sub-pixel stereo matching." European Conference on ComputerVision. Springer Berlin Heidelberg, 2002.@@ -662,13 +721,13 @@ class DepthWarper(nn.Module):return torch.min(0.5 / dxdd)def warp_grid(self, depth_src: torch.Tensor) -> torch.Tensor:- """Compute a grid for warping a given the depth from the reference pinhole camera.+ """Compute where each source pixel samples the destination image, given the depth in the source frame.- See the Convention block on :class:`~kornia.geometry.depth.DepthWarper`.+ See the Convention block on :class:`DepthWarper`.- The function `compute_projection_matrix` has to be called beforehand in order to have precomputed the relative- projection matrices encoding the relative pose and the intrinsics between the reference and a non reference- camera.+ The method ``compute_projection_matrix`` has to be called beforehand in order to have precomputed the+ projection matrix, which moves a source-frame point into the destination camera frame and applies the+ destination intrinsics."""# TODO: add type and value checkingsif self._dst_proj_src is None or self._pinhole_src is None:@@ -700,20 +759,20 @@ class DepthWarper(nn.Module):return pixel_coords_src_normdef forward(self, depth_src: torch.Tensor, patch_dst: torch.Tensor) -> torch.Tensor:- """Warp a tensor from destination frame to reference given the depth in the reference frame.+ """Warp a tensor from the destination frame to the source frame, given the depth in the source frame.- See the Convention block on :class:`~kornia.geometry.depth.DepthWarper`.+ See the Convention block on :class:`DepthWarper`.Args:- depth_src: the depth in the reference frame. The tensor must have a shape :math:`(B, 1, H, W)`.- patch_dst: the patch in the destination frame. The tensor must have a shape :math:`(B, C, H, W)`.+ depth_src: the depth in the source frame. The tensor must have a shape ``(B, 1, H, W)``.+ patch_dst: the patch in the destination frame. The tensor must have a shape ``(B, C, H, W)``.Return:- the warped patch from destination frame to reference.+ the patch warped from the destination frame to the source frame.Shape:- - Input: :math:`(B, 1, H, W)` and :math:`(B, C, H, W)`.- - Output: :math:`(B, C, H, W)` where C = number of channels.+ - Input: ``(B, 1, H, W)`` and ``(B, C, H, W)``.+ - Output: ``(B, C, H, W)`` where C = number of channels.Example:>>> # pinholes camera models@@ -724,7 +783,7 @@ class DepthWarper(nn.Module):>>> # create the depth warper, compute the projection matrix>>> warper = DepthWarper(pinhole_dst, 32, 32)>>> _ = warper.compute_projection_matrix(pinhole_src)- >>> # warp the destination frame to reference by depth+ >>> # warp the destination frame to the source frame by depth>>> depth_src = torch.ones(1, 1, 32, 32) # Nx1xHxW>>> image_dst = torch.rand(1, 3, 32, 32) # NxCxHxW>>> image_src = warper(depth_src, image_dst) # NxCxHxW@@ -748,14 +807,32 @@ def depth_warp(width: int,align_corners: bool = True,) -> torch.Tensor:- """Warp a tensor from destination frame to reference given the depth in the reference frame.+ """Render an image from another viewpoint by depth, given two PinholeCamera models (one call).- See the Convention block on :class:`~kornia.geometry.depth.DepthWarper`.+ ``image = depth_warp(pinhole_dst, pinhole_src, depth_src, patch_dst, H, W)`` samples the destination image+ ``patch_dst`` of shape ``(B, C, H, W)`` at the pixels where the source-frame depth ``depth_src`` projects, so the+ result shows ``patch_dst`` as the source camera sees it. It is :class:`DepthWarper` in one call, with that+ class's default ``mode`` and ``padding_mode`` and the same output bit for bit; see its Convention block.+ :func:`warp_frame_depth` takes a 4x4 pose and one intrinsics matrix instead of two cameras.- This function is that class's functional form: it constructs a- :class:`~kornia.geometry.depth.DepthWarper`, calls its ``compute_projection_matrix`` and returns its- output, which is equal to the class's bit for bit under the default ``mode`` and ``padding_mode``, the only- ones this function offers (``align_corners`` is forwarded).+ Args:+ pinhole_dst: the pinhole model for the destination frame, the one ``patch_dst`` is seen from.+ pinhole_src: the pinhole model for the source frame, the one ``depth_src`` belongs to.+ depth_src: the depth in the source frame, with shape ``(B, 1, H, W)``.+ patch_dst: the image in the destination frame, with shape ``(B, C, H, W)``.+ height: the height of the images, ``H``.+ width: the width of the images, ``W``.+ align_corners: forwarded to ``grid_sample`` only; the sampling grid is always normalized for+ ``align_corners=True``, so ``False`` misaligns the warp+ (`#6317 <https://github.com/kornia/kornia/issues/6317>`_). The default ``True`` is what+ :class:`DepthWarper` uses.++ Return:+ ``patch_dst`` resampled onto the source pixel grid, with shape ``(B, C, H, W)``.++ See Also:+ - :class:`DepthWarper`: the module form, with ``mode`` and ``padding_mode``.+ - :func:`warp_frame_depth`: the same warp from a 4x4 pose and one camera matrix.Example:>>> # pinholes camera models@@ -763,7 +840,7 @@ def depth_warp(... torch.tensor([32]), torch.tensor([32]))>>> pinhole_src = PinholeCamera(torch.randn(1, 4, 4), torch.randn(1, 4, 4),... torch.tensor([32]), torch.tensor([32]))- >>> # warp the destination frame to reference by depth+ >>> # warp the destination frame to the source frame by depth>>> depth_src = torch.ones(1, 1, 32, 32) # Nx1xHxW>>> image_dst = torch.rand(1, 3, 32, 32) # NxCxHxW>>> image_src = depth_warp(pinhole_dst, pinhole_src, depth_src, image_dst, 32, 32) # NxCxHxW@@ -800,38 +877,51 @@ def _per_sample_camera_parameter(parameter: float | torch.Tensor, disparity: tordef depth_from_disparity(disparity: torch.Tensor, baseline: float | torch.Tensor, focal: float | torch.Tensor) -> torch.Tensor:- """Compute depth from disparity.+ """Convert a rectified stereo disparity map to depth.++ ``depth = depth_from_disparity(disparity, baseline, focal)`` returns ``baseline * focal / disparity`` for every+ pixel of a ``(*, H, W)`` disparity map, with ``baseline`` the distance between the two camera centres and+ ``focal`` the focal length in pixels, so the depth comes out in the unit of ``baseline``. A zero disparity+ gives a large finite depth, not ``inf``, except in float16 (see below). To go from disparity straight to 3D+ points with a calibrated stereo rig, use+ :meth:`~kornia.geometry.camera.stereo.StereoCamera.reproject_disparity_to_3D`, which takes a ``(B, H, W, 1)``+ disparity.Convention:- - the depth is ``baseline * focal / (disparity + 1e-8)``, elementwise: ``baseline`` is the distance- between the two camera centres and ``focal`` the focal length in pixels, so a disparity of 2 with a- baseline of 0.5 and a focal length of 100 gives a depth of 25. The ``1e-8`` lowers the depth by a+ - the exact formula is ``baseline * focal / (disparity + 1e-8)``: a disparity of 2 with a baseline of+ 0.5 and a focal length of 100 gives a depth of 25. The ``1e-8`` lowers the depth by arelative ``1e-8 / disparity``. Float32 rounds that away from a disparity of 0.25 up; below it the biasshows, ``1e-6`` relative (10 float32 ulps) at a disparity of 0.01.- a zero disparity (no stereo match, or a point at infinity) gives a finite far depth,``baseline * focal / 1e-8`` (``5e9`` for baseline 0.5 and focal 100), not ``inf``. Such a point warpsas a point at infinity, along the rotation-only homography, in- :func:`~kornia.geometry.depth.warp_frame_depth`, whereas an ``inf`` depth would turn into ``NaN`` in- :func:`~kornia.geometry.depth.depth_to_3d` wherever a ray component is zero. The far depth is a+ :func:`warp_frame_depth`, whereas an ``inf`` depth would turn into ``NaN`` in+ :func:`depth_to_3d` wherever a ray component is zero. The far depth is aplaceholder, not a measurement: mask ``disparity > 0`` to tell matched pixels apart.- in float16 the ``1e-8`` rounds to ``0`` and the far depth would overflow anyway, so a zero disparitygives ``inf``. A float32 far depth turns back into ``inf`` wherever the warp casts it to float16, as afloat16 pose or float16 autocast does, so run the whole warp (depth, image, pose and camera matrix) infloat32, outside float16 autocast, when zero disparities flow into it.- - ``baseline`` and ``focal`` are each a scalar (Python number, 0-d or :math:`(1,)` tensor) shared by the- whole disparity, or a :math:`(B,)` tensor paired with ``disparity[b]``, which then needs a leading+ - ``baseline`` and ``focal`` are each a scalar (Python number, 0-d or ``(1,)`` tensor) shared by the+ whole disparity, or a ``(B,)`` tensor paired with ``disparity[b]``, which then needs a leadingbatch axis of size ``B`` (otherwise ``ShapeError``). The two may mix.- - ``disparity`` is :math:`(*, H, W)` and the result has its shape. Its sign is not checked.+ - ``disparity`` is ``(*, H, W)`` and the result has its shape. Its sign is not checked.Args:- disparity: Disparity tensor of shape :math:`(*, H, W)`.+ disparity: Disparity tensor of shape ``(*, H, W)``.baseline: Distance between the two lenses, as an int, float, or tensor of shape ``()`` or ``(1,)``,or of shape ``(B,)`` for one value per batch element.focal: Focal length, as an int, float, or tensor of shape ``()`` or ``(1,)``, or of shape ``(B,)`` forone value per batch element.Return:- Depth map of the shape :math:`(*, H, W)`.+ Depth map of the shape ``(*, H, W)``.++ See Also:+ - :func:`depth_to_3d`, :func:`depth_to_3d_v2`: unproject the depth map to 3D points.+ - :meth:`~kornia.geometry.camera.stereo.StereoCamera.reproject_disparity_to_3D`: disparity to 3D points in one+ step.+ - :func:`depth_from_plane_equation`: the depth of given pixels on a known plane, ``(B, N)``, not a map.Example:>>> disparity = torch.rand(4, 1, 4, 4)diff --git a/readthedocs.yml b/readthedocs.ymlindex e9666e3ef..c4ea6a7ce 100644--- a/readthedocs.yml+++ b/readthedocs.yml@@ -13,13 +13,14 @@ build:# Build documentation in the "docs/" directory with Sphinxsphinx:configuration: docs/source/conf.py+ fail_on_warning: true-# Optional but recommended, declare the Python requirements required-# to build your documentation-# See https://docs.readthedocs.io/en/stable/guides/reproducible-builds.html+# Install kornia and its docs extra from uv.lock (`uv sync --extra docs`), the versions that `pixi run build-docs`+# and the docs workflow use, so that `fail_on_warning` above checks pinned versions rather than the newest release+# of Sphinx or an extension. Update the docs dependencies by relocking.python:install:- - method: pip- path: .- extra_requirements:+ - method: uv+ command: sync+ extras:- docsdiff --git a/testing/docstring_rollout.py b/testing/docstring_rollout.pynew file mode 100644index 000000000..926a19495--- /dev/null+++ b/testing/docstring_rollout.py@@ -0,0 +1,65 @@+# LICENSE HEADER MANAGED BY add-license-header+#+# Copyright 2018 Kornia Team+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+#++"""Which parts of kornia the docstring-style checks enforce, widened one batch at a time.++``tests/test_docstring_style.py`` reads these values. A rollout batch converts a module and then adds it to the+lists below, so that the style it was converted to cannot regress.+"""++from __future__ import annotations++IN_SCOPE_PACKAGES: tuple[str, ...] = (+ "augmentation",+ "color",+ "config",+ "constants",+ "contrib",+ "core",+ "enhance",+ "feature",+ "filters",+ "geometry",+ "image",+ "io",+ "losses",+ "metrics",+ "models",+ "morphology",+ "onnx",+ "sensors",+ "tracking",+)+"""Top-level ``kornia`` packages and modules the rollout covers."""++EXCLUDED_PACKAGES: dict[str, str] = {+ "utils": "deprecated shims that keep their 'Deprecated: use X' first lines",+ "transpiler": "a removal stub",+}+"""Top-level packages left out of the rollout, with the reason."""++SHAPE_CHECK_MODULES: tuple[str, ...] | None = ("kornia.geometry.depth",)+"""Module prefixes whose source may not write a shape as ``:math:``; ``None`` means all of ``kornia/``."""++CATALOG_NAMESPACES: tuple[str, ...] = ("kornia.geometry.depth",)+"""Namespaces whose module docstring must name every export in ``__all__``."""++DOCSTRING_MODULES: tuple[str, ...] = ("kornia.geometry.depth",)+"""Prefixes of the defining modules whose public objects carry the converted docstring style."""++SEE_ALSO_EXCEPTIONS: dict[str, str] = {}+"""Qualified name of a converted object that needs no ``See Also:`` section, with the reason."""diff --git a/testing/docstring_style.py b/testing/docstring_style.pynew file mode 100644index 000000000..e05fc7de2--- /dev/null+++ b/testing/docstring_style.py@@ -0,0 +1,863 @@+# LICENSE HEADER MANAGED BY add-license-header+#+# Copyright 2018 Kornia Team+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+#++"""Helpers shared by the tests that check kornia's docstring style.++They find the public API, read the structure of a docstring (``See Also`` entries, cross-reference roles, shape+tuples) and resolve a cross-reference the way Sphinx does, through the names that the ``.rst`` pages under+``docs/source`` register and, for torch, Python and NumPy objects, the cached intersphinx inventories.+"""++from __future__ import annotations++import ast+import contextlib+import importlib+import inspect+import io+import re+import sys+import tokenize+import warnings+import zlib+from functools import cache+from pathlib import Path+from typing import Iterable, Mapping, NamedTuple++import kornia++_KORNIA_ROOT = Path(kornia.__file__).resolve().parent+++def modules_declaring_all() -> list[str]:+ """Name every non-private kornia module that assigns ``__all__``, found from source without importing it.++ The same parse as ``_declared_inventory_modules`` in ``tests/test_api_surface.py``, over the whole package+ rather than the inventory roots: the inventory leaves out ``kornia.feature``, whose matchers and LAF estimators+ are among the symbols the docstring tests exist for.+ """+ found = []+ for path in sorted(_KORNIA_ROOT.rglob("*.py")):+ parts = list(path.relative_to(_KORNIA_ROOT).with_suffix("").parts)+ if parts[-1] == "__init__":+ parts.pop()+ if any(part.startswith("_") for part in parts):+ continue+ tree = ast.parse(path.read_bytes(), filename=str(path))+ if any(+ (+ isinstance(node, ast.Assign)+ and any(isinstance(target, ast.Name) and target.id == "__all__" for target in node.targets)+ )+ or (isinstance(node, ast.AnnAssign) and isinstance(node.target, ast.Name) and node.target.id == "__all__")+ for node in tree.body+ ):+ found.append(".".join(["kornia", *parts]))+ return found+++def own_docstring(obj: object) -> str | None:+ """Return the cleaned docstring ``obj`` defines itself, or ``None``.++ A class does not inherit one from its base here, unlike with ``inspect.getdoc``.+ """+ doc = obj.__dict__.get("__doc__") if inspect.isclass(obj) else getattr(obj, "__doc__", None)+ cleaned = inspect.cleandoc(doc) if doc else ""+ return cleaned or None+++def _import_exported(module_name: str) -> object | None:+ """Import ``module_name`` quietly; ``None`` when it needs an optional package that is not installed."""+ with warnings.catch_warnings():+ warnings.simplefilter("ignore")+ try:+ return importlib.import_module(module_name)+ except ModuleNotFoundError as error:+ if (error.name or "").partition(".")[0] == "kornia":+ raise+ return None+++def _is_kornia_function_or_class(obj: object) -> bool:+ if not (inspect.isclass(obj) or inspect.isfunction(obj)):+ return False+ module_of_obj = obj.__module__ or ""+ return module_of_obj == "kornia" or module_of_obj.startswith("kornia.")+++@cache+def public_objects() -> dict[int, tuple[object, str]]:+ """Map ``id(obj)`` to ``(obj, "module.qualname")`` for every exported kornia function and class with a docstring.++ Covers every name in the ``__all__`` of a non-private kornia module that is a function or class defined in+ kornia and has a docstring of its own, deduplicated by object identity. Names starting with an underscore are+ out of scope. The dict is cached and shared between callers, who must not mutate it.+ """+ collected: dict[int, tuple[object, str]] = {}+ for module_name in modules_declaring_all():+ module = _import_exported(module_name)+ if module is None:+ continue+ with warnings.catch_warnings():+ # ``getattr`` runs module-level ``__getattr__`` shims, which warn about deprecated names.+ warnings.simplefilter("ignore")+ exported = [getattr(module, name, None) for name in module.__all__ if not name.startswith("_")]+ for obj in exported:+ if _is_kornia_function_or_class(obj) and own_docstring(obj):+ collected[id(obj)] = (obj, f"{obj.__module__}.{obj.__qualname__}")+ return collected+++def covered(module_name: str, prefixes: Iterable[str]) -> bool:+ """Whether ``module_name`` equals one of ``prefixes`` or lies below it (``prefix + "."``)."""+ return any(module_name == prefix or module_name.startswith(prefix + ".") for prefix in prefixes)+++_SHAPE_OPERAND = r"(?:[A-Z]\w*|\d+)"+_SHAPE_ELEMENT = re.compile(rf"[A-Z]\w*|\d+|\*|\.\.\.|{_SHAPE_OPERAND}\s*(?://|[/*+-])\s*{_SHAPE_OPERAND}")+++def is_shape_tuple(content: str) -> bool:+ """Whether ``content`` is a tensor shape such as ``(B, 3, H, W)``, ``(*, H, W)`` or ``(B, H/2, W/2)``.++ The elements must be uppercase identifiers, non-negative integers, ``*``, ``...`` or one binary+ ``//``, ``/``, ``*``, ``+`` or ``-`` between two of the first two. Coordinate pairs such as ``(x, y)``, LaTeX+ tuples, ranges with signs or decimals and the empty tuple are not shapes.+ """+ text = content.strip()+ if not (text.startswith("(") and text.endswith(")")):+ return False+ elements = [element.strip() for element in text[1:-1].split(",")]+ if len(elements) > 1 and elements[-1] == "":+ elements.pop() # a trailing comma, as in ``(B,)``+ return all(_SHAPE_ELEMENT.fullmatch(element) for element in elements)+++_MATH_ROLE = re.compile(r":math:`([^`]*)`")+++def math_shape_roles(text: str) -> list[str]:+ """Return the contents of every ``:math:`` role in ``text`` that is a shape tuple, in order."""+ return [content for content in _MATH_ROLE.findall(text) if is_shape_tuple(content)]+++# The Python-domain roles that link to an object. ``:mod:`` links to a module page and is not checked here.+_PY_ROLES = "func|class|meth|attr|data|const|exc|obj"+_XREF_ROLE = re.compile(rf":(?:py:)?({_PY_ROLES}):`~?([^`]+)`")+++def docstring_roles(doc: str) -> list[tuple[str, str]]:+ """Return ``(role, target)`` for every Python-domain object role in ``doc``, without a leading ``~``.++ The roles are ``func``, ``class``, ``meth``, ``attr``, ``data``, ``const``, ``exc`` and ``obj``, with or without+ the ``py:`` prefix; ``:mod:`` and ``:math:`` are not object references.+ """+ return [(match.group(1), match.group(2)) for match in _XREF_ROLE.finditer(doc)]+++_SEE_ALSO = re.compile(r"^(\s*)See Also:\s*$")+++_LEADING_ROLES = re.compile(rf"(?::(?:py:)?(?:{_PY_ROLES}):`~?[^`]+`[\s,]*)+")+++def see_also_entries(doc: str) -> list[tuple[str, str]] | None:+ """Parse the ``See Also:`` section of ``doc`` into ``(target, explanation)`` pairs.++ Returns ``None`` when there is no such section, and ``[]`` when it has no bullets. Each ``- `` bullet gives one+ pair per role in its leading role list (one or more roles separated by commas or whitespace); they share the+ explanation, which is the text after the colon that follows that list, joined across continuation lines+ (``""`` when missing). Roles inside the explanation are not targets. A bullet without a leading role renders+ without a link; it gives one pair ``("", text)`` with its whole text, so a caller can report it. The section+ ends at the first non-blank line indented at or below the ``See Also:`` header, or at the end of the docstring;+ text before the first bullet is ignored.+ """+ lines = doc.splitlines()+ start = next((i for i, line in enumerate(lines) if _SEE_ALSO.match(line)), None)+ if start is None:+ return None+ indent = len(lines[start]) - len(lines[start].lstrip())+ bullets: list[list[str]] = []+ for line in lines[start + 1 :]:+ stripped = line.strip()+ if not stripped:+ continue+ if len(line) - len(line.lstrip()) <= indent:+ break+ if stripped.startswith("- "):+ bullets.append([stripped[2:].strip()])+ elif bullets:+ bullets[-1].append(stripped)+ entries: list[tuple[str, str]] = []+ for parts in bullets:+ text = " ".join(parts)+ leading = _LEADING_ROLES.match(text)+ if leading is None:+ entries.append(("", text))+ continue+ tail = text[leading.end() :].strip()+ explanation = tail[1:].strip() if tail.startswith(":") else ""+ entries.extend((match.group(2), explanation) for match in _XREF_ROLE.finditer(leading.group(0)))+ return entries+++def is_private_target(target: str) -> bool:+ """Whether the last component of ``target`` is private: a leading underscore, unless it is a ``__name__``.++ A special method such as ``__mul__`` is public, and ``:special-members:`` documents it.+ """+ name = target.removesuffix("()").rpartition(".")[2]+ return name.startswith("_") and not (name.startswith("__") and name.endswith("__"))+++_DIRECTIVE_KINDS = "autofunction|autoclass|automethod|autoexception|automodule|autosummary|currentmodule|module"+_DIRECTIVE = re.compile(rf"^(\s*)\.\. (?:py:)?({_DIRECTIVE_KINDS})::\s*(.*?)\s*$")+# The directive options the registry models, and the ones that do not change which names autodoc registers. Any+# other option, such as ``:no-index:``, ``:exclude-members:`` or ``:inherited-members:``, raises, so that a page that+# adds one fails the tests instead of silently making the registry disagree with Sphinx.+_KNOWN_OPTIONS = frozenset(+ {"members", "undoc-members", "special-members", "toctree", "show-inheritance", "member-order", "nosignatures"}+)+++def _import_dotted(name: str, as_module: bool = False) -> object | None:+ """Resolve ``name`` the way autodoc does; ``None`` on any failure.++ Imports the longest importable parent module and walks the rest with ``getattr``, so a function that shares its+ name with a submodule (``kornia.filters.sobel``) is the function. The whole name is tried as a module first only+ for ``as_module`` (``automodule``) and as a last fallback otherwise.+ """+ parts = name.split(".")+ ends = list(range(len(parts) - 1, 0, -1))+ ends = [len(parts), *ends] if as_module else [*ends, len(parts)]+ with warnings.catch_warnings():+ warnings.simplefilter("ignore")+ for end in ends:+ try:+ obj: object = importlib.import_module(".".join(parts[:end]))+ for attr in parts[end:]:+ obj = getattr(obj, attr)+ except Exception: # noqa: BLE001, S112 - an optional dependency may fail in any way+ continue+ return obj+ return None+++def _autodoc_documents(owner: object, name: str, member: object, undoc_members: bool) -> bool:+ """Whether autodoc's ``:members:`` documents ``member``, found as ``name`` on the class or module ``owner``.++ Mirrors ``Documenter.filter_members`` with the default ``autodoc_inherit_docstrings = True``: a member is kept+ with ``:undoc-members:`` or when it has a docstring, its own or, for a class member, the first one found under+ the same name up the MRO, or else what ``inspect.getdoc`` finds (a class inherits its base's docstring there).+ """+ if undoc_members:+ return True+ doc = getattr(member, "__doc__", None)+ if doc is None and inspect.isclass(owner):+ for base in owner.__mro__:+ inherited = getattr(base, name, None)+ # ``None.__doc__`` is the docstring of ``NoneType`` from Python 3.13 on, so skip a missing name.+ doc = None if inherited is None else getattr(inherited, "__doc__", None)+ if doc is not None:+ break+ if doc is None:+ doc = inspect.getdoc(member)+ # autodoc drops a docstring that is only the one of the member's type, such as ``property.__doc__``.+ return isinstance(doc, str) and bool(doc) and doc != getattr(type(member), "__doc__", None)+++def _public_methods(cls: type, undoc_members: bool, special: list[str] | None = None) -> dict[str, object]:+ """Public methods and properties defined on ``cls`` itself that ``autoclass :members:`` documents.++ Static and class methods are unwrapped. Inherited members are left out, as autodoc does without+ ``:inherited-members:``; an inherited docstring still documents a method that ``cls`` overrides. ``special`` is+ the ``:special-members:`` option: ``None`` keeps out every ``__name__``, ``[]`` admits all, a list the listed.+ """+ methods: dict[str, object] = {}+ for name, value in vars(cls).items():+ is_special = name.startswith("__") and name.endswith("__") and name != "__doc__"+ if name.startswith("_") and not (is_special and special is not None and (not special or name in special)):+ continue+ if isinstance(value, (staticmethod, classmethod)):+ value = value.__func__+ if (inspect.isfunction(value) or isinstance(value, property)) and _autodoc_documents(+ cls, name, value, undoc_members+ ):+ methods[name] = value+ return methods+++def _module_members(module: object, undoc_members: bool) -> dict[str, object]:+ """What ``automodule :members:`` documents: ``__all__`` when declared, else the public names defined in it."""+ declared = getattr(module, "__all__", None)+ if declared is not None:+ names = [name for name in declared if not name.startswith("_")]+ else:+ names = [name for name, value in vars(module).items() if not name.startswith("_")]+ members = {}+ for name in names:+ value = getattr(module, name, None)+ if not (inspect.isfunction(value) or inspect.isclass(value)):+ continue+ if declared is None and value.__module__ != module.__name__:+ continue+ if _autodoc_documents(module, name, value, undoc_members):+ members[name] = value+ return members+++class _Attribute(NamedTuple):+ """What the registry maps a documented data attribute to, in place of its value, which may be ``None``."""++ owner: object+ name: str+++_ATTRIBUTE_COMMENT = re.compile(r"^\s*#: ?(.*)$")+++class _AttributeDocPicker(ast.NodeVisitor):+ """Collect ``(namespace, name)`` of the documented variables of a module, as ``VariableCommentPicker`` does.++ An assignment documents its targets with a ``#:`` comment after it, with ``#:`` lines right above it, or with+ a string literal right after it. The namespace is the enclosing class path, ``""`` at module level. Inside a+ function only ``self.name`` assignments in a class's ``__init__`` count, under that class; nested functions and+ ``except`` and ``finally`` blocks are not read.+ """++ def __init__(self, lines: list[str], comment_columns: dict[int, int]) -> None:+ self.lines = lines+ self.comment_columns = comment_columns+ self.context: list[str] = []+ self.classes = 0+ self.function: ast.FunctionDef | ast.AsyncFunctionDef | None = None+ self.previous: ast.AST | None = None+ self.found: set[tuple[str, str]] = set()++ def visit(self, node: ast.AST) -> None:+ super().visit(node)+ self.previous = node++ def _self_name(self) -> str | None:+ if self.function is None:+ return None+ arguments = self.function.args.args or self.function.args.posonlyargs+ return arguments[0].arg if arguments else None++ def _names(self, target: ast.AST) -> list[str]:+ """The variables an assignment target creates; ``TypeError`` when it creates none (``a[0] = ...``)."""+ self_name = self._self_name()+ if isinstance(target, ast.Name):+ if self_name is None or target.id == self_name:+ return [target.id]+ elif isinstance(target, (ast.Tuple, ast.List)):+ names = []+ for element in target.elts:+ with contextlib.suppress(TypeError):+ names += self._names(element)+ return names+ elif isinstance(target, ast.Attribute) and isinstance(target.value, ast.Name):+ if self_name is not None and target.value.id == self_name:+ return [target.attr]+ elif isinstance(target, ast.Starred):+ return self._names(target.value)+ raise TypeError(target)++ def _namespace(self) -> str | None:+ if self.function is None:+ return ".".join(self.context)+ if self.classes and self.context[-1] == "__init__":+ return ".".join(self.context[:-1])+ return None++ def _record(self, names: list[str]) -> None:+ namespace = self._namespace()+ if namespace is not None:+ self.found.update((namespace, name) for name in names)++ def visit_Assign(self, node: ast.Assign | ast.AnnAssign) -> None:+ targets = node.targets if isinstance(node, ast.Assign) else [node.target]+ try:+ names = [name for target in targets for name in self._names(target)]+ except TypeError:+ return+ column = self.comment_columns.get(node.end_lineno or node.lineno)+ if (column is not None and column >= (node.end_col_offset or 0)) or (+ node.lineno > 1+ and not self.lines[node.lineno - 1][: node.col_offset].strip()+ and _ATTRIBUTE_COMMENT.match(self.lines[node.lineno - 2])+ ):+ self._record(names)++ visit_AnnAssign = visit_Assign++ def visit_Expr(self, node: ast.Expr) -> None:+ previous = self.previous+ if (+ isinstance(previous, (ast.Assign, ast.AnnAssign))+ and isinstance(node.value, ast.Constant)+ and isinstance(node.value.value, str)+ ):+ target = previous.targets[0] if isinstance(previous, ast.Assign) else previous.target+ with contextlib.suppress(TypeError):+ self._record(self._names(target))++ def visit_Try(self, node: ast.Try) -> None:+ for child in [*node.body, *node.orelse]:+ self.visit(child)++ def visit_ClassDef(self, node: ast.ClassDef) -> None:+ self.classes += 1+ self.context.append(node.name)+ self.previous = node+ for child in node.body:+ self.visit(child)+ self.context.pop()+ self.classes -= 1++ def visit_FunctionDef(self, node: ast.FunctionDef | ast.AsyncFunctionDef) -> None:+ if self.function is not None:+ return+ self.context.append(node.name)+ self.function = node+ for child in node.body:+ self.visit(child)+ self.context.pop()+ self.function = None++ visit_AsyncFunctionDef = visit_FunctionDef+++@cache+def _attribute_docs(module_name: str) -> frozenset[tuple[str, str]]:+ """``(namespace, name)`` of the variables the source of ``module_name`` documents (see ``_AttributeDocPicker``)."""+ path = getattr(sys.modules.get(module_name), "__file__", None)+ if not path or not path.endswith(".py"):+ return frozenset()+ source = Path(path).read_text(encoding="utf-8")+ comment_columns = {+ token.start[0]: token.start[1]+ for token in tokenize.generate_tokens(io.StringIO(source).readline)+ if token.type == tokenize.COMMENT and _ATTRIBUTE_COMMENT.match(token.string)+ }+ picker = _AttributeDocPicker(source.splitlines(), comment_columns)+ picker.visit(ast.parse(source))+ return frozenset(picker.found)+++def _is_data(value: object) -> bool:+ """Whether autodoc documents ``value`` as data rather than as a function, method, property, class or module."""+ if isinstance(value, (staticmethod, classmethod)):+ return False+ return not (+ inspect.isroutine(value) or isinstance(value, property) or inspect.isclass(value) or inspect.ismodule(value)+ )+++def _documented_attributes(owner: object, undoc_members: bool) -> dict[str, _Attribute]:+ """The public data attributes of the class or module ``owner`` that autodoc's ``:members:`` documents.++ Mirrors ``get_class_members``, ``get_module_members`` and ``filter_members``. A class contributes the data in+ its own ``__dict__``, enum members included, its own annotations (``x: int``, dataclass fields) and the instance+ attributes its ``__init__`` documents; such an attribute is documented when the source documents it (a ``#:``+ comment or a string after the assignment), when its value has a docstring other than its type's (a+ ``NamedTuple`` field), or under ``:undoc-members:``. A module's data is documented only when the source+ documents it, or, under ``:undoc-members:``, when it is a bare annotation, as ``DataDocumenter`` takes nothing+ else; with ``__all__``, only the names in it.+ """+ if inspect.isclass(owner):+ module_name, namespace = owner.__module__, owner.__qualname__+ values = {name: value for name, value in vars(owner).items() if _is_data(value)}+ annotated = list(inspect.get_annotations(owner))+ documented = {name for scope, name in _attribute_docs(module_name) if scope == namespace}+ else:+ module_name, namespace = getattr(owner, "__name__", ""), ""+ declared = getattr(owner, "__all__", None)+ annotations = inspect.get_annotations(owner)+ present = set(vars(owner)) | set(annotations) if declared is None else set(declared)+ values = {}+ annotated = [name for name in annotations if name in present and name not in vars(owner)]+ documented = {name for scope, name in _attribute_docs(module_name) if scope == namespace and name in present}++ def kept(name: str) -> bool:+ if name.startswith("_"):+ return False+ return (+ name in documented+ or undoc_members+ or (name in values and _autodoc_documents(owner, name, values[name], False))+ )++ candidates = [*values, *annotated, *sorted(documented)]+ return {name: _Attribute(owner, name) for name in dict.fromkeys(candidates) if kept(name)}+++def _directive_options(lines: list[str], index: int, indent: int) -> dict[str, str]:+ """Read the option block of the directive at ``index``: the ``:name: value`` lines right below it."""+ options: dict[str, str] = {}+ for line in lines[index + 1 :]:+ stripped = line.strip()+ if not stripped or len(line) - len(line.lstrip()) <= indent or not stripped.startswith(":"):+ break+ name, _, value = stripped[1:].partition(":")+ options[name] = value.strip()+ return options+++def _members_option(options: dict[str, str], option: str = "members") -> list[str] | None:+ """Read ``:members:`` or another member option: ``None`` when absent, ``[]`` for all, else the listed names."""+ if option not in options:+ return None+ return [name.strip() for name in options[option].split(",") if name.strip()]+++def _autosummary_names(lines: list[str], index: int, indent: int) -> list[str]:+ names = []+ for line in lines[index + 1 :]:+ stripped = line.strip()+ if not stripped:+ continue+ if len(line) - len(line.lstrip()) <= indent:+ break+ if stripped.startswith((":", "..")):+ continue+ names.append(stripped.removeprefix("~"))+ return names+++def _add(registry: dict[str, object], full_name: str, as_module: bool = False) -> object | None:+ obj = _import_dotted(full_name, as_module)+ if obj is not None:+ registry[full_name] = obj+ return obj+++def _add_methods(+ registry: dict[str, object],+ cls_name: str,+ cls: object,+ listed: list[str],+ undoc_members: bool,+ special: list[str] | None = None,+) -> None:+ """Register the members ``:members:`` documents: the listed names, or the public ones defined on ``cls``.++ Either way autodoc keeps only members with a docstring, unless the directive has ``:undoc-members:``; a data+ attribute counts as documented as ``_documented_attributes`` says. With all members, ``special``+ (``:special-members:``) selects the ``__name__`` methods as well.+ """+ if not inspect.isclass(cls):+ return+ attributes = _documented_attributes(cls, undoc_members)+ if listed:+ for name in listed:+ if name in attributes:+ registry[f"{cls_name}.{name}"] = attributes[name]+ continue+ member = _import_dotted(f"{cls_name}.{name}")+ if member is not None and _autodoc_documents(cls, name, member, undoc_members):+ registry[f"{cls_name}.{name}"] = member+ else:+ for name, method in _public_methods(cls, undoc_members, special).items():+ registry[f"{cls_name}.{name}"] = method+ for name, attribute in attributes.items():+ registry[f"{cls_name}.{name}"] = attribute+++def _add_module_members(+ registry: dict[str, object],+ module_name: str,+ module: object,+ listed: list[str],+ undoc_members: bool,+ special: list[str] | None = None,+) -> None:+ attributes = _documented_attributes(module, undoc_members)+ if listed:+ attributes = {name: attribute for name, attribute in attributes.items() if name in listed}+ members = {name: getattr(module, name, None) for name in listed if name not in attributes}+ members = {+ name: member+ for name, member in members.items()+ if member is not None and not _is_data(member) and _autodoc_documents(module, name, member, undoc_members)+ }+ else:+ members = _module_members(module, undoc_members)+ for name, attribute in attributes.items():+ registry[f"{module_name}.{name}"] = attribute+ for name, member in members.items():+ registry[f"{module_name}.{name}"] = member+ _add_methods(registry, f"{module_name}.{name}", member, [], undoc_members, special)+++# Directories of ``docs/source`` that Sphinx does not read pages from: ``conf.py``'s ``exclude_patterns``,+# ``templates_path``, ``html_static_path`` and ``html_extra_path``.+_NOT_PAGES = frozenset({"_build", ".ipynb_checkpoints", "_templates", "_static", "_extra"})+++def _rst_pages(docs_source: Path) -> list[Path]:+ """Every ``.rst`` page under ``docs_source``, subdirectories included, except those Sphinx does not build."""+ root = Path(docs_source)+ return sorted(page for page in root.rglob("*.rst") if _NOT_PAGES.isdisjoint(page.relative_to(root).parts[:-1]))+++def sphinx_registry(docs_source: Path) -> dict[str, object]:+ """Map every full name that the ``.rst`` pages under ``docs_source`` register to the imported object.++ Reads ``autofunction``, ``autoclass``, ``automethod``, ``autoexception``, ``automodule`` and ``autosummary``+ entries, resolving relative names against the latest ``currentmodule`` or ``module`` and a nested ``automethod``+ against the enclosing class. ``autoclass`` and ``automodule`` with ``:members:`` register the methods and+ properties defined on the class and the functions and classes of the module that autodoc documents (public, with+ a docstring or under ``:undoc-members:``), the data attributes it documents (enum members, dataclass fields and+ commented variables; see ``_documented_attributes``), each mapped to an ``_Attribute`` rather than its value, and+ the ``__name__`` methods that ``:special-members:`` selects. An ``autosummary`` registers its entries only with+ ``:toctree:``, which generates their pages; without it, it only links to them. Names that do not import are left+ out. A directive option outside the ones modelled here raises ``ValueError``.+ """+ registry: dict[str, object] = {}++ for page in _rst_pages(docs_source):+ lines = page.read_text(encoding="utf-8").splitlines()+ current = ""+ enclosing_class = ""+ for index, line in enumerate(lines):+ match = _DIRECTIVE.match(line)+ if match is None:+ continue+ indent, kind, argument = len(match.group(1)), match.group(2), match.group(3)+ if kind in ("currentmodule", "module"):+ current = argument+ continue+ qualified = argument if argument.startswith("kornia") or not current else f"{current}.{argument}"+ if kind == "automethod" and indent > 0 and enclosing_class:+ qualified = f"{enclosing_class}.{argument}"+ options = _directive_options(lines, index, indent)+ unknown = sorted(set(options) - _KNOWN_OPTIONS)+ if unknown:+ raise ValueError(+ f"{page}:{index + 1}: sphinx_registry does not model the {kind} option(s) {unknown}; "+ "teach it what autodoc registers with them"+ )+ members = _members_option(options)+ special = _members_option(options, "special-members")+ # Like autodoc's ``merge_members_option``, a ``:special-members:`` list joins a ``:members:`` that does+ # not already document all members, and stands in for an absent one.+ if special and members != []:+ members = [*(members or []), *(name for name in special if name not in (members or []))]+ undoc_members = "undoc-members" in options+ if kind == "autosummary":+ if "toctree" in options:+ for name in _autosummary_names(lines, index, indent):+ _add(registry, name if name.startswith("kornia") or not current else f"{current}.{name}")+ elif kind == "automodule":+ module = _add(registry, qualified, as_module=True)+ if module is not None and members is not None:+ _add_module_members(registry, qualified, module, members, undoc_members, special)+ else:+ obj = _add(registry, qualified)+ if kind == "autoclass":+ enclosing_class = qualified+ if members is not None:+ _add_methods(registry, qualified, obj, members, undoc_members, special)+ return registry+++_INVENTORY_LINE = re.compile(r"(.+?)\s+(\S+)\s+(-?\d+)\s+?(\S*)\s+(.*)")+_ALL_OBJECT_TYPES = frozenset(+ "function data class exception method classmethod staticmethod attribute property type module".split()+)+# The Python object types that intersphinx links each role to: the roles of the Python domain's ``object_types``,+# plus ``method`` for ``:attr:``, where inventories from before Sphinx 2.1 store properties. ``:const:`` is in no+# object type's roles, so intersphinx links it to nothing.+_ROLE_OBJECT_TYPES: dict[str, frozenset[str]] = {+ "func": frozenset({"function"}),+ "data": frozenset({"data"}),+ "class": frozenset({"class", "exception"}),+ "exc": frozenset({"class", "exception"}),+ "meth": frozenset({"method", "classmethod", "staticmethod"}),+ "attr": frozenset({"attribute", "property", "method"}),+ "const": frozenset(),+ "obj": _ALL_OBJECT_TYPES,+}+++def intersphinx_names(docs_source: Path) -> dict[str, frozenset[str]]:+ """Map each Python object name of the cached intersphinx inventories in ``docs_source/_intersphinx`` to its types.++ ``conf.py`` falls back to these ``python``, ``numpy`` and ``torch`` inventories when it cannot fetch the live+ ones. Each file is a Sphinx inventory version 2: four header lines, then zlib-compressed+ ``name domain:role priority uri dispname`` lines. The types are the Python domain's object types without the+ ``py:`` prefix, such as ``function`` or ``attribute``; ``reference_resolves`` matches them against the role.+ """+ types: dict[str, set[str]] = {}+ for path in sorted((Path(docs_source) / "_intersphinx").glob("*.inv")):+ with path.open("rb") as stream:+ header = [stream.readline() for _ in range(4)]+ if not header[0].startswith(b"# Sphinx inventory version 2") or b"zlib" not in header[3]:+ raise ValueError(f"{path} is not a zlib-compressed Sphinx inventory version 2")+ body = zlib.decompress(stream.read()).decode("utf-8")+ for line in body.splitlines():+ match = _INVENTORY_LINE.match(line.rstrip())+ if match is not None and match.group(2).startswith("py:"):+ types.setdefault(match.group(1), set()).add(match.group(2).removeprefix("py:"))+ return {name: frozenset(kinds) for name, kinds in types.items()}+++def _reference_scopes(obj: object, registry: dict[str, object]) -> list[str]:+ """The prefixes Sphinx tries a reference in the docstring of ``obj`` under: its module, then its class."""+ scopes: list[str] = []+ for name, registered in registry.items():+ if registered is not obj:+ continue+ parent = name.rpartition(".")[0]+ if inspect.isclass(obj):+ scopes += [parent, name]+ elif parent in registry and inspect.isclass(registry[parent]):+ scopes += [parent.rpartition(".")[0], parent]+ else:+ scopes.append(parent)+ return [scope for scope in scopes if scope]+++def is_documented(obj: object, registry: dict[str, object]) -> bool:+ """Whether a docs page registers ``obj`` itself, so that short names in its docstring have a scope."""+ return any(registered is obj for registered in registry.values())+++def _role_target(target: str, role: str | None) -> str:+ """``target`` as Sphinx looks it up: ``:func:`` and ``:meth:`` drop a trailing ``()``, other roles keep it."""+ return target.removesuffix("()") if role in (None, "func", "meth") else target+++def resolve_reference(obj: object, target: str, registry: dict[str, object], role: str | None = None) -> object | None:+ """Return the registered object that ``target``, written in the docstring of ``obj``, resolves to, or ``None``.++ As Sphinx does for a Python-domain role: a trailing ``()`` is dropped for ``:func:`` and ``:meth:`` (and when+ ``role`` is ``None``), then the target is tried as written and under each scope of ``obj``, the module it is+ documented under and, for a class or a method, the class, so ``to_tensor`` and ``Boxes.to_tensor`` both resolve+ inside the ``Boxes`` page. The role does not restrict the object type: Sphinx links a name it registers whatever+ its type. A short import alias is not registered, so it does not resolve; neither does a short name in the+ docstring of an object that no docs page registers. Only kornia objects resolve here; see+ ``intersphinx_names`` for the rest.+ """+ target = _role_target(target, role)+ candidates = [target, *(f"{scope}.{target}" for scope in _reference_scopes(obj, registry))]+ for candidate in candidates:+ if candidate in registry:+ return registry[candidate]+ return None+++def reference_resolves(+ obj: object,+ target: str,+ registry: dict[str, object],+ external: Mapping[str, frozenset[str]] | None = None,+ role: str | None = None,+) -> bool:+ """Whether ``target``, in a ``role`` role in the docstring of ``obj``, renders as a link.++ True when it resolves to a registered kornia object (see ``resolve_reference``) or is an ``external`` name, such+ as one from ``intersphinx_names(docs_source)``, of an object type that intersphinx links ``role`` to. Unlike the+ local lookup, intersphinx matches the type: ``:meth:`torch.svd``` (a function) and every ``:const:`` stay plain+ text. A ``role`` of ``None`` accepts any type.+ """+ if resolve_reference(obj, target, registry, role) is not None:+ return True+ types = (external or {}).get(_role_target(target, role), frozenset())+ return bool(types if role is None else types & _ROLE_OBJECT_TYPES.get(role, frozenset()))+++def catalog_missing(doc: str, names: list[str], namespace: object) -> list[str]:+ """Return the ``names`` exported by ``namespace`` that ``doc`` mentions in no Python role or literal.++ A name counts only as the whole target of a Python-domain role, such as :func:`name` or :func:`~kornia.x.name`,+ or as a double-backtick literal, such as ``name`` or ``name()``. A qualified target counts only when it imports+ as the object ``namespace`` exports under that name, so ``torch.nn.functional.normalize`` does not mention+ ``kornia.enhance.normalize``. The same word in plain prose (``normalize``, ``threshold``), in single backticks+ (the default role, which renders as italics) or in a ``:math:`` role does not count, and ``depth_to_3d_v2`` does+ not count as mentioning ``depth_to_3d``.+ """++ def mentioned(name: str) -> bool:+ target = rf"((?:[\w.]*\.)?{re.escape(name)})(?:\(\))?"+ exported = getattr(namespace, name, None)+ for match in re.finditer(rf"``{target}``|:(?:py:)?(?:{_PY_ROLES}):`~?{target}`", doc):+ written = match.group(1) or match.group(2)+ if written == name or (exported is not None and _import_dotted(written) is exported):+ return True+ return False++ return [name for name in names if not mentioned(name)]+++def _import_role_target(module: object, target: str) -> object:+ """Import a role target: longest importable dotted prefix, then ``getattr``; a bare name is read off ``module``.++ A trailing ``()`` is dropped first, as Sphinx drops it from a role target such as ``name()``.+ """+ target = target.removesuffix("()")+ if "." not in target:+ return getattr(module, target)+ parts = target.split(".")+ for end in range(len(parts), 0, -1):+ try:+ obj: object = importlib.import_module(".".join(parts[:end]))+ except ImportError:+ continue+ for attr in parts[end:]:+ obj = getattr(obj, attr)+ return obj+ raise ImportError(target)+++def catalog_unimportable(module: object, doc: str) -> list[str]:+ """Return the role targets in the module catalog ``doc`` of ``module`` that do not import.++ Reads every Python-domain object role (see ``docstring_roles``). A bare target is looked up on ``module``, a+ dotted one from the longest importable module prefix.+ """+ broken = []+ for _, target in docstring_roles(doc):+ try:+ _import_role_target(module, target)+ except (ImportError, AttributeError):+ broken.append(target)+ return broken+++def catalog_required(namespace: str, catalogued: Iterable[str]) -> bool:+ """Whether ``namespace`` needs a catalog of its own.++ False when every object in its ``__all__`` is also exported, as the same object, by an ancestor namespace listed+ in ``catalogued``; true otherwise.+ """+ catalogued = set(catalogued)+ module = importlib.import_module(namespace)+ parts = namespace.split(".")+ ancestors = [importlib.import_module(".".join(parts[:end])) for end in range(1, len(parts))]+ ancestors = [ancestor for ancestor in ancestors if ancestor.__name__ in catalogued]+ with warnings.catch_warnings():+ warnings.simplefilter("ignore")+ for name in getattr(module, "__all__", []):+ obj = getattr(module, name, None)+ if not any(+ name in getattr(ancestor, "__all__", []) and getattr(ancestor, name, None) is obj+ for ancestor in ancestors+ ):+ return True+ return Falsediff --git a/tests/test_docstring_first_lines.py b/tests/test_docstring_first_lines.pyindex c4cc61f33..4d1ae97b5 100644--- a/tests/test_docstring_first_lines.py+++ b/tests/test_docstring_first_lines.py@@ -33,43 +33,12 @@ without a docstring of its own, which inherits one from its base. Lines are compcollapsing whitespace, so this catches copies, not near-duplicates: two lines that differ by a single word pass."""-import ast-import importlibimport inspect-import warningsfrom functools import cache-from pathlib import Pathimport kornia-_KORNIA_ROOT = Path(kornia.__file__).resolve().parent---def _modules_declaring_all() -> list[str]:- """Name every non-private kornia module that assigns ``__all__``, found from source without importing it.-- The same parse as ``_declared_inventory_modules`` in ``tests/test_api_surface.py``, over the whole package- rather than the inventory roots: the inventory leaves out ``kornia.feature``, whose matchers and LAF estimators- are among the symbols this test exists for.- """- found = []- for path in sorted(_KORNIA_ROOT.rglob("*.py")):- parts = list(path.relative_to(_KORNIA_ROOT).with_suffix("").parts)- if parts[-1] == "__init__":- parts.pop()- if any(part.startswith("_") for part in parts):- continue- tree = ast.parse(path.read_bytes(), filename=str(path))- if any(- (- isinstance(node, ast.Assign)- and any(isinstance(target, ast.Name) and target.id == "__all__" for target in node.targets)- )- or (isinstance(node, ast.AnnAssign) and isinstance(node.target, ast.Name) and node.target.id == "__all__")- for node in tree.body- ):- found.append(".".join(["kornia", *parts]))- return found+from testing.docstring_style import own_docstring, public_objectsdef _first_line(doc: str) -> str:@@ -106,30 +75,7 @@ def _is_wrapper_pair(objects: list) -> bool:@cachedef _public_first_lines() -> dict[int, tuple[object, str]]:"""Map ``id(obj)`` to ``(obj, first docstring line)`` for every public kornia function and class."""- collected: dict[int, tuple[object, str]] = {}- for module_name in _modules_declaring_all():- with warnings.catch_warnings():- # ``getattr`` runs module-level ``__getattr__`` shims, which warn about deprecated names.- warnings.simplefilter("ignore")- try:- module = importlib.import_module(module_name)- except ModuleNotFoundError as error:- # A module that needs an optional package which is not installed is out of scope here.- if (error.name or "").partition(".")[0] == "kornia":- raise- continue- exported = [(name, getattr(module, name, None)) for name in module.__all__ if not name.startswith("_")]- for _, obj in exported:- if not (inspect.isclass(obj) or inspect.isfunction(obj)):- continue- module_of_obj = obj.__module__ or ""- if not (module_of_obj == "kornia" or module_of_obj.startswith("kornia.")):- continue- # ``inspect.getdoc`` would hand a class without a docstring its base class's one.- doc = obj.__dict__.get("__doc__") if inspect.isclass(obj) else obj.__doc__- if doc:- collected[id(obj)] = (obj, _first_line(doc))- return collected+ return {key: (obj, _first_line(own_docstring(obj))) for key, (obj, _) in public_objects().items()}def test_the_scan_covers_the_public_api():diff --git a/tests/test_docstring_style.py b/tests/test_docstring_style.pynew file mode 100644index 000000000..48856148d--- /dev/null+++ b/tests/test_docstring_style.py@@ -0,0 +1,234 @@+# LICENSE HEADER MANAGED BY add-license-header+#+# Copyright 2018 Kornia Team+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+#++"""Converted kornia modules keep the docstring style the rollout set out to give them.++``testing/docstring_rollout.py`` lists the modules that are converted. For those, this file enforces what a reader,+an IDE or a coding agent relies on and what a refactor silently breaks:++* every public function and class has a ``See Also:`` section whose entries name a sibling and say how it differs;+* every Python-domain object role (``:func:``, ``:class:``, ``:meth:``, ``:attr:``, ``:data:``, ``:const:``,+ ``:exc:``, ``:obj:``) resolves to a name that Sphinx registers from ``docs/source``, or to a torch, Python or NumPy+ object of a type that role links in the cached intersphinx inventories, so it renders as a link and not as plain+ text (a short import alias is importable but is not a target); See Also entries name kornia objects only;+* the source writes a tensor shape as a literal such as ``(B, 1, H, W)``, not as ``:math:``;+* the module docstring of a namespace names every export of its ``__all__`` in a role or a double-backtick literal.++The test ids are qualified names, so a failure names the object to fix. Run with ``-s`` to see the progress table.+"""++from __future__ import annotations++import importlib+import inspect+from pathlib import Path++import pytest++import kornia++from testing.docstring_rollout import (+ CATALOG_NAMESPACES,+ DOCSTRING_MODULES,+ EXCLUDED_PACKAGES,+ IN_SCOPE_PACKAGES,+ SEE_ALSO_EXCEPTIONS,+ SHAPE_CHECK_MODULES,+)+from testing.docstring_style import (+ catalog_missing,+ catalog_required,+ catalog_unimportable,+ covered,+ docstring_roles,+ intersphinx_names,+ is_documented,+ is_private_target,+ math_shape_roles,+ modules_declaring_all,+ own_docstring,+ public_objects,+ reference_resolves,+ resolve_reference,+ see_also_entries,+ sphinx_registry,+)++KORNIA_ROOT = Path(kornia.__file__).resolve().parent+DOCS = KORNIA_ROOT.parent / "docs" / "source"+REGISTRY = sphinx_registry(DOCS)+INTERSPHINX = intersphinx_names(DOCS)++CONVERTED = sorted(+ ((qualified, obj) for obj, qualified in public_objects().values() if covered(obj.__module__, DOCSTRING_MODULES)),+ key=lambda pair: pair[0],+)+++def _module_name(path: Path) -> str:+ parts = list(path.relative_to(KORNIA_ROOT.parent).with_suffix("").parts)+ if parts[-1] == "__init__":+ parts.pop()+ return ".".join(parts)+++SHAPE_CHECK_FILES = sorted(+ path+ for path in KORNIA_ROOT.rglob("*.py")+ if SHAPE_CHECK_MODULES is None or covered(_module_name(path), SHAPE_CHECK_MODULES)+)+++def _suggest(target: str) -> str:+ """Name the one registered full name that shares the last component of ``target``, if exactly one does."""+ last = target.removesuffix("()").rpartition(".")[2]+ matches = [name for name in REGISTRY if name.rpartition(".")[2] == last]+ return f" (registered as {matches[0]!r})" if len(matches) == 1 else ""+++def _wrong_role(role: str, target: str) -> str:+ """Name the intersphinx types of ``target`` when it is there under a type that ``role`` does not link."""+ types = INTERSPHINX.get(target.removesuffix("()") if role in ("func", "meth") else target)+ return f" (an intersphinx {', '.join(sorted(types))}, which :{role}: does not link)" if types else ""+++def test_rollout_selects_something() -> None:+ """The parametrized checks below are not vacuous: the rollout lists select objects and files."""+ assert CONVERTED, f"DOCSTRING_MODULES {DOCSTRING_MODULES} select no public object"+ assert SHAPE_CHECK_FILES, f"SHAPE_CHECK_MODULES {SHAPE_CHECK_MODULES} select no source file"+ assert CATALOG_NAMESPACES, "CATALOG_NAMESPACES is empty, so no module catalog is checked"+ assert REGISTRY, f"sphinx_registry({DOCS}) registered nothing"+ assert INTERSPHINX, f"intersphinx_names({DOCS}) found no inventory names"+ for prefix in DOCSTRING_MODULES:+ assert any(covered(obj.__module__, [prefix]) for _, obj in CONVERTED), (+ f"DOCSTRING_MODULES entry {prefix!r} selects no public object with a docstring"+ )+ for prefix in SHAPE_CHECK_MODULES or ():+ assert any(covered(_module_name(path), [prefix]) for path in SHAPE_CHECK_FILES), (+ f"SHAPE_CHECK_MODULES entry {prefix!r} selects no source file"+ )+++def test_every_package_is_assigned() -> None:+ present = {path.name for path in KORNIA_ROOT.iterdir() if path.is_dir() and (path / "__init__.py").exists()}+ present |= {path.stem for path in KORNIA_ROOT.glob("*.py") if not path.name.startswith("_")}+ assigned = set(IN_SCOPE_PACKAGES) | set(EXCLUDED_PACKAGES)+ assert present == assigned, (+ f"add {sorted(present - assigned)} to IN_SCOPE_PACKAGES or EXCLUDED_PACKAGES in testing/docstring_rollout.py; "+ f"remove {sorted(assigned - present)}, which no longer exist"+ )+++def test_rollout_lists_are_real() -> None:+ lists = {+ "DOCSTRING_MODULES": DOCSTRING_MODULES,+ "CATALOG_NAMESPACES": CATALOG_NAMESPACES,+ "SHAPE_CHECK_MODULES": SHAPE_CHECK_MODULES or (),+ }+ for list_name, entries in lists.items():+ for entry in entries:+ parts = entry.split(".")+ package = parts[1] if parts[0] == "kornia" and len(parts) > 1 else None+ assert package in IN_SCOPE_PACKAGES, (+ f"{list_name} entry {entry!r} is not under kornia.<pkg> for an in-scope package"+ )+ importlib.import_module(entry)+ for entry in CATALOG_NAMESPACES:+ assert hasattr(importlib.import_module(entry), "__all__"), f"CATALOG_NAMESPACES entry {entry!r} has no __all__"+ converted = {qualified for qualified, _ in CONVERTED}+ for key, reason in SEE_ALSO_EXCEPTIONS.items():+ assert key in converted, f"SEE_ALSO_EXCEPTIONS key {key!r} is not a converted object"+ assert reason.strip(), f"SEE_ALSO_EXCEPTIONS entry {key!r} needs a reason"++[email protected](("qualified", "obj"), CONVERTED, ids=[qualified for qualified, _ in CONVERTED])+def test_converted_object_has_see_also(qualified: str, obj: object) -> None:+ if qualified in SEE_ALSO_EXCEPTIONS:+ pytest.skip(f"excepted: {SEE_ALSO_EXCEPTIONS[qualified]}")+ entries = see_also_entries(own_docstring(obj))+ assert entries, (+ f"{qualified} needs a 'See Also:' section with at least one bullet like "+ "'- :func:`name`: how it differs.' (or an entry in SEE_ALSO_EXCEPTIONS with a reason)"+ )+ problems = []+ for target, explanation in entries:+ if not target:+ problems.append(f"{explanation!r} does not start with a role such as :func:`name`, so it is no link")+ continue+ if not explanation:+ problems.append(f"{target!r} has no explanation after the colon")+ if is_private_target(target):+ problems.append(f"{target!r} is private")+ resolved = resolve_reference(obj, target, REGISTRY)+ if resolved is obj:+ problems.append(f"{target!r} links the object to itself")+ if resolved is None and target.removesuffix("()") in INTERSPHINX:+ problems.append(+ f"{target!r} is not a kornia object; See Also lists kornia objects, so mention torch and Python "+ "functions in the contract paragraph instead"+ )+ assert not problems, f"{qualified} See Also: " + "; ".join(problems)++[email protected](("qualified", "obj"), CONVERTED, ids=[qualified for qualified, _ in CONVERTED])+def test_converted_object_references_resolve(qualified: str, obj: object) -> None:+ unresolved = [+ f":{role}:`{target}`{_suggest(target)}{_wrong_role(role, target)}"+ for role, target in docstring_roles(own_docstring(obj))+ if not reference_resolves(obj, target, REGISTRY, INTERSPHINX, role)+ ]+ hint = "write the full name the docs register"+ if not is_documented(obj, REGISTRY):+ hint = f"{qualified} is not documented on any docs/source page, so short names have no scope; {hint}"+ assert not unresolved, f"{qualified} has references Sphinx cannot link ({hint}): " + ", ".join(unresolved)+++ "path", SHAPE_CHECK_FILES, ids=[str(path.relative_to(KORNIA_ROOT.parent)) for path in SHAPE_CHECK_FILES]+)+def test_no_math_shape_roles(path: Path) -> None:+ found = math_shape_roles(path.read_text(encoding="utf-8"))+ assert found == [], (+ f"{path.relative_to(KORNIA_ROOT.parent)} writes shapes as :math: {found}; use literals like ``(B, 1, H, W)``"+ )++[email protected]("namespace", CATALOG_NAMESPACES)+def test_catalog_names_every_export(namespace: str) -> None:+ module = importlib.import_module(namespace)+ doc = inspect.getdoc(module) or ""+ missing = catalog_missing(doc, sorted(module.__all__), module)+ assert missing == [], (+ f"the module docstring of {namespace} does not mention {missing}; list every export as a role such as "+ ":func:`name` or a literal such as ``name``, and spell a qualified name as a path to that export"+ )+ broken = catalog_unimportable(module, doc)+ assert not broken, f"the module docstring of {namespace} has references that do not import: {broken}"+++def test_rollout_progress() -> None:+ """Print, per in-scope package, the converted objects and catalogued namespaces (read it with ``-s``)."""+ objects = [obj for obj, _ in public_objects().values()]+ namespaces = modules_declaring_all()+ print("\npackage converted objects catalogued namespaces")+ for package in IN_SCOPE_PACKAGES:+ prefix = f"kornia.{package}"+ in_package = [obj for obj in objects if covered(obj.__module__, [prefix])]+ done = [obj for obj in in_package if covered(obj.__module__, DOCSTRING_MODULES)]+ required = [ns for ns in namespaces if covered(ns, [prefix]) and catalog_required(ns, CATALOG_NAMESPACES)]+ catalogued = [ns for ns in required if ns in CATALOG_NAMESPACES]+ print(f"{package:<14} {len(done):>4} / {len(in_package):<12} {len(catalogued):>4} / {len(required)}")diff --git a/tests/test_docstring_style_helpers.py b/tests/test_docstring_style_helpers.pynew file mode 100644index 000000000..025837007--- /dev/null+++ b/tests/test_docstring_style_helpers.py@@ -0,0 +1,569 @@+# LICENSE HEADER MANAGED BY add-license-header+#+# Copyright 2018 Kornia Team+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+#++"""Tests for the shared docstring-style helpers in ``testing/docstring_style.py``."""++import inspect+from functools import cache+from pathlib import Path++import pytest++import kornia+from kornia.augmentation.auto.operations.ops import AutoContrast+from kornia.geometry.boxes import Boxes, Boxes3D+from kornia.geometry.depth import DepthWarper, depth_to_3d, depth_to_3d_v2++from testing.docstring_style import (+ catalog_missing,+ catalog_required,+ catalog_unimportable,+ covered,+ docstring_roles,+ intersphinx_names,+ is_documented,+ is_private_target,+ is_shape_tuple,+ math_shape_roles,+ own_docstring,+ public_objects,+ reference_resolves,+ resolve_reference,+ see_also_entries,+ sphinx_registry,+)++DOCS = Path(__file__).resolve().parents[1] / "docs" / "source"+++@cache+def _registry():+ return sphinx_registry(DOCS)+++def test_shape_predicate():+ for s in ["(B, 3, H, W)", "(*, H, W)", "(B,)", "(B, N, 2)", "(B, H/2, W/2)", "(..., 3)", "(H_out, W_out)"]:+ assert is_shape_tuple(s), s+ for s in [+ "(x, y)",+ "(u, v)",+ "(B, C_{in}, H, W)",+ r"(H \times W)",+ "()",+ "(B, C, h, w)",+ "(-0.436, 0.436)",+ "(1, kH, kW)",+ ]:+ assert not is_shape_tuple(s), s+++def test_math_shape_roles():+ assert math_shape_roles("a :math:`(B, 3, H, W)` b :math:`(x, y)` c ``(B, N)``") == ["(B, 3, H, W)"]+++def test_docstring_roles():+ doc = "Use :func:`~kornia.a.b` or :py:class:`C`, :meth:`forward`; not :cite:`X` or :math:`y`."+ assert docstring_roles(doc) == [("func", "kornia.a.b"), ("class", "C"), ("meth", "forward")]+ doc = "Read :attr:`data`, :py:exc:`ValueError`, :data:`sys.stdout`, :const:`LIMIT`, :obj:`x`; not :mod:`torch`."+ assert docstring_roles(doc) == [+ ("attr", "data"),+ ("exc", "ValueError"),+ ("data", "sys.stdout"),+ ("const", "LIMIT"),+ ("obj", "x"),+ ]+++def test_see_also_entries():+ doc = (+ "Do a thing.\n\nArgs:\n x: input.\n\nSee Also:\n"+ " - :func:`depth_to_3d_v2`: the same points channels last.\n"+ " - :func:`depth_to_3d_v2`, :func:`~kornia.geometry.camera.perspective.project_points`: the two halves\n"+ " of the warp.\n\nExample:\n >>> 1\n"+ )+ assert see_also_entries(doc) == [+ ("depth_to_3d_v2", "the same points channels last."),+ ("depth_to_3d_v2", "the two halves of the warp."),+ ("kornia.geometry.camera.perspective.project_points", "the two halves of the warp."),+ ]+ assert see_also_entries(+ "Do.\n\nSee Also:\n - :func:`depth_to_3d_v2`: like :func:`depth_to_3d` but channels last.\n"+ ) == [("depth_to_3d_v2", "like :func:`depth_to_3d` but channels last.")]+ assert see_also_entries("Do.\n\nSee Also:\n Prose only.\n") == []+ assert see_also_entries("Do.\n\nSee Also:\n - :func:`a`: b.\n.. image:: foo.png\n") == [("a", "b.")]+ assert see_also_entries("Do.\n\nArgs:\n x: y.\n") is None+ assert see_also_entries("Do.\n\nSee Also:\n - :func:`a`\n") == [("a", "")]+ # A bullet without a leading role renders without a link; it is an entry with an empty target, not skipped.+ assert see_also_entries("Do.\n\nSee Also:\n - :func:`a`: b.\n - ``c``: d.\n - kornia.e: f.\n") == [+ ("a", "b."),+ ("", "``c``: d."),+ ("", "kornia.e: f."),+ ]+ # Any Python-domain object role links, so it leads an entry; :mod: does not name an object.+ doc = "Do.\n\nSee Also:\n - :attr:`~kornia.x.Y.z`: an attribute.\n - :exc:`E`: raised.\n - :mod:`m`: no.\n"+ assert see_also_entries(doc) == [("kornia.x.Y.z", "an attribute."), ("E", "raised."), ("", ":mod:`m`: no.")]+++def test_registry_uses_documented_paths():+ reg = _registry()+ assert "kornia.geometry.camera.perspective.unproject_points" in reg+ assert "kornia.geometry.camera.unproject_points" not in reg+ assert "kornia.geometry.homography.find_homography_dlt" in reg # automodule :members:+ assert "kornia.geometry.depth.DepthWarper.compute_projection_matrix" in reg # autoclass :members:+++def test_reference_resolution():+ reg = _registry()+ assert reference_resolves(depth_to_3d, "depth_to_3d_v2", reg)+ assert reference_resolves(depth_to_3d, "kornia.geometry.camera.perspective.unproject_points", reg)+ assert not reference_resolves(depth_to_3d, "kornia.geometry.camera.unproject_points", reg)+ assert not reference_resolves(depth_to_3d, "kornia.geometry.depth.no_such_function", reg)+ assert reference_resolves(DepthWarper, "compute_projection_matrix", reg)+ # Sphinx drops a trailing ``()`` and tries a dotted target under the page's module too.+ assert resolve_reference(depth_to_3d, "depth_to_3d_v2()", reg) is depth_to_3d_v2+ assert resolve_reference(Boxes3D, "Boxes.to_tensor", reg) is Boxes.to_tensor+ assert not reference_resolves(depth_to_3d, "kornia.geometry.camera.unproject_points()", reg)+ assert not reference_resolves(Boxes3D, "geometry.boxes.Boxes.to_tensor", reg)+++def test_resolve_reference_returns_the_target_object():+ reg = _registry()+ assert resolve_reference(depth_to_3d, "depth_to_3d_v2", reg) is depth_to_3d_v2+ assert resolve_reference(depth_to_3d, "depth_to_3d", reg) is depth_to_3d+ assert resolve_reference(depth_to_3d, "no_such_function", reg) is None+ assert resolve_reference(depth_to_3d, "kornia.geometry.camera.unproject_points", reg) is None+++def test_intersphinx_names():+ names = intersphinx_names(DOCS)+ assert names["torch.nn.functional.grid_sample"] == {"function"}+ assert names["torch.Tensor"] == {"class"}+ assert names["ValueError"] == {"exception"}+ assert names["random"] == {"module"}+ assert "torch.nn.functional.no_such_function" not in names+ reg = _registry()+ assert resolve_reference(depth_to_3d, "torch.nn.functional.grid_sample", reg) is None+ assert reference_resolves(depth_to_3d, "torch.nn.functional.grid_sample", reg, names)+ assert not reference_resolves(depth_to_3d, "torch.nn.functional.no_such_function", reg, names)+++def test_intersphinx_links_a_role_only_to_its_object_types():+ """Intersphinx matches the role to the object type, unlike the local lookup (Sphinx ``objtypes_for_role``)."""+ names, reg = intersphinx_names(DOCS), _registry()++ cases = [+ ("func", "torch.svd", True),+ ("obj", "torch.svd", True),+ ("meth", "torch.svd", False),+ ("attr", "torch.svd", False),+ ("meth", "torch.Tensor.add", True),+ ("func", "torch.Tensor.add", False),+ # Inventories from before Sphinx 2.1 store properties as methods, so intersphinx lets :attr: find a method.+ ("attr", "torch.Tensor.add", True),+ ("attr", "torch.Tensor.shape", True),+ ("meth", "torch.Tensor.shape", False),+ ("exc", "ValueError", True),+ ("class", "ValueError", True),+ ("func", "ValueError", False),+ ("class", "torch.Tensor", True),+ ("exc", "torch.Tensor", True),+ ("data", "sys.stdout", True),+ ("attr", "sys.stdout", False),+ # :const: is in no object type's roles, so intersphinx never links it.+ ("const", "sys.stdout", False),+ ("const", "math.pi", False),+ ("obj", "random", True),+ ("func", "random", False),+ ]+ for role, target, expected in cases:+ assert reference_resolves(depth_to_3d, target, reg, names, role) is expected, (role, target)+++def test_only_func_and_meth_drop_parentheses():+ names, reg = intersphinx_names(DOCS), _registry()+ assert resolve_reference(depth_to_3d, "depth_to_3d_v2()", reg, "func") is depth_to_3d_v2+ assert resolve_reference(DepthWarper, "compute_projection_matrix()", reg, "meth") is not None+ assert resolve_reference(depth_to_3d, "DepthWarper()", reg, "class") is None+ assert resolve_reference(depth_to_3d, "DepthWarper", reg, "class") is DepthWarper+ assert reference_resolves(depth_to_3d, "torch.svd()", reg, names, "func")+ assert not reference_resolves(depth_to_3d, "torch.Tensor()", reg, names, "class")+++def test_short_names_need_a_documented_object():+ reg = _registry()+ assert is_documented(depth_to_3d, reg)+ assert not is_documented(AutoContrast, reg)+ # With no page, and so no scope, only a full name resolves from its docstring.+ assert resolve_reference(AutoContrast, "kornia.geometry.depth.depth_to_3d", reg) is depth_to_3d+ assert resolve_reference(AutoContrast, "depth_to_3d", reg) is None+++def _write_page(root: Path, relative: str, text: str) -> None:+ page = root / relative+ page.parent.mkdir(parents=True, exist_ok=True)+ page.write_text(text, encoding="utf-8")+++def test_autosummary_registers_only_with_toctree(tmp_path):+ _write_page(tmp_path, "links.rst", ".. currentmodule:: kornia.color\n\n.. autosummary::\n\n yuv_to_rgb\n")+ assert sphinx_registry(tmp_path) == {}+ _write_page(+ tmp_path,+ "links.rst",+ ".. currentmodule:: kornia.color\n\n.. autosummary::\n :toctree: api\n\n yuv_to_rgb\n",+ )+ assert sphinx_registry(tmp_path) == {"kornia.color.yuv_to_rgb": kornia.color.yuv_to_rgb}+++def test_registry_reads_pages_in_subdirectories(tmp_path):+ _write_page(tmp_path, "models/page.rst", ".. autofunction:: kornia.color.yuv_to_rgb\n")+ _write_page(tmp_path, "_build/page.rst", ".. autofunction:: kornia.color.rgb_to_yuv\n")+ _write_page(tmp_path, "_templates/page.rst", ".. autofunction:: kornia.color.rgb_to_hsv\n")+ assert sphinx_registry(tmp_path) == {"kornia.color.yuv_to_rgb": kornia.color.yuv_to_rgb}+++def test_members_follow_autodoc_docstring_rule(tmp_path):+ """``:members:`` documents an inherited docstring; a method with none only under ``:undoc-members:``."""+ page = ".. currentmodule:: kornia.augmentation\n\n.. autoclass:: {}\n :members:\n{}"+ intensity = "kornia.augmentation.IntensityAugmentationBase2D"+ mix = "kornia.augmentation.MixAugmentationBaseV2"+ assert own_docstring(kornia.augmentation.IntensityAugmentationBase2D.apply_transform_mask) is None+ _write_page(tmp_path, "page.rst", page.format("IntensityAugmentationBase2D", ""))+ assert f"{intensity}.apply_transform_mask" in sphinx_registry(tmp_path)+ assert own_docstring(kornia.augmentation.MixAugmentationBaseV2.apply_non_transform) is None+ _write_page(tmp_path, "page.rst", page.format("MixAugmentationBaseV2", ""))+ assert f"{mix}.apply_non_transform" not in sphinx_registry(tmp_path)+ _write_page(tmp_path, "page.rst", page.format("MixAugmentationBaseV2", " :undoc-members:\n"))+ assert f"{mix}.apply_non_transform" in sphinx_registry(tmp_path)+++def test_registry_registers_documented_data_attributes():+ """Enum members and dataclass fields under ``:undoc-members:`` link, even when the value is ``None``."""+ reg = _registry()+ assert kornia.models.sam.SamConfig.checkpoint is None+ for target in ("kornia.color.CFA.BG", "kornia.image.ImageSize.height", "kornia.models.sam.SamConfig.checkpoint"):+ assert resolve_reference(depth_to_3d, target, reg) is not None, target+ assert reference_resolves(depth_to_3d, target, reg, role="attr"), target+++_ATTRIBUTE_SOURCES = {+ "docstyle_attrs.py": '''+import enum+from dataclasses import dataclass+from typing import NamedTuple+++class Commented:+ """A class."""++ #: before+ before = 1+ after = 2 #: after+ annotated: int+ """string after"""+ plain = 3+ hashed = 4 # an ordinary comment++ #: two lines+ #: of comment+ two = 5++ #: separated by a blank line++ separated = 6+ multi = (+ 1,+ 2,+ ) #: after a multi-line value+ try:+ in_try = 7 #: in try+ except Exception:+ in_except = 8 #: in except+ _private = 9 #: private++ def __init__(self):+ self.instance = 10 #: instance+ self.undocumented = 11+ local = 12 #: a local++ def nested():+ self.nested = 13 #: in a nested function++ self.after_nested = 15 #: after a nested function++ def other(self):+ self.elsewhere = 14 #: in another method+++class Undoc:+ """Same kinds, under undoc-members."""++ plain = 1+ annotated_only: int+ hashed = 2 # ordinary++ def __init__(self):+ self.instance = 3++ @property+ def prop(self):+ return 1+++class Point(NamedTuple):+ """A point."""++ x: float+ y: float+++class Color(enum.Enum):+ """Colors."""++ RED = 1+ GREEN = 2 #: green+++@dataclass+class Config:+ """A config."""++ size: int = 1+ name: str | None = None+''',+ "docstyle_module.py": (+ '"""Data with __all__."""\n\n#: documented\nLIMIT = 3\nOTHER = 4\n__all__ = ["LIMIT", "OTHER"]\n'+ ),+ "docstyle_noall.py": (+ '"""Data without __all__."""\n\nfrom math import pi #: imported here\n\n#: documented\nLIMIT = 3\nOTHER = 4\n'+ ),+ "docstyle_undoc.py": (+ '"""Data with __all__, under undoc-members."""\n\n__all__ = ["BARE", "PLAIN", "COMMENTED"]\nBARE: int\n'+ "PLAIN = 1\n#: doc\nCOMMENTED = 2\n"+ ),+}++_ATTRIBUTE_PAGE = """+.. autoclass:: docstyle_attrs.Commented+ :members:++.. autoclass:: docstyle_attrs.Undoc+ :members:+ :undoc-members:++.. autoclass:: docstyle_attrs.Point+ :members:++.. autoclass:: docstyle_attrs.Color+ :members:++.. autoclass:: docstyle_attrs.Config+ :members:+ :undoc-members:++.. automodule:: docstyle_module+ :members:++.. automodule:: docstyle_noall+ :members:+ :undoc-members:++.. automodule:: docstyle_undoc+ :members:+ :undoc-members:+"""+++def test_registry_matches_sphinx_on_documented_attributes(tmp_path, monkeypatch):+ """The registry holds the names a Sphinx 8.2.3 build of the same page puts into ``objects.inv``.++ The expected set is that build's inventory, modules left out. To regenerate it, write these sources and the page+ (as ``index.rst``, with a ``conf.py`` that adds ``sphinx.ext.autodoc`` and puts the sources on ``sys.path``), run+ ``uv run --no-project --with sphinx==8.2.3 python -m sphinx -b html src out``, then+ ``python -m sphinx.ext.intersphinx out/objects.inv``.+ """+ for name, source in _ATTRIBUTE_SOURCES.items():+ (tmp_path / name).write_text(source, encoding="utf-8")+ monkeypatch.syspath_prepend(str(tmp_path))+ _write_page(tmp_path / "docs", "index.rst", _ATTRIBUTE_PAGE)+ registered = {name for name, obj in sphinx_registry(tmp_path / "docs").items() if not inspect.ismodule(obj)}+ a = "docstyle_attrs"+ assert registered == {+ *(f"{a}.{name}" for name in ("Commented", "Undoc", "Point", "Color", "Config")),+ *(f"{a}.Commented.{name}" for name in ("before", "after", "annotated", "two", "multi", "in_try")),+ f"{a}.Commented.instance",+ f"{a}.Commented.after_nested",+ *(f"{a}.Undoc.{name}" for name in ("plain", "annotated_only", "hashed", "prop")),+ f"{a}.Point.x",+ f"{a}.Point.y",+ f"{a}.Color.GREEN",+ f"{a}.Config.size",+ f"{a}.Config.name",+ "docstyle_module.LIMIT",+ "docstyle_noall.LIMIT",+ "docstyle_undoc.BARE",+ "docstyle_undoc.COMMENTED",+ }+++def test_covered_prefix():+ assert covered("kornia.color.rgb", ["kornia.color"])+ assert not covered("kornia.colorx", ["kornia.color"])+++def test_catalog_missing():+ depth, enhance = kornia.geometry.depth, kornia.enhance+ names = ["depth_to_3d", "depth_to_3d_v2"]+ assert catalog_missing("use :func:`depth_to_3d_v2` here", names, depth) == ["depth_to_3d"]+ assert catalog_missing("use ``depth_to_3d_v2()`` here", names, depth) == ["depth_to_3d"]+ assert catalog_missing("- ``depth_to_3d``: points.", ["depth_to_3d"], depth) == []+ assert catalog_missing("- ``depth_to_3d()``: points.", ["depth_to_3d"], depth) == []+ assert catalog_missing("- :func:`~kornia.geometry.depth.depth_to_3d`: points.", ["depth_to_3d"], depth) == []+ assert catalog_missing("- :func:`kornia.geometry.depth.depth_to_3d`: points.", ["depth_to_3d"], depth) == []+ # A plain word is not a mention, and neither is a longer name that ends with it.+ assert catalog_missing("Use the morphological opening and closing.", ["opening", "closing"], kornia.morphology) == [+ "opening",+ "closing",+ ]+ assert catalog_missing("use depth_to_3d here", ["depth_to_3d"], depth) == ["depth_to_3d"]+ assert catalog_missing(":func:`my_depth_to_3d`", ["depth_to_3d"], depth) == ["depth_to_3d"]+ # Single backticks are the default role, which renders as italics, and :math: is no reference: neither counts.+ assert catalog_missing("use `depth_to_3d` here", ["depth_to_3d"], depth) == ["depth_to_3d"]+ assert catalog_missing("the :math:`depth_to_3d` term", ["depth_to_3d"], depth) == ["depth_to_3d"]+ assert catalog_missing("use :py:func:`depth_to_3d` here", ["depth_to_3d"], depth) == []+ # A qualified target counts only as the exported object: torch's normalize is not kornia.enhance.normalize, which+ # is reached through the package or its defining module even though a submodule shares its name.+ for other in (":func:`torch.nn.functional.normalize`", "``torch.nn.functional.normalize``"):+ assert catalog_missing(f"for L2, use {other}", ["normalize"], enhance) == ["normalize"]+ for same in (+ ":func:`~kornia.enhance.normalize`",+ "``kornia.enhance.normalize``",+ ":func:`kornia.enhance.normalize.normalize`",+ ):+ assert catalog_missing(f"use {same}", ["normalize"], enhance) == []+++def test_catalog_unimportable():+ depth = kornia.geometry.depth+ doc = (+ ":func:`depth_to_3d`, :func:`depth_to_3d()`, :func:`~kornia.geometry.depth.depth_to_3d_v2()` and "+ ":class:`kornia.geometry.depth.DepthWarper`"+ )+ assert catalog_unimportable(depth, doc) == []+ assert catalog_unimportable(depth, ":func:`depth_to_4d()` and :func:`kornia.geometry.depth.nope`") == [+ "depth_to_4d()",+ "kornia.geometry.depth.nope",+ ]+++def test_catalog_required():+ assert catalog_required("kornia.geometry.depth", [])+ # kornia.enhance re-exports everything kornia.enhance.normalize declares, as the same objects.+ assert not catalog_required("kornia.enhance.normalize", ["kornia.enhance"])+ assert catalog_required("kornia.enhance.normalize", [])+++def test_own_docstring_and_public_objects():+ class Base:+ """Base doc."""++ class Child(Base):+ pass++ assert own_docstring(Base) == "Base doc."+ assert own_docstring(Child) is None+ assert id(depth_to_3d) in public_objects()+ assert public_objects()[id(depth_to_3d)][1] == "kornia.geometry.depth.depth_to_3d"+++def test_function_sharing_a_submodule_name_is_the_function():+ reg = _registry()+ assert reg["kornia.filters.sobel"] is kornia.filters.sobel+ assert resolve_reference(kornia.filters.sobel, "sobel", reg) is kornia.filters.sobel+++def test_explicit_members_list_registers_only_the_listed_names():+ reg = _registry()+ assert "kornia.feature.SOLD2.match" not in reg+ assert "kornia.feature.SOLD2.forward" in reg+++def test_automodule_members_register_class_methods():+ reg = _registry()+ assert "kornia.geometry.boxes.Boxes.to_tensor" in reg+++def test_special_members_register_dunder_methods(tmp_path):+ """``:special-members:`` alone selects every documented ``__name__`` method, a list only the listed ones."""+ reg = _registry()+ assert reg["kornia.geometry.quaternion.Quaternion.__init__"] is kornia.geometry.quaternion.Quaternion.__init__+ assert "kornia.geometry.quaternion.Quaternion.__add__" in reg+ # No docstring, and none to inherit: a one-page Sphinx 8.2.3 build leaves it out too.+ assert "kornia.geometry.quaternion.Quaternion.__mul__" not in reg+ assert "kornia.geometry.pose.NamedPose.__mul__" in reg # :special-members: __init__, __mul__+ assert "kornia.geometry.pose.NamedPose.__repr__" not in reg+ quaternion = "kornia.geometry.quaternion.Quaternion"+ page = ".. currentmodule:: kornia.geometry.quaternion\n\n.. autoclass:: Quaternion\n{}"+ _write_page(tmp_path, "page.rst", page.format(" :members:\n"))+ assert f"{quaternion}.__init__" not in sphinx_registry(tmp_path)+ # Without :members:, all special members document nothing; a list documents the listed names.+ _write_page(tmp_path, "page.rst", page.format(" :special-members:\n"))+ assert sphinx_registry(tmp_path) == {quaternion: kornia.geometry.quaternion.Quaternion}+ _write_page(tmp_path, "page.rst", page.format(" :special-members: __add__\n"))+ assert set(sphinx_registry(tmp_path)) == {quaternion, f"{quaternion}.__add__"}+ _write_page(tmp_path, "page.rst", page.format(" :members: w\n :special-members: __add__\n"))+ assert set(sphinx_registry(tmp_path)) == {quaternion, f"{quaternion}.w", f"{quaternion}.__add__"}+ # A module's special members apply to its classes.+ _write_page(+ tmp_path, "page.rst", ".. automodule:: kornia.geometry.quaternion\n :members:\n :special-members:\n"+ )+ assert f"{quaternion}.__add__" in sphinx_registry(tmp_path)+++def test_nested_automethod_registers_under_its_class():+ assert "kornia.geometry.camera.stereo.StereoCamera.__init__" in _registry()+++def test_registry_rejects_options_it_does_not_model(tmp_path):+ """An option that changes what autodoc registers fails loudly instead of skewing the registry."""+ for option in ("no-index", "exclude-members", "inherited-members", "private-members"):+ _write_page(+ tmp_path, "page.rst", f".. autoclass:: kornia.geometry.depth.DepthWarper\n :members:\n :{option}:\n"+ )+ with pytest.raises(ValueError, match=option):+ sphinx_registry(tmp_path)+++def test_py_prefixed_currentmodule_sets_the_scope(tmp_path):+ _write_page(tmp_path, "page.rst", ".. py:currentmodule:: kornia.color\n\n.. autofunction:: yuv_to_rgb\n")+ assert sphinx_registry(tmp_path) == {"kornia.color.yuv_to_rgb": kornia.color.yuv_to_rgb}+++def test_private_target():+ assert is_private_target("_helper")+ assert is_private_target("kornia.geometry.depth._depth_grid_dtype")+ assert is_private_target("kornia.x.Class.__mangled")+ # A special method that ``:special-members:`` documents is public.+ assert not is_private_target("kornia.geometry.pose.NamedPose.__mul__")+ assert not is_private_target("depth_to_3d")+++def test_own_docstring_ignores_whitespace_only():+ def blank():+ """ """++ assert own_docstring(blank) is None